|
| 1 | +import { spawn, SpawnOptions, exec } from "child_process"; |
| 2 | +import fs from "fs"; |
| 3 | +import { z } from "zod"; |
| 4 | +import { promisify } from 'util'; |
| 5 | + |
| 6 | +const execAsync = promisify(exec); |
| 7 | + |
| 8 | +const NULL_DEVICE = "/dev/null"; |
| 9 | + |
| 10 | +const COMMAND = "docker"; |
| 11 | + |
| 12 | +type CommandResult = Promise<string>; |
| 13 | + |
| 14 | +const PS_PATTERN = "\"{psID: {{.ID}}, psName: {{.Names}}, workspaceFolder: {{.Label \"devcontainer.local_folder\"}}, container: {{.Label \"dev.containers.id\"}}}\"" |
| 15 | + |
| 16 | +export const DevCleanupSchema = z.object({}); |
| 17 | + |
| 18 | +export const DevListSchema = z.object({}); |
| 19 | + |
| 20 | +type DevCleanupArgs = z.infer<typeof DevCleanupSchema>; |
| 21 | +type DevListArgs = z.infer<typeof DevListSchema>; |
| 22 | + |
| 23 | +function createOutputStream( |
| 24 | + stdioFilePath: string = NULL_DEVICE |
| 25 | +): fs.WriteStream { |
| 26 | + try { |
| 27 | + return fs.createWriteStream(stdioFilePath, { flags: "w" }); |
| 28 | + } catch (error) { |
| 29 | + throw new Error( |
| 30 | + `Failed to create output stream: ${(error as Error).message}` |
| 31 | + ); |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +async function runCommand( |
| 36 | + args: string[], |
| 37 | + stdoutStream: fs.WriteStream |
| 38 | +): CommandResult { |
| 39 | + return new Promise((resolve, reject) => { |
| 40 | + const child = spawn(COMMAND, [...args], { |
| 41 | + stdio: ["ignore", "pipe", "pipe"], |
| 42 | + } as SpawnOptions); |
| 43 | + |
| 44 | + const stdoutData: string[] = []; |
| 45 | + const stderrData: string[] = []; |
| 46 | + |
| 47 | + child.on("error", (error) => { |
| 48 | + cleanup(error); |
| 49 | + reject(new Error(`Process spawn failed: ${error.message}`)); |
| 50 | + }); |
| 51 | + |
| 52 | + // Pipe stdout to the stream as before, but also collect it |
| 53 | + child.stdout?.on("data", (data) => { |
| 54 | + stdoutData.push(data.toString()); |
| 55 | + stdoutStream.write(data); |
| 56 | + }); |
| 57 | + |
| 58 | + // Collect stderr data instead of piping to process.stderr |
| 59 | + child.stderr?.on("data", (data) => { |
| 60 | + stderrData.push(data.toString().trim()); |
| 61 | + }); |
| 62 | + |
| 63 | + const cleanup = (error?: Error) => { |
| 64 | + child.stdout?.removeAllListeners(); |
| 65 | + child.stderr?.removeAllListeners(); |
| 66 | + if (!stdoutStream.writableEnded) { |
| 67 | + stdoutStream.end(); |
| 68 | + } |
| 69 | + if (error) { |
| 70 | + stdoutStream.destroy(); |
| 71 | + } |
| 72 | + }; |
| 73 | + |
| 74 | + child.on("close", (code, signal) => { |
| 75 | + cleanup(); |
| 76 | + if (code === 0) { |
| 77 | + resolve( |
| 78 | + `success with code ${code}\n-------\n${stdoutData.join("\n\n")}` |
| 79 | + ); |
| 80 | + } else { |
| 81 | + const reason = signal |
| 82 | + ? `terminated by signal ${signal}` |
| 83 | + : `exited with code ${code}`; |
| 84 | + |
| 85 | + // Combine the error message with the collected stderr output |
| 86 | + const errorMessage = `Command failed: ${COMMAND} ${args.join( |
| 87 | + " " |
| 88 | + )} (${reason})\n-------\n${stderrData.join("\n\n")}`; |
| 89 | + reject(new Error(errorMessage)); |
| 90 | + } |
| 91 | + }); |
| 92 | + }); |
| 93 | +} |
| 94 | + |
| 95 | +export async function devCleanup(options: DevCleanupArgs): CommandResult { |
| 96 | + void options; |
| 97 | + const stream = createOutputStream(NULL_DEVICE); |
| 98 | + |
| 99 | + let ids: string[]; |
| 100 | + |
| 101 | + try { |
| 102 | + const { stdout } = await execAsync("docker ps -aq -f label=dev.containers.id") |
| 103 | + const raw = stdout.toString().trim(); |
| 104 | + ids = raw ? raw.split("\n") : []; |
| 105 | + } catch (error) { |
| 106 | + return Promise.reject(`Cannot list all docker ps: ${(error as Error).message}`); |
| 107 | + } |
| 108 | + |
| 109 | + if (ids.length === 0) { |
| 110 | + return Promise.resolve( |
| 111 | + "No 'docker ps' results found; all devcontainers have already been cleaned up." |
| 112 | + ); |
| 113 | + } |
| 114 | + |
| 115 | + return runCommand(["rm", "-f", ...ids], stream); |
| 116 | +} |
| 117 | + |
| 118 | +export async function devList(options: DevListArgs): CommandResult { |
| 119 | + void options; |
| 120 | + const stream = createOutputStream(NULL_DEVICE); |
| 121 | + |
| 122 | + return runCommand( |
| 123 | + ["ps", "-a", "--filter", "label=dev.containers.id", "--format", PS_PATTERN], |
| 124 | + stream |
| 125 | + ); |
| 126 | +} |
0 commit comments