mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-17 14:08:19 +00:00
refactor: migrate to directory-based stack structure
- Updated ComposeService to run docker commands from stack-specific directories, ensuring relative paths resolve correctly. - Refactored FileSystemService to manage stacks as directories, including methods for creating, updating, and deleting stacks. - Implemented automatic migration of existing flat-file stacks to the new directory structure on server startup. - Adjusted API routes to use stack names instead of filenames, simplifying stack management. - Modified frontend components to align with the new stack naming conventions and removed unnecessary file extensions.
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import { promises as fs, Dirent } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export class FileSystemService {
|
||||
@@ -8,41 +8,109 @@ export class FileSystemService {
|
||||
this.baseDir = process.env.COMPOSE_DIR || path.join(process.cwd(), '..', 'mock_data', 'docker', 'compose');
|
||||
}
|
||||
|
||||
async getStackFiles(): Promise<string[]> {
|
||||
/**
|
||||
* Check if a directory contains a valid compose file
|
||||
*/
|
||||
private async hasComposeFile(dir: string): Promise<boolean> {
|
||||
const composeFiles = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
|
||||
|
||||
for (const file of composeFiles) {
|
||||
try {
|
||||
await fs.access(path.join(dir, file));
|
||||
return true;
|
||||
} catch {
|
||||
// Continue checking other options
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path to the compose file for a stack
|
||||
* Throws if no compose file is found
|
||||
*/
|
||||
private async getComposeFilePath(stackName: string): Promise<string> {
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
const composeFiles = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
|
||||
|
||||
for (const file of composeFiles) {
|
||||
const filePath = path.join(stackDir, file);
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
return filePath;
|
||||
} catch {
|
||||
// Continue checking other options
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`No compose file found for stack: ${stackName}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all stacks (directories containing compose files)
|
||||
* Returns array of stack names (directory names)
|
||||
*/
|
||||
async getStacks(): Promise<string[]> {
|
||||
try {
|
||||
const files = await fs.readdir(this.baseDir);
|
||||
return files.filter(file => file.endsWith('.yml') || file.endsWith('.yaml'));
|
||||
const items = await fs.readdir(this.baseDir, { withFileTypes: true });
|
||||
const stackNames: string[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
if (!item.isDirectory()) continue;
|
||||
|
||||
const stackDir = path.join(this.baseDir, item.name);
|
||||
const hasCompose = await this.hasComposeFile(stackDir);
|
||||
|
||||
if (hasCompose) {
|
||||
stackNames.push(item.name);
|
||||
}
|
||||
}
|
||||
|
||||
return stackNames;
|
||||
} catch (error) {
|
||||
console.error('Error reading stack files:', error);
|
||||
console.error('Error reading stacks:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getStackContent(filename: string): Promise<string> {
|
||||
const filePath = path.join(this.baseDir, filename);
|
||||
/**
|
||||
* Get the content of a stack's compose file
|
||||
*/
|
||||
async getStackContent(stackName: string): Promise<string> {
|
||||
try {
|
||||
const filePath = await this.getComposeFilePath(stackName);
|
||||
return await fs.readFile(filePath, 'utf-8');
|
||||
} catch (error) {
|
||||
console.error('Error reading file:', error);
|
||||
throw new Error(`Failed to read file: ${filename}`);
|
||||
console.error('Error reading stack content:', error);
|
||||
throw new Error(`Failed to read stack: ${stackName}`);
|
||||
}
|
||||
}
|
||||
|
||||
async saveStackContent(filename: string, content: string): Promise<void> {
|
||||
const filePath = path.join(this.baseDir, filename);
|
||||
/**
|
||||
* Save content to a stack's compose file
|
||||
* Always writes to compose.yaml (standardizing on this filename)
|
||||
*/
|
||||
async saveStackContent(stackName: string, content: string): Promise<void> {
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
const filePath = path.join(stackDir, 'compose.yaml');
|
||||
|
||||
console.log('Saving to path:', filePath);
|
||||
|
||||
try {
|
||||
await fs.writeFile(filePath, content, 'utf-8');
|
||||
console.log('File written successfully');
|
||||
} catch (error) {
|
||||
console.error('Error writing file:', error);
|
||||
throw new Error(`Failed to save file: ${filename}`);
|
||||
throw new Error(`Failed to save stack: ${stackName}`);
|
||||
}
|
||||
}
|
||||
|
||||
async envExists(filename: string): Promise<boolean> {
|
||||
const envFilename = filename.replace(/\.yml$/, '.env');
|
||||
const envPath = path.join(this.baseDir, envFilename);
|
||||
/**
|
||||
* Check if a stack has an .env file
|
||||
*/
|
||||
async envExists(stackName: string): Promise<boolean> {
|
||||
const envPath = path.join(this.baseDir, stackName, '.env');
|
||||
try {
|
||||
await fs.access(envPath);
|
||||
return true;
|
||||
@@ -51,66 +119,156 @@ export class FileSystemService {
|
||||
}
|
||||
}
|
||||
|
||||
async getEnvContent(filename: string): Promise<string> {
|
||||
const envFilename = filename.replace(/\.yml$/, '.env');
|
||||
const envPath = path.join(this.baseDir, envFilename);
|
||||
/**
|
||||
* Get the content of a stack's .env file
|
||||
*/
|
||||
async getEnvContent(stackName: string): Promise<string> {
|
||||
const envPath = path.join(this.baseDir, stackName, '.env');
|
||||
try {
|
||||
return await fs.readFile(envPath, 'utf-8');
|
||||
} catch (error) {
|
||||
console.error('Error reading env file:', error);
|
||||
throw new Error(`Failed to read env file for: ${filename}`);
|
||||
throw new Error(`Failed to read env file for stack: ${stackName}`);
|
||||
}
|
||||
}
|
||||
|
||||
async saveEnvContent(filename: string, content: string): Promise<void> {
|
||||
const envFilename = filename.replace(/\.yml$/, '.env');
|
||||
const envPath = path.join(this.baseDir, envFilename);
|
||||
/**
|
||||
* Save content to a stack's .env file
|
||||
*/
|
||||
async saveEnvContent(stackName: string, content: string): Promise<void> {
|
||||
const envPath = path.join(this.baseDir, stackName, '.env');
|
||||
console.log('Saving env to path:', envPath);
|
||||
|
||||
try {
|
||||
await fs.writeFile(envPath, content, 'utf-8');
|
||||
console.log('Env file written successfully');
|
||||
} catch (error) {
|
||||
console.error('Error writing env file:', error);
|
||||
throw new Error(`Failed to save env file for: ${filename}`);
|
||||
throw new Error(`Failed to save env file for stack: ${stackName}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createStack(filename: string): Promise<void> {
|
||||
if (!filename.endsWith('.yml')) {
|
||||
throw new Error('Filename must end with .yml');
|
||||
/**
|
||||
* Create a new stack (directory with boilerplate compose.yaml)
|
||||
*/
|
||||
async createStack(stackName: string): Promise<void> {
|
||||
// Validate stack name (no special characters, not empty)
|
||||
if (!stackName || !/^[a-zA-Z0-9_-]+$/.test(stackName)) {
|
||||
throw new Error('Stack name must contain only alphanumeric characters, underscores, or hyphens');
|
||||
}
|
||||
const filePath = path.join(this.baseDir, filename);
|
||||
const boilerplate = `version: '3.8'
|
||||
|
||||
services:
|
||||
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
|
||||
// Check if directory already exists
|
||||
try {
|
||||
await fs.access(stackDir);
|
||||
throw new Error(`Stack "${stackName}" already exists`);
|
||||
} catch (error: any) {
|
||||
if (error.message.includes('already exists')) {
|
||||
throw error;
|
||||
}
|
||||
// Directory doesn't exist, proceed
|
||||
}
|
||||
|
||||
// Create the directory
|
||||
await fs.mkdir(stackDir, { recursive: true });
|
||||
|
||||
// Write boilerplate compose.yaml
|
||||
const composePath = path.join(stackDir, 'compose.yaml');
|
||||
const boilerplate = `services:
|
||||
# Add your services here
|
||||
`;
|
||||
try {
|
||||
await fs.writeFile(filePath, boilerplate, 'utf-8');
|
||||
console.log('Stack file created successfully:', filename);
|
||||
await fs.writeFile(composePath, boilerplate, 'utf-8');
|
||||
console.log('Stack created successfully:', stackName);
|
||||
} catch (error) {
|
||||
console.error('Error creating stack file:', error);
|
||||
throw new Error(`Failed to create stack file: ${filename}`);
|
||||
console.error('Error creating stack:', error);
|
||||
throw new Error(`Failed to create stack: ${stackName}`);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteStack(filename: string): Promise<void> {
|
||||
const filePath = path.join(this.baseDir, filename);
|
||||
const envFilename = filename.replace(/\.yml$/, '.env');
|
||||
const envPath = path.join(this.baseDir, envFilename);
|
||||
/**
|
||||
* Delete a stack (entire directory and its contents)
|
||||
*/
|
||||
async deleteStack(stackName: string): Promise<void> {
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
|
||||
try {
|
||||
await fs.unlink(filePath);
|
||||
console.log('Stack file deleted successfully:', filename);
|
||||
// Try to delete env file if it exists
|
||||
await fs.rm(stackDir, { recursive: true, force: true });
|
||||
console.log('Stack deleted successfully:', stackName);
|
||||
} catch (error) {
|
||||
console.error('Error deleting stack:', error);
|
||||
throw new Error(`Failed to delete stack: ${stackName}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the base directory path for stacks
|
||||
*/
|
||||
getBaseDir(): string {
|
||||
return this.baseDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate existing flat-file stacks to directory-based structure
|
||||
* This runs automatically on server startup
|
||||
*/
|
||||
async migrateFlatToDirectory(): Promise<void> {
|
||||
try {
|
||||
// Ensure base directory exists
|
||||
try {
|
||||
await fs.unlink(envPath);
|
||||
console.log('Associated env file deleted:', envFilename);
|
||||
await fs.access(this.baseDir);
|
||||
} catch {
|
||||
// Env file doesn't exist, ignore
|
||||
console.log('Creating compose directory:', this.baseDir);
|
||||
await fs.mkdir(this.baseDir, { recursive: true });
|
||||
return; // No files to migrate in a new directory
|
||||
}
|
||||
|
||||
const items = await fs.readdir(this.baseDir, { withFileTypes: true });
|
||||
|
||||
for (const item of items) {
|
||||
// Only process .yml/.yaml files (skip directories and other files)
|
||||
if (!item.isFile()) continue;
|
||||
if (!item.name.endsWith('.yml') && !item.name.endsWith('.yaml')) continue;
|
||||
|
||||
const stackName = item.name.replace(/\.(yml|yaml)$/, '');
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
|
||||
// Check if target directory already exists
|
||||
try {
|
||||
await fs.access(stackDir);
|
||||
console.log(`Skipping migration for "${stackName}": directory already exists`);
|
||||
continue;
|
||||
} catch {
|
||||
// Directory doesn't exist, proceed with migration
|
||||
}
|
||||
|
||||
console.log(`Migrating stack: ${stackName}`);
|
||||
|
||||
// Create the stack directory
|
||||
await fs.mkdir(stackDir, { recursive: true });
|
||||
|
||||
// Move compose file to new location (standardize on compose.yaml)
|
||||
const oldComposePath = path.join(this.baseDir, item.name);
|
||||
const newComposePath = path.join(stackDir, 'compose.yaml');
|
||||
await fs.rename(oldComposePath, newComposePath);
|
||||
|
||||
// Move env file if it exists (old pattern: stackname.env)
|
||||
const oldEnvPath = path.join(this.baseDir, `${stackName}.env`);
|
||||
const newEnvPath = path.join(stackDir, '.env');
|
||||
try {
|
||||
await fs.access(oldEnvPath);
|
||||
await fs.rename(oldEnvPath, newEnvPath);
|
||||
console.log(`Migrated env file for: ${stackName}`);
|
||||
} catch {
|
||||
// No env file to migrate, that's fine
|
||||
}
|
||||
|
||||
console.log(`Successfully migrated stack: ${stackName}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting stack file:', error);
|
||||
throw new Error(`Failed to delete stack file: ${filename}`);
|
||||
console.error('Migration error:', error);
|
||||
// Don't throw - allow the server to start even if migration fails
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user