-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathrunDockerCommand.ts
More file actions
60 lines (53 loc) · 1.41 KB
/
runDockerCommand.ts
File metadata and controls
60 lines (53 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { execFile } from 'node:child_process';
export type RunDockerCommandParameters = {
image: string;
command?: string[];
entrypoint?: string;
env?: Record<string, string | undefined>;
};
export type RunDockerCommandResult = {
argv: string[];
stdout: string;
stderr: string;
exitCode: number;
};
export function runDockerCommand(
params: RunDockerCommandParameters,
): Promise<RunDockerCommandResult> {
const envEntries = Object.entries(params.env ?? {}).filter((entry) => entry[1] !== undefined);
const argv = [
'docker',
'run',
'--rm',
...envEntries.flatMap(([name]) => ['--env', name]),
...(params.entrypoint ? ['--entrypoint', params.entrypoint] : []),
params.image,
...(params.command ?? []),
];
const environment = {
...process.env,
...Object.fromEntries(envEntries),
};
return new Promise((resolve, reject) => {
execFile('docker', argv.slice(1), { env: environment }, (error, stdout, stderr) => {
if (error) {
return reject(
Object.assign(new Error(`Docker command failed: ${error.message}`), {
name: 'RunDockerCommandError',
argv,
stdout,
stderr,
exitCode: typeof error.code === 'number' ? error.code : 1,
cause: error,
}),
);
}
resolve({
argv,
stdout,
stderr,
exitCode: 0,
});
});
});
}