forked from remix-run/react-router
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
315 lines (273 loc) · 8.9 KB
/
Copy pathutils.ts
File metadata and controls
315 lines (273 loc) · 8.9 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
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
import fs from "node:fs";
import { readdir } from "node:fs/promises";
import path from "node:path";
import process from "node:process";
import os from "node:os";
import { type Key as ActionKey } from "node:readline";
import { erase, cursor } from "sisteransi";
import pc from "picocolors";
// https://no-color.org/
// picocolors natively respects NO_COLOR and FORCE_COLOR env vars
const SUPPORTS_COLOR = pc.isColorSupported;
export const color = {
supportsColor: SUPPORTS_COLOR,
heading: safeColor(pc.bold),
arg: safeColor(pc.yellowBright),
error: safeColor(pc.red),
warning: safeColor(pc.yellow),
hint: safeColor(pc.blue),
bold: safeColor(pc.bold),
black: safeColor(pc.black),
white: safeColor(pc.white),
blue: safeColor(pc.blue),
cyan: safeColor(pc.cyan),
red: safeColor(pc.red),
yellow: safeColor(pc.yellow),
green: safeColor(pc.green),
blackBright: safeColor(pc.blackBright),
whiteBright: safeColor(pc.whiteBright),
blueBright: safeColor(pc.blueBright),
cyanBright: safeColor(pc.cyanBright),
redBright: safeColor(pc.redBright),
yellowBright: safeColor(pc.yellowBright),
greenBright: safeColor(pc.greenBright),
bgBlack: safeColor(pc.bgBlack),
bgWhite: safeColor(pc.bgWhite),
bgBlue: safeColor(pc.bgBlue),
bgCyan: safeColor(pc.bgCyan),
bgRed: safeColor(pc.bgRed),
bgYellow: safeColor(pc.bgYellow),
bgGreen: safeColor(pc.bgGreen),
bgBlackBright: safeColor(pc.bgBlackBright),
bgWhiteBright: safeColor(pc.bgWhiteBright),
bgBlueBright: safeColor(pc.bgBlueBright),
bgCyanBright: safeColor(pc.bgCyanBright),
bgRedBright: safeColor(pc.bgRedBright),
bgYellowBright: safeColor(pc.bgYellowBright),
bgGreenBright: safeColor(pc.bgGreenBright),
gray: safeColor(pc.gray),
dim: safeColor(pc.dim),
reset: safeColor(pc.reset),
inverse: safeColor(pc.inverse),
hex: (hex: string) => safeColor(hexColor(hex)),
underline: pc.underline,
};
/**
* Converts a hex color string to an ANSI true-color (24-bit) formatter.
* Used by the loading indicator gradient animation.
*/
function hexColor(hex: string): (input: string) => string {
let h = hex.replace("#", "");
let r = parseInt(h.substring(0, 2), 16);
let g = parseInt(h.substring(2, 4), 16);
let b = parseInt(h.substring(4, 6), 16);
return (input: string) => `\x1b[38;2;${r};${g};${b}m${input}\x1b[39m`;
}
function safeColor(style: (input: string) => string) {
return SUPPORTS_COLOR ? style : identity;
}
export { type ActionKey };
const unicode = { enabled: os.platform() !== "win32" };
export const shouldUseAscii = () => !unicode.enabled;
export function isInteractive() {
// Support explicit override for testing purposes
if ("CREATE_REACT_ROUTER_FORCE_INTERACTIVE" in process.env) {
return true;
}
// Adapted from https://github.com/sindresorhus/is-interactive
return Boolean(
process.stdout.isTTY &&
process.env.TERM !== "dumb" &&
!("CI" in process.env),
);
}
export function log(message: string) {
return process.stdout.write(message + "\n");
}
export let stderr = process.stderr;
/** @internal Used to mock `process.stderr.write` for testing purposes */
export function setStderr(writable: typeof process.stderr) {
stderr = writable;
}
export function logError(message: string) {
return stderr.write(message + "\n");
}
function logBullet(
logger: typeof log | typeof logError,
colorizePrefix: (v: string) => string,
colorizeText: (v: string) => string,
symbol: string,
prefix: string,
text?: string | string[],
) {
let textParts = Array.isArray(text) ? text : [text || ""].filter(Boolean);
let formattedText = textParts
.map((textPart) => colorizeText(textPart))
.join("");
if (process.stdout.columns < 80) {
logger(
`${" ".repeat(5)} ${colorizePrefix(symbol)} ${colorizePrefix(prefix)}`,
);
logger(`${" ".repeat(9)}${formattedText}`);
} else {
logger(
`${" ".repeat(5)} ${colorizePrefix(symbol)} ${colorizePrefix(
prefix,
)} ${formattedText}`,
);
}
}
export function debug(prefix: string, text?: string | string[]) {
logBullet(log, color.yellow, color.dim, "●", prefix, text);
}
export function info(prefix: string, text?: string | string[]) {
logBullet(log, color.cyan, color.dim, "◼", prefix, text);
}
export function success(text: string) {
logBullet(log, color.green, color.dim, "✔", text);
}
export function error(prefix: string, text?: string | string[]) {
log("");
logBullet(logError, color.red, color.error, "▲", prefix, text);
}
export function sleep(ms: number) {
return new Promise<void>((resolve) => setTimeout(resolve, ms));
}
export function toValidProjectName(projectName: string) {
if (isValidProjectName(projectName)) {
return projectName;
}
return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/^[._]/, "")
.replace(/[^a-z\d\-~]+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
}
function isValidProjectName(projectName: string) {
return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(
projectName,
);
}
export function identity<V>(v: V) {
return v;
}
export function strip(str: string) {
let pattern = [
"[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)",
"(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))",
].join("|");
let RGX = new RegExp(pattern, "g");
return typeof str === "string" ? str.replace(RGX, "") : str;
}
export function reverse<T>(arr: T[]): T[] {
return [...arr].reverse();
}
export function isValidJsonObject(obj: any): obj is Record<string, unknown> {
return !!(obj && typeof obj === "object" && !Array.isArray(obj));
}
export async function directoryExists(p: string) {
try {
let stat = await fs.promises.stat(p);
return stat.isDirectory();
} catch {
return false;
}
}
export async function fileExists(p: string) {
try {
let stat = await fs.promises.stat(p);
return stat.isFile();
} catch {
return false;
}
}
export async function ensureDirectory(dir: string) {
if (!(await directoryExists(dir))) {
await fs.promises.mkdir(dir, { recursive: true });
}
}
export function pathContains(path: string, dir: string) {
let relative = path.replace(dir, "");
return relative.length < path.length && !relative.startsWith("..");
}
export function isUrl(value: string | URL) {
try {
new URL(value);
return true;
} catch {
return false;
}
}
export function clear(prompt: string, perLine: number) {
if (!perLine) return erase.line + cursor.to(0);
let rows = 0;
let lines = prompt.split(/\r?\n/);
for (let line of lines) {
rows += 1 + Math.floor(Math.max(strip(line).length - 1, 0) / perLine);
}
return erase.lines(rows);
}
export function lines(msg: string, perLine: number) {
let lines = String(strip(msg) || "").split(/\r?\n/);
if (!perLine) return lines.length;
return lines
.map((l) => Math.ceil(l.length / perLine))
.reduce((a, b) => a + b);
}
export function action(key: ActionKey, isSelect: boolean) {
if (key.meta && key.name !== "escape") return;
if (key.ctrl) {
if (key.name === "a") return "first";
if (key.name === "c") return "abort";
if (key.name === "d") return "abort";
if (key.name === "e") return "last";
if (key.name === "g") return "reset";
}
if (isSelect) {
if (key.name === "j") return "down";
if (key.name === "k") return "up";
}
if (key.name === "return") return "submit";
if (key.name === "enter") return "submit"; // ctrl + J
if (key.name === "backspace") return "delete";
if (key.name === "delete") return "deleteForward";
if (key.name === "abort") return "abort";
if (key.name === "escape") return "exit";
if (key.name === "tab") return "next";
if (key.name === "pagedown") return "nextPage";
if (key.name === "pageup") return "prevPage";
if (key.name === "home") return "home";
if (key.name === "end") return "end";
if (key.name === "up") return "up";
if (key.name === "down") return "down";
if (key.name === "right") return "right";
if (key.name === "left") return "left";
return false;
}
export function stripDirectoryFromPath(dir: string, filePath: string) {
// Can't just do a regexp replace here since the windows paths mess it up :/
let stripped = filePath;
if (
(dir.endsWith(path.sep) && filePath.startsWith(dir)) ||
(!dir.endsWith(path.sep) && filePath.startsWith(dir + path.sep))
) {
stripped = filePath.slice(dir.length);
if (stripped.startsWith(path.sep)) {
stripped = stripped.slice(1);
}
}
return stripped;
}
// We do not copy these folders from templates so we can ignore them for comparisons
export const IGNORED_TEMPLATE_DIRECTORIES = [".git", "node_modules"];
export async function getDirectoryFilesRecursive(dir: string) {
return (await readdir(dir, { recursive: true })).filter((file) => {
let parts = file.split(path.sep);
return (
parts.length <= 1 || !IGNORED_TEMPLATE_DIRECTORIES.includes(parts[0])
);
});
}