-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathscripts.ts
More file actions
244 lines (212 loc) · 6.42 KB
/
scripts.ts
File metadata and controls
244 lines (212 loc) · 6.42 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
/**
* Script executor — resolves and runs scripts from .eser/manifest.yml.
*
* Supports:
* - String shorthand: `ok: "eser workflows run -e precommit"`
* - Object form: `{ command, description, workingDirectory, depends }`
* - Dependency resolution with cycle detection
* - Arg passing (remaining CLI args appended to command)
*
* @module
*/
import * as shellExec from "@eserstack/shell/exec";
import * as results from "@eserstack/primitives/results";
import * as span from "@eserstack/streams/span";
import * as streams from "@eserstack/streams";
import { runtime } from "@eserstack/standards/cross-runtime";
import type * as shellArgs from "@eserstack/shell/args";
import type { ScriptConfig } from "@eserstack/workflows/mod";
/** Parsed representation of a script config entry. */
type ParsedScript = {
readonly command: string;
readonly description: string;
readonly workingDirectory: string | undefined;
readonly depends: readonly string[];
};
/**
* Parse a script config entry into a normalized form.
*
* String values are treated as the command with sensible defaults.
* Object values have their fields extracted with defaults applied.
*/
export const parseScript = (
name: string,
config: ScriptConfig,
): ParsedScript => {
if (typeof config === "string") {
return {
command: config,
description: name,
workingDirectory: undefined,
depends: [],
};
}
return {
command: config.command,
description: config.description ?? name,
workingDirectory: config.workingDirectory,
depends: config.depends ?? [],
};
};
/**
* Resolve the dependency graph for a script using topological DFS.
*
* Returns an ordered list of script names that must execute before
* the target script. Throws on circular or missing dependencies.
*/
export const resolveDependencies = (
name: string,
scripts: Readonly<Record<string, ScriptConfig>>,
visited: Set<string> = new Set(),
resolved: Set<string> = new Set(),
): readonly string[] => {
if (resolved.has(name)) {
return [];
}
if (visited.has(name)) {
throw new Error(
`Circular dependency detected: ${name} depends on itself (cycle in dependency chain)`,
);
}
const config = scripts[name];
if (config === undefined) {
throw new Error(`Unknown script dependency: "${name}"`);
}
visited.add(name);
const parsed = parseScript(name, config);
const order: string[] = [];
for (const dep of parsed.depends) {
const depOrder = resolveDependencies(dep, scripts, visited, resolved);
for (const d of depOrder) {
if (!resolved.has(d)) {
order.push(d);
resolved.add(d);
}
}
}
resolved.add(name);
return order;
};
/**
* Resolve the CLI self-invocation prefix.
*
* When scripts reference `eser` as a command, we replace it with the
* current runtime's exec path + the CLI entrypoint so scripts work
* without requiring a global `eser` installation.
*/
const resolveCliPrefix = (): string => {
const mainUrl = new URL("./main.ts", import.meta.url);
const mainPath = mainUrl.protocol === "file:"
? mainUrl.pathname
: mainUrl.href;
const execPath = runtime.process.execPath();
return `${execPath} run --allow-all ${mainPath}`;
};
/**
* Replace a leading `eser ` token in a command with the resolved CLI
* self-invocation so scripts work in development without a global install.
*/
const resolveCommand = (command: string): string => {
if (command === "eser" || command.startsWith("eser ")) {
const rest = command.slice("eser".length);
return `${resolveCliPrefix()}${rest}`;
}
return command;
};
/**
* Execute a shell command string, optionally in a working directory
* and with extra arguments appended.
*
* Returns the process exit code.
*/
export const executeCommand = async (
command: string,
workingDirectory?: string,
extraArgs?: readonly string[],
): Promise<number> => {
const resolved = resolveCommand(command);
const fullCommand = (extraArgs !== undefined && extraArgs.length > 0)
? `${resolved} ${extraArgs.join(" ")}`
: resolved;
const cwd = workingDirectory ?? ".";
const builder = new shellExec.CommandBuilder("sh", ["-c", fullCommand])
.cwd(cwd)
.stdin("inherit")
.stdout("inherit")
.stderr("inherit")
.noThrow();
const output = await builder.spawn();
return output.code;
};
/**
* Run a script by name, resolving and executing its dependencies first.
*
* Dependencies are executed without extra args. The main script receives
* any remaining CLI arguments appended to its command.
*/
export const runScript = async (
name: string,
_config: ScriptConfig,
scripts: Readonly<Record<string, ScriptConfig>>,
remainingArgs: readonly string[],
): Promise<shellArgs.CliResult<void>> => {
const out = streams.output({
renderer: streams.renderers.ansi(),
sink: streams.sinks.stdout(),
});
// Resolve dependency order
const deps = resolveDependencies(name, scripts);
// Execute dependencies first (no extra args)
for (const dep of deps) {
const depParsed = parseScript(dep, scripts[dep]!);
out.writeln(span.dim(`$ ${dep}`));
const depCode = await executeCommand(
depParsed.command,
depParsed.workingDirectory,
);
if (depCode !== 0) {
out.writeln(
span.red(
`Script dependency "${dep}" failed with exit code ${depCode}`,
),
);
await out.close();
return results.fail({ exitCode: depCode });
}
}
// Execute the main script
const parsed = parseScript(name, scripts[name]!);
out.writeln(span.dim(`$ ${name}`));
const exitCode = await executeCommand(
parsed.command,
parsed.workingDirectory,
remainingArgs,
);
if (exitCode !== 0) {
await out.close();
return results.fail({ exitCode });
}
await out.close();
return results.ok(undefined);
};
/**
* Print a formatted list of available scripts for the help display.
*/
export const showScripts = (
scripts: Readonly<Record<string, ScriptConfig>>,
): void => {
const out = streams.output({
renderer: streams.renderers.ansi(),
sink: streams.sinks.stdout(),
});
out.writeln(span.text("Scripts:"));
for (const [name, config] of Object.entries(scripts)) {
const parsed = parseScript(name, config);
out.writeln(
span.text(` ${name.padEnd(20)} `),
span.dim(parsed.description),
);
}
out.writeln();
};