1.0.13
This commit is contained in:
1 parent
a88d3d5788
commit
8f3a7eb435
96 files changed
+5235
-1870
No files matched your search
@@ -243,6 +243,7 @@
|
||||
{ value: 'running', label: 'Running', icon: Play, color: 'text-emerald-500' },
|
||||
{ value: 'partial', label: 'Partial', icon: CircleDashed, color: 'text-amber-500' },
|
||||
{ value: 'stopped', label: 'Stopped', icon: Square, color: 'text-rose-500' },
|
||||
{ value: 'created', label: 'Created', icon: CircleDashed, color: 'text-slate-500' },
|
||||
{ value: 'not deployed', label: 'Not deployed', icon: Rocket, color: 'text-violet-500' }
|
||||
];
|
||||
|
||||
@@ -335,13 +336,13 @@
|
||||
const query = searchQuery.toLowerCase();
|
||||
result = result.filter(stack =>
|
||||
stack.name.toLowerCase().includes(query) ||
|
||||
stack.status.toLowerCase().includes(query)
|
||||
getDisplayStatus(stack).toLowerCase().includes(query)
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by status
|
||||
// Filter by status (uses display status so git "created" matches "not deployed")
|
||||
if (statusFilter.length > 0) {
|
||||
result = result.filter(stack => statusFilter.includes(stack.status.toLowerCase()));
|
||||
result = result.filter(stack => statusFilter.includes(getDisplayStatus(stack).toLowerCase()));
|
||||
}
|
||||
|
||||
// Sort
|
||||
@@ -355,7 +356,7 @@
|
||||
cmp = a.containers.length - b.containers.length;
|
||||
break;
|
||||
case 'status':
|
||||
cmp = a.status.localeCompare(b.status);
|
||||
cmp = getDisplayStatus(a).localeCompare(getDisplayStatus(b));
|
||||
break;
|
||||
case 'cpu':
|
||||
const cpuA = getStackStats(a)?.cpuPercent ?? -1;
|
||||
@@ -391,7 +392,7 @@
|
||||
|
||||
// Count by status for selected stacks
|
||||
const selectedRunning = $derived(selectedInFilter.filter(s => s.status === 'running' || s.status === 'partial' || s.status === 'restarting'));
|
||||
const selectedStopped = $derived(selectedInFilter.filter(s => s.status === 'stopped' || s.status === 'not deployed'));
|
||||
const selectedStopped = $derived(selectedInFilter.filter(s => s.status === 'stopped' || s.status === 'not deployed' || s.status === 'created'));
|
||||
|
||||
function toggleSelectAll() {
|
||||
if (allFilteredSelected) {
|
||||
@@ -655,6 +656,13 @@
|
||||
return stackSources[stackName] || { sourceType: 'external' };
|
||||
}
|
||||
|
||||
function getDisplayStatus(stack: ComposeStackInfo): string {
|
||||
if (stack.status === 'created' && getStackSource(stack.name).sourceType === 'git') {
|
||||
return 'not deployed';
|
||||
}
|
||||
return stack.status;
|
||||
}
|
||||
|
||||
async function openGitModal(gitStack?: any) {
|
||||
editingGitStack = gitStack || null;
|
||||
// Fetch repositories and credentials before opening modal
|
||||
@@ -679,8 +687,14 @@
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/start`, envId), { method: 'POST' });
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
const errorMsg = data.error || 'Failed to start stack';
|
||||
const rawText = await response.text();
|
||||
let errorMsg = 'Failed to start stack';
|
||||
try {
|
||||
const data = JSON.parse(rawText);
|
||||
errorMsg = data.error || errorMsg;
|
||||
} catch {
|
||||
errorMsg = rawText || errorMsg;
|
||||
}
|
||||
showErrorDialog(`Failed to start ${name}`, errorMsg);
|
||||
return;
|
||||
}
|
||||
@@ -701,8 +715,14 @@
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/stop`, envId), { method: 'POST' });
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
const errorMsg = data.error || 'Failed to stop stack';
|
||||
const rawText = await response.text();
|
||||
let errorMsg = 'Failed to stop stack';
|
||||
try {
|
||||
const data = JSON.parse(rawText);
|
||||
errorMsg = data.error || errorMsg;
|
||||
} catch {
|
||||
errorMsg = rawText || errorMsg;
|
||||
}
|
||||
showErrorDialog(`Failed to stop ${name}`, errorMsg);
|
||||
return;
|
||||
}
|
||||
@@ -723,8 +743,14 @@
|
||||
try {
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}/restart`, envId), { method: 'POST' });
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
const errorMsg = data.error || 'Failed to restart stack';
|
||||
const rawText = await response.text();
|
||||
let errorMsg = 'Failed to restart stack';
|
||||
try {
|
||||
const data = JSON.parse(rawText);
|
||||
errorMsg = data.error || errorMsg;
|
||||
} catch {
|
||||
errorMsg = rawText || errorMsg;
|
||||
}
|
||||
showErrorDialog(`Failed to restart ${name}`, errorMsg);
|
||||
return;
|
||||
}
|
||||
@@ -817,6 +843,8 @@
|
||||
return `${base} bg-red-200 dark:bg-red-800 text-red-900 dark:text-red-100`;
|
||||
case 'partial':
|
||||
return `${base} bg-amber-200 dark:bg-amber-800 text-amber-900 dark:text-amber-100`;
|
||||
case 'created':
|
||||
return `${base} bg-slate-200 dark:bg-slate-700 text-slate-900 dark:text-slate-100`;
|
||||
case 'not deployed':
|
||||
return `${base} bg-violet-200 dark:bg-violet-800 text-violet-900 dark:text-violet-100`;
|
||||
default:
|
||||
@@ -1342,13 +1370,19 @@
|
||||
Internal
|
||||
</span>
|
||||
{:else}
|
||||
<span
|
||||
class="inline-flex items-center justify-center gap-1 text-xs px-1.5 py-0.5 rounded-sm bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200 shadow-sm min-w-[5.5rem]"
|
||||
title="File location unknown"
|
||||
>
|
||||
<ExternalLink class="w-3 h-3" />
|
||||
Untracked
|
||||
</span>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<span
|
||||
class="inline-flex items-center justify-center gap-1 text-xs px-1.5 py-0.5 rounded-sm bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200 shadow-sm min-w-[5.5rem]"
|
||||
>
|
||||
<ExternalLink class="w-3 h-3" />
|
||||
Untracked
|
||||
</span>
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content class="whitespace-nowrap">
|
||||
Compose file location unknown. Click the stack name or edit button to locate it.
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
{/if}
|
||||
{:else if column.id === 'location'}
|
||||
{#if source.composePath}
|
||||
@@ -1364,7 +1398,7 @@
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
{:else}
|
||||
<span class="text-xs text-muted-foreground/50">—</span>
|
||||
<span class="text-xs text-muted-foreground/50 italic">Not set</span>
|
||||
{/if}
|
||||
{:else if column.id === 'containers'}
|
||||
<div class="flex items-center gap-1">
|
||||
@@ -1465,10 +1499,11 @@
|
||||
{getStackVolumeCount(stack) || '-'}
|
||||
</span>
|
||||
{:else if column.id === 'status'}
|
||||
{@const StatusIcon = getStackStatusIcon(stack.status)}
|
||||
<span class={getStatusClasses(stack.status)}>
|
||||
{@const displayStatus = getDisplayStatus(stack)}
|
||||
{@const StatusIcon = getStackStatusIcon(displayStatus)}
|
||||
<span class={getStatusClasses(displayStatus)}>
|
||||
<StatusIcon class="w-3 h-3" />
|
||||
{stack.status}
|
||||
{displayStatus}
|
||||
</span>
|
||||
{:else if column.id === 'actions'}
|
||||
<div class="relative flex gap-1 justify-end">
|
||||
@@ -1481,7 +1516,7 @@
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{#if stack.status === 'not deployed' && source.gitStack}
|
||||
{#if (stack.status === 'not deployed' || stack.status === 'created') && source.gitStack}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => openGitModal(source.gitStack)}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { TogglePill } from '$lib/components/ui/toggle-pill';
|
||||
import { Loader2, GitBranch, RefreshCw, Webhook, Rocket, RefreshCcw, Copy, Check, FolderGit2, Github, Key, KeyRound, Lock, FileText, HelpCircle, GripVertical, X } from 'lucide-svelte';
|
||||
import { Loader2, GitBranch, RefreshCw, Webhook, Rocket, RefreshCcw, Copy, Check, FolderGit2, Github, Key, KeyRound, Lock, FileText, HelpCircle, GripVertical, X, Download } from 'lucide-svelte';
|
||||
import * as Tooltip from '$lib/components/ui/tooltip';
|
||||
import CronEditor from '$lib/components/cron-editor.svelte';
|
||||
import StackEnvVarsPanel from '$lib/components/StackEnvVarsPanel.svelte';
|
||||
@@ -102,25 +102,13 @@
|
||||
let fileEnvVars = $state<Record<string, string>>({});
|
||||
let loadingFileVars = $state(false);
|
||||
let existingSecretKeys = $state<Set<string>>(new Set());
|
||||
let populatingEnvVars = $state(false);
|
||||
|
||||
// Resizable split panel state
|
||||
let splitRatio = $state(60); // percentage for form panel
|
||||
let isDraggingSplit = $state(false);
|
||||
let containerRef: HTMLDivElement | null = $state(null);
|
||||
|
||||
// Derived state for merged variables and sources
|
||||
const envVarSources = $derived<Record<string, 'file' | 'override'>>(() => {
|
||||
const sources: Record<string, 'file' | 'override'> = {};
|
||||
// File vars
|
||||
for (const key of Object.keys(fileEnvVars)) {
|
||||
sources[key] = 'file';
|
||||
}
|
||||
// Overrides take precedence
|
||||
for (const v of envVars.filter(v => v.key)) {
|
||||
sources[v.key] = 'override';
|
||||
}
|
||||
return sources;
|
||||
});
|
||||
|
||||
// Track which gitStack was initialized to avoid repeated resets
|
||||
let lastInitializedStackId = $state<number | null | undefined>(undefined);
|
||||
@@ -263,6 +251,79 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function populateEnvVars() {
|
||||
// Validate we have repository info
|
||||
if (formRepoMode === 'existing' && !formRepositoryId) {
|
||||
toast.error('Please select a repository first');
|
||||
return;
|
||||
}
|
||||
if (formRepoMode === 'new' && !formNewRepoUrl.trim()) {
|
||||
toast.error('Please enter a repository URL first');
|
||||
return;
|
||||
}
|
||||
|
||||
populatingEnvVars = true;
|
||||
try {
|
||||
const body: Record<string, any> = {
|
||||
composePath: formComposePath || 'compose.yaml',
|
||||
envFilePath: formEnvFilePath || null
|
||||
};
|
||||
|
||||
if (formRepoMode === 'existing') {
|
||||
body.repositoryId = formRepositoryId;
|
||||
} else {
|
||||
body.url = formNewRepoUrl;
|
||||
body.branch = formNewRepoBranch || 'main';
|
||||
body.credentialId = formNewRepoCredentialId;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/git/preview-env', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
toast.error('Failed to load env variables', {
|
||||
description: data.error || 'Unknown error'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const vars = data.vars as Record<string, string>;
|
||||
const count = Object.keys(vars).length;
|
||||
|
||||
if (count === 0) {
|
||||
toast.info('No environment variables found', {
|
||||
description: 'No .env files found in the repository. You can still add variables manually.'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert to EnvVar array - preserve existing user entries that aren't in repo
|
||||
const existingUserVars = envVars.filter(v => v.key.trim() && !(v.key in vars));
|
||||
const newVars: EnvVar[] = Object.entries(vars).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
isSecret: false
|
||||
}));
|
||||
|
||||
envVars = [...newVars, ...existingUserVars];
|
||||
fileEnvVars = vars;
|
||||
|
||||
toast.success(`Loaded ${count} variable${count === 1 ? '' : 's'}`, {
|
||||
description: 'You can now customize values before deploying'
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to populate env vars:', e);
|
||||
toast.error('Failed to load env variables');
|
||||
} finally {
|
||||
populatingEnvVars = false;
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
// Clear state BEFORE async loads to avoid race conditions
|
||||
formError = '';
|
||||
@@ -344,6 +405,15 @@
|
||||
formError = '';
|
||||
|
||||
try {
|
||||
// Only save vars that are actual overrides (differ from file) or new (not in file)
|
||||
// This ensures file updates from git are picked up on next sync
|
||||
const overrideVars = envVars.filter(v => {
|
||||
if (!v.key.trim()) return false;
|
||||
const fileValue = fileEnvVars[v.key];
|
||||
// Save if: not in file (new var), value differs from file, or is a secret
|
||||
return fileValue === undefined || v.value !== fileValue || v.isSecret;
|
||||
});
|
||||
|
||||
let body: any = {
|
||||
stackName: formStackName,
|
||||
composePath: formComposePath || 'compose.yaml',
|
||||
@@ -353,7 +423,12 @@
|
||||
autoUpdateCron: formAutoUpdateCron,
|
||||
webhookEnabled: formWebhookEnabled,
|
||||
webhookSecret: formWebhookEnabled ? formWebhookSecret : null,
|
||||
deployNow: deployAfterSave
|
||||
deployNow: deployAfterSave,
|
||||
envVars: overrideVars.map(v => ({
|
||||
key: v.key.trim(),
|
||||
value: v.value,
|
||||
isSecret: v.isSecret
|
||||
}))
|
||||
};
|
||||
|
||||
if (formRepoMode === 'existing') {
|
||||
@@ -394,31 +469,6 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// Save environment variable overrides (always save to ensure DB is in sync)
|
||||
// This handles both adding new vars and clearing all vars
|
||||
const definedVars = envVars.filter(v => v.key.trim());
|
||||
try {
|
||||
const envResponse = await fetch(
|
||||
`/api/stacks/${encodeURIComponent(formStackName)}/env${environmentId ? `?env=${environmentId}` : ''}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
variables: definedVars.map(v => ({
|
||||
key: v.key.trim(),
|
||||
value: v.value,
|
||||
isSecret: v.isSecret
|
||||
}))
|
||||
})
|
||||
}
|
||||
);
|
||||
if (!envResponse.ok) {
|
||||
console.error('Failed to save environment variables');
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save environment variables:', e);
|
||||
}
|
||||
|
||||
onSaved();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
@@ -433,17 +483,26 @@
|
||||
if (formRepoMode === 'existing' && formRepositoryId && !gitStack && !formStackNameUserModified) {
|
||||
const repo = repositories.find(r => r.id === formRepositoryId);
|
||||
if (repo) {
|
||||
// Normalize repo name: lowercase, spaces/underscores to hyphens, strip invalid chars
|
||||
const normalizedName = repo.name
|
||||
.toLowerCase()
|
||||
.replace(/[\s_]+/g, '-')
|
||||
.replace(/[^a-z0-9-]/g, '')
|
||||
.replace(/-+/g, '-')
|
||||
.replace(/^-|-$/g, '');
|
||||
|
||||
// Extract compose filename without extension for stack name
|
||||
const composeName = formComposePath
|
||||
.replace(/^.*\//, '') // Remove directory path
|
||||
.replace(/\.(yml|yaml)$/i, '') // Remove extension
|
||||
.replace(/^docker-compose\.?/, ''); // Remove docker-compose prefix
|
||||
.replace(/^docker-compose\.?/, '') // Remove docker-compose prefix
|
||||
.replace(/^compose$/, ''); // Remove plain "compose"
|
||||
|
||||
// Combine repo name with compose name if it's not the default
|
||||
if (composeName && composeName !== 'docker-compose') {
|
||||
formStackName = `${repo.name}-${composeName}`;
|
||||
formStackName = `${normalizedName}-${composeName}`;
|
||||
} else {
|
||||
formStackName = repo.name;
|
||||
formStackName = normalizedName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -669,71 +728,26 @@
|
||||
<!-- Additional env file for variable substitution -->
|
||||
<div class="space-y-2">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<Label for="env-file-path">Additional .env file (optional)</Label>
|
||||
<Label for="env-file-path">Additional env file (optional)</Label>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground cursor-help" />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content>
|
||||
<div class="w-80">
|
||||
<p class="text-xs">All files in the git repository are cloned automatically, including any files referenced by <code class="bg-muted px-1 rounded">env_file:</code> directives.</p>
|
||||
<p class="text-xs mt-2">Only use this field for additional environment variables to be passed to Docker Compose.</p>
|
||||
<p class="text-xs mt-2">The contents will be parsed and passed as shell environment variables.</p>
|
||||
<p class="text-xs">A <code class="bg-muted px-1 rounded">.env</code> file in the compose directory is always loaded automatically, if present.</p>
|
||||
<p class="text-xs mt-2">Use this field for an additional env file with a non-standard name (e.g. <code class="bg-muted px-1 rounded">.env.production</code>). Its values override the default <code class="bg-muted px-1 rounded">.env</code>.</p>
|
||||
<p class="text-xs mt-2">Overrides from the environment variables editor on the right always take highest precedence.</p>
|
||||
</div>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
</div>
|
||||
{#if gitStack && envFiles.length > 0}
|
||||
<!-- Dropdown selector for existing stacks with discovered .env files -->
|
||||
<Select.Root
|
||||
type="single"
|
||||
value={formEnvFilePath ?? 'none'}
|
||||
onValueChange={(v) => {
|
||||
formEnvFilePath = v === 'none' ? null : v;
|
||||
if (formEnvFilePath) {
|
||||
loadEnvFileContents(formEnvFilePath);
|
||||
} else {
|
||||
fileEnvVars = {};
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Select.Trigger class="w-full">
|
||||
{#if loadingEnvFiles}
|
||||
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
|
||||
Loading...
|
||||
{:else if formEnvFilePath}
|
||||
<FileText class="w-4 h-4 mr-2 text-muted-foreground" />
|
||||
{formEnvFilePath}
|
||||
{:else}
|
||||
<FileText class="w-4 h-4 mr-2 text-muted-foreground" />
|
||||
None
|
||||
{/if}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
<Select.Item value="none">
|
||||
<span class="text-muted-foreground">None</span>
|
||||
</Select.Item>
|
||||
{#each envFiles as file}
|
||||
<Select.Item value={file}>
|
||||
<span class="flex items-center gap-2">
|
||||
<FileText class="w-4 h-4 text-muted-foreground" />
|
||||
{file}
|
||||
</span>
|
||||
</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
{:else}
|
||||
<!-- Text input for new stacks or when no .env files discovered -->
|
||||
<Input
|
||||
id="env-file-path"
|
||||
bind:value={formEnvFilePath}
|
||||
placeholder=".env"
|
||||
placeholder=""
|
||||
/>
|
||||
{/if}
|
||||
<p class="text-xs text-muted-foreground">
|
||||
For variable substitution from a file outside the compose directory.
|
||||
</p>
|
||||
<p class="text-xs text-muted-foreground">Additional env file to pass to Docker Compose</p>
|
||||
</div>
|
||||
|
||||
<!-- Auto-update section -->
|
||||
@@ -877,12 +891,43 @@
|
||||
<div class="flex-1 min-w-0 flex flex-col overflow-hidden bg-zinc-50 dark:bg-zinc-800/50">
|
||||
<StackEnvVarsPanel
|
||||
bind:variables={envVars}
|
||||
showSource={!!formEnvFilePath && gitStack !== null}
|
||||
sources={envVarSources}
|
||||
placeholder={{ key: 'OVERRIDE_VAR', value: 'override value' }}
|
||||
infoText="These environment variables are optional. If a .env file is specified in the repository, these values will be merged with the file values. Variables defined here take precedence over .env file values."
|
||||
placeholder={{ key: 'MY_VAR', value: 'value' }}
|
||||
infoText="Override variables from your repository env files. Non-secrets are saved to <code class='bg-muted px-1 rounded'>.env.dockhand</code> in the stack directory. Secrets are stored in the database and injected via shell environment at deploy time."
|
||||
existingSecretKeys={gitStack !== null ? existingSecretKeys : new Set()}
|
||||
/>
|
||||
>
|
||||
{#snippet headerActions()}
|
||||
{#if !gitStack}
|
||||
<div class="flex items-center gap-0.5">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onclick={populateEnvVars}
|
||||
disabled={populatingEnvVars || (formRepoMode === 'existing' && !formRepositoryId) || (formRepoMode === 'new' && !formNewRepoUrl.trim())}
|
||||
class="h-6 text-xs px-2"
|
||||
>
|
||||
{#if populatingEnvVars}
|
||||
<Loader2 class="w-3.5 h-3.5 mr-1 animate-spin" />
|
||||
Loading...
|
||||
{:else}
|
||||
<Download class="w-3.5 h-3.5 mr-1" />
|
||||
Populate
|
||||
{/if}
|
||||
</Button>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground cursor-help" />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content>
|
||||
<div class="w-64">
|
||||
<p class="text-xs">Clone the repository and load environment variables from the <code class="bg-muted px-1 rounded">.env</code> file (in compose directory) and additional env file (if specified), so you can see what you can override.</p>
|
||||
</div>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</StackEnvVarsPanel>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import { Import, Loader2, Play, Info } from 'lucide-svelte';
|
||||
import FilesystemBrowser, { type FileEntry } from './FilesystemBrowser.svelte';
|
||||
import CodeEditor from '$lib/components/CodeEditor.svelte';
|
||||
import yaml from 'js-yaml';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { currentEnvironment, environments } from '$lib/stores/environment';
|
||||
import { getIconComponent } from '$lib/utils/icons';
|
||||
@@ -83,11 +84,13 @@
|
||||
const data = await res.json();
|
||||
previewContent = data.content || '';
|
||||
// Count services in the compose file
|
||||
const serviceMatches = previewContent?.match(/^services:\s*\n((?:\s{2,}\w+:.*\n?)+)/m);
|
||||
if (serviceMatches) {
|
||||
const servicesBlock = serviceMatches[1];
|
||||
const serviceNames = servicesBlock.match(/^\s{2}\w+:/gm);
|
||||
previewServiceCount = serviceNames?.length || 0;
|
||||
try {
|
||||
const doc = yaml.load(previewContent) as Record<string, unknown> | null;
|
||||
if (doc?.services && typeof doc.services === 'object') {
|
||||
previewServiceCount = Object.keys(doc.services).length;
|
||||
}
|
||||
} catch {
|
||||
previewServiceCount = 0;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -87,6 +87,7 @@
|
||||
// Base directory when user browsed to a directory (without stack name yet)
|
||||
let browsedBaseDirectory = $state<string | null>(null);
|
||||
|
||||
|
||||
// UI state
|
||||
let composePathCopied = $state(false);
|
||||
let envPathCopied = $state(false);
|
||||
@@ -123,9 +124,8 @@
|
||||
if (!workingComposePath) return undefined;
|
||||
switch (pathSource) {
|
||||
case 'browsed':
|
||||
return 'Custom location';
|
||||
case 'custom':
|
||||
return 'Using saved location';
|
||||
return 'Custom location';
|
||||
case 'default':
|
||||
return 'Using default location';
|
||||
default:
|
||||
@@ -398,9 +398,8 @@
|
||||
}
|
||||
|
||||
// In CREATE mode, we only want the content - don't store external paths
|
||||
// Files will be saved to internal stack directory
|
||||
// Files will be saved to the directory containing the selected compose file
|
||||
if (mode === 'create') {
|
||||
pathSource = 'browsed';
|
||||
showFileBrowser = false;
|
||||
|
||||
// Load compose file content when selecting a file (not directory)
|
||||
@@ -409,9 +408,14 @@
|
||||
const dir = finalPath.replace(/\/[^/]+$/, '');
|
||||
const potentialEnvPath = `${dir}/.env`;
|
||||
await loadFilesFromLocalFilesystem(finalPath, potentialEnvPath);
|
||||
// Don't set workingComposePath/workingEnvPath - use internal defaults
|
||||
workingComposePath = '';
|
||||
workingEnvPath = '';
|
||||
// Use the selected file's path directly
|
||||
workingComposePath = finalPath;
|
||||
workingEnvPath = `${dir}/.env`;
|
||||
browsedBaseDirectory = null;
|
||||
// 'custom' prevents the path effect from overriding (it only acts on 'browsed')
|
||||
pathSource = 'custom';
|
||||
} else {
|
||||
pathSource = 'browsed';
|
||||
}
|
||||
isDirty = true;
|
||||
return;
|
||||
@@ -480,12 +484,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
// In CREATE mode, don't store external path - content will be saved to internal directory
|
||||
// In EDIT mode, store the path for the file location
|
||||
if (mode !== 'create') {
|
||||
// Store the selected path:
|
||||
// - Always in EDIT mode
|
||||
// - In CREATE mode when user selected a custom compose location OR explicitly selected an env file
|
||||
if (mode !== 'create' || pathSource === 'custom' || pathSource === 'browsed' || !isDirectory) {
|
||||
workingEnvPath = finalPath;
|
||||
}
|
||||
// If CREATE mode, workingEnvPath stays empty - will use internal default
|
||||
// Otherwise CREATE mode with internal location uses default via suggestedEnvPath
|
||||
|
||||
isDirty = true;
|
||||
}
|
||||
@@ -1063,32 +1068,32 @@ services:
|
||||
throw new Error(rawEnvError.error || 'Failed to save environment file');
|
||||
}
|
||||
|
||||
// Save ALL vars to DB (includes secrets with real values)
|
||||
const definedVars = prepared.variables;
|
||||
if (definedVars.length > 0 || hadExistingDbVars) {
|
||||
// Save only secrets to DB (non-secrets are in the .env file written above)
|
||||
const secretVars = prepared.variables.filter(v => v.isSecret);
|
||||
if (secretVars.length > 0 || hadExistingDbVars) {
|
||||
const envResponse = await fetch(
|
||||
appendEnvParam(`/api/stacks/${encodeURIComponent(stackName)}/env`, envId),
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
variables: definedVars.map(v => ({
|
||||
variables: secretVars.map(v => ({
|
||||
key: v.key.trim(),
|
||||
value: v.value,
|
||||
isSecret: v.isSecret
|
||||
isSecret: true
|
||||
}))
|
||||
})
|
||||
}
|
||||
);
|
||||
|
||||
if (!envResponse.ok) {
|
||||
// Log but don't fail - DB stores secret metadata
|
||||
console.warn('Failed to save environment variable metadata to database');
|
||||
// Log but don't fail - DB stores secret values
|
||||
console.warn('Failed to save secret variables to database');
|
||||
}
|
||||
|
||||
hadExistingDbVars = definedVars.length > 0;
|
||||
hadExistingDbVars = secretVars.length > 0;
|
||||
existingSecretKeys = new Set(
|
||||
definedVars.filter(v => v.isSecret && v.key.trim()).map(v => v.key.trim())
|
||||
secretVars.filter(v => v.key.trim()).map(v => v.key.trim())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1220,6 +1225,33 @@ services:
|
||||
return () => clearTimeout(timeout);
|
||||
});
|
||||
|
||||
// Pre-fetched default base directory for create mode (fetched once on open/env change)
|
||||
let defaultStackDir = $state<string | null>(null);
|
||||
|
||||
async function fetchDefaultBasePath(envId: number | null, location: string | null) {
|
||||
const params = new URLSearchParams({ name: '__placeholder__' });
|
||||
if (envId) params.set('env', String(envId));
|
||||
if (location) params.set('location', location);
|
||||
try {
|
||||
const r = await fetch(`/api/stacks/default-path?${params}`);
|
||||
if (r.ok) {
|
||||
const data = await r.json();
|
||||
// Extract base dir by removing the placeholder name
|
||||
defaultStackDir = data.stackDir.replace('/__placeholder__', '');
|
||||
}
|
||||
} catch {
|
||||
// Ignore fetch errors
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch default base path when modal opens or environment changes
|
||||
$effect(() => {
|
||||
if (!open || mode !== 'create') return;
|
||||
const envId = $currentEnvironment?.id ?? null;
|
||||
const location = $appSettings.primaryStackLocation;
|
||||
fetchDefaultBasePath(envId, location);
|
||||
});
|
||||
|
||||
// Auto-update default paths when stack name changes in create mode
|
||||
// This unified effect handles both default paths and browsed directory paths
|
||||
$effect(() => {
|
||||
@@ -1227,17 +1259,21 @@ services:
|
||||
|
||||
const name = newStackName.trim();
|
||||
|
||||
// Case 1: No name entered yet - clear paths
|
||||
// User selected a specific file - paths are locked, don't touch them
|
||||
if (pathSource === 'custom') return;
|
||||
|
||||
// No name entered yet - clear paths but preserve browsed state
|
||||
if (!name) {
|
||||
workingComposePath = '';
|
||||
workingEnvPath = '';
|
||||
autoComputedComposePath = '';
|
||||
pathSource = null;
|
||||
if (!browsedBaseDirectory) {
|
||||
pathSource = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 2: User has browsed and selected a directory - use that as base
|
||||
// Keep updating as user types (don't clear browsedBaseDirectory!)
|
||||
// User browsed and selected a directory - build path from that base
|
||||
if (browsedBaseDirectory) {
|
||||
workingComposePath = `${browsedBaseDirectory}/${name}/compose.yaml`;
|
||||
workingEnvPath = `${browsedBaseDirectory}/${name}/.env`;
|
||||
@@ -1245,54 +1281,14 @@ services:
|
||||
return;
|
||||
}
|
||||
|
||||
// Case 3: User already has a browsed path set (from previous name entry)
|
||||
// Update the stack name portion in the existing path
|
||||
if (pathSource === 'browsed' && workingComposePath) {
|
||||
// Extract base directory from existing path and rebuild with new name
|
||||
// Path format: {baseDir}/{stackName}/compose.yaml
|
||||
const pathParts = workingComposePath.split('/');
|
||||
pathParts.pop(); // remove 'compose.yaml'
|
||||
pathParts.pop(); // remove old stack name
|
||||
const baseDir = pathParts.join('/');
|
||||
if (baseDir) {
|
||||
workingComposePath = `${baseDir}/${name}/compose.yaml`;
|
||||
workingEnvPath = `${baseDir}/${name}/.env`;
|
||||
}
|
||||
return;
|
||||
// Use pre-fetched default base directory
|
||||
if (defaultStackDir) {
|
||||
const dir = `${defaultStackDir}/${name}`;
|
||||
autoComputedComposePath = `${dir}/compose.yaml`;
|
||||
workingComposePath = `${dir}/compose.yaml`;
|
||||
workingEnvPath = `${dir}/.env`;
|
||||
pathSource = 'default';
|
||||
}
|
||||
|
||||
// Case 4: Default path from settings/API
|
||||
const location = $appSettings.primaryStackLocation;
|
||||
const envId = $currentEnvironment?.id ?? null;
|
||||
|
||||
const fetchDefaultPath = async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({ name });
|
||||
if (envId) params.set('env', String(envId));
|
||||
if (location) {
|
||||
params.set('location', location);
|
||||
}
|
||||
const response = await fetch(`/api/stacks/default-path?${params}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
// Check if user has customized before updating auto-computed
|
||||
// Compare current working path against OLD auto path (before we update it)
|
||||
const userHasCustomized = workingComposePath !== '' &&
|
||||
workingComposePath !== autoComputedComposePath;
|
||||
// Track the auto-computed path
|
||||
autoComputedComposePath = data.composePath;
|
||||
// Only update working paths if user hasn't customized
|
||||
if (!userHasCustomized) {
|
||||
workingComposePath = data.composePath;
|
||||
workingEnvPath = data.envPath;
|
||||
pathSource = data.source || 'default';
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to fetch default path:', e);
|
||||
}
|
||||
};
|
||||
fetchDefaultPath();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -1433,7 +1429,7 @@ services:
|
||||
<AlertCircle class="w-4 h-4 shrink-0 text-amber-500 mt-0.5" />
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-400 mb-2">
|
||||
<span class="font-medium text-amber-800 dark:text-amber-300">Untracked stack.</span> Select the compose file location to start managing this stack with Dockhand.
|
||||
<span class="font-medium text-amber-800 dark:text-amber-300">Untracked stack</span> — this stack is running in Docker but Dockhand doesn't know where its compose file is stored on disk. Browse to locate the file to start editing and managing it.
|
||||
</p>
|
||||
{#if stackContainers.length > 0}
|
||||
<div class="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
@@ -1621,10 +1617,10 @@ services:
|
||||
<Button class="w-36" onclick={() => handleSave(true)} disabled={saving || loading || (needsFileLocation && !workingComposePath.trim())}>
|
||||
{#if saving && savingWithRestart}
|
||||
<Loader2 class="w-4 h-4 mr-2 animate-spin" />
|
||||
Restarting...
|
||||
Deploying...
|
||||
{:else}
|
||||
<Play class="w-4 h-4 mr-2" />
|
||||
Save & restart
|
||||
Save & redeploy
|
||||
{/if}
|
||||
</Button>
|
||||
{/if}
|
||||
|
||||
Reference in new issue
Block a user