-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathutils.ts
305 lines (271 loc) · 8.26 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
// Copyright 2024 the JSR authors. MIT license.
import * as path from "node:path";
import * as fs from "node:fs";
import { PkgManagerName } from "./pkg_manager";
import { spawn } from "node:child_process";
export let DEBUG = false;
export function setDebug(enabled: boolean) {
DEBUG = enabled;
}
export function logDebug(msg: string) {
if (DEBUG) {
console.log(msg);
}
}
const EXTRACT_REG = /^@([a-z0-9-]+)\/([a-z0-9-]+)(@(.+))?$/;
const EXTRACT_REG_PROXY = /^@jsr\/([a-z0-9-]+)__([a-z0-9-]+)(@(.+))?$/;
export class JsrPackageNameError extends Error {}
export class JsrPackage {
static from(input: string) {
const exactMatch = input.match(EXTRACT_REG);
if (exactMatch !== null) {
const scope = exactMatch[1];
const name = exactMatch[2];
const version = exactMatch[4] ?? null;
return new JsrPackage(scope, name, version);
}
const proxyMatch = input.match(EXTRACT_REG_PROXY);
if (proxyMatch !== null) {
const scope = proxyMatch[1];
const name = proxyMatch[2];
const version = proxyMatch[4] ?? null;
return new JsrPackage(scope, name, version);
}
throw new JsrPackageNameError(
`Invalid jsr package name: A jsr package name must have the format @<scope>/<name>, but got "${input}"`,
);
}
private constructor(
public scope: string,
public name: string,
public version: string | null,
) {}
toNpmPackage(): string {
const version = this.version !== null ? `@${this.version}` : "";
return `@jsr/${this.scope}__${this.name}${version}`;
}
toString() {
const version = this.version !== null ? `@${this.version}` : "";
return `@${this.scope}/${this.name}${version}`;
}
}
export async function fileExists(file: string): Promise<boolean> {
try {
const stat = await fs.promises.stat(file);
return stat.isFile();
} catch (err) {
return false;
}
}
export interface ProjectInfo {
projectDir: string;
pkgManagerName: PkgManagerName | null;
pkgJsonPath: string | null;
root: string | null;
}
export async function findProjectDir(
cwd: string,
dir: string = cwd,
result: ProjectInfo = {
projectDir: cwd,
pkgManagerName: null,
pkgJsonPath: null,
root: null,
},
): Promise<ProjectInfo> {
// Ensure we check for `package.json` first as this defines
// the root project location.
if (result.pkgJsonPath === null) {
const pkgJsonPath = path.join(dir, "package.json");
if (await fileExists(pkgJsonPath)) {
logDebug(`Found package.json at ${pkgJsonPath}`);
logDebug(`Setting project directory to ${dir}`);
result.projectDir = dir;
result.pkgJsonPath = pkgJsonPath;
}
} else {
const pkgJsonPath = path.join(dir, "package.json");
if (await fileExists(pkgJsonPath)) {
const json = await readJson<PkgJson>(pkgJsonPath);
// npm + yarn + bun workspaces
if (Array.isArray(json.workspaces)) {
result.root = dir;
} // pnpm workspaces
else if (await fileExists(path.join(dir, "pnpm-workspace.yaml"))) {
result.root = dir;
}
}
}
const npmLockfile = path.join(dir, "package-lock.json");
if (await fileExists(npmLockfile)) {
logDebug(`Detected npm from lockfile ${npmLockfile}`);
result.pkgManagerName = "npm";
return result;
}
// prefer bun.lockb over yarn.lock
// In some cases, both bun.lockb and yarn.lock can exist in the same project.
// https://bun.sh/docs/install/lockfile
const bunbLockfile = path.join(dir, "bun.lockb");
if (await fileExists(bunbLockfile)) {
logDebug(`Detected bun from lockfile ${bunbLockfile}`);
result.pkgManagerName = "bun";
return result;
}
const bunLockfile = path.join(dir, "bun.lock");
if (await fileExists(bunLockfile)) {
logDebug(`Detected bun from lockfile ${bunLockfile}`);
result.pkgManagerName = "bun";
return result;
}
const yarnLockFile = path.join(dir, "yarn.lock");
if (await fileExists(yarnLockFile)) {
logDebug(`Detected yarn from lockfile ${yarnLockFile}`);
result.pkgManagerName = "yarn";
return result;
}
const pnpmLockfile = path.join(dir, "pnpm-lock.yaml");
if (await fileExists(pnpmLockfile)) {
logDebug(`Detected pnpm from lockfile ${pnpmLockfile}`);
result.pkgManagerName = "pnpm";
return result;
}
const prev = dir;
dir = path.dirname(dir);
if (dir === prev) {
return result;
}
return findProjectDir(cwd, dir, result);
}
const PERIODS = {
year: 365 * 24 * 60 * 60 * 1000,
month: 30 * 24 * 60 * 60 * 1000,
week: 7 * 24 * 60 * 60 * 1000,
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
seconds: 1000,
};
export function prettyTime(diff: number) {
if (diff > PERIODS.day) {
return Math.floor(diff / PERIODS.day) + "d";
} else if (diff > PERIODS.hour) {
return Math.floor(diff / PERIODS.hour) + "h";
} else if (diff > PERIODS.minute) {
return Math.floor(diff / PERIODS.minute) + "m";
} else if (diff > PERIODS.seconds) {
return Math.floor(diff / PERIODS.seconds) + "s";
}
return diff + "ms";
}
export function timeAgo(diff: number) {
if (diff > PERIODS.year) {
const v = Math.floor(diff / PERIODS.year);
return `${v} year${v > 1 ? "s" : ""} ago`;
} else if (diff > PERIODS.month) {
const v = Math.floor(diff / PERIODS.month);
return `${v} month${v > 1 ? "s" : ""} ago`;
} else if (diff > PERIODS.week) {
const v = Math.floor(diff / PERIODS.week);
return `${v} week${v > 1 ? "s" : ""} ago`;
} else if (diff > PERIODS.day) {
const v = Math.floor(diff / PERIODS.day);
return `${v} day${v > 1 ? "s" : ""} ago`;
} else if (diff > PERIODS.hour) {
const v = Math.floor(diff / PERIODS.hour);
return `${v} hour${v > 1 ? "s" : ""} ago`;
} else if (diff > PERIODS.minute) {
const v = Math.floor(diff / PERIODS.minute);
return `${v} minute${v > 1 ? "s" : ""} ago`;
} else if (diff > PERIODS.seconds) {
const v = Math.floor(diff / PERIODS.seconds);
return `${v} second${v > 1 ? "s" : ""} ago`;
}
return "just now";
}
export class ExecError extends Error {
constructor(public code: number) {
super(`Child process exited with: ${code}`);
}
}
export interface ExecOutput {
combined: string;
stdout: string;
stderr: string;
}
export async function exec(
cmd: string,
args: string[],
cwd: string,
env?: Record<string, string | undefined>,
captureOutput?: boolean,
): Promise<ExecOutput> {
const cp = spawn(
cmd,
args.map((arg) => process.platform === "win32" ? `"${arg}"` : `'${arg}'`),
{
stdio: captureOutput ? "pipe" : "inherit",
cwd,
shell: true,
env,
},
);
let combined = "";
let stdout = "";
let stderr = "";
if (captureOutput) {
cp.stdout?.on("data", (data) => {
combined += data;
stdout += data;
});
cp.stderr?.on("data", (data) => {
combined += data;
stderr += data;
});
}
return new Promise<ExecOutput>((resolve, reject) => {
cp.on("exit", (code) => {
if (code === 0) resolve({ combined, stdout, stderr });
else reject(new ExecError(code ?? 1));
});
});
}
export function getNewLineChars(source: string) {
var temp = source.indexOf("\n");
if (source[temp - 1] === "\r") {
return "\r\n";
}
return "\n";
}
export async function readJson<T>(file: string): Promise<T> {
const content = await fs.promises.readFile(file, "utf-8");
return JSON.parse(content);
}
export interface PkgJson {
name?: string;
version?: string;
license?: string;
workspaces?: string[];
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
exports?: string | Record<string, string | Record<string, string>>;
scripts?: Record<string, string>;
}
export async function writeJson<T>(file: string, data: T): Promise<void> {
try {
await fs.promises.mkdir(path.dirname(file), { recursive: true });
} catch (_) {}
await fs.promises.writeFile(file, JSON.stringify(data, null, 2), "utf-8");
}
export async function readTextFile(file: string): Promise<string> {
return fs.promises.readFile(file, "utf-8");
}
export async function writeTextFile(
file: string,
content: string,
): Promise<void> {
try {
await fs.promises.mkdir(path.dirname(file), { recursive: true });
} catch (_) {}
await fs.promises.writeFile(file, content, "utf-8");
}