Skip to content

Modern Docker Management, Designed for Everyone

feat: convert docker run to docker compose (#219)

Kyle Mendell3da1db7452de
diff --git a/src/lib/services/api/stack-api-service.ts b/src/lib/services/api/stack-api-service.ts
index 519709690..8476aba4c 100644
--- a/src/lib/services/api/stack-api-service.ts
+++ b/src/lib/services/api/stack-api-service.ts
@@ -77,4 +77,11 @@ export default class StackAPIService extends BaseAPIService {
const res = await this.api.get('');
return res.data;
}
+
+ async convertDockerRun(dockerRunCommand: string) {
+ const res = await this.api.post('/convert', {
+ dockerRunCommand
+ });
+ return res.data;
+ }
}
diff --git a/src/lib/services/converter-service.ts b/src/lib/services/converter-service.ts
new file mode 100644
index 000000000..b08952e69
--- /dev/null
+++ b/src/lib/services/converter-service.ts
@@ -0,0 +1,483 @@
+export interface DockerRunCommand {
+ image: string;
+ name?: string;
+ ports?: string[];
+ volumes?: string[];
+ environment?: string[];
+ networks?: string[];
+ restart?: string;
+ workdir?: string;
+ user?: string;
+ entrypoint?: string;
+ command?: string;
+ detached?: boolean;
+ interactive?: boolean;
+ tty?: boolean;
+ remove?: boolean;
+ privileged?: boolean;
+ labels?: string[];
+ healthCheck?: string;
+ memoryLimit?: string;
+ cpuLimit?: string;
+}
+
+export function parseDockerRunCommand(command: string): DockerRunCommand {
+ try {
+ // Validate input
+ if (!command || typeof command !== 'string') {
+ throw new Error('Docker run command must be a non-empty string');
+ }
+
+ // Remove 'docker run' from the beginning
+ let cmd = command.trim().replace(/^docker\s+run\s+/, '');
+
+ if (!cmd) {
+ throw new Error('No arguments found after "docker run"');
+ }
+
+ const result: DockerRunCommand = { image: '' };
+ let tokens: string[];
+
+ // Parse tokens with error handling
+ try {
+ tokens = parseCommandTokens(cmd);
+ } catch (error) {
+ throw new Error(`Failed to parse command tokens: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+
+ if (tokens.length === 0) {
+ throw new Error('No valid tokens found in docker run command');
+ }
+
+ for (let i = 0; i < tokens.length; i++) {
+ const token = tokens[i];
+
+ try {
+ switch (token) {
+ case '-d':
+ case '--detach':
+ result.detached = true;
+ break;
+
+ case '-i':
+ case '--interactive':
+ result.interactive = true;
+ break;
+
+ case '-t':
+ case '--tty':
+ result.tty = true;
+ break;
+
+ case '--rm':
+ result.remove = true;
+ break;
+
+ case '--privileged':
+ result.privileged = true;
+ break;
+
+ case '--name':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --name flag');
+ }
+ const nameValue = tokens[++i];
+ if (!nameValue || nameValue.startsWith('-')) {
+ throw new Error('Invalid value for --name flag: must not be empty or start with -');
+ }
+ result.name = nameValue;
+ break;
+
+ case '-p':
+ case '--port':
+ case '--publish':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for port flag');
+ }
+ const portValue = tokens[++i];
+ if (!portValue || portValue.startsWith('-')) {
+ throw new Error('Invalid value for port flag: must not be empty or start with -');
+ }
+ if (!result.ports) result.ports = [];
+ result.ports.push(portValue);
+ break;
+
+ case '-v':
+ case '--volume':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for volume flag');
+ }
+ const volumeValue = tokens[++i];
+ if (!volumeValue || volumeValue.startsWith('-')) {
+ throw new Error('Invalid value for volume flag: must not be empty or start with -');
+ }
+ if (!result.volumes) result.volumes = [];
+ result.volumes.push(volumeValue);
+ break;
+
+ case '-e':
+ case '--env':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for environment flag');
+ }
+ const envValue = tokens[++i];
+ if (!envValue || envValue.startsWith('-')) {
+ throw new Error('Invalid value for environment flag: must not be empty or start with -');
+ }
+ if (!result.environment) result.environment = [];
+ result.environment.push(envValue);
+ break;
+
+ case '--network':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --network flag');
+ }
+ const networkValue = tokens[++i];
+ if (!networkValue || networkValue.startsWith('-')) {
+ throw new Error('Invalid value for --network flag: must not be empty or start with -');
+ }
+ if (!result.networks) result.networks = [];
+ result.networks.push(networkValue);
+ break;
+
+ case '--restart':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --restart flag');
+ }
+ const restartValue = tokens[++i];
+ if (!restartValue || restartValue.startsWith('-')) {
+ throw new Error('Invalid value for --restart flag: must not be empty or start with -');
+ }
+ result.restart = restartValue;
+ break;
+
+ case '-w':
+ case '--workdir':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for workdir flag');
+ }
+ const workdirValue = tokens[++i];
+ if (!workdirValue || workdirValue.startsWith('-')) {
+ throw new Error('Invalid value for workdir flag: must not be empty or start with -');
+ }
+ result.workdir = workdirValue;
+ break;
+
+ case '-u':
+ case '--user':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for user flag');
+ }
+ const userValue = tokens[++i];
+ if (!userValue || userValue.startsWith('-')) {
+ throw new Error('Invalid value for user flag: must not be empty or start with -');
+ }
+ result.user = userValue;
+ break;
+
+ case '--entrypoint':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --entrypoint flag');
+ }
+ const entrypointValue = tokens[++i];
+ if (!entrypointValue || entrypointValue.startsWith('-')) {
+ throw new Error('Invalid value for --entrypoint flag: must not be empty or start with -');
+ }
+ result.entrypoint = entrypointValue;
+ break;
+
+ case '--health-cmd':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --health-cmd flag');
+ }
+ const healthValue = tokens[++i];
+ if (!healthValue || healthValue.startsWith('-')) {
+ throw new Error('Invalid value for --health-cmd flag: must not be empty or start with -');
+ }
+ result.healthCheck = healthValue;
+ break;
+
+ case '-m':
+ case '--memory':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for memory flag');
+ }
+ const memoryValue = tokens[++i];
+ if (!memoryValue || memoryValue.startsWith('-')) {
+ throw new Error('Invalid value for memory flag: must not be empty or start with -');
+ }
+ result.memoryLimit = memoryValue;
+ break;
+
+ case '--cpus':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --cpus flag');
+ }
+ const cpusValue = tokens[++i];
+ if (!cpusValue || cpusValue.startsWith('-')) {
+ throw new Error('Invalid value for --cpus flag: must not be empty or start with -');
+ }
+ result.cpuLimit = cpusValue;
+ break;
+
+ case '--label':
+ if (i + 1 >= tokens.length) {
+ throw new Error('Missing value for --label flag');
+ }
+ const labelValue = tokens[++i];
+ if (!labelValue || labelValue.startsWith('-')) {
+ throw new Error('Invalid value for --label flag: must not be empty or start with -');
+ }
+ if (!result.labels) result.labels = [];
+ result.labels.push(labelValue);
+ break;
+
+ default:
+ // Handle unknown flags
+ if (token.startsWith('-')) {
+ // Check if it's a flag that expects a value
+ const flagsWithValues = ['-p', '--port', '--publish', '-v', '--volume', '-e', '--env', '--network', '--restart', '-w', '--workdir', '-u', '--user', '--entrypoint', '--health-cmd', '-m', '--memory', '--cpus', '--label', '--name'];
+
+ // Check if it's a combined short flag (e.g., -it for -i -t)
+ if (token.startsWith('-') && !token.startsWith('--') && token.length > 2) {
+ // Handle combined short flags like -it, -dit, etc.
+ const flags = token.slice(1).split('');
+ for (const flag of flags) {
+ switch (flag) {
+ case 'd':
+ result.detached = true;
+ break;
+ case 'i':
+ result.interactive = true;
+ break;
+ case 't':
+ result.tty = true;
+ break;
+ default:
+ console.warn(`Unknown short flag in combined flag: -${flag}`);
+ break;
+ }
+ }
+ break;
+ }
+
+ // For unknown flags, check if they expect a value
+ const isKnownFlag = flagsWithValues.includes(token);
+ if (!isKnownFlag) {
+ // Unknown flag - decide whether to throw error or warn
+ console.warn(`Unknown docker run flag: ${token}`);
+
+ // Skip potential value if next token doesn't look like a flag or image
+ if (i + 1 < tokens.length && !tokens[i + 1].startsWith('-') && !result.image && tokens[i + 1].includes(':')) {
+ // Likely this unknown flag has a value, skip it
+ i++;
+ }
+ }
+ } else {
+ // Token doesn't start with '-', it's either image or command
+ if (!result.image) {
+ if (!token) {
+ throw new Error('Image name cannot be empty');
+ }
+ // Validate image name format (basic check)
+ if (!/^[a-zA-Z0-9._/-]+(:[\w.-]+)?$/.test(token)) {
+ console.warn(`Image name "${token}" may not be valid`);
+ }
+ result.image = token;
+ } else {
+ // Everything from this point forward is part of the command
+ // Join all remaining tokens to handle multi-argument commands properly
+ const remainingTokens = tokens.slice(i);
+ result.command = remainingTokens.join(' ');
+
+ // Important: return here to stop processing since we've captured the command
+ return result;
+ }
+ }
+ break;
+ }
+ } catch (error) {
+ // Add context about which token caused the error
+ throw new Error(`Error processing token "${token}" at position ${i}: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+ }
+
+ // Validate that we have at least an image
+ if (!result.image) {
+ throw new Error('No Docker image specified in command');
+ }
+
+ return result;
+ } catch (error) {
+ // Wrap all errors with context about the original command
+ const errorMessage = error instanceof Error ? error.message : 'Unknown parsing error';
+ throw new Error(`Failed to parse Docker run command: ${errorMessage}. Original command: "${command}"`);
+ }
+}
+
+function parseCommandTokens(command: string): string[] {
+ try {
+ const tokens: string[] = [];
+ let current = '';
+ let inQuotes = false;
+ let quoteChar = '';
+
+ for (let i = 0; i < command.length; i++) {
+ const char = command[i];
+
+ if ((char === '"' || char === "'") && !inQuotes) {
+ inQuotes = true;
+ quoteChar = char;
+ } else if (char === quoteChar && inQuotes) {
+ inQuotes = false;
+ quoteChar = '';
+ } else if (char === ' ' && !inQuotes) {
+ if (current) {
+ tokens.push(current);
+ current = '';
+ }
+ } else {
+ current += char;
+ }
+ }
+
+ if (inQuotes) {
+ throw new Error(`Unclosed quote in command: missing closing ${quoteChar}`);
+ }
+
+ if (current) {
+ tokens.push(current);
+ }
+
+ return tokens;
+ } catch (error) {
+ throw new Error(`Token parsing failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+}
+
+export function convertToDockerCompose(parsed: DockerRunCommand): string {
+ try {
+ if (!parsed.image) {
+ throw new Error('Cannot convert to Docker Compose: no image specified');
+ }
+
+ const serviceName = parsed.name || 'app';
+
+ const service: any = {
+ image: parsed.image
+ };
+
+ if (parsed.name) {
+ service.container_name = parsed.name;
+ }
+
+ if (parsed.ports && parsed.ports.length > 0) {
+ service.ports = parsed.ports;
+ }
+
+ if (parsed.volumes && parsed.volumes.length > 0) {
+ service.volumes = parsed.volumes;
+ }
+
+ if (parsed.environment && parsed.environment.length > 0) {
+ service.environment = parsed.environment;
+ }
+
+ if (parsed.networks && parsed.networks.length > 0) {
+ service.networks = parsed.networks;
+ }
+
+ if (parsed.restart) {
+ service.restart = parsed.restart;
+ }
+
+ if (parsed.workdir) {
+ service.working_dir = parsed.workdir;
+ }
+
+ if (parsed.user) {
+ service.user = parsed.user;
+ }
+
+ if (parsed.entrypoint) {
+ service.entrypoint = parsed.entrypoint;
+ }
+
+ if (parsed.command) {
+ service.command = parsed.command;
+ }
+
+ if (parsed.interactive && parsed.tty) {
+ service.stdin_open = true;
+ service.tty = true;
+ }
+
+ if (parsed.privileged) {
+ service.privileged = true;
+ }
+
+ if (parsed.labels && parsed.labels.length > 0) {
+ service.labels = parsed.labels;
+ }
+
+ if (parsed.healthCheck) {
+ service.healthcheck = {
+ test: parsed.healthCheck
+ };
+ }
+
+ if (parsed.memoryLimit) {
+ if (!service.deploy) service.deploy = {};
+ if (!service.deploy.resources) service.deploy.resources = {};
+ if (!service.deploy.resources.limits) service.deploy.resources.limits = {};
+ service.deploy.resources.limits.memory = parsed.memoryLimit;
+ }
+
+ if (parsed.cpuLimit) {
+ if (!service.deploy) service.deploy = {};
+ if (!service.deploy.resources) service.deploy.resources = {};
+ if (!service.deploy.resources.limits) service.deploy.resources.limits = {};
+ service.deploy.resources.limits.cpus = parsed.cpuLimit;
+ }
+
+ const compose = {
+ services: {
+ [serviceName]: service
+ }
+ };
+
+ // Convert to YAML-like string
+ return generateYaml(compose);
+ } catch (error) {
+ throw new Error(`Failed to convert to Docker Compose: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+}
+
+function generateYaml(obj: any, indent = 0): string {
+ try {
+ const spaces = ' '.repeat(indent);
+ let result = '';
+
+ for (const [key, value] of Object.entries(obj)) {
+ if (value === null || value === undefined) continue;
+
+ result += `${spaces}${key}:`;
+
+ if (Array.isArray(value)) {
+ result += '\n';
+ for (const item of value) {
+ result += `${spaces} - ${item}\n`;
+ }
+ } else if (typeof value === 'object') {
+ result += '\n';
+ result += generateYaml(value, indent + 1);
+ } else {
+ result += ` ${value}\n`;
+ }
+ }
+
+ return result;
+ } catch (error) {
+ throw new Error(`YAML generation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
+ }
+}
diff --git a/src/routes/api/convert/+server.ts b/src/routes/api/convert/+server.ts
new file mode 100644
index 000000000..da98a4405
--- /dev/null
+++ b/src/routes/api/convert/+server.ts
@@ -0,0 +1,57 @@
+import { json } from '@sveltejs/kit';
+import type { RequestHandler } from './$types';
+import { parseDockerRunCommand, convertToDockerCompose } from '$lib/services/converter-service';
+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';
+import { tryCatch } from '$lib/utils/try-catch';
+
+export const POST: RequestHandler = async ({ request }) => {
+ const bodyResult = await tryCatch(request.json());
+ if (bodyResult.error) {
+ const response: ApiErrorResponse = {
+ success: false,
+ error: 'Invalid JSON payload',
+ code: ApiErrorCode.BAD_REQUEST
+ };
+ return json(response, { status: 400 });
+ }
+
+ const { dockerRunCommand } = bodyResult.data as { dockerRunCommand: string };
+
+ if (!dockerRunCommand || !dockerRunCommand.trim()) {
+ const response: ApiErrorResponse = {
+ success: false,
+ error: 'Docker run command is required',
+ code: ApiErrorCode.BAD_REQUEST
+ };
+ return json(response, { status: 400 });
+ }
+
+ try {
+ const parsed = parseDockerRunCommand(dockerRunCommand);
+ const dockerCompose = convertToDockerCompose(parsed);
+
+ // Extract environment variables for the .env file
+ const envVars =
+ parsed.environment
+ ?.map((env) => {
+ // Convert -e KEY=value format to KEY=value
+ return env;
+ })
+ .join('\n') || '';
+
+ return json({
+ success: true,
+ dockerCompose,
+ envVars,
+ serviceName: parsed.name || 'app'
+ });
+ } catch (error) {
+ console.error('Error converting docker run command:', error);
+ const response: ApiErrorResponse = {
+ success: false,
+ error: 'Failed to parse docker run command. Please check the syntax.',
+ code: ApiErrorCode.INTERNAL_SERVER_ERROR
+ };
+ return json(response, { status: 500 });
+ }
+};
diff --git a/src/routes/stacks/new/+page.server.ts b/src/routes/stacks/new/+page.server.ts
new file mode 100644
index 000000000..45fd039dd
--- /dev/null
+++ b/src/routes/stacks/new/+page.server.ts
@@ -0,0 +1,5 @@
+import type { PageServerLoad } from './$types';
+
+export const load: PageServerLoad = async () => {
+ return {};
+};
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
index db51278b1..8f64f9781 100644
--- a/src/routes/stacks/new/+page.svelte
+++ b/src/routes/stacks/new/+page.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
- import { ArrowLeft, FileStack } from '@lucide/svelte';
+ import { ArrowLeft, FileStack, Terminal, Copy, Wand2, Loader2 } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { Input } from '$lib/components/ui/input/index.js';
import { Label } from '$lib/components/ui/label/index.js';
@@ -15,13 +15,17 @@
import EnvEditor from '$lib/components/env-editor.svelte';
import { defaultEnvTemplate, defaultComposeTemplate } from '$lib/constants';
import ArcaneButton from '$lib/components/arcane-button.svelte';
+ import { Textarea } from '$lib/components/ui/textarea/index.js';
+ import DropdownCard from '$lib/components/dropdown-card.svelte';
const stackApi = new StackAPIService();
let saving = $state(false);
+ let converting = $state(false);
let name = $state('');
let composeContent = $state(defaultComposeTemplate);
let envContent = $state(defaultEnvTemplate);
+ let dockerRunCommand = $state('');
async function handleSubmit() {
handleApiResultWithCallbacks({
@@ -35,6 +39,40 @@
}
});
}
+
+ async function handleConvertDockerRun() {
+ if (!dockerRunCommand.trim()) {
+ toast.error('Please enter a docker run command');
+ return;
+ }
+
+ handleApiResultWithCallbacks({
+ result: await tryCatch(stackApi.convertDockerRun(dockerRunCommand)),
+ message: 'Failed to Convert Docker Run Command',
+ setLoadingState: (value) => (converting = value),
+ onSuccess: (data) => {
+ const { dockerCompose, envVars, serviceName } = data;
+
+ composeContent = dockerCompose;
+ if (envVars) {
+ envContent = envVars;
+ }
+ if (serviceName && !name) {
+ name = serviceName;
+ }
+
+ toast.success('Docker run command converted successfully!');
+ // Clear the command after successful conversion
+ dockerRunCommand = '';
+ }
+ });
+ }
+
+ const exampleCommands = ['docker run -d --name nginx -p 8080:80 -v nginx_data:/usr/share/nginx/html nginx:alpine', 'docker run -d --name postgres -e POSTGRES_DB=mydb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass -v postgres_data:/var/lib/postgresql/data postgres:15', 'docker run -d --name redis -p 6379:6379 --restart unless-stopped redis:alpine'];
+
+ function useExample(command: string) {
+ dockerRunCommand = command;
+ }
</script>
<div class="space-y-6 pb-8">
@@ -60,6 +98,40 @@
</div>
</div>
+ <!-- Docker Run to Compose Converter -->
+ <DropdownCard id="docker-run-converter" title="Docker Run to Compose Converter" description="Convert existing docker run commands to Docker Compose format" icon={Terminal}>
+ <div class="space-y-4">
+ <div class="space-y-2">
+ <Label for="dockerRunCommand">Docker Run Command</Label>
+ <Textarea id="dockerRunCommand" bind:value={dockerRunCommand} placeholder="docker run -d --name my-app -p 8080:80 nginx:alpine" rows={3} disabled={converting} class="font-mono text-sm" />
+ </div>
+
+ <div class="flex items-center gap-2">
+ <Button type="button" disabled={!dockerRunCommand.trim() || converting} size="sm" onclick={handleConvertDockerRun}>
+ {#if converting}
+ <Loader2 class="mr-2 size-4 animate-spin" />
+ Converting...
+ {:else}
+ <Wand2 class="mr-2 size-4" />
+ Convert to Compose
+ {/if}
+ </Button>
+ </div>
+
+ <div class="space-y-2">
+ <Label class="text-xs text-muted-foreground">Example Commands:</Label>
+ <div class="space-y-1">
+ {#each exampleCommands as command}
+ <Button type="button" variant="ghost" size="sm" class="h-auto p-2 text-xs font-mono text-left justify-start w-full" onclick={() => useExample(command)}>
+ <Copy class="mr-2 size-3" />
+ {command}
+ </Button>
+ {/each}
+ </div>
+ </div>
+ </div>
+ </DropdownCard>
+
<form class="space-y-6" onsubmit={preventDefault(handleSubmit)}>
<Card.Root class="border shadow-sm">
<Card.Header>
diff --git a/tests/.auth/login.json b/tests/.auth/login.json
index c702524cb..2a9b977a9 100644
--- a/tests/.auth/login.json
+++ b/tests/.auth/login.json
@@ -2,10 +2,10 @@
"cookies": [
{
"name": "kit.session",
- "value": "91db7b852496b39ef73bd81573df7c55fad3696257b160cf2d2f98e876a42622bc423a1130e065c8b4e0a7048fc19b489da9a44900c1e95696ec0745fc1e6a08d7232f32e19655db9509540bdace6084620291c51668c51bfb0910b6fe079df639d2feca20f64711ca8f1503d093f82637c0329722212cf9e74c709a2e8b61dec2f97cc4f4fbacee80ff8a8b5b76affc8891b7b321fec72f837507f10b99d0275f1bad678fc9002f59729d2ad3c747a3b83516c56b0e820c7de5f77604%26id%3D1",
+ "value": "51e972dc20999f886ad5304cc98ca9d304f8c07a97dfef48a600949ded39cffcdf58fa8c19cd35fc2f0ae018a4358203efd2a524e0f9ef6c8deabb3ac9f68e5efaa4529f9cc9aa99d48605624925fa2bf248a3979294ba44a27ff97a259a3214ab580619bc6492eb5899591b6977742e2116329e701d186956f8c7827afeae4f06066bfa5af4a4c2f70d218dff7f3aadcbac7ad4bdf2bf40ad4a0830ab4fc0204bc7be1d9c11320a4488e5d16d3ec8700f477456e7c7684eab174590a7%26id%3D1",
"domain": "localhost",
"path": "/",
- "expires": 1782584367.292194,
+ "expires": 1782709844.331035,
"httpOnly": true,
"secure": false,
"sameSite": "Lax"
diff --git a/tests/converter.spec.ts b/tests/converter.spec.ts
new file mode 100644
index 000000000..8a659b8f7
--- /dev/null
+++ b/tests/converter.spec.ts
@@ -0,0 +1,194 @@
+import { test, expect } from '@playwright/test';
+
+test.describe('Docker Run to Compose Converter', () => {
+ test.beforeEach(async ({ page }) => {
+ // Navigate to the new stack page
+ await page.goto('/stacks/new');
+ await page.waitForLoadState('networkidle');
+ });
+
+ test('should display converter section', async ({ page }) => {
+ // Check if the converter dropdown card is visible
+ await expect(page.getByText('Docker Run to Compose Converter')).toBeVisible();
+ await expect(page.getByText('Convert existing docker run commands to Docker Compose format')).toBeVisible();
+ });
+
+ test('should convert simple docker run command', async ({ page }) => {
+ await page.waitForLoadState('networkidle');
+ // Expand converter
+ await page.getByText('Docker Run to Compose Converter').click();
+ await page.waitForTimeout(300);
+
+ // Enter a simple docker run command using the textarea
+ const dockerCommand = 'docker run -d --name nginx -p 8080:80 nginx:alpine';
+ await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill(dockerCommand);
+
+ // Mock the API response
+ await page.route('/api/convert', async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ dockerCompose: `services:
+ nginx:
+ image: nginx:alpine
+ container_name: nginx
+ ports:
+ - 8080:80`,
+ envVars: '',
+ serviceName: 'nginx'
+ })
+ });
+ });
+
+ // Click convert button
+ await page.getByRole('button', { name: 'Convert to Compose' }).click();
+
+ // Wait for success toast
+ await expect(page.getByText('Docker run command converted successfully!')).toBeVisible();
+
+ // Check if stack name was populated
+ await expect(page.getByPlaceholder('e.g., my-web-app')).toHaveValue('nginx');
+
+ // Check if docker run command was cleared
+ await expect(page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine')).toHaveValue('');
+ });
+
+ test('should convert docker run command with environment variables', async ({ page }) => {
+ // Expand converter
+ await page.getByText('Docker Run to Compose Converter').click();
+ await page.waitForTimeout(300);
+
+ // Enter docker run command with environment variables
+ const dockerCommand = 'docker run -d --name postgres -e POSTGRES_DB=mydb -e POSTGRES_USER=user -e POSTGRES_PASSWORD=pass postgres:15';
+ await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill(dockerCommand);
+
+ // Mock the API response
+ await page.route('/api/convert', async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ dockerCompose: `services:
+ postgres:
+ image: postgres:15
+ container_name: postgres
+ environment:
+ - POSTGRES_DB=mydb
+ - POSTGRES_USER=user
+ - POSTGRES_PASSWORD=pass`,
+ envVars: 'POSTGRES_DB=mydb\nPOSTGRES_USER=user\nPOSTGRES_PASSWORD=pass',
+ serviceName: 'postgres'
+ })
+ });
+ });
+
+ // Click convert button
+ await page.getByRole('button', { name: 'Convert to Compose' }).click();
+
+ // Wait for success toast
+ await expect(page.getByText('Docker run command converted successfully!')).toBeVisible();
+
+ // Check if stack name was populated
+ await expect(page.getByPlaceholder('e.g., my-web-app')).toHaveValue('postgres');
+ });
+
+ test('should use example commands', async ({ page }) => {
+ // Expand converter
+ await page.getByText('Docker Run to Compose Converter').click();
+ await page.waitForTimeout(300);
+
+ // Click on the first example command (using a more specific selector)
+ await page
+ .getByRole('button', { name: /docker run -d --name nginx/ })
+ .first()
+ .click();
+
+ // Check if the command was populated in the textarea
+ const expectedCommand = 'docker run -d --name nginx -p 8080:80 -v nginx_data:/usr/share/nginx/html nginx:alpine';
+ await expect(page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine')).toHaveValue(expectedCommand);
+ });
+
+ test('should handle API error gracefully', async ({ page }) => {
+ // Expand converter
+ await page.getByText('Docker Run to Compose Converter').click();
+ await page.waitForTimeout(300);
+
+ // Enter a docker run command
+ await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill('docker run nginx:alpine');
+
+ // Mock API error response
+ await page.route('/api/convert', async (route) => {
+ await route.fulfill({
+ status: 400,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: false,
+ error: 'Failed to parse docker run command. Please check the syntax.',
+ code: 'BAD_REQUEST'
+ })
+ });
+ });
+
+ // Click convert button
+ await page.getByRole('button', { name: 'Convert to Compose' }).click();
+
+ // Check for error toast
+ await expect(page.getByText('Failed to Convert Docker Run Command')).toBeVisible();
+ });
+
+ test('should disable convert button when no command is entered', async ({ page }) => {
+ // Expand converter
+ await page.getByText('Docker Run to Compose Converter').click();
+ await page.waitForTimeout(300);
+
+ // Check that convert button is disabled when textarea is empty
+ await expect(page.getByRole('button', { name: 'Convert to Compose' })).toBeDisabled();
+
+ // Enter some text
+ await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill('docker run nginx');
+
+ // Check that convert button is now enabled
+ await expect(page.getByRole('button', { name: 'Convert to Compose' })).toBeEnabled();
+
+ // Clear the text
+ await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').clear();
+
+ // Check that convert button is disabled again
+ await expect(page.getByRole('button', { name: 'Convert to Compose' })).toBeDisabled();
+ });
+
+ test('should populate stack name only when empty', async ({ page }) => {
+ // Expand converter
+ await page.getByText('Docker Run to Compose Converter').click();
+ await page.waitForTimeout(300);
+
+ // Enter docker run command with name
+ await page.getByPlaceholder('docker run -d --name my-app -p 8080:80 nginx:alpine').fill('docker run --name redis redis:alpine');
+
+ // Mock the API response
+ await page.route('/api/convert', async (route) => {
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ success: true,
+ dockerCompose: 'services:\n redis:\n image: redis:alpine',
+ envVars: '',
+ serviceName: 'redis'
+ })
+ });
+ });
+
+ // Click convert button
+ await page.getByRole('button', { name: 'Convert to Compose' }).click();
+
+ // Wait for success
+ await expect(page.getByText('Docker run command converted successfully!')).toBeVisible();
+
+ // Check that stack name was populated from service name
+ await expect(page.getByPlaceholder('e.g., my-web-app')).toHaveValue('redis');
+ });
+});