Skip to content

Commit 15a2bc9

Browse files
committed
feat: Container compose supports .env file operations
1 parent d1c2a69 commit 15a2bc9

File tree

14 files changed

+341
-295
lines changed

14 files changed

+341
-295
lines changed

agent/app/service/container_compose.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ func recreateCompose(content, path string) error {
404404

405405
func loadEnv(list []dto.ComposeInfo) []dto.ComposeInfo {
406406
for i := 0; i < len(list); i++ {
407-
envFilePath := path.Join(path.Dir(list[i].Path), "1panel.env")
407+
envFilePath := path.Join(path.Dir(list[i].Path), ".env")
408408
file, err := os.ReadFile(envFilePath)
409409
if err != nil {
410410
continue
@@ -424,7 +424,7 @@ func newComposeEnv(pathItem string, env []string) error {
424424
if len(env) == 0 {
425425
return nil
426426
}
427-
envFilePath := path.Join(path.Dir(pathItem), "1panel.env")
427+
envFilePath := path.Join(path.Dir(pathItem), ".env")
428428
file, err := os.OpenFile(envFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, constant.FilePerm)
429429
if err != nil {
430430
global.LOG.Errorf("failed to create env file: %v", err)
@@ -438,6 +438,6 @@ func newComposeEnv(pathItem string, env []string) error {
438438
return err
439439
}
440440
}
441-
global.LOG.Infof("1panel.env file successfully created or updated with env variables in %s", envFilePath)
441+
global.LOG.Infof(".env file successfully created or updated with env variables in %s", envFilePath)
442442
return nil
443443
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
<template>
2+
<div>
3+
<el-space wrap>
4+
<div v-for="(env, index) in tmpLabels" :key="index">
5+
<fu-read-write-switch write-trigger="onDblclick">
6+
<template #read>
7+
<el-button plain>
8+
{{ env }}
9+
<el-button
10+
circle
11+
plain
12+
size="small"
13+
type="danger"
14+
class="float-right -mr-6 -mt-8"
15+
icon="Close"
16+
@click="remove(index)"
17+
/>
18+
</el-button>
19+
</template>
20+
<template #default="{ read }">
21+
<el-input class="p-w-300" v-model="tmpLabels[index]" @blur="read" />
22+
</template>
23+
</fu-read-write-switch>
24+
</div>
25+
<el-input v-if="showAdd" v-model="labelItem">
26+
<template #append>
27+
<el-button icon="Check" @click="save()" />
28+
<el-button icon="Close" @click="cancel()" />
29+
</template>
30+
</el-input>
31+
<el-button plain icon="Plus" @click="add()" />
32+
</el-space>
33+
</div>
34+
</template>
35+
36+
<script lang="ts" setup>
37+
import { ref, onMounted } from 'vue';
38+
const em = defineEmits(['update:labels']);
39+
40+
const tmpLabels = ref([]);
41+
const labelItem = ref('');
42+
const showAdd = ref(false);
43+
44+
const props = defineProps({
45+
labels: { type: Array<string>, default: [] },
46+
});
47+
watch(
48+
() => props.labels,
49+
(newVal) => {
50+
tmpLabels.value = newVal || [];
51+
},
52+
);
53+
const add = () => {
54+
showAdd.value = true;
55+
labelItem.value = '';
56+
};
57+
const cancel = () => {
58+
showAdd.value = false;
59+
labelItem.value = '';
60+
};
61+
const save = () => {
62+
if (labelItem.value && tmpLabels.value.indexOf(labelItem.value) === -1) {
63+
tmpLabels.value.push(labelItem.value);
64+
}
65+
showAdd.value = false;
66+
labelItem.value = '';
67+
handleUpdate();
68+
};
69+
const remove = (index: number) => {
70+
tmpLabels.value.splice(index, 1);
71+
handleUpdate();
72+
};
73+
const handleUpdate = () => {
74+
em('update:labels', tmpLabels.value);
75+
};
76+
onMounted(() => {
77+
tmpLabels.value = props.labels || [];
78+
});
79+
</script>

frontend/src/lang/modules/en.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -852,8 +852,6 @@ const message = {
852852
privileged: 'Privileged',
853853
privilegedHelper:
854854
'Allow the container to perform certain privileged operations on the host, which may increase container risks. Use with caution!',
855-
editComposeHelper:
856-
'Note: Environment variables are saved to the 1panel.env file and need to be referenced via env_file in compose.\nVariables only take effect inside the container and do not participate in ${VAR} substitution in the compose file.',
857855

858856
upgradeHelper: 'Repository Name/Image Name: Image Version',
859857
upgradeWarning2:
@@ -1008,6 +1006,9 @@ const message = {
10081006
composeOperatorHelper: '{1} operation will be performed on {0}. Do you want to continue?',
10091007
composeDownHelper:
10101008
'This will stop and remove all containers and networks under the {0} compose. Do you want to continue?',
1009+
composeEnvHelper1: 'Double-click to edit existing environment variables.',
1010+
composeEnvHelper2:
1011+
'This orchestration was created by the 1Panel App Store. Please modify environment variables in the installed applications.',
10111012

10121013
setting: 'Setting | Settings',
10131014
goSetting: 'Go to edit',

frontend/src/lang/modules/es-es.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -856,8 +856,6 @@ const message = {
856856
privileged: 'Privilegiado',
857857
privilegedHelper:
858858
'Permite que el contenedor realice ciertas operaciones privilegiadas en el host, lo que puede aumentar los riesgos. ¡Úselo con precaución!',
859-
editComposeHelper:
860-
'Nota: Las variables de entorno se guardan en el archivo 1panel.env y deben ser referenciadas mediante env_file en compose.\nLas variables solo tienen efecto dentro del contenedor y no participan en la sustitución ${VAR} en el archivo compose.',
861859
upgradeHelper: 'Nombre de repositorio/imagen: versión de la imagen',
862860
upgradeWarning2:
863861
'La operación de actualización requiere reconstruir el contenedor, cualquier dato no persistente se perderá. ¿Desea continuar?',
@@ -1012,6 +1010,10 @@ const message = {
10121010
composeOperatorHelper: 'La operación {1} se realizará en {0}. ¿Desea continuar?',
10131011
composeDownHelper:
10141012
'Esto detendrá y eliminará todos los contenedores y redes bajo la composición {0}. ¿Desea continuar?',
1013+
composeEnvHelper1: 'Haga doble clic para editar las variables de entorno existentes.',
1014+
composeEnvHelper2:
1015+
'Esta orquestación fue creada por la Tienda de Aplicaciones 1Panel. Modifique las variables de entorno en las aplicaciones instaladas.',
1016+
10151017
setting: 'Configuración | Configuraciones',
10161018
goSetting: 'Ir a editar',
10171019
operatorStatusHelper: 'Esto "{0}" el servicio Docker. ¿Desea continuar?',

frontend/src/lang/modules/ja.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -984,6 +984,9 @@ const message = {
984984
composeOperatorHelper: '{1}操作は{0}で実行されます。続けたいですか?',
985985
composeDownHelper:
986986
'これにより、{0}構成の下のすべてのコンテナとネットワークが停止して削除されます。続けたいですか?',
987+
composeEnvHelper1: '既存の環境変数を編集するにはダブルクリックしてください。',
988+
composeEnvHelper2:
989+
'このオーケストレーションは1Panelアプリストアで作成されました。インストール済みアプリケーションで環境変数を変更してください。',
987990

988991
setting: '設定|設定',
989992
operatorStatusHelper: 'これは「{0}」Dockerサービスになります。続けたいですか?',

frontend/src/lang/modules/ko.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -827,8 +827,6 @@ const message = {
827827
privileged: '특권 모드',
828828
privilegedHelper:
829829
'컨테이너가 호스트에서 특정 특권 작업을 수행할 수 있도록 허용합니다. 이는 보안 위험을 초래할 수 있으므로 주의해서 사용하십시오.',
830-
editComposeHelper:
831-
'참고: 환경 변수는 1panel.env 파일에 저장되며 compose에서 env_file을 통해 참조해야 합니다.\n변수는 컨테이너 내부에서만 유효하며 compose 파일의 ${VAR} 치환에 참여하지 않습니다.',
832830
upgradeHelper: '레포지토리 이름/이미지 이름: 이미지 버전',
833831
upgradeWarning2:
834832
'업그레이드 작업은 컨테이너를 재빌드해야 하며, 비지속적인 데이터가 손실됩니다. 계속하시겠습니까?',
@@ -974,6 +972,9 @@ const message = {
974972
composeOperatorHelper: '{1} 작업이 {0}에서 수행됩니다. 계속 하시겠습니까?',
975973
composeDownHelper:
976974
'이 작업은 {0} 컴포즈 아래의 모든 컨테이너와 네트워크를 중지하고 제거합니다. 계속 하시겠습니까?',
975+
composeEnvHelper1: '기존 환경 변수를 편집하려면 더블 클릭하세요.',
976+
composeEnvHelper2:
977+
'이 오케스트레이션은 1Panel 앱 스토어에서 생성되었습니다. 설치된 애플리케이션에서 환경 변수를 수정하세요.',
977978

978979
setting: '설정 | 설정들',
979980
operatorStatusHelper: '이 작업은 Docker 서비스를 "{0}" 합니다. 계속 하시겠습니까?',

frontend/src/lang/modules/ms.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -846,8 +846,6 @@ const message = {
846846
privileged: 'Privileged',
847847
privilegedHelper:
848848
'Benarkan kontena menjalankan operasi teristimewa tertentu pada hos, yang boleh meningkatkan risiko kontena. Gunakan dengan berhati-hati!',
849-
editComposeHelper:
850-
'Nota: Pembolehubah persekitaran disimpan ke fail 1panel.env dan perlu dirujuk melalui env_file dalam compose.\nPembolehubah hanya berkesan di dalam bekas dan tidak mengambil bahagian dalam penggantian ${VAR} dalam fail compose.',
851849

852850
upgradeHelper: 'Nama Repository/Nama Imej: Versi Imej',
853851
upgradeWarning2:
@@ -1002,6 +1000,9 @@ const message = {
10021000
composeOperatorHelper: 'Operasi {1} akan dilakukan pada {0}. Adakah anda mahu meneruskan?',
10031001
composeDownHelper:
10041002
'Ini akan menghentikan dan menghapuskan semua kontena dan rangkaian di bawah komposisi {0}. Adakah anda mahu meneruskan?',
1003+
composeEnvHelper1: 'Klik dua kali untuk mengedit pembolehubah persekitaran sedia ada.',
1004+
composeEnvHelper2:
1005+
'Penyelarasan ini dibuat oleh Kedai Apl 1Panel. Sila ubah pembolehubah persekitaran dalam aplikasi yang dipasang.',
10051006

10061007
setting: 'Tetapan | Tetapan',
10071008
operatorStatusHelper: 'Ini akan "{0}" perkhidmatan Docker. Adakah anda mahu meneruskan?',

frontend/src/lang/modules/pt-br.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -844,8 +844,6 @@ const message = {
844844
privileged: 'Privilegiado',
845845
privilegedHelper:
846846
'Permite que o contêiner execute determinadas operações privilegiadas no host, o que pode aumentar os riscos do contêiner. Use com cautela!',
847-
editComposeHelper:
848-
'Nota: As variáveis de ambiente são salvas no arquivo 1panel.env e precisam ser referenciadas via env_file no compose.\nAs variáveis só têm efeito dentro do contêiner e não participam da substituição ${VAR} no arquivo compose.',
849847
upgradeHelper: 'Nome do Repositório/Nome da Imagem: Versão da Imagem',
850848
upgradeWarning2:
851849
'A operação de upgrade requer a reconstrução do contêiner, e qualquer dado não persistente será perdido. Deseja continuar?',
@@ -999,6 +997,9 @@ const message = {
999997
composeOperatorHelper: 'A operação {1} será realizada no {0}. Deseja continuar?',
1000998
composeDownHelper:
1001999
'Isso irá parar e remover todos os containers e redes sob a composição {0}. Deseja continuar?',
1000+
composeEnvHelper1: 'Clique duas vezes para editar variáveis de ambiente existentes.',
1001+
composeEnvHelper2:
1002+
'Esta orquestração foi criada pela Loja de Aplicativos 1Panel. Modifique as variáveis de ambiente nos aplicativos instalados.',
10021003

10031004
setting: 'Configuração | Configurações',
10041005
operatorStatusHelper: 'Isso irá "{0}" o serviço Docker. Deseja continuar?',

frontend/src/lang/modules/ru.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -840,8 +840,6 @@ const message = {
840840
privileged: 'Привилегированный',
841841
privilegedHelper:
842842
'Разрешить контейнеру выполнять определенные привилегированные операции на хосте, что может повысить риски контейнера. Используйте с осторожностью!',
843-
editComposeHelper:
844-
'Примечание: Переменные среды сохраняются в файл 1panel.env и должны быть указаны через env_file в compose.\nПеременные действуют только внутри контейнера и не участвуют в замене ${VAR} в файле compose.',
845843

846844
upgradeHelper: 'Имя репозитория/Имя образа: Версия образа',
847845
upgradeWarning2:
@@ -996,6 +994,9 @@ const message = {
996994
composeDetailHelper: 'Compose создан вне 1Panel. Операции запуска и остановки не поддерживаются.',
997995
composeOperatorHelper: 'Операция {1} будет выполнена для {0}. Хотите продолжить?',
998996
composeDownHelper: 'Это остановит и удалит все контейнеры и сети под compose {0}. Хотите продолжить?',
997+
composeEnvHelper1: 'Дважды щелкните, чтобы редактировать существующие переменные среды.',
998+
composeEnvHelper2:
999+
'Эта оркестрация создана Магазином приложений 1Panel. Измените переменные среды в установленных приложениях.',
9991000

10001001
setting: 'Настройка | Настройки',
10011002
operatorStatusHelper: 'Это выполнит "{0}" службы Docker. Хотите продолжить?',

frontend/src/lang/modules/tr.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -860,8 +860,6 @@ const message = {
860860
privileged: 'Ayrıcalıklı',
861861
privilegedHelper:
862862
'Konteynerin ana bilgisayarda belirli ayrıcalıklı işlemler gerçekleştirmesine izin verir, bu da konteyner risklerini artırabilir. Dikkatli kullanın!',
863-
editComposeHelper:
864-
'Not: Ortam değişkenleri 1panel.env dosyasına kaydedilir ve compose içinde env_file aracılığıyla referans alınmalıdır.\nDeğişkenler yalnızca konteyner içinde geçerlidir ve compose dosyasındaki ${VAR} değiştirmesine katılmaz.',
865863

866864
upgradeHelper: 'Depo Adı/İmaj Adı: İmaj Sürümü',
867865
upgradeWarning2:
@@ -1019,6 +1017,9 @@ const message = {
10191017
composeOperatorHelper: '{0} üzerinde {1} işlemi gerçekleştirilecek. Devam etmek istiyor musunuz?',
10201018
composeDownHelper:
10211019
'Bu, {0} compose altındaki tüm konteynerleri ve ağları durduracak ve kaldıracaktır. Devam etmek istiyor musunuz?',
1020+
composeEnvHelper1: 'Mevcut ortam değişkenlerini düzenlemek için çift tıklayın.',
1021+
composeEnvHelper2:
1022+
'Bu düzenleme 1Panel Uygulama Mağazası tarafından oluşturuldu. Lütfen ortam değişkenlerini yüklü uygulamalarda değiştirin.',
10221023

10231024
setting: 'Ayar | Ayarlar',
10241025
goSetting: 'Düzenlemeye git',

0 commit comments

Comments
 (0)