Skip to content

Modern Docker Management, Designed for Everyone

feat: use stack names as folder names (#143)

Kyle Mendell537ea9f42f36
diff --git a/package-lock.json b/package-lock.json
index 54b6b525b..ec356e2e9 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "arcane",
- "version": "0.5.0",
+ "version": "0.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "arcane",
- "version": "0.5.0",
+ "version": "0.6.0",
"dependencies": {
"@codemirror/lang-yaml": "^6.1.2",
"@codemirror/legacy-modes": "^6.5.1",
@@ -21,6 +21,7 @@
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.3.3",
"proper-lockfile": "^4.1.2",
+ "slugify": "^1.6.6",
"svelte-codemirror-editor": "^1.4.1",
"svelte-kit-cookie-session": "^4.1.1",
"thememirror": "^2.0.1"
@@ -6196,6 +6197,15 @@
"node": ">=18"
}
},
+ "node_modules/slugify": {
+ "version": "1.6.6",
+ "resolved": "https://registry.npmjs.org/slugify/-/slugify-1.6.6.tgz",
+ "integrity": "sha512-h+z7HKHYXj6wJU+AnS/+IH8Uh9fdcX1Lrhg1/VMdf9PwoBQXFcXiAdsy2tSK0P6gKwJLXp02r90ahUCqHk9rrw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
diff --git a/package.json b/package.json
index a9e5ee78c..65ce0d486 100644
--- a/package.json
+++ b/package.json
@@ -66,6 +66,7 @@
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.3.3",
"proper-lockfile": "^4.1.2",
+ "slugify": "^1.6.6",
"svelte-codemirror-editor": "^1.4.1",
"svelte-kit-cookie-session": "^4.1.1",
"thememirror": "^2.0.1"
diff --git a/src/lib/services/api/stack-api-service.ts b/src/lib/services/api/stack-api-service.ts
index 6481624c5..c28b654a1 100644
--- a/src/lib/services/api/stack-api-service.ts
+++ b/src/lib/services/api/stack-api-service.ts
@@ -58,6 +58,11 @@ export default class StackAPIService extends BaseAPIService {
return res.data;
}
+ async migrate(id: string) {
+ const res = await this.api.post(`/stacks/${id}/migrate`);
+ return res.data;
+ }
+
async list() {
const res = await this.api.get('');
return res.data;
diff --git a/src/lib/services/docker/stack-migration-service.ts b/src/lib/services/docker/stack-migration-service.ts
new file mode 100644
index 000000000..c4a3e75bb
--- /dev/null
+++ b/src/lib/services/docker/stack-migration-service.ts
@@ -0,0 +1,195 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import slugify from 'slugify';
+import { ensureStacksDir, stopStack, startStack, isStackRunning } from './stack-service';
+
+export async function migrateStacksToNameFolders() {
+ const stacksDir = await ensureStacksDir();
+ const dirs = await fs.readdir(stacksDir);
+
+ for (const dir of dirs) {
+ const oldDirPath = path.join(stacksDir, dir);
+
+ // Only process directories
+ const stat = await fs.stat(oldDirPath);
+ if (!stat.isDirectory()) continue;
+
+ const metaPath = path.join(oldDirPath, 'meta.json');
+ const newMetaPath = path.join(oldDirPath, '.stack.json');
+ const oldComposePath = path.join(oldDirPath, 'docker-compose.yml');
+ const newComposePath = path.join(oldDirPath, 'compose.yaml');
+
+ // Only migrate if meta.json exists and .stack.json does not
+ try {
+ await fs.access(metaPath);
+ } catch {
+ continue; // No meta.json, skip
+ }
+ try {
+ await fs.access(newMetaPath);
+ continue; // Already migrated
+ } catch {}
+
+ // Check if stack is running before migration
+ let wasRunning = false;
+ try {
+ wasRunning = await isStackRunning(dir);
+ } catch {
+ wasRunning = false;
+ }
+
+ // Stop the stack before migration
+ try {
+ await stopStack(dir);
+ console.log(`Stopped stack "${dir}" before migration.`);
+ } catch (err) {
+ console.warn(`Failed to stop stack "${dir}" before migration:`, err);
+ }
+
+ // Read and parse meta.json
+ const metaRaw = await fs.readFile(metaPath, 'utf8');
+ const meta = JSON.parse(metaRaw);
+
+ // Generate new directory name
+ const slug = slugify(meta.name, { lower: true, strict: true, trim: true });
+ let newDirName = slug;
+ let counter = 1;
+ while (dirs.includes(newDirName) && newDirName !== dir) {
+ newDirName = `${slug}-${counter++}`;
+ }
+ const newDirPath = path.join(stacksDir, newDirName);
+
+ // Rename directory if needed
+ if (newDirName !== dir) {
+ await fs.rename(oldDirPath, newDirPath);
+ }
+
+ // Migrate docker-compose.yml to compose.yaml if needed
+ try {
+ await fs.access(path.join(newDirPath, 'docker-compose.yml'));
+ try {
+ await fs.access(path.join(newDirPath, 'compose.yaml'));
+ // compose.yaml already exists, do nothing
+ } catch {
+ await fs.rename(path.join(newDirPath, 'docker-compose.yml'), path.join(newDirPath, 'compose.yaml'));
+ console.log(`Migrated docker-compose.yml to compose.yaml in "${newDirName}"`);
+ }
+ } catch {
+ // docker-compose.yml does not exist, nothing to do
+ }
+
+ // Update and write .stack.json
+ meta.dirName = newDirName;
+ meta.path = newDirPath;
+ await fs.writeFile(path.join(newDirPath, '.stack.json'), JSON.stringify(meta, null, 2), 'utf8');
+
+ // Remove old meta.json
+ await fs.rm(path.join(newDirPath, 'meta.json'));
+
+ console.log(`Migrated stack "${meta.name}" to folder "${newDirName}"`);
+
+ // Start the stack after migration if it was running before
+ if (wasRunning) {
+ try {
+ await startStack(newDirName);
+ console.log(`Started stack "${newDirName}" after migration.`);
+ } catch (err) {
+ console.warn(`Failed to start stack "${newDirName}" after migration:`, err);
+ }
+ }
+ }
+}
+
+export async function migrateStackToNameFolder(stackId: string): Promise<void> {
+ const stacksDir = await ensureStacksDir();
+ const oldDirPath = path.join(stacksDir, stackId);
+
+ // Only process if directory exists
+ const stat = await fs.stat(oldDirPath);
+ if (!stat.isDirectory()) throw new Error(`Stack directory "${stackId}" does not exist`);
+
+ const metaPath = path.join(oldDirPath, 'meta.json');
+ const newMetaPath = path.join(oldDirPath, '.stack.json');
+ const oldComposePath = path.join(oldDirPath, 'docker-compose.yml');
+ const newComposePath = path.join(oldDirPath, 'compose.yaml');
+
+ // Only migrate if meta.json exists and .stack.json does not
+ try {
+ await fs.access(metaPath);
+ } catch {
+ throw new Error(`No meta.json found for stack "${stackId}"`);
+ }
+ try {
+ await fs.access(newMetaPath);
+ throw new Error(`Stack "${stackId}" is already migrated`);
+ } catch {}
+
+ // Check if stack is running before migration
+ let wasRunning = false;
+ try {
+ wasRunning = await isStackRunning(stackId);
+ } catch {
+ wasRunning = false;
+ }
+
+ // Stop the stack before migration
+ try {
+ await stopStack(stackId);
+ console.log(`Stopped stack "${stackId}" before migration.`);
+ } catch (err) {
+ console.warn(`Failed to stop stack "${stackId}" before migration:`, err);
+ }
+
+ // Read and parse meta.json
+ const metaRaw = await fs.readFile(metaPath, 'utf8');
+ const meta = JSON.parse(metaRaw);
+
+ // Generate new directory name
+ const slug = slugify(meta.name, { lower: true, strict: true, trim: true });
+ let newDirName = slug;
+ let counter = 1;
+ const dirs = await fs.readdir(stacksDir);
+ while (dirs.includes(newDirName) && newDirName !== stackId) {
+ newDirName = `${slug}-${counter++}`;
+ }
+ const newDirPath = path.join(stacksDir, newDirName);
+
+ // Rename directory if needed
+ if (newDirName !== stackId) {
+ await fs.rename(oldDirPath, newDirPath);
+ }
+
+ // Migrate docker-compose.yml to compose.yaml if needed
+ try {
+ await fs.access(path.join(newDirPath, 'docker-compose.yml'));
+ try {
+ await fs.access(path.join(newDirPath, 'compose.yaml'));
+ // compose.yaml already exists, do nothing
+ } catch {
+ await fs.rename(path.join(newDirPath, 'docker-compose.yml'), path.join(newDirPath, 'compose.yaml'));
+ console.log(`Migrated docker-compose.yml to compose.yaml in "${newDirName}"`);
+ }
+ } catch {
+ // docker-compose.yml does not exist, nothing to do
+ }
+
+ // Update and write .stack.json
+ meta.dirName = newDirName;
+ meta.path = newDirPath;
+ await fs.writeFile(path.join(newDirPath, '.stack.json'), JSON.stringify(meta, null, 2), 'utf8');
+
+ // Remove old meta.json
+ await fs.rm(path.join(newDirPath, 'meta.json'));
+
+ console.log(`Migrated stack "${meta.name}" to folder "${newDirName}"`);
+
+ // Start the stack after migration if it was running before
+ if (wasRunning) {
+ try {
+ await startStack(newDirName);
+ console.log(`Started stack "${newDirName}" after migration.`);
+ } catch (err) {
+ console.warn(`Failed to start stack "${newDirName}" after migration:`, err);
+ }
+ }
+}
diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.ts
index 101db60c1..b83a48753 100644
--- a/src/lib/services/docker/stack-service.ts
+++ b/src/lib/services/docker/stack-service.ts
@@ -1,14 +1,13 @@
import { promises as fs } from 'node:fs';
-import { join } from 'node:path';
+import path, { join } from 'node:path';
import { basename } from 'node:path';
import DockerodeCompose from 'dockerode-compose';
import yaml from 'js-yaml';
import { nanoid } from 'nanoid';
-import Dockerode from 'dockerode';
-
+import slugify from 'slugify';
+import { directoryExists } from '$lib/utils/fs.utils';
import { getDockerClient } from '$lib/services/docker/core';
import { getSettings, ensureStacksDirectory } from '$lib/services/settings-service';
-
import type { Stack, StackMeta, StackService, StackUpdate } from '$lib/types/docker/stack.type';
/* The above code is declaring a variable `STACKS_DIR` with an empty string as its initial value in
@@ -50,7 +49,7 @@ export function updateStacksDirectory(directory: string): void {
* @returns The function `ensureStacksDir()` returns the `STACKS_DIR` variable after ensuring that the
* stacks directory exists.
*/
-async function ensureStacksDir(): Promise<string> {
+export async function ensureStacksDir(): Promise<string> {
try {
if (!STACKS_DIR) {
STACKS_DIR = await ensureStacksDirectory();
@@ -65,16 +64,11 @@ async function ensureStacksDir(): Promise<string> {
}
/**
- * The function `getStackDir` returns the directory path for a given stack ID after ensuring the
- * existence of the stacks directory.
- * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
- * of a stack.
- * @returns The function `getStackDir` returns a Promise that resolves to a string representing the
- * directory path where the stack with the given `stackId` is located.
+ * Returns the stack directory for a given stackId (unchanged)
*/
async function getStackDir(stackId: string): Promise<string> {
const stacksDir = await ensureStacksDir();
- const safeId = basename(stackId); // strips path
+ const safeId = basename(stackId);
if (safeId !== stackId) {
throw new Error('Invalid stack id');
}
@@ -82,35 +76,39 @@ async function getStackDir(stackId: string): Promise<string> {
}
/**
- * The function `getComposeFilePath` returns the path to the docker-compose.yml file within the
- * directory of a given stack ID.
- * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
- * of a stack in a system.
- * @returns The function `getComposeFilePath` returns a Promise that resolves to a string representing
- * the file path of the `docker-compose.yml` file within the directory of the stack identified by
- * `stackId`.
+ * Returns the path to the compose file, prioritizing compose.yaml, fallback to docker-compose.yml
*/
async function getComposeFilePath(stackId: string): Promise<string> {
const stackDir = await getStackDir(stackId);
- return join(stackDir, 'docker-compose.yml');
+ const newPath = join(stackDir, 'compose.yaml');
+ const oldPath = join(stackDir, 'docker-compose.yml');
+ try {
+ await fs.access(newPath);
+ return newPath;
+ } catch {
+ await fs.access(oldPath);
+ return oldPath;
+ }
}
/**
- * The function `getStackMetaPath` returns the path to the meta.json file within the directory of a
- * given stack ID.
- * @param {string} stackId - StackId is a string parameter that represents the unique identifier of a
- * stack.
- * @returns The function `getStackMetaPath` returns a `Promise` that resolves to a string representing
- * the path to the `meta.json` file within the directory of the stack identified by the `stackId`
- * parameter.
+ * Returns the path to the meta file, prioritizing .stack.json, fallback to meta.json
*/
async function getStackMetaPath(stackId: string): Promise<string> {
const stackDir = await getStackDir(stackId);
- return join(stackDir, 'meta.json');
+ const newPath = join(stackDir, '.stack.json');
+ const oldPath = join(stackDir, 'meta.json');
+ try {
+ await fs.access(newPath);
+ return newPath;
+ } catch {
+ await fs.access(oldPath);
+ return oldPath;
+ }
}
/**
- * Gets the path to the .env file for a specific stack
+ * Returns the path to the .env file (no fallback needed, just .env)
*/
async function getEnvFilePath(stackId: string): Promise<string> {
const stackDir = await getStackDir(stackId);
@@ -319,13 +317,36 @@ export async function loadComposeStacks(): Promise<Stack[]> {
const stacks: Stack[] = [];
for (const dir of stackDirs) {
- try {
- const metaPath = await getStackMetaPath(dir);
- const composePath = await getComposeFilePath(dir);
+ const stackDir = path.join(stacksDir, dir);
- const [metaContent, composeContent] = await Promise.all([fs.readFile(metaPath, 'utf8'), fs.readFile(composePath, 'utf8')]);
+ // Skip if not a directory (e.g., .DS_Store or other files)
+ let stat;
+ try {
+ stat = await fs.stat(stackDir);
+ } catch {
+ continue;
+ }
+ if (!stat.isDirectory()) continue;
- const meta = JSON.parse(metaContent) as StackMeta;
+ try {
+ const newMetaPath = path.join(stackDir, '.stack.json');
+ const newComposePath = path.join(stackDir, 'compose.yaml');
+
+ let metaContent: string;
+ let composeContent: string;
+ let meta: StackMeta;
+
+ try {
+ [metaContent, composeContent] = await Promise.all([fs.readFile(newMetaPath, 'utf8'), fs.readFile(newComposePath, 'utf8')]);
+ meta = JSON.parse(metaContent) as StackMeta;
+ } catch (newWayErr) {
+ // Fallback to old way
+ const oldMetaPath = await getStackMetaPath(dir);
+ const oldComposePath = await getComposeFilePath(dir);
+
+ [metaContent, composeContent] = await Promise.all([fs.readFile(oldMetaPath, 'utf8'), fs.readFile(oldComposePath, 'utf8')]);
+ meta = JSON.parse(metaContent) as StackMeta;
+ }
const services = await getStackServices(dir, composeContent);
@@ -339,6 +360,11 @@ export async function loadComposeStacks(): Promise<Stack[]> {
status = 'partially running';
}
+ const isLegacy = !(await fs.access(path.join(stackDir, '.stack.json')).then(
+ () => true,
+ () => false
+ ));
+
stacks.push({
id: dir,
name: meta.name,
@@ -346,7 +372,8 @@ export async function loadComposeStacks(): Promise<Stack[]> {
runningCount,
status,
createdAt: meta.createdAt,
- updatedAt: meta.updatedAt
+ updatedAt: meta.updatedAt,
+ isLegacy
});
} catch (err) {
console.warn(`Error loading stack ${dir}:`, err);
@@ -364,53 +391,73 @@ export async function loadComposeStacks(): Promise<Stack[]> {
* Creates a new stack with a compose file and optional .env file
*/
export async function createStack(name: string, composeContent: string, envContent?: string): Promise<Stack> {
- const stackId = nanoid();
- const stackDir = await getStackDir(stackId);
- const composePath = join(stackDir, 'docker-compose.yml');
- const metaPath = join(stackDir, 'meta.json');
+ // Generate a unique ID for references (still needed for APIs)
+ const id = nanoid();
+
+ // Create a safe directory name from the stack name
+ const dirName = slugify(name, {
+ lower: true, // Convert to lowercase
+ strict: true, // Strip special chars
+ replacement: '-', // Replace spaces with hyphens
+ trim: true // Trim leading/trailing spaces
+ });
+
+ // Ensure directory name is unique - add suffix if needed
+ const stacksDir = await ensureStacksDirectory();
+ let counter = 1;
+ let uniqueDirName = dirName;
+
+ while (await directoryExists(join(stacksDir, uniqueDirName))) {
+ uniqueDirName = `${dirName}-${counter}`;
+ counter++;
+ }
+
+ // Create stack directory with the name-based folder
+ const stackDir = join(stacksDir, uniqueDirName);
+ await fs.mkdir(stackDir, { recursive: true });
- const meta: StackMeta = {
+ // Save compose file
+ await fs.writeFile(join(stackDir, 'compose.yaml'), composeContent);
+
+ // Save env file if provided
+ if (envContent) {
+ await fs.writeFile(join(stackDir, '.env'), envContent);
+ }
+
+ // Create stack metadata file with the ID reference
+ const meta = {
+ id,
name,
+ dirName: uniqueDirName,
+ path: stackDir,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
};
- try {
- await fs.mkdir(stackDir, { recursive: true });
+ await fs.writeFile(join(stackDir, '.stack.json'), JSON.stringify(meta, null, 2));
- // Write all files in parallel
- await Promise.all([fs.writeFile(composePath, composeContent, 'utf8'), fs.writeFile(metaPath, JSON.stringify(meta, null, 2), 'utf8'), saveEnvFile(stackId, envContent)]);
-
- let serviceCount = 0;
- try {
- const composeData = yaml.load(composeContent) as any;
- if (composeData?.services) {
- serviceCount = Object.keys(composeData.services).length;
- }
- } catch (parseErr) {
- console.warn(`Could not parse compose file during creation for stack ${stackId}:`, parseErr);
- }
-
- return {
- id: stackId,
- name: meta.name,
- serviceCount: serviceCount,
- runningCount: 0,
- status: 'stopped',
- createdAt: meta.createdAt,
- updatedAt: meta.updatedAt,
- composeContent: composeContent,
- envContent: envContent || ''
- };
- } catch (err) {
- console.error('Error creating stack:', err);
- try {
- await fs.rm(stackDir, { recursive: true, force: true });
- } catch (cleanupErr) {
- console.error(`Failed to cleanup partially created stack directory ${stackDir}:`, cleanupErr);
+ let serviceCount = 0;
+ try {
+ const composeData = yaml.load(composeContent) as any;
+ if (composeData?.services) {
+ serviceCount = Object.keys(composeData.services).length;
}
- throw new Error('Failed to create stack files');
+ } catch (parseErr) {
+ console.warn(`Could not parse compose file during creation for stack ${meta.name}:`, parseErr);
}
+
+ return {
+ id: meta.id,
+ name: meta.name,
+ serviceCount: serviceCount,
+ runningCount: 0,
+ status: 'stopped',
+ createdAt: meta.createdAt,
+ updatedAt: meta.updatedAt,
+ composeContent: composeContent,
+ envContent: envContent || '',
+ meta
+ };
}
/**
@@ -418,14 +465,29 @@ export async function createStack(name: string, composeContent: string, envConte
*/
export async function getStack(stackId: string): Promise<Stack> {
try {
- const metaPath = await getStackMetaPath(stackId);
- const composePath = await getComposeFilePath(stackId);
+ // Try the new way first (.stack.json and compose.yaml)
+ const stackDir = await getStackDir(stackId);
+ const newMetaPath = path.join(stackDir, '.stack.json');
+ const newComposePath = path.join(stackDir, 'compose.yaml');
- const [metaContent, composeContent, envContent] = await Promise.all([fs.readFile(metaPath, 'utf8'), fs.readFile(composePath, 'utf8'), loadEnvFile(stackId)]);
+ let metaContent: string;
+ let composeContent: string;
+ let envContent: string;
+ let meta: StackMeta;
- const meta = JSON.parse(metaContent) as StackMeta;
- const services = await getStackServices(stackId, composeContent);
+ try {
+ [metaContent, composeContent, envContent] = await Promise.all([fs.readFile(newMetaPath, 'utf8'), fs.readFile(newComposePath, 'utf8'), loadEnvFile(stackId)]);
+ meta = JSON.parse(metaContent) as StackMeta;
+ } catch (newWayErr) {
+ // If new way fails, fall back to old way (meta.json and docker-compose.yml)
+ const oldMetaPath = await getStackMetaPath(stackId);
+ const oldComposePath = await getComposeFilePath(stackId);
+
+ [metaContent, composeContent, envContent] = await Promise.all([fs.readFile(oldMetaPath, 'utf8'), fs.readFile(oldComposePath, 'utf8'), loadEnvFile(stackId)]);
+ meta = JSON.parse(metaContent) as StackMeta;
+ }
+ const services = await getStackServices(stackId, composeContent);
const serviceCount = services.length;
const runningCount = services.filter((s) => s.state?.Running).length;
@@ -961,3 +1023,34 @@ export async function listStacks(includeExternal = false): Promise<Stack[]> {
// Combine managed and external stacks
return [...enrichedManagedStacks, ...externalStacks];
}
+
+/**
+ * Checks if any service in the stack is currently running.
+ * @param {string} stackId - The stack/project name or directory.
+ * @returns {Promise<boolean>} - True if any container in the stack is running.
+ */
+export async function isStackRunning(stackId: string): Promise<boolean> {
+ const docker = getDockerClient();
+ const composeProjectLabel = 'com.docker.compose.project';
+
+ try {
+ // Find containers belonging to the stack (by label or name convention)
+ const containers = await docker.listContainers({
+ all: true,
+ filters: JSON.stringify({
+ label: [`${composeProjectLabel}=${stackId}`]
+ })
+ });
+
+ // Fallback: Also check by name prefix if label is missing
+ const allContainers = await docker.listContainers({ all: true });
+ const nameFilteredContainers = allContainers.filter((c) => !containers.some((fc) => fc.Id === c.Id) && (c.Labels?.[composeProjectLabel] === stackId || c.Names?.some((name) => name.startsWith(`/${stackId}_`))));
+
+ const stackContainers = [...containers, ...nameFilteredContainers];
+ // If any container is running, the stack is considered running
+ return stackContainers.some((c) => c.State === 'running');
+ } catch (err) {
+ console.error(`Error checking if stack ${stackId} is running:`, err);
+ return false;
+ }
+}
diff --git a/src/lib/types/actions.type.ts b/src/lib/types/actions.type.ts
index 5fcdf67e1..6509b3f84 100644
--- a/src/lib/types/actions.type.ts
+++ b/src/lib/types/actions.type.ts
@@ -1,3 +1,3 @@
-export type StackActions = 'start' | 'stop' | 'restart' | 'redeploy' | 'import' | 'destroy' | 'pull';
+export type StackActions = 'start' | 'stop' | 'restart' | 'redeploy' | 'import' | 'destroy' | 'pull' | 'migrate';
export type ContainerActions = 'start' | 'stop' | 'restart' | 'pull' | 'remove';
export type PruneType = 'containers' | 'images' | 'networks' | 'volumes';
diff --git a/src/lib/types/docker/stack.type.ts b/src/lib/types/docker/stack.type.ts
index e54d24e5c..2022c4377 100644
--- a/src/lib/types/docker/stack.type.ts
+++ b/src/lib/types/docker/stack.type.ts
@@ -1,8 +1,11 @@
export interface StackMeta {
+ id: string;
name: string;
createdAt: string;
updatedAt: string;
autoUpdate?: boolean;
+ dirName?: string;
+ path: string;
}
export interface StackService {
@@ -20,16 +23,16 @@ export interface Stack {
id: string;
name: string;
services?: StackService[];
- serviceCount: number;
- runningCount: number;
- status: 'running' | 'partially running' | 'stopped';
- createdAt: string;
- updatedAt: string;
+ serviceCount?: number;
+ runningCount?: number;
+ status: 'running' | 'stopped' | 'partially running';
+ isExternal?: boolean;
+ createdAt?: string;
+ updatedAt?: string;
composeContent?: string;
envContent?: string;
- isExternal?: boolean;
- compose?: any;
meta?: StackMeta;
+ isLegacy?: boolean;
}
export interface StackUpdate {
diff --git a/src/lib/utils/fs.utils.ts b/src/lib/utils/fs.utils.ts
new file mode 100644
index 000000000..3d984007b
--- /dev/null
+++ b/src/lib/utils/fs.utils.ts
@@ -0,0 +1,22 @@
+import { promises as fs } from 'node:fs';
+
+/**
+ * Helper function to check if a file exists
+ */
+export async function fileExists(filePath: string): Promise<boolean> {
+ try {
+ const stats = await fs.stat(filePath);
+ return stats.isFile();
+ } catch (err) {
+ return false;
+ }
+}
+
+export async function directoryExists(dir: string): Promise<boolean> {
+ try {
+ const stats = await fs.stat(dir);
+ return stats.isDirectory();
+ } catch (err) {
+ return false;
+ }
+}
diff --git a/src/routes/api/stacks/[stackId]/migrate/+server.ts b/src/routes/api/stacks/[stackId]/migrate/+server.ts
new file mode 100644
index 000000000..4e58dddd2
--- /dev/null
+++ b/src/routes/api/stacks/[stackId]/migrate/+server.ts
@@ -0,0 +1,19 @@
+import type { RequestHandler } from '@sveltejs/kit';
+import { error, json } from '@sveltejs/kit';
+import { migrateStackToNameFolder } from '$lib/services/docker/stack-migration-service';
+
+export const POST: RequestHandler = async ({ params }) => {
+ const { stackId } = params;
+
+ if (!stackId) {
+ throw error(400, 'Missing stackId');
+ }
+
+ try {
+ await migrateStackToNameFolder(stackId);
+ return json({ success: true, message: `Stack "${stackId}" migrated successfully.` });
+ } catch (err: any) {
+ console.error(err);
+ throw error(500, err?.message || 'Failed to migrate stack');
+ }
+};
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte
index ef90a78aa..1cdb8ab78 100644
--- a/src/routes/stacks/+page.svelte
+++ b/src/routes/stacks/+page.svelte
@@ -2,7 +2,7 @@
import type { PageData } from './$types';
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { Plus, AlertCircle, Layers, Upload, FileStack, Loader2, Play, RotateCcw, StopCircle, Trash2, Ellipsis, Pen, Import } from '@lucide/svelte';
+ import { Plus, AlertCircle, Layers, FileStack, Loader2, Play, RotateCcw, StopCircle, Trash2, Ellipsis, Pen, Import } from '@lucide/svelte';
import UniversalTable from '$lib/components/universal-table.svelte';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import * as Table from '$lib/components/ui/table';
@@ -29,7 +29,8 @@
import: false,
redeploy: false,
destroy: false,
- pull: false
+ pull: false,
+ migrate: false
});
const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
@@ -112,6 +113,16 @@
}
}
});
+ } else if (action === 'migrate') {
+ handleApiReponse(
+ await tryCatch(stackApi.migrate(id)),
+ 'Failed to Migrate Stack',
+ (value) => (isLoading.migrate = value),
+ async () => {
+ toast.success('Stack Migrated Successfully.');
+ await invalidateAll();
+ }
+ );
} else {
console.error('An Unknown Error Occurred');
toast.error('An Unknown Error Occurred');
@@ -229,7 +240,18 @@
>
{#snippet rows({ item })}
{@const stateVariant = statusVariantMap[item.status.toLowerCase()]}
- <Table.Cell><a class="font-medium hover:underline" href="/stacks/{item.id}/">{item.name}</a></Table.Cell>
+ <Table.Cell>
+ <div class="flex items-center gap-2">
+ <a class="font-medium hover:underline" href="/stacks/{item.id}/">
+ {item.name}
+ </a>
+ {#if item.isLegacy}
+ <span title="This stack uses the legacy layout. Migrate to the new layout from the dropdown menu." class="ml-1 flex items-center" style="filter: drop-shadow(0 0 4px #fbbf24);">
+ <AlertCircle class="w-4 h-4 text-amber-400 animate-pulse" />
+ </span>
+ {/if}
+ </div>
+ </Table.Cell>
<Table.Cell>{item.serviceCount}</Table.Cell>
<Table.Cell><StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.status)} /></Table.Cell>
<Table.Cell><StatusBadge variant={item.isExternal ? 'amber' : 'green'} text={item.isExternal ? 'External' : 'Managed'} /></Table.Cell>
@@ -290,6 +312,15 @@
</DropdownMenu.Item>
{/if}
+ {#if item.isLegacy}
+ <DropdownMenu.Item onclick={() => performStackAction('migrate', item.id)} class="text-amber-600 hover:text-amber-800 flex items-center">
+ <span title="This stack uses the legacy layout. Migrate to the new layout." class="mr-2 flex items-center">
+ <AlertCircle class="w-4 h-4 text-amber-500" />
+ </span>
+ Migrate
+ </DropdownMenu.Item>
+ {/if}
+
<DropdownMenu.Separator />
<DropdownMenu.Item class="text-red-500 focus:!text-red-700" onclick={() => performStackAction('destroy', item.id)} disabled={isLoading.remove || isAnyLoading}>
diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelte
index 05c6439a1..86aee99b5 100644
--- a/src/routes/stacks/[stackId]/+page.svelte
+++ b/src/routes/stacks/[stackId]/+page.svelte
@@ -224,7 +224,7 @@
<div>
<p class="text-sm font-medium text-muted-foreground">Created</p>
<p class="text-lg font-medium">
- {new Date(stack.createdAt).toLocaleString()}
+ {new Date(stack.createdAt ?? '').toLocaleString()}
</p>
</div>
<div class="bg-blue-500/10 p-2 rounded-full">
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
index b252517c7..ab373a0e6 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -32,7 +32,7 @@
async (data) => {
toast.success(`Stack "${data.stack.name}" created with environment file.`);
await invalidateAll();
- goto(`/stacks/${data.stack.id}`);
+ goto(`/stacks/${data.stack.name}`);
}
);
}