path-class 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { expect, spyOn, test } from "bun:test";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- import { Path, stringifyIfPath } from ".";
4
+ import { Path, stringifyIfPath } from "./Path";
5
5
 
6
6
  test("constructor", async () => {
7
7
  expect(new Path("foo").path).toEqual("foo");
@@ -176,6 +176,20 @@ test(".mkdir(…) (nested)", async () => {
176
176
  expect(await dir.exists()).toBe(true);
177
177
  });
178
178
 
179
+ test(".cp(…)", async () => {
180
+ const parentDir = await Path.makeTempDir();
181
+ const file1 = parentDir.join("file1.txt");
182
+ const file2 = parentDir.join("file2.txt");
183
+
184
+ await file1.write("hello world");
185
+ expect(await file1.exists()).toBe(true);
186
+ expect(await file2.exists()).toBe(false);
187
+
188
+ await file1.cp(file2);
189
+ expect(await file1.exists()).toBe(true);
190
+ expect(await file2.exists()).toBe(true);
191
+ });
192
+
179
193
  test(".rename(…)", async () => {
180
194
  const parentDir = await Path.makeTempDir();
181
195
  const file1 = parentDir.join("file1.txt");
@@ -268,14 +282,14 @@ test(".readJSON()", async () => {
268
282
  test(".write(…)", async () => {
269
283
  const tempDir = await Path.makeTempDir();
270
284
  const file = tempDir.join("file.json");
271
- await file.write("foo");
285
+ expect(await file.write("foo")).toBe(file);
272
286
 
273
287
  expect(await readFile(join(tempDir.path, "./file.json"), "utf-8")).toEqual(
274
288
  "foo",
275
289
  );
276
290
 
277
291
  const file2 = tempDir.join("nested/file2.json");
278
- await file2.write("bar");
292
+ expect(await file2.write("bar")).toBe(file2);
279
293
  expect(
280
294
  await readFile(join(tempDir.path, "./nested/file2.json"), "utf-8"),
281
295
  ).toEqual("bar");
@@ -283,7 +297,7 @@ test(".write(…)", async () => {
283
297
 
284
298
  test(".writeJSON(…)", async () => {
285
299
  const file = (await Path.makeTempDir()).join("file.json");
286
- await file.writeJSON({ foo: "bar" });
300
+ expect(await file.writeJSON({ foo: "bar" })).toBe(file);
287
301
 
288
302
  expect(await file.readJSON()).toEqual<Record<string, string>>({ foo: "bar" });
289
303
  });
@@ -296,7 +310,44 @@ test(".readDir(…)", async () => {
296
310
  const contentsAsStrings = await dir.readDir();
297
311
  expect(new Set(contentsAsStrings)).toEqual(new Set(["file.txt", "dir"]));
298
312
 
299
- // const contentsAsEntries = await dir.readDir({ withFileTypes: true });
313
+ const contentsAsEntries = await dir.readDir({ withFileTypes: true });
314
+ expect(new Set(contentsAsEntries.map((entry) => entry.name))).toEqual(
315
+ new Set(["file.txt", "dir"]),
316
+ );
317
+ });
318
+
319
+ test(".symlink(…)", async () => {
320
+ const tempDir = await Path.makeTempDir();
321
+ const source = tempDir.join("foo.txt");
322
+ const target = tempDir.join("bar.txt");
323
+ await source.symlink(target);
324
+ expect(await target.existsAsFile()).toBe(false);
325
+ expect(() => target.readText()).toThrow(/ENOENT/);
326
+ await source.write("hello");
327
+ expect(await target.existsAsFile()).toBe(true);
328
+ expect(await target.readText()).toEqual("hello");
329
+ });
330
+
331
+ test(".stat(…)", async () => {
332
+ const file = (await Path.makeTempDir()).join("foo.txt");
333
+ await file.write("hello");
334
+
335
+ expect((await file.stat()).size).toEqual(5);
336
+ expect((await file.stat()).size).toBeTypeOf("number");
337
+ expect((await file.stat({ bigint: true })).size).toBeTypeOf("bigint");
338
+ });
339
+
340
+ test(".lstat(…)", async () => {
341
+ const tempDir = await Path.makeTempDir();
342
+ const source = tempDir.join("foo.txt");
343
+ const target = tempDir.join("bar.txt");
344
+ await source.symlink(target);
345
+ await source.write("hello");
346
+
347
+ expect((await source.lstat()).isSymbolicLink()).toBe(false);
348
+ expect((await target.lstat()).isSymbolicLink()).toBe(true);
349
+
350
+ expect(await target.readText()).toEqual("hello");
300
351
  });
301
352
 
302
353
  test(".homedir", async () => {
@@ -308,6 +359,10 @@ test(".xdg", async () => {
308
359
  expect(Path.xdg.config.path).toEqual("/xdg/config");
309
360
  expect(Path.xdg.data.path).toEqual("/mock/home/dir/.local/share");
310
361
  expect(Path.xdg.state.path).toEqual("/mock/home/dir/.local/state");
362
+ expect(Path.xdg.runtime).toBeUndefined();
363
+ expect(Path.xdg.runtimeWithStateFallback.path).toEqual(
364
+ "/mock/home/dir/.local/state",
365
+ );
311
366
  });
312
367
 
313
368
  const spy = spyOn(console, "log");
package/src/Path.ts ADDED
@@ -0,0 +1,398 @@
1
+ import {
2
+ cp,
3
+ lstat,
4
+ mkdir,
5
+ mkdtemp,
6
+ readdir,
7
+ readFile,
8
+ rename,
9
+ rm,
10
+ stat,
11
+ symlink,
12
+ writeFile,
13
+ } from "node:fs/promises";
14
+ import { homedir, tmpdir } from "node:os";
15
+ import { basename, dirname, extname, join } from "node:path";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import {
18
+ xdgCache,
19
+ xdgConfig,
20
+ xdgData,
21
+ xdgRuntime,
22
+ xdgState,
23
+ } from "xdg-basedir";
24
+ import type { readDirType, readFileType } from "./modifiedNodeTypes";
25
+
26
+ export class Path {
27
+ // @ts-expect-error ts(2564): False positive. https://github.com/microsoft/TypeScript/issues/32194
28
+ #path: string;
29
+ /**
30
+ * If `path` is a string starting with `file:///`, it will be parsed as a file URL.
31
+ */
32
+ constructor(path: string | URL | Path) {
33
+ this.#setNormalizedPath(Path.#pathlikeToString(path));
34
+ }
35
+
36
+ /**
37
+ * Similar to `new URL(path, base)`, but accepting and returning `Path` objects.
38
+ * Note that `base` must be one of:
39
+ *
40
+ * - a valid second argument to `new URL(…)`.
41
+ * - a `Path` representing an absolute path.
42
+ *
43
+ */
44
+ static resolve(path: string | URL | Path, base: string | URL | Path): Path {
45
+ const baseURL = (() => {
46
+ if (!(base instanceof Path)) {
47
+ return base;
48
+ }
49
+ if (!base.isAbsolutePath()) {
50
+ throw new Error(
51
+ "The `base` arg to `Path.resolve(…)` must be an absolute path.",
52
+ );
53
+ }
54
+ return pathToFileURL(base.#path);
55
+ })();
56
+ return new Path(new URL(Path.#pathlikeToString(path), baseURL));
57
+ }
58
+
59
+ static #pathlikeToString(path: string | URL | Path): string {
60
+ if (path instanceof Path) {
61
+ return path.#path;
62
+ }
63
+ if (path instanceof URL) {
64
+ return fileURLToPath(path);
65
+ }
66
+ if (typeof path === "string") {
67
+ // TODO: allow turning off this heuristic?
68
+ if (path.startsWith("file:///")) {
69
+ return fileURLToPath(path);
70
+ }
71
+ return path;
72
+ }
73
+ throw new Error("Invalid path");
74
+ }
75
+
76
+ #setNormalizedPath(path: string): void {
77
+ this.#path = join(path);
78
+ }
79
+
80
+ isAbsolutePath(): boolean {
81
+ return this.#path.startsWith("/");
82
+ }
83
+
84
+ toFileURL(): URL {
85
+ if (!this.isAbsolutePath()) {
86
+ throw new Error(
87
+ "Tried to convert to file URL when the path is not absolute.",
88
+ );
89
+ }
90
+ return pathToFileURL(this.#path);
91
+ }
92
+
93
+ /**
94
+ * The `Path` can have a trailing slash, indicating that it represents a
95
+ * directory. (If there is no trailing slash, it can represent either a file
96
+ * or a directory.)
97
+ *
98
+ * Some operations will refuse to treat a directory path as a file path. This
99
+ * function identifies such paths.
100
+ */
101
+ hasTrailingSlash(): boolean {
102
+ // TODO: handle Windows semantically
103
+ return this.#path.endsWith("/");
104
+ }
105
+
106
+ /**
107
+ * Same as `.toString()`, but more concise.
108
+ */
109
+ get path() {
110
+ return this.#path;
111
+ }
112
+
113
+ toString(): string {
114
+ return this.#path;
115
+ }
116
+
117
+ /** Constructs a new path by appending the given path segments.
118
+ * This follows `node` semantics for absolute paths: leading slashes in the given descendant segments are ignored.
119
+ */
120
+ join(...segments: (string | Path)[]): Path {
121
+ const segmentStrings = segments.map((segment) =>
122
+ segment instanceof Path ? segment.path : segment,
123
+ );
124
+ return new Path(join(this.#path, ...segmentStrings));
125
+ }
126
+
127
+ extendBasename(suffix: string): Path {
128
+ const joinedSuffix = join(suffix);
129
+ if (joinedSuffix !== basename(joinedSuffix)) {
130
+ throw new Error("Invalid suffix to extend file name.");
131
+ }
132
+ // TODO: join basename and dirname instead?
133
+ return new Path(this.#path + joinedSuffix);
134
+ }
135
+
136
+ get parent(): Path {
137
+ return new Path(dirname(this.#path));
138
+ }
139
+
140
+ // Normally I'd stick with `node`'s name, but I think `.dirname` is a
141
+ // particularly poor name. So we support `.dirname` for discovery but mark it
142
+ // as deprecated, even if it will never be removed.
143
+ /** @deprecated Alias for `.parent`. */
144
+ get dirname(): Path {
145
+ return this.parent;
146
+ }
147
+
148
+ get basename(): Path {
149
+ return new Path(basename(this.#path));
150
+ }
151
+
152
+ get extension(): string {
153
+ mustNotHaveTrailingSlash(this);
154
+ return extname(this.#path);
155
+ }
156
+
157
+ // Normally I'd stick with `node`'s name, but I think `.extname` is a
158
+ // particularly poor name. So we support `.extname` for discovery but mark it
159
+ // as deprecated, even if it will never be removed.
160
+ /** @deprecated Alias for `.extension`. */
161
+ get extname(): string {
162
+ return this.extension;
163
+ }
164
+
165
+ // TODO: find a neat way to dedup with the sync version?
166
+ async exists(constraints?: {
167
+ mustBe: "file" | "directory";
168
+ }): Promise<boolean> {
169
+ let stats: Awaited<ReturnType<typeof stat>>;
170
+ try {
171
+ stats = await stat(this.#path);
172
+ // biome-ignore lint/suspicious/noExplicitAny: TypeScript limitation
173
+ } catch (e: any) {
174
+ if (e.code === "ENOENT") {
175
+ return false;
176
+ }
177
+ throw e;
178
+ }
179
+ if (!constraints?.mustBe) {
180
+ return true;
181
+ }
182
+ switch (constraints?.mustBe) {
183
+ case "file": {
184
+ mustNotHaveTrailingSlash(this);
185
+ if (stats.isFile()) {
186
+ return true;
187
+ }
188
+ throw new Error(`Path exists but is not a file: ${this.#path}`);
189
+ }
190
+ case "directory": {
191
+ if (stats.isDirectory()) {
192
+ return true;
193
+ }
194
+ throw new Error(`Path exists but is not a directory: ${this.#path}`);
195
+ }
196
+ default: {
197
+ throw new Error("Invalid path type constraint");
198
+ }
199
+ }
200
+ }
201
+
202
+ async existsAsFile(): Promise<boolean> {
203
+ return this.exists({ mustBe: "file" });
204
+ }
205
+
206
+ async existsAsDir(): Promise<boolean> {
207
+ return this.exists({ mustBe: "directory" });
208
+ }
209
+
210
+ // I don't think `mkdir` is a great name, but it does match the
211
+ // well-established canonical commandline name. So in this case we keep the
212
+ // awkward abbreviation.
213
+ /** Defaults to `recursive: true`. */
214
+ async mkdir(options?: Parameters<typeof mkdir>[1]): Promise<Path> {
215
+ const optionsObject = (() => {
216
+ if (typeof options === "string" || typeof options === "number") {
217
+ return { mode: options };
218
+ }
219
+ return options ?? {};
220
+ })();
221
+ await mkdir(this.#path, { recursive: true, ...optionsObject });
222
+ return this;
223
+ }
224
+
225
+ // TODO: check idempotency semantics when the destination exists and is a folder.
226
+ /** Returns the destination path. */
227
+ async cp(
228
+ destination: string | URL | Path,
229
+ options?: Parameters<typeof cp>[2],
230
+ ): Promise<Path> {
231
+ await cp(this.#path, new Path(destination).#path, options);
232
+ return new Path(destination);
233
+ }
234
+
235
+ // TODO: check idempotency semantics when the destination exists and is a folder.
236
+ async rename(destination: string | URL | Path): Promise<void> {
237
+ await rename(this.#path, new Path(destination).#path);
238
+ }
239
+
240
+ /** Create a temporary dir inside the global temp dir for the current user. */
241
+ static async makeTempDir(prefix?: string): Promise<Path> {
242
+ return new Path(
243
+ await mkdtemp(new Path(tmpdir()).join(prefix ?? "js-temp-").toString()),
244
+ );
245
+ }
246
+
247
+ async rm(options?: Parameters<typeof rm>[1]): Promise<void> {
248
+ await rm(this.#path, options);
249
+ }
250
+
251
+ /**
252
+ * Equivalent to:
253
+ *
254
+ * .rm({ recursive: true, force: true, ...(options ?? {}) })
255
+ *
256
+ */
257
+ async rm_rf(options?: Parameters<typeof rm>[1]): Promise<void> {
258
+ await this.rm({ recursive: true, force: true, ...(options ?? {}) });
259
+ }
260
+
261
+ read: typeof readFileType = (options) =>
262
+ // biome-ignore lint/suspicious/noExplicitAny: Needed to wrangle the types.
263
+ readFile(this.#path, options as any) as any;
264
+
265
+ async readText(): Promise<string> {
266
+ return readFile(this.#path, "utf-8");
267
+ }
268
+
269
+ async readJSON<T>(): Promise<T> {
270
+ return JSON.parse(await this.readText());
271
+ }
272
+
273
+ /** Creates intermediate directories if they do not exist.
274
+ *
275
+ * Returns the original `Path` (for chaining).
276
+ */
277
+ async write(
278
+ data: Parameters<typeof writeFile>[1],
279
+ options?: Parameters<typeof writeFile>[2],
280
+ ): Promise<Path> {
281
+ await this.parent.mkdir();
282
+ await writeFile(this.#path, data, options);
283
+ return this;
284
+ }
285
+
286
+ /**
287
+ * If only `data` is provided, this is equivalent to:
288
+ *
289
+ * .write(JSON.stringify(data, null, " "));
290
+ *
291
+ * `replacer` and `space` can also be specified, making this equivalent to:
292
+ *
293
+ * .write(JSON.stringify(data, replacer, space));
294
+ *
295
+ * Returns the original `Path` (for chaining).
296
+ */
297
+ async writeJSON<T>(
298
+ data: T,
299
+ replacer: Parameters<typeof JSON.stringify>[1] = null,
300
+ space: Parameters<typeof JSON.stringify>[2] = " ",
301
+ ): Promise<Path> {
302
+ await this.write(JSON.stringify(data, replacer, space));
303
+ return this;
304
+ }
305
+
306
+ // Normally we'd add a `@deprecated` alias named `.readdir`, but that would
307
+ // differ only by capitalization of a single non-leading character. This can
308
+ // be a bit confusing, especially when autocompleting. So for this function in
309
+ // particular we don't include an alias.
310
+ readDir: typeof readDirType = (options) =>
311
+ // biome-ignore lint/suspicious/noExplicitAny: Needed to wrangle the types.
312
+ readdir(this.#path, options as any) as any;
313
+
314
+ /** Returns the destination path. */
315
+ async symlink(
316
+ target: string | URL | Path,
317
+ type?: Parameters<typeof symlink>[2],
318
+ ): Promise<Path> {
319
+ const targetPath = new Path(target);
320
+ await symlink(
321
+ this.path,
322
+ targetPath.path,
323
+ type as Exclude<Parameters<typeof symlink>[2], undefined>, // 🤷
324
+ );
325
+ return targetPath;
326
+ }
327
+
328
+ stat(options?: Parameters<typeof stat>[1]): ReturnType<typeof stat> {
329
+ return stat(this.path, options);
330
+ }
331
+
332
+ // I don't think `lstat` is a great name, but it does match the
333
+ // well-established canonical system call. So in this case we keep the
334
+ // awkward abbreviation.
335
+ lstat(options?: Parameters<typeof lstat>[1]): ReturnType<typeof lstat> {
336
+ return lstat(this.path, options);
337
+ }
338
+
339
+ static get homedir(): Path {
340
+ return new Path(homedir());
341
+ }
342
+
343
+ static xdg = {
344
+ cache: new Path(xdgCache ?? Path.homedir.join(".cache")),
345
+ config: new Path(xdgConfig ?? Path.homedir.join(".config")),
346
+ data: new Path(xdgData ?? Path.homedir.join(".local/share")),
347
+ state: new Path(xdgState ?? Path.homedir.join(".local/state")),
348
+ /**
349
+ * {@link Path.xdg.runtime} does not have a default value. Consider
350
+ * {@link Path.xdg.runtimeWithStateFallback} if you need a fallback but do not have a particular fallback in mind.
351
+ */
352
+ runtime: xdgRuntime ? new Path(xdgRuntime) : undefined,
353
+ runtimeWithStateFallback: xdgRuntime
354
+ ? new Path(xdgRuntime)
355
+ : new Path(xdgState ?? Path.homedir.join(".local/state")),
356
+ };
357
+
358
+ /** Chainable function to print the path. Prints the same as:
359
+ *
360
+ * if (args.length > 0) {
361
+ * console.log(...args);
362
+ * }
363
+ * console.log(this.path);
364
+ *
365
+ */
366
+ // biome-ignore lint/suspicious/noExplicitAny: This is the correct type, based on `console.log(…)`.
367
+ debugPrint(...args: any[]): Path {
368
+ if (args.length > 0) {
369
+ console.log(...args);
370
+ }
371
+ console.log(this.#path);
372
+ return this;
373
+ }
374
+ }
375
+
376
+ /**
377
+ * This function is useful to serialize any `Path`s in a structure to pass on to
378
+ * functions that do not know about the `Path` class, e.g.
379
+ *
380
+ * function process(args: (string | Path)[]) {
381
+ * const argsAsStrings = args.map(stringifyIfPath);
382
+ * }
383
+ *
384
+ */
385
+ export function stringifyIfPath<T>(value: T | Path): T | string {
386
+ if (value instanceof Path) {
387
+ return value.toString();
388
+ }
389
+ return value;
390
+ }
391
+
392
+ export function mustNotHaveTrailingSlash(path: Path): void {
393
+ if (path.hasTrailingSlash()) {
394
+ throw new Error(
395
+ "Path ends with a slash, which cannot be treated as a file.",
396
+ );
397
+ }
398
+ }