-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
run.ts
249 lines (219 loc) · 7.21 KB
/
run.ts
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
245
246
247
248
249
// deno-lint-ignore-file no-inner-declarations
/**
* Copyright (c) Crew Dev.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { parseToYaml } from "../tools/parse_to_yaml.ts";
import { Match } from "../utils/file_resolver.ts";
import type { runJson } from "../utils/types.ts";
import { exists, readJson } from "tools-fs";
import { isGH } from "../utils/storage.ts";
import * as colors from "fmt/colors.ts";
import { join } from "path/mod.ts";
const { red, yellow, green } = colors;
const { env, run } = Deno;
/**
* execute subprocess script
* @param command
*/
export async function Run(command: string, runArgs: string[] = []) {
let prefix = (await exists("./run.json")) ? "json" : "yaml";
if (
!(await exists("./run.json")) &&
!(await exists("./run.yaml")) &&
!(await exists("./run.yml"))
) {
throw new Error(red(`: ${yellow("run.json or run.yaml not found")}`))
.message;
}
if (
(await exists("./run.json")) &&
((await exists("./run.yaml")) || (await exists("./run.yml")))
) {
throw new Error(
red(`: ${yellow("use a single format run.json or run.yaml file")}`),
).message;
} else {
async function Thread() {
try {
const runJsonFile = await Scripts();
if (!runJsonFile?.scripts) {
throw new Error(
red(
`: ${
yellow(`the 'scripts' key not found in run.${prefix} file`)
}`,
),
).message;
}
const scripts = Object.keys(runJsonFile.scripts);
const toRun = scripts
.map((key) => key === command ? runJsonFile.scripts[key] : undefined)
.filter((el) => !!el) as string[];
if (!toRun.length) {
throw new Error(red(`: ${yellow("command not found")}`)).message;
}
// normalize command
const runnerCommand = toRun[0].split(" ").filter((arg) => !!arg);
// github action fallback deno dir path
const ghFallBack = Match(Deno.build.os)
.case("darwin", () => "/Users/runner/.deno/bin")
.case("linux", () => "/home/runner/.deno/bin")
.case("windows", () => "C:\\Users\\runneradmin\\.deno\\bin")
.default()
.Value() as string;
// get path to deno scripts
const scriptPath = isGH ? ghFallBack : Deno.build.os === "windows"
// to windows base
? join(
"C:",
"Users",
env.get("USERNAME")!,
".deno",
"bin",
runnerCommand[0],
)
// to unix base
: join(env.get("HOME")!, ".deno", "bin", runnerCommand[0]);
// prevent deno scrips not found error
if ((await exists(scriptPath)) || (await exists(`${scriptPath}.cmd`))) {
if (Deno.build.os === "linux" || Deno.build.os === "darwin") {
runnerCommand[0] = scriptPath;
} else if (Deno.build.os === "windows") {
runnerCommand[0] = `${runnerCommand[0]}.cmd`;
}
}
const [currentCMD, execCommand] = [
["trex", "run", command].join(" "),
[...runnerCommand]
.map((cmd) => cmd?.trim())
.join(" ")
.replaceAll(".cmd", ""),
];
const last = execCommand.split("/");
// remove path to compare on unix base os
const toCompare =
Deno.build.os === "linux" || Deno.build.os === "darwin"
? last[last.length - 1]
: execCommand;
// prevent circular call
if (currentCMD === toCompare) {
throw new EvalError(
`${yellow("Circular call found in: ")}${red(toRun[0])}`,
).message;
}
const process = run({
cmd: [...runnerCommand, ...runArgs].map((command, index) =>
command === "deno" && (index === 0 || index === 1)
? ResolveDenoPath()
: command
),
stderr: "piped",
stdout: "inherit",
env: env.toObject(),
cwd: Deno.cwd(),
});
const [status] = await Promise.all([
process.status(),
]);
if (!(await process.status()).success) {
Deno.close(process.rid);
throw new Error(`Error: running command ${red(toRun[0])}`).message;
}
Deno.close(process.rid);
} catch (err) {
throw new Error(
err instanceof SyntaxError
? red(
`the ${yellow(`'run.${prefix}'`)} file not have a valid syntax`,
)
: err instanceof Deno.errors.NotFound
? red(err.message)
: yellow(err.message ?? `${err}`),
).message;
}
}
const filesToWatch = prefix === "json"
? ((await readJson("./run.json")) as runJson)
: await parseToYaml();
const watchFlags = Deno.args[2] === "--watch" ||
Deno.args[2] === "-w" ||
Deno.args[2] === "-wv";
// run using trp (trex reboot protocol)
if (filesToWatch?.files && watchFlags) {
const files = filesToWatch.files.length ? [...filesToWatch.files] : ["."];
let throttle = 700;
let timeout: number | null = null;
function logMessages(verbose?: Deno.FsEvent) {
console.clear();
console.log(green("[Reboot protocol]"));
console.log(green("[*] watching files:"));
console.info(
red(
`[#] exit using ctrl+c \n ${
filesToWatch?.files?.length
? filesToWatch.files
.map((file: string) => {
console.log(" |- ", yellow(join(file)));
return "";
})
.join("")
: (console.log(
` |- ${yellow("all files [ .* ]")}`,
) as undefined) ?? ""
} `,
),
);
if (Deno.args[2] === "-wv" && verbose) {
console.log(
green(` ╭─ Verbose output ${yellow("-wv")}:\n`),
green(`│- Event Kind: ${yellow(verbose?.kind)}\n`),
green(`╰─ Path: ${yellow(verbose?.paths.join(""))}\n`),
);
}
}
logMessages();
await Thread();
for await (const event of Deno.watchFs(files, { recursive: true })) {
if (event.kind !== "access") {
if (timeout) clearTimeout(timeout);
console.log(yellow("reloading..."));
logMessages(event);
timeout = setTimeout(Thread, throttle);
}
}
} // run a single exec thread
else {
await Thread();
}
}
}
/**
* return run.json, run.yml .yaml info file
*/
export async function Scripts() {
let prefix = (await exists("./run.json")) ? "json" : "yaml";
const runJsonFile = prefix === "json"
? ((await readJson("./run.json")) as runJson)
: await parseToYaml();
return runJsonFile;
}
/**
* resolve deno bin path.
*/
export function ResolveDenoPath() {
let fallback = "deno";
switch (Deno.build.os) {
case "linux":
fallback = `${Deno.env.get("HOME")}/.deno/bin/deno`;
break;
case "darwin":
// TODO(buttercubz) resolve macos path
break;
case "windows":
break;
}
return Deno.execPath() ?? fallback;
}