Skip to content

Modern Docker Management, Designed for Everyone

2.7 KB
Raw Blame
import { execFileSync } from 'child_process';
import { captureComposeDiagnostics } from './global-setup';
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function globalTeardown() {
	console.log('\nStarting global teardown...');

	const composeFile = process.env.COMPOSE_FILE
		? path.resolve(__dirname, '..', process.env.COMPOSE_FILE)
		: path.resolve(__dirname, 'compose.yaml');
	const projectsDir = path.resolve(__dirname, 'projects');
	const failures: unknown[] = [];
	captureComposeDiagnostics(composeFile);

	// 1. Stop and remove Docker containers
	try {
		console.log('Stopping Docker containers...');
		execFileSync('docker', ['compose', '-f', composeFile, 'down', '-v'], {
			stdio: 'inherit',
			timeout: 60_000
		});
		console.log('Docker containers stopped and volumes removed.');
	} catch (error) {
		failures.push(error);
		console.error('Warning: Failed to stop Docker containers cleanly:', error);
	}

	// 2. Clean up test projects created on disk
	try {
		if (fs.existsSync(projectsDir)) {
			console.log('Cleaning up test projects...');
			const items = fs.readdirSync(projectsDir);

			for (const item of items) {
				const itemPath = path.join(projectsDir, item);

				// Keep .env.global and test-project-static if they exist, remove everything else that looks like a test project
				if (item === '.env.global' || item === 'test-project-static') continue;

				if (fs.lstatSync(itemPath).isDirectory()) {
					try {
						fs.rmSync(itemPath, { recursive: true, force: true });
					} catch (err) {
						if (
							err instanceof Error &&
							'code' in err &&
							(err.code === 'EACCES' || err.code === 'EPERM')
						) {
							// Arcane container creates files as root, fallback to docker to remove them
							execFileSync(
								'docker',
								[
									'run',
									'--rm',
									'-v',
									`${projectsDir}:/projects`,
									'public.ecr.aws/docker/library/alpine:3.20',
									'sh',
									'-c',
									'rm -rf "/projects/$1"',
									'--',
									item
								],
								{ stdio: 'inherit', timeout: 30_000 }
							);
						} else {
							throw err;
						}
					}
					console.log(`   - Removed directory: ${item}`);
				} else if (item.startsWith('test-project-')) {
					fs.unlinkSync(itemPath);
					console.log(`   - Removed file: ${item}`);
				}
			}
		}
	} catch (error) {
		failures.push(error);
		console.error('Warning: Failed to clean up projects directory:', error);
	}

	if (failures.length > 0) throw new AggregateError(failures, 'E2E environment cleanup failed');
	console.log('Global teardown complete.\n');
}

export default globalTeardown;