Skip to content

Commit

Permalink
fix: allow format calls with one side of (file + ext) missing
Browse files Browse the repository at this point in the history
In node, the following are valid calls of `format`:

```ts
format({ file: 'foo' });
// foo

format({ dir: '/foo', name: 'bar' });
// /foo/bar

format({ dir: '/foo', ext: 'bar' });
// /foo/.bar
```

The last one is a little nonsensical, but the other two are valid
(extensionless files for example). We should also be matching node's
behaviour of course.

Also enables `strict: true` in TypeScript, which is what caught this.
  • Loading branch information
43081j committed Jan 9, 2025
1 parent ef12c12 commit 2ed85f3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/_path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,10 @@ export const dirname: typeof path.dirname = function (p) {
};

export const format: typeof path.format = function (p) {
const segments = [p.root, p.dir, p.base ?? p.name + p.ext].filter(Boolean);
const ext = p.ext ? (p.ext.startsWith(".") ? p.ext : `.${p.ext}`) : "";
const segments = [p.root, p.dir, p.base ?? (p.name ?? "") + ext].filter(
Boolean,
) as string[];
return normalizeWindowsPath(
p.root ? resolve(...segments) : segments.join("/"),
);
Expand Down
4 changes: 4 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,10 @@ runTest("format", format, [
[{ root: "/", base: "file.txt", ext: "ignored" }, "/file.txt"],
[{ root: "/", name: "file", ext: ".txt" }, "/file.txt"],
[{ name: "file", ext: ".txt" }, "file.txt"],
[{ name: "file" }, "file"],
[{ ext: "ext" }, ".ext"],
[{ ext: ".ext" }, ".ext"],
[{ dir: "/foo", name: "file" }, "/foo/file"],

// Windows
[{ name: "file", base: "file.txt" }, "file.txt"],
Expand Down

0 comments on commit 2ed85f3

Please sign in to comment.