-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.js
More file actions
217 lines (217 loc) · 6.99 KB
/
utils.js
File metadata and controls
217 lines (217 loc) · 6.99 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
import { exec, spawn } from "child_process";
import { existsSync } from "fs";
import http from "http";
import https from "https";
import path from "path";
import { SSH_HOST, SSH_USER } from "./config.js";
import { MEGABYTES, Obj, Promise_all, Str } from "@merrymake/utils";
import { debugLog } from "./printUtils.js";
import { readdir, readFile } from "fs/promises";
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, ...alphabets) {
const alphabet = alphabets.join("");
const result = new Array(length);
for (let i = 0; i < length; i++) {
result.push(alphabet.charAt(Math.floor(Math.random() * alphabet.length)));
}
return result.join("");
}
export class Path {
offset;
constructor(offset = ".") {
this.offset = 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) {
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) {
return getFiles_internal(path, "");
}
async function getFiles_internal(path, prefix) {
try {
if (!existsSync(path.toString()))
return [];
return (await Promise_all(...(await readdir(path.toString(), { withFileTypes: true }).then()).map((x) => x.isDirectory()
? getFiles_internal(path.with(x.name), prefix + x.name + "/")
: Promise.resolve([prefix + x.name]))).then()).flat();
}
catch (e) {
throw e;
}
}
export async function fetchOrgRaw() {
try {
if (existsSync(path.join(".merrymake", "conf.json"))) {
const org = JSON.parse(await readFile(path.join(".merrymake", "conf.json"), "utf-8"));
return { org, serviceGroup: null, pathToRoot: "." + path.sep };
}
const cwd = process.cwd().split(/\/|\\/);
let out = "";
let folder = path.sep;
let serviceGroup = null;
for (let i = cwd.length - 1; i >= 0; i--) {
if (existsSync(out + path.join("..", ".merrymake", "conf.json"))) {
serviceGroup = cwd[i];
const org = (JSON.parse("" + readFile(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 };
}
catch (e) {
throw e;
}
}
export async function fetchOrg() {
try {
const res = await fetchOrgRaw();
if (res.org === null)
throw "Not inside a Merrymake organization";
return res;
}
catch (e) {
throw e;
}
}
export function execPromise(cmd, cwd) {
return new Promise((resolve, reject) => {
debugLog(cmd);
exec(cmd, { cwd, maxBuffer: 10 * MEGABYTES }, (error, stdout, stderr) => {
const errors = [];
if (error !== null) {
if (error.message.length > 0)
errors.push(error.message);
else
errors.push(error);
if (stderr.length > 0)
errors.push(stderr);
}
if (errors.length > 0) {
reject({ cmd, errors, stdout });
}
else {
resolve(stdout);
}
});
});
}
export function typedKeys(o) {
return Object.keys(o);
}
export function execStreamPromise(full, onData, cwd) {
return new Promise((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();
});
});
}
function sshReqInternal(cmd) {
return execPromise(`ssh -o ConnectTimeout=10 ${SSH_USER}@${SSH_HOST} "${cmd}"`);
}
export async function sshReq(...cmd) {
const spinner = typeof process.stdout.moveCursor === "function"
? Str.Spinner.start()
: undefined;
try {
const result = await sshReqInternal(cmd
.map((x) => (x.length === 0 || x.includes(" ") ? `\\"${x}\\"` : x))
.join(" "));
return result;
}
catch (e) {
if (Obj.hasKey("stdout", e))
throw e.stdout;
throw e;
}
finally {
spinner?.stop();
}
}
export function urlReq(url, method = "GET", data, contentType = "application/json") {
return new Promise((resolve, reject) => {
const [protocol, fullPath] = url.indexOf("://") >= 0 ? Str.partitionLeft(url, "://") : ["http", url];
const [base, path] = Str.partitionLeft(fullPath, "/");
const [host, port] = Str.partitionLeft(base, ":");
let headers;
if (data !== undefined)
headers = {
"Content-Type": contentType,
"Content-Length": data.length,
};
const sender = protocol === "http" ? http : https;
const before = Date.now();
const req = sender.request({
host,
port,
path: "/" + path,
method,
headers,
}, (resp) => {
let str = "";
resp.on("data", (chunk) => {
str += chunk;
});
resp.on("end", () => {
const after = Date.now();
resolve({
body: str,
code: resp.statusCode,
time: after - before,
});
});
});
req.on("error", (e) => {
reject(`Unable to connect to ${host}. Please verify your internet connection.`);
});
if (data !== undefined)
req.write(data);
req.end();
});
}
export async function directoryNames(path, exclude) {
try {
if (!existsSync(path.toString()))
return [];
return (await readdir(path.toString(), { withFileTypes: true })).filter((x) => x.isDirectory() && !exclude.includes(x.name) && !x.name.startsWith("."));
}
catch (e) {
throw e;
}
}
export function toSubdomain(displayName) {
return displayName
.toLowerCase()
.replace(/[ _]/g, "-")
.replace(/[^a-z0-9\-]/g, ""); // Remove special characters
}