-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
411 lines (387 loc) · 11.2 KB
/
utils.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import { exec, ExecOptions, spawn } from "child_process";
import fs from "fs";
import http from "http";
import https from "https";
import { readdirSync } from "node:fs";
import os from "os";
import path from "path";
import { SSH_HOST } from "./config.js";
// IN THE FUTURE: import conf from "./package.json" with {type:"json"};
import {
BLUE,
GRAY,
GREEN,
NORMAL_COLOR,
RED,
REMOVE_INVISIBLE,
YELLOW,
exit,
output,
spinner_start,
spinner_stop,
timer_start,
timer_stop,
} from "./prompt.js";
import { PathTo } from "./types.js";
import { createRequire } from "node:module";
import { stdout } from "process";
const require = createRequire(import.meta.url);
export const package_json = require("./package.json");
export const lowercase = "abcdefghijklmnopqrstuvwxyz";
export const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
export const digits = "0123456789";
export const underscore = "_";
export const dash = "-";
export const all = lowercase + uppercase + digits + underscore + dash;
export function generateString(length: number, alphabet: string) {
let result = "";
for (let i = 0; i < length; i++) {
result += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}
return result;
}
export class Path {
constructor(private offset = ".") {
let end = this.offset.length;
while (this.offset.charAt(end - 1) === "/") end--;
this.offset = this.offset.substring(0, end);
if (this.offset.length === 0) this.offset = ".";
}
with(next: string) {
return new Path(path.join(this.offset, next));
}
withoutLastUp() {
return new Path(this.offset.substring(0, this.offset.lastIndexOf("..")));
}
toString() {
return this.offset;
}
}
export function getFiles(path: PathTo): string[] {
return getFiles_internal(path, "");
}
function getFiles_internal(path: PathTo, prefix: string): string[] {
if (!fs.existsSync(path.toString())) return [];
return readdirSync(path.toString(), { withFileTypes: true }).flatMap((x) =>
x.isDirectory()
? getFiles_internal(path.with(x.name), prefix + x.name + "/")
: [prefix + x.name]
);
}
const toExecute: (() => Promise<unknown>)[] = [];
let dryrun = false;
export function setDryrun() {
outputGit(
`${BLUE}Dryrun mode, changes will not be performed.${NORMAL_COLOR}`
);
dryrun = true;
}
export function addToExecuteQueue(f: () => Promise<unknown>) {
if (!dryrun) toExecute.push(f);
}
let printOnExit: string[] = [];
export function addExitMessage(str: string) {
printOnExit.push(str);
}
function printExitMessages() {
printOnExit.forEach((x) => output(x + "\n"));
}
export function abort(): never {
exit();
printExitMessages();
process.exit(0);
}
export async function finish(): Promise<never> {
try {
exit();
for (let i = 0; i < toExecute.length; i++) {
await toExecute[i]();
}
printExitMessages();
process.exit(0);
} catch (e) {
throw e;
}
}
export function TODO(): never {
console.log("TODO");
exit();
process.exit(0);
}
export interface OrgFile {
organizationId: string;
}
interface CacheFile {
registered: boolean;
hasOrgs: boolean;
}
export function getCache(): CacheFile {
if (!fs.existsSync(`${historyFolder}cache`)) {
return { registered: false, hasOrgs: false };
}
return JSON.parse(fs.readFileSync(`${historyFolder}cache`).toString());
}
export function saveCache(cache: CacheFile) {
fs.writeFileSync(`${historyFolder}cache`, JSON.stringify(cache));
}
export function fetchOrgRaw() {
if (fs.existsSync(path.join(".merrymake", "conf.json"))) {
const org: OrgFile = JSON.parse(
"" + fs.readFileSync(path.join(".merrymake", "conf.json"))
);
return { org, serviceGroup: null, pathToRoot: "." + path.sep };
}
const cwd = process.cwd().split(/\/|\\/);
let out = "";
let folder = path.sep;
let serviceGroup: string | null = null;
for (let i = cwd.length - 1; i >= 0; i--) {
if (fs.existsSync(out + path.join("..", ".merrymake", "conf.json"))) {
serviceGroup = cwd[i];
const org = <OrgFile>(
JSON.parse(
"" + fs.readFileSync(path.join(`${out}..`, `.merrymake`, `conf.json`))
)
);
return { org, serviceGroup, pathToRoot: out + ".." + path.sep };
}
folder = path.sep + cwd[i] + folder;
out += ".." + path.sep;
}
return { org: null, serviceGroup: null, pathToRoot: null };
}
export function fetchOrg() {
const res = fetchOrgRaw();
if (res.org === null) throw "Not inside a Merrymake organization";
return res;
}
export function printWithPrefix(str: string, prefix: string = "") {
const prefixLength = prefix.replace(REMOVE_INVISIBLE, "").length;
console.log(
prefix +
str
.trimEnd()
.split("\n")
.flatMap((x) =>
(
x.match(
new RegExp(
`.{1,${stdout.getWindowSize()[0] - prefixLength}}( |$)|.{1,${
stdout.getWindowSize()[0] - prefixLength
}}`,
"g"
)
) || []
).map((x) => x.trimEnd())
)
.join(`\n${prefix}`)
);
}
export function outputGit(str: string) {
const st = (str || "").trimEnd();
if (st.endsWith("elapsed")) {
return;
} else {
const wasRunning = timer_stop();
if (wasRunning) process.stdout.write(`\n`);
}
console.log(
st
.split("\n")
.map((x) => {
const lineParts = x.trimEnd().split("remote: ");
const line = lineParts[lineParts.length - 1];
const color =
line.match(/fail|error|fatal/i) !== null
? RED
: line.match(/warn/i) !== null
? YELLOW
: line.match(/succe/i) !== null
? GREEN
: NORMAL_COLOR;
const commands = line.split("'mm");
for (let i = 1; i < commands.length; i++) {
const ind = commands[i].indexOf("'");
const cmd = commands[i].substring(0, ind);
const rest = commands[i].substring(ind);
commands[i] = `'${YELLOW}mm ${cmd}${color}${rest}`;
}
lineParts[lineParts.length - 1] =
color + commands.join("") + NORMAL_COLOR;
return lineParts.join(`${GRAY}remote: `);
})
.join("\n")
);
if (st.endsWith("(this may take a few minutes)...")) {
process.stdout.write(`${GRAY}remote: ${NORMAL_COLOR} `);
timer_start("s elapsed");
}
}
function versionIsOlder(old: string, new_: string) {
const os = old.split(".");
const ns = new_.split(".");
if (+os[0] < +ns[0]) return true;
else if (+os[0] > +ns[0]) return false;
else if (+os[1] < +ns[1]) return true;
else if (+os[1] > +ns[1]) return false;
else if (+os[2] < +ns[2]) return true;
return false;
}
export function execPromise(cmd: string, cwd?: string) {
return new Promise<string>((resolve, reject) => {
const a = exec(cmd, { cwd }, (error, stdout, stderr) => {
const err = error?.message || stderr;
if (err) {
reject(stderr || stdout);
} else {
resolve(stdout);
}
});
});
}
const historyFolder = os.homedir() + "/.merrymake/";
const historyFile = "history";
const updateFile = "last_update_check";
export async function checkVersion() {
if (!fs.existsSync(historyFolder)) fs.mkdirSync(historyFolder);
const lastCheck = fs.existsSync(historyFolder + updateFile)
? +fs.readFileSync(historyFolder + updateFile).toString()
: 0;
if (Date.now() - lastCheck > 4 * 60 * 60 * 1000) {
try {
const call = await execPromise(
"npm show @merrymake/cli dist-tags --json"
);
const version: { latest: string } = JSON.parse(call);
if (versionIsOlder(package_json.version, version.latest)) {
addExitMessage(`
New version of merrymake-cli available, ${process.env["UPDATE_MESSAGE"]}`);
}
} catch (e) {}
fs.writeFileSync(historyFolder + updateFile, "" + Date.now());
}
}
export function typedKeys<T extends object>(o: T): Array<keyof T> {
return Object.keys(o) as any;
}
export function execStreamPromise(
full: string,
onData: (_: string) => void,
cwd?: string
) {
return new Promise<void>((resolve, reject) => {
const [cmd, ...args] = full.split(" ");
const p = spawn(cmd, args, { cwd, shell: "sh" });
p.stdout.on("data", (data) => {
onData(data.toString());
});
p.stderr.on("data", (data) => {
console.log(data.toString());
});
p.on("exit", (code) => {
if (code !== 0) reject("subprocess failed");
else resolve();
});
});
}
export function spawnPromise(str: string) {
return new Promise<void>((resolve, reject) => {
const [cmd, ...args] = str.split(" ");
const options: ExecOptions = {
cwd: ".",
shell: "sh",
};
const ls = spawn(cmd, args, options);
ls.stdout.on("data", (data: Buffer | string) => {
outputGit(data.toString());
});
ls.stderr.on("data", (data: Buffer | string) => {
outputGit(data.toString());
});
ls.on("close", (code) => {
if (code === 0) resolve();
else reject();
});
});
}
function sshReqInternal(cmd: string) {
return execPromise(`ssh -o ConnectTimeout=10 mist@${SSH_HOST} "${cmd}"`);
}
export async function sshReq(...cmd: string[]) {
try {
spinner_start();
const result = await sshReqInternal(
cmd
.map((x) => (x.length === 0 || x.includes(" ") ? `\\"${x}\\"` : x))
.join(" ")
);
spinner_stop();
return result;
} catch (e) {
throw e;
}
}
export function partition(str: string, radix: string) {
const index = str.indexOf(radix);
if (index < 0) return [str, ""];
return [str.substring(0, index), str.substring(index + radix.length)];
}
export function urlReq(
url: string,
method: "POST" | "GET" = "GET",
data?: string,
contentType = "application/json"
) {
return new Promise<{ body: string; code: number | undefined }>(
(resolve, reject) => {
const [protocol, fullPath] =
url.indexOf("://") >= 0 ? partition(url, "://") : ["http", url];
const [base, path] = partition(fullPath, "/");
const [host, port] = partition(base, ":");
let headers;
if (data !== undefined)
headers = {
"Content-Type": contentType,
"Content-Length": data.length,
};
const sender = protocol === "http" ? http : https;
const req = sender.request(
{
host,
port,
path: "/" + path,
method,
headers,
},
(resp) => {
let str = "";
resp.on("data", (chunk) => {
str += chunk;
});
resp.on("end", () => {
resolve({ body: str, code: resp.statusCode });
});
}
);
req.on("error", (e) => {
reject(
`Unable to connect to ${host}. Please verify your internet connection.`
);
});
if (data !== undefined) req.write(data);
req.end();
}
);
}
export function directoryNames(path: PathTo, exclude: string[]) {
if (!fs.existsSync(path.toString())) return [];
return fs
.readdirSync(path.toString(), { withFileTypes: true })
.filter(
(x) =>
x.isDirectory() && !exclude.includes(x.name) && !x.name.startsWith(".")
);
}
export function toFolderName(str: string) {
return str.toLowerCase().replace(/[^a-z0-9\-_]/g, "-");
}