@williamthorsen/nmr-core 0.13.0 โ 0.13.2
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.
- package/.meta/changelog.json +89 -1
- package/CHANGELOG.md +30 -0
- package/README.md +9 -38
- package/dist/esm/cache-store.d.ts +25 -21
- package/dist/esm/cache-store.js +7 -30
- package/dist/esm/findPackageRoot.d.ts +1 -1
- package/dist/esm/gitOutputLimit.d.ts +4 -6
- package/dist/esm/hasErrnoCode.d.ts +1 -1
- package/dist/esm/hashWorkingTree.d.ts +13 -13
- package/dist/esm/hashWorkingTree.js +5 -5
- package/dist/esm/helpers/workspace-patterns.d.ts +6 -11
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.js +2 -1
- package/dist/esm/parseArgs.d.ts +6 -10
- package/dist/esm/readPackageVersion.d.ts +3 -8
- package/dist/esm/terminal.d.ts +10 -12
- package/dist/esm/terminal.js +28 -0
- package/dist/esm/updateManagedFile.d.ts +19 -0
- package/dist/esm/updateManagedFile.js +41 -0
- package/dist/esm/workspace.d.ts +27 -37
- package/dist/esm/workspace.js +2 -11
- package/dist/esm/writeFileWithCheck.d.ts +4 -5
- package/package.json +7 -6
package/.meta/changelog.json
CHANGED
|
@@ -1,4 +1,92 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.13.2",
|
|
4
|
+
"date": "2026-10-08",
|
|
5
|
+
"sections": [
|
|
6
|
+
{
|
|
7
|
+
"title": "๐๏ธ Internal features",
|
|
8
|
+
"audience": "dev",
|
|
9
|
+
"items": [
|
|
10
|
+
{
|
|
11
|
+
"description": "Adds an optional `stopAtDir` to `CacheDirRef`, which limits the upward search by `resolveCacheDir` for a `node_modules` to that directory, inclusive, and makes resolution throw when it is not the scope directory or one of its ancestors. (#969)",
|
|
12
|
+
"hash": "39d2c16c19382e68080c05b2ca4db191aa5dac89",
|
|
13
|
+
"entry": 1
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"title": "โป๏ธ Refactoring",
|
|
19
|
+
"audience": "dev",
|
|
20
|
+
"items": [
|
|
21
|
+
{
|
|
22
|
+
"description": "Replaces the hand-written atomic cache write and directory walks in `nmr-core` and `nmr` with `writeAtomic` and `findDirectoryChainMatch` from `@williamthorsen/toolbelt.filesystem`, which both packages now declare in `dependencies`. (#966)",
|
|
23
|
+
"hash": "0177be3ace33150a7ac67725dd539fb0ee63b833",
|
|
24
|
+
"entry": 1
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"title": "๐งช Tests",
|
|
30
|
+
"audience": "dev",
|
|
31
|
+
"items": [
|
|
32
|
+
{
|
|
33
|
+
"description": "Replaces the hand-rolled `try`/`catch` in nmr-core's `expectParseError` test helper with `captureError`, which fails the test when parsing does not throw. (#964)",
|
|
34
|
+
"hash": "38cc179b4116bcd5aba8371b17b0816150c9e9a3",
|
|
35
|
+
"entry": 5
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"description": "Stops the tests in `cache-store.unit.test.ts` from writing and removing cache entries in an ancestor's `node_modules` outside their temp trees, which also made the fallback test fail, and adds a test that a scope below `stopAtDir` does not hoist past it. (#969)",
|
|
39
|
+
"hash": "39d2c16c19382e68080c05b2ca4db191aa5dac89",
|
|
40
|
+
"entry": 2
|
|
41
|
+
}
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
]
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
"version": "0.13.1",
|
|
48
|
+
"date": "2026-10-01",
|
|
49
|
+
"sections": [
|
|
50
|
+
{
|
|
51
|
+
"title": "โป๏ธ Refactoring",
|
|
52
|
+
"audience": "dev",
|
|
53
|
+
"items": [
|
|
54
|
+
{
|
|
55
|
+
"description": "Replaces every `.sort()` call that suppressed `unicorn/no-array-sort` with `toSorted()` and drops the spread copy wherever the source was already an array. (#925)",
|
|
56
|
+
"hash": "4680fb4e865ffce0bd135fac20d49b766b156992",
|
|
57
|
+
"entry": 1
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"title": "๐งช Tests",
|
|
63
|
+
"audience": "dev",
|
|
64
|
+
"items": [
|
|
65
|
+
{
|
|
66
|
+
"description": "Stubs `GIT_CEILING_DIRECTORIES` to the fixture's parent in every test that expects git to find no repository, so that a repository above the temp directory can no longer change the test's result. (#923)",
|
|
67
|
+
"hash": "71d8c3dfb45aca872ca897ee589aae6351a1f516",
|
|
68
|
+
"entry": 2
|
|
69
|
+
}
|
|
70
|
+
]
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"title": "๐ Documentation",
|
|
74
|
+
"audience": "dev",
|
|
75
|
+
"items": [
|
|
76
|
+
{
|
|
77
|
+
"description": "Revises the comments in `packages/nmr-core/src` against the comment-discipline rules, correcting the `writeFileWithCheck` description, which omitted the `skipped` outcome for an unreadable existing file, and the `WorkspaceResolution` description, which named `unreadable-manifest` as the only cause with no patterns. (#920)",
|
|
78
|
+
"hash": "72b361c63e67e58ee5ebfb4dae10d9b144517a85",
|
|
79
|
+
"entry": 1
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"description": "Revises the README, doc comments, inline comments, and test titles in `packages/nmr-core` to align with the plain-speech doctrine and the writing conventions, including four failure `reason` strings returned by `hashWorkingTree`. (#934)",
|
|
83
|
+
"hash": "f084ddcecec9be602a97cdf3158eabd5aaebbe09",
|
|
84
|
+
"entry": 1
|
|
85
|
+
}
|
|
86
|
+
]
|
|
87
|
+
}
|
|
88
|
+
]
|
|
89
|
+
},
|
|
2
90
|
{
|
|
3
91
|
"version": "0.13.0",
|
|
4
92
|
"date": "2026-09-22",
|
|
@@ -168,7 +256,7 @@
|
|
|
168
256
|
},
|
|
169
257
|
{
|
|
170
258
|
"description": "Adopt `isError` and consolidate errno narrowing on a shared helper (#697)",
|
|
171
|
-
"body": "Replaces every hand-rolled `instanceof Error` narrowing with `hasErrnoCode`, a new predicate exported from `@williamthorsen/nmr-core`, or with `isError` from `@williamthorsen/toolbelt.errors`. Previously the errno question was answered by inline copies alongside two private helpers of differing shape; both helpers are removed.\
|
|
259
|
+
"body": "Replaces every hand-rolled `instanceof Error` narrowing with `hasErrnoCode`, a new predicate exported from `@williamthorsen/nmr-core`, or with `isError` from `@williamthorsen/toolbelt.errors`. Previously the errno question was answered by inline copies alongside two private helpers of differing shape; both helpers are removed.\n\nSeparately, `eslint.config.ts` now bans `instanceof Error` in every position rather than in a ternary alone.",
|
|
172
260
|
"hash": "c5e8e8a5e006b451e8c5aeea75d35772926d503c"
|
|
173
261
|
}
|
|
174
262
|
]
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,36 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## 0.13.2 โ 2026-10-08
|
|
6
|
+
|
|
7
|
+
### ๐๏ธ Internal features
|
|
8
|
+
|
|
9
|
+
- Adds an optional `stopAtDir` to `CacheDirRef`, which limits the upward search by `resolveCacheDir` for a `node_modules` to that directory, inclusive, and makes resolution throw when it is not the scope directory or one of its ancestors. (#969)
|
|
10
|
+
|
|
11
|
+
### โป๏ธ Refactoring
|
|
12
|
+
|
|
13
|
+
- Replaces the hand-written atomic cache write and directory walks in `nmr-core` and `nmr` with `writeAtomic` and `findDirectoryChainMatch` from `@williamthorsen/toolbelt.filesystem`, which both packages now declare in `dependencies`. (#966)
|
|
14
|
+
|
|
15
|
+
### ๐งช Tests
|
|
16
|
+
|
|
17
|
+
- Replaces the hand-rolled `try`/`catch` in nmr-core's `expectParseError` test helper with `captureError`, which fails the test when parsing does not throw. (#964)
|
|
18
|
+
- Stops the tests in `cache-store.unit.test.ts` from writing and removing cache entries in an ancestor's `node_modules` outside their temp trees, which also made the fallback test fail, and adds a test that a scope below `stopAtDir` does not hoist past it. (#969)
|
|
19
|
+
|
|
20
|
+
## 0.13.1 โ 2026-10-01
|
|
21
|
+
|
|
22
|
+
### โป๏ธ Refactoring
|
|
23
|
+
|
|
24
|
+
- Replaces every `.sort()` call that suppressed `unicorn/no-array-sort` with `toSorted()` and drops the spread copy wherever the source was already an array. (#925)
|
|
25
|
+
|
|
26
|
+
### ๐งช Tests
|
|
27
|
+
|
|
28
|
+
- Stubs `GIT_CEILING_DIRECTORIES` to the fixture's parent in every test that expects git to find no repository, so that a repository above the temp directory can no longer change the test's result. (#923)
|
|
29
|
+
|
|
30
|
+
### ๐ Documentation
|
|
31
|
+
|
|
32
|
+
- Revises the comments in `packages/nmr-core/src` against the comment-discipline rules, correcting the `writeFileWithCheck` description, which omitted the `skipped` outcome for an unreadable existing file, and the `WorkspaceResolution` description, which named `unreadable-manifest` as the only cause with no patterns. (#920)
|
|
33
|
+
- Revises the README, doc comments, inline comments, and test titles in `packages/nmr-core` to align with the plain-speech doctrine and the writing conventions, including four failure `reason` strings returned by `hashWorkingTree`. (#934)
|
|
34
|
+
|
|
5
35
|
## 0.13.0 โ 2026-09-22
|
|
6
36
|
|
|
7
37
|
### ๐ Features
|
package/README.md
CHANGED
|
@@ -6,37 +6,7 @@ Shared utilities for node-monorepo-tools packages.
|
|
|
6
6
|
|
|
7
7
|
This package serves as the shared library foundation for the monorepo. For the nmr CLI tool, see [`@williamthorsen/nmr`](../nmr).
|
|
8
8
|
|
|
9
|
-
<!-- section:release-notes -->
|
|
10
|
-
## Release notes โ v0.13.0 (2026-09-22)
|
|
11
|
-
|
|
12
|
-
### ๐ Features
|
|
13
|
-
|
|
14
|
-
- ๐จ **Breaking:** Hoist the pnpm-workspace resolver into nmr-core as a total API (#864)
|
|
15
|
-
|
|
16
|
-
- Adds a `./workspace` subpath export to `@williamthorsen/nmr-core`, whose `resolveWorkspace` returns a pnpm workspace's package directories, or the cause of an empty result, as a value rather than as a thrown error.
|
|
17
|
-
- Reports a `pnpm-workspace.yaml` that the YAML parser rejects under a cause of its own, `unreadable-manifest`, so `nmr -R build` names the syntax error and its remedy in place of failing with the parser's own error.
|
|
18
|
-
- Removes `diagnoseEmptyWorkspace` and `EmptyWorkspaceDiagnosis` from `@williamthorsen/nmr/workspace`, since `resolveWorkspace` reports the same cause in one call.
|
|
19
|
-
|
|
20
|
-
Migration: Replace each `diagnoseEmptyWorkspace` call with `resolveWorkspace`, which reports the cause on the empty result it already returns, and rename the `no-manifest` cause to `no-package`. `EmptyWorkspaceCause` also gains `unreadable-manifest`, so an exhaustive switch over it stops compiling until it handles the new member; every other export of `@williamthorsen/nmr/workspace` keeps its signature and its `UserError` throws.
|
|
21
|
-
|
|
22
|
-
- ๐จ **Breaking:** Adopt the shared workspace resolver in release-kit, honoring exclusions (#865)
|
|
23
|
-
|
|
24
|
-
- ๐จ **Breaking:** Narrows `no-pattern` in `@williamthorsen/nmr-core`'s `EmptyWorkspaceCause`, moving an absent or empty `packages` list onto `no-packages-list` and a value that is not a list of strings onto `unreadable-packages`.
|
|
25
|
-
- Stops `release-kit` from tagging, publishing, and label-syncing a package that a `!` entry in `pnpm-workspace.yaml` excludes, which its previous `glob`-based resolution could not remove from the match.
|
|
26
|
-
- Replaces the release of the root package alone with a failure naming the condition that emptied the workspace, when `pnpm-workspace.yaml` does not hold valid YAML or declares a workspace that does not resolve to a package.
|
|
27
|
-
- Replaces the `no-pattern` remedy that `nmr` printed for a `pnpm-workspace.yaml` declaring no `packages` list, and for one declaring a `packages` value that is not a list of strings.
|
|
28
|
-
- Raises `engines.node` to `>=24.16.0` in `@williamthorsen/nmr-core` and `@williamthorsen/release-kit`, because Node 24.0 through 24.15 ignores the `followSymlinks` option that the workspace matcher passes to `globSync` and drops a symlinked package directory from the resolution without reporting it.
|
|
29
|
-
|
|
30
|
-
Migration: Add a `no-packages-list` arm and an `unreadable-packages` arm to any `switch` that covers `EmptyWorkspaceCause` exhaustively. `no-pattern` now names only a list that the resolver read in full and whose entries all failed to become a positive pattern, so move the handling of an absent `packages` key, an empty list, and a value that is not a list of strings out of the `no-pattern` arm into the two new ones. Route `no-packages-list` to single-package behavior rather than to a failure path: pnpm resolves such a manifest to the root package alone.
|
|
31
|
-
|
|
32
|
-
### ๐ Bug fixes
|
|
33
|
-
|
|
34
|
-
- Truncate release-kit commit subjects by display column (#840)
|
|
35
|
-
|
|
36
|
-
- Fixes the issue that the `release-kit` prepare report cut a commit subject at 69 UTF-16 code units instead of at display columns, so a subject of CJK characters printed about twice the intended 72-column width and a cut inside an emoji left a broken character that a terminal drew as a replacement glyph.
|
|
37
|
-
- Replaces the `...` marker on a truncated subject with `โฆ`, the default of the width-aware truncation that now does the cutting.
|
|
38
|
-
- Exports `truncateToWidth` and `measureWidth` from `@williamthorsen/nmr-core`, which measure and cut text by display width without splitting a grapheme cluster.
|
|
39
|
-
<!-- /section:release-notes -->
|
|
9
|
+
<!-- section:release-notes --><!-- /section:release-notes -->
|
|
40
10
|
|
|
41
11
|
## Installation
|
|
42
12
|
|
|
@@ -49,8 +19,8 @@ pnpm add -D @williamthorsen/nmr-core
|
|
|
49
19
|
## Workspace introspection
|
|
50
20
|
|
|
51
21
|
The `./workspace` entry publishes the pnpm-workspace lookups that nmr and release-kit share. Every one of them
|
|
52
|
-
is total:
|
|
53
|
-
[Workspace introspection](../nmr/docs/workspace.md) documents what each lookup returns and
|
|
22
|
+
is total: It returns a value rather than throwing, so each CLI keeps its own error boundary.
|
|
23
|
+
[Workspace introspection](../nmr/docs/workspace.md) documents what each lookup returns and how it diverges
|
|
54
24
|
from pnpm.
|
|
55
25
|
|
|
56
26
|
The entry stays out of the root export, which keeps `yaml` out of the module closure of every other importer,
|
|
@@ -59,9 +29,10 @@ the build bootstrap's included.
|
|
|
59
29
|
## The `nmr-source` export condition
|
|
60
30
|
|
|
61
31
|
Both entries declare an `nmr-source` export condition resolving to their TypeScript source. It exists for one
|
|
62
|
-
caller: the compiler that builds this package. That compiler imports this package, so on a tree
|
|
63
|
-
output it has to
|
|
32
|
+
caller: the compiler that builds this package. That compiler imports this package, so on a tree without build
|
|
33
|
+
output it has to import the source, and the condition resolves the import to that source.
|
|
64
34
|
|
|
65
|
-
Nothing else should pass `--conditions nmr-source`.
|
|
66
|
-
resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without
|
|
67
|
-
is unaffected:
|
|
35
|
+
Nothing else should pass `--conditions nmr-source`. Because the published package contains only `dist`, the
|
|
36
|
+
condition resolves to a file that is not in the tarball and fails with `ERR_MODULE_NOT_FOUND`. Resolution without
|
|
37
|
+
the flag is unaffected: An unmatched condition is skipped, and each entry resolves to the build output as it always
|
|
38
|
+
has.
|
|
@@ -1,9 +1,14 @@
|
|
|
1
|
-
/** Names the cache directory a tool's entries
|
|
1
|
+
/** Names the cache directory that contains a tool's entries: `{home}/node_modules/.cache/{tool}/`. */
|
|
2
2
|
export interface CacheDirRef {
|
|
3
|
-
/** The tool the cache belongs
|
|
3
|
+
/** The tool to which the cache belongs, e.g. `nmr-compile`. Becomes the directory name. */
|
|
4
4
|
tool: string;
|
|
5
|
-
/** The directory the cache serves; its nearest `node_modules` ancestor
|
|
5
|
+
/** The directory that the cache serves; its nearest `node_modules` ancestor contains the cache. */
|
|
6
6
|
scopeDir: string;
|
|
7
|
+
/**
|
|
8
|
+
* Bounds the search for a `node_modules` ancestor, inclusive. Must be the scope directory or one of its ancestors;
|
|
9
|
+
* resolution throws otherwise.
|
|
10
|
+
*/
|
|
11
|
+
stopAtDir?: string;
|
|
7
12
|
}
|
|
8
13
|
/** Locates a single entry within a tool's cache directory. */
|
|
9
14
|
export interface CacheEntryRef extends CacheDirRef {
|
|
@@ -12,44 +17,43 @@ export interface CacheEntryRef extends CacheDirRef {
|
|
|
12
17
|
/** Filename extension, including the leading dot. */
|
|
13
18
|
extension: string;
|
|
14
19
|
/**
|
|
15
|
-
* Strings folded into the filename digest alongside the absolute scope directory, so that one scope can
|
|
16
|
-
* several entries.
|
|
20
|
+
* Strings folded into the filename digest alongside the absolute scope directory, so that one scope can have
|
|
21
|
+
* several entries.
|
|
17
22
|
*/
|
|
18
23
|
discriminators?: string[];
|
|
19
24
|
}
|
|
20
25
|
/**
|
|
21
26
|
* Reads an entry's raw text, or `undefined` when it is absent or unreadable. A cache that cannot be read is a
|
|
22
|
-
* miss, never an error:
|
|
27
|
+
* miss, never an error: The caller's fallback is to do the work again, which is always correct.
|
|
23
28
|
*/
|
|
24
29
|
export declare function readCacheEntry(entryPath: string): Promise<string | undefined>;
|
|
25
30
|
/**
|
|
26
31
|
* Reads a JSON entry and narrows it with `isValidEntry`, returning `undefined` when the entry is missing,
|
|
27
|
-
* unparseable, or of the wrong shape. Content written
|
|
28
|
-
*
|
|
32
|
+
* unparseable, or of the wrong shape. Content written in an older format therefore reads as a miss rather than
|
|
33
|
+
* being returned to the caller as a value that it cannot trust.
|
|
29
34
|
*/
|
|
30
35
|
export declare function readJsonCacheEntry<T>(entryPath: string, isValidEntry: (value: unknown) => value is T): Promise<T | undefined>;
|
|
31
|
-
/** Removes a tool's entire cache directory. Idempotent:
|
|
36
|
+
/** Removes a tool's entire cache directory. Idempotent: An absent directory is a silent no-op. */
|
|
32
37
|
export declare function removeCacheDir(ref: CacheDirRef): Promise<void>;
|
|
33
|
-
/** Removes a single entry. Idempotent:
|
|
38
|
+
/** Removes a single entry. Idempotent: An absent entry is a silent no-op, as is an absent cache directory. */
|
|
34
39
|
export declare function removeCacheEntry(entryPath: string): Promise<void>;
|
|
35
40
|
/**
|
|
36
41
|
* Resolves the absolute path of a tool's cache directory. The conventional `node_modules/.cache/{tool}/` home is
|
|
37
|
-
* git-ignored and outside any `files` convention, so an entry never
|
|
38
|
-
* nearest enclosing directory that already has a `node_modules`: the scope's own when it has one, otherwise
|
|
39
|
-
* hoisted ancestor, such as the workspace root for a zero-dependency package.
|
|
40
|
-
*
|
|
42
|
+
* git-ignored and outside any `files` convention, so an entry is never included in a published tarball. The home
|
|
43
|
+
* is the nearest enclosing directory that already has a `node_modules`: the scope's own when it has one, otherwise
|
|
44
|
+
* a hoisted ancestor, such as the workspace root for a zero-dependency package. The search does not go above
|
|
45
|
+
* `stopAtDir` when one is given. The function never materializes a `node_modules` solely to store the cache.
|
|
41
46
|
*/
|
|
42
47
|
export declare function resolveCacheDir(ref: CacheDirRef): string;
|
|
43
48
|
/**
|
|
44
|
-
* Resolves the absolute path of a single cache entry. The
|
|
45
|
-
*
|
|
46
|
-
*
|
|
49
|
+
* Resolves the absolute path of a single cache entry. The function folds a digest of the absolute scope directory
|
|
50
|
+
* (and any discriminators) into a readable base name, so scopes sharing a hoisted `node_modules` never collide
|
|
51
|
+
* while the path stays stable across runs for the same scope.
|
|
47
52
|
*/
|
|
48
53
|
export declare function resolveCacheEntryPath(ref: CacheEntryRef): string;
|
|
49
54
|
/**
|
|
50
|
-
* Writes an entry, creating the cache directory as needed
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
* worth failing over catches it.
|
|
55
|
+
* Writes an entry atomically, creating the cache directory as needed, so that a concurrent reader sees either the
|
|
56
|
+
* previous entry or the new one and never a half-written file. Throws when the write cannot be completed; a caller
|
|
57
|
+
* for whom a failed cache write is not worth failing over catches it.
|
|
54
58
|
*/
|
|
55
59
|
export declare function writeCacheEntry(entryPath: string, content: string): Promise<void>;
|
package/dist/esm/cache-store.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { createHash
|
|
2
|
-
import {
|
|
3
|
-
import { mkdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises';
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile, rm } from 'node:fs/promises';
|
|
4
3
|
import path from 'node:path';
|
|
4
|
+
import { findDirectoryChainMatch } from '@williamthorsen/toolbelt.filesystem';
|
|
5
|
+
import { writeAtomic } from '@williamthorsen/toolbelt.filesystem/candidate';
|
|
5
6
|
const DIGEST_LENGTH = 8;
|
|
6
7
|
export async function readCacheEntry(entryPath) {
|
|
7
8
|
try {
|
|
@@ -33,7 +34,8 @@ export async function removeCacheEntry(entryPath) {
|
|
|
33
34
|
}
|
|
34
35
|
export function resolveCacheDir(ref) {
|
|
35
36
|
const absoluteScopeDir = path.resolve(ref.scopeDir);
|
|
36
|
-
const
|
|
37
|
+
const stopAtDir = ref.stopAtDir === undefined ? undefined : path.resolve(ref.stopAtDir);
|
|
38
|
+
const home = findDirectoryChainMatch(absoluteScopeDir, ['node_modules'], { stopAtDir })?.dir ?? absoluteScopeDir;
|
|
37
39
|
return path.join(home, 'node_modules', '.cache', ref.tool);
|
|
38
40
|
}
|
|
39
41
|
export function resolveCacheEntryPath(ref) {
|
|
@@ -45,30 +47,5 @@ export function resolveCacheEntryPath(ref) {
|
|
|
45
47
|
return path.join(resolveCacheDir(ref), `${ref.slug}-${digest}${ref.extension}`);
|
|
46
48
|
}
|
|
47
49
|
export async function writeCacheEntry(entryPath, content) {
|
|
48
|
-
await
|
|
49
|
-
const temporaryPath = `${entryPath}.${randomUUID()}.tmp`;
|
|
50
|
-
try {
|
|
51
|
-
await writeFile(temporaryPath, content);
|
|
52
|
-
await rename(temporaryPath, entryPath);
|
|
53
|
-
}
|
|
54
|
-
catch (error) {
|
|
55
|
-
try {
|
|
56
|
-
await unlink(temporaryPath);
|
|
57
|
-
}
|
|
58
|
-
catch {
|
|
59
|
-
}
|
|
60
|
-
throw error;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
function findNearestNodeModulesHost(startDir) {
|
|
64
|
-
let current = startDir;
|
|
65
|
-
let parent = path.dirname(current);
|
|
66
|
-
while (!existsSync(path.join(current, 'node_modules'))) {
|
|
67
|
-
if (parent === current) {
|
|
68
|
-
return undefined;
|
|
69
|
-
}
|
|
70
|
-
current = parent;
|
|
71
|
-
parent = path.dirname(current);
|
|
72
|
-
}
|
|
73
|
-
return current;
|
|
50
|
+
await writeAtomic(entryPath, content);
|
|
74
51
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Finds the nearest ancestor directory containing `package.json`, starting from
|
|
3
3
|
* the directory of the given `import.meta.url`.
|
|
4
4
|
*
|
|
5
5
|
* Useful for resolving bundled assets (presets, templates) relative to the
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The `maxBuffer` every git invocation that pipes stdout
|
|
3
|
-
*
|
|
2
|
+
* The `maxBuffer` for every git invocation that pipes stdout, raised well above Node's 1 MiB default so that a
|
|
3
|
+
* tree with thousands of untracked files still reports a status and a long-lived repo still lists its tags.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* output that overflowed. A call site that omits the option inherits the default silently and fails only once
|
|
8
|
-
* the repo it runs against has grown enough, which is why the value is shared rather than chosen per site.
|
|
5
|
+
* Past the limit, Node kills the child and reports `ENOBUFS`, an error that names the spawned program rather than
|
|
6
|
+
* the output that overflowed. A call site that omits the option fails this way only once its repo has grown enough.
|
|
9
7
|
*/
|
|
10
8
|
export declare const GIT_OUTPUT_LIMIT: number;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Narrows a thrown value to an `Error`
|
|
2
|
+
* Narrows a thrown value to an `Error` with the given Node errno code.
|
|
3
3
|
*
|
|
4
4
|
* `isError` recognizes an `Error` crossing a realm boundary, which a bare `instanceof` test reports as false.
|
|
5
5
|
*/
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* A whole-repo content hash, or the reason one could not be produced.
|
|
3
|
-
* no commit, a git failure, a tree this hash cannot describe)
|
|
4
|
-
*
|
|
2
|
+
* A whole-repo content hash, or the reason one could not be produced. For every degraded condition (no repository,
|
|
3
|
+
* no commit, a git failure, a tree that this hash cannot describe), the result is `ok: false` rather than a hash on
|
|
4
|
+
* which a caller might act.
|
|
5
5
|
*/
|
|
6
6
|
export type WorkingTreeHashResult = {
|
|
7
7
|
ok: true;
|
|
@@ -14,21 +14,21 @@ export type WorkingTreeHashResult = {
|
|
|
14
14
|
};
|
|
15
15
|
/**
|
|
16
16
|
* Produces a content hash of the entire working tree at `cwd`: the commit's tree object folded with the current
|
|
17
|
-
* content of every path git reports as changed or untracked. Two trees
|
|
18
|
-
*
|
|
17
|
+
* content of every path that git reports as changed or untracked. Two trees with the same content hash alike, so a
|
|
18
|
+
* `touch` that does not change any bytes leaves the hash unchanged, while any edit, addition, or deletion moves it.
|
|
19
19
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* the same after taking one.
|
|
20
|
+
* Reading git's own status keeps the running time proportional to what has changed rather than to the size of the
|
|
21
|
+
* repository, and applies git's ignore rules. Nothing here writes to the object database or the index: A hash is
|
|
22
|
+
* an observation, and a repository must look exactly the same after taking one.
|
|
24
23
|
*
|
|
25
24
|
* Because the commit's tree object is the base of the fold, committing an already-hashed tree moves the hash
|
|
26
|
-
* even though
|
|
27
|
-
* preserves content leaves the hash alone, as does checking out a branch whose tree is identical.
|
|
25
|
+
* even though the content did not change. The reverse holds too, and usefully: A rebase or an amended message
|
|
26
|
+
* that preserves content leaves the hash alone, as does checking out a branch whose tree is identical.
|
|
28
27
|
*/
|
|
29
28
|
export declare function hashWorkingTree(cwd: string): WorkingTreeHashResult;
|
|
30
29
|
/**
|
|
31
|
-
* Returns the commit `HEAD` names, or `undefined` when git cannot say.
|
|
32
|
-
*
|
|
30
|
+
* Returns the commit that `HEAD` names, or `undefined` when git cannot say. Because it is cheap next to a full
|
|
31
|
+
* hash, a caller that has observed a tree can check whether `HEAD` still names the same commit without hashing the
|
|
32
|
+
* tree again.
|
|
33
33
|
*/
|
|
34
34
|
export declare function readHeadSha(cwd: string): string | undefined;
|
|
@@ -20,7 +20,7 @@ export function hashWorkingTree(cwd) {
|
|
|
20
20
|
}
|
|
21
21
|
const toplevel = toplevelResult.stdout.trim();
|
|
22
22
|
if (toplevel === '') {
|
|
23
|
-
return { ok: false, reason: 'git
|
|
23
|
+
return { ok: false, reason: 'git did not report a repository toplevel' };
|
|
24
24
|
}
|
|
25
25
|
if (existsSync(path.join(toplevel, '.gitmodules'))) {
|
|
26
26
|
return { ok: false, reason: 'the repository declares submodules, whose content this hash does not cover' };
|
|
@@ -31,7 +31,7 @@ export function hashWorkingTree(cwd) {
|
|
|
31
31
|
}
|
|
32
32
|
const [headSha, headTreeSha] = revisionResult.stdout.trim().split('\n', 2);
|
|
33
33
|
if (headSha === undefined || headTreeSha === undefined) {
|
|
34
|
-
return { ok: false, reason: 'git
|
|
34
|
+
return { ok: false, reason: 'git did not report a HEAD commit and tree' };
|
|
35
35
|
}
|
|
36
36
|
const statusResult = runGit(['status', '--porcelain=v2', '-z', '--untracked-files=all'], cwd);
|
|
37
37
|
if (!statusResult.ok) {
|
|
@@ -46,7 +46,7 @@ export function hashWorkingTree(cwd) {
|
|
|
46
46
|
hash.update('\0');
|
|
47
47
|
hash.update(headTreeSha);
|
|
48
48
|
hash.update('\0');
|
|
49
|
-
for (const relativePath of [...pathsResult.paths].
|
|
49
|
+
for (const relativePath of [...pathsResult.paths].toSorted()) {
|
|
50
50
|
const content = digestPathContent(toplevel, relativePath);
|
|
51
51
|
if (!content.ok) {
|
|
52
52
|
return content;
|
|
@@ -81,7 +81,7 @@ function collectChangedPaths(statusOutput) {
|
|
|
81
81
|
continue;
|
|
82
82
|
}
|
|
83
83
|
if (SUBMODULE_BEARING_TYPES.has(type) && extractField(record, 2)?.startsWith('S') === true) {
|
|
84
|
-
return { ok: false, reason: 'the working tree
|
|
84
|
+
return { ok: false, reason: 'the working tree contains a submodule, whose content this hash does not cover' };
|
|
85
85
|
}
|
|
86
86
|
const precedingFieldCount = PRECEDING_FIELD_COUNTS[type];
|
|
87
87
|
if (precedingFieldCount === undefined) {
|
|
@@ -96,7 +96,7 @@ function collectChangedPaths(statusOutput) {
|
|
|
96
96
|
index++;
|
|
97
97
|
const originalPath = records[index];
|
|
98
98
|
if (originalPath === undefined || originalPath === '') {
|
|
99
|
-
return { ok: false, reason: 'git status reported a rename
|
|
99
|
+
return { ok: false, reason: 'git status reported a rename without an original path' };
|
|
100
100
|
}
|
|
101
101
|
paths.add(originalPath);
|
|
102
102
|
}
|
|
@@ -1,19 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The manifest patterns a declared `packages` list resolves to, split by what each entry asks of the matcher.
|
|
2
|
+
* The manifest patterns that a declared `packages` list resolves to, split by what each entry asks of the matcher.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Each entry is already rewritten to match a manifest, so that a caller re-matching a subset applies the same
|
|
5
|
+
* rewriting as a full resolution.
|
|
6
6
|
*/
|
|
7
7
|
export interface WorkspacePatternSplit {
|
|
8
8
|
excludedPatterns: string[];
|
|
9
9
|
includedPatterns: string[];
|
|
10
10
|
}
|
|
11
11
|
/**
|
|
12
|
-
* Matches manifest patterns against a monorepo root, returning the absolute directories that
|
|
12
|
+
* Matches manifest patterns against a monorepo root, returning the absolute directories that contain a matched
|
|
13
13
|
* manifest, sorted and free of duplicates.
|
|
14
|
-
*
|
|
15
|
-
* Takes the exclusion set as an argument of its own, so a caller diagnosing an empty resolution can re-match
|
|
16
|
-
* the positive patterns alone and learn whether the exclusions are what emptied it.
|
|
17
14
|
*/
|
|
18
15
|
export declare function matchPackageDirs(monorepoRoot: string, includedPatterns: readonly string[], excludedPatterns: readonly string[]): string[];
|
|
19
16
|
/**
|
|
@@ -25,9 +22,7 @@ export declare function matchPackageDirs(monorepoRoot: string, includedPatterns:
|
|
|
25
22
|
*/
|
|
26
23
|
export declare function resolvePackageDirs(monorepoRoot: string, patterns: readonly string[]): string[];
|
|
27
24
|
/**
|
|
28
|
-
* Splits a declared `packages` list into the manifest patterns the matcher includes and the ones it
|
|
29
|
-
*
|
|
30
|
-
* The sole reader of what counts as a positive pattern, shared by a resolution and by a diagnosis of its empty
|
|
31
|
-
* result: two readers classifying entries separately could disagree about which condition a manifest is in.
|
|
25
|
+
* Splits a declared `packages` list into the manifest patterns that the matcher includes and the ones that it
|
|
26
|
+
* excludes. A resolution and the diagnosis of its empty result both classify entries here, so that they agree.
|
|
32
27
|
*/
|
|
33
28
|
export declare function splitWorkspacePatterns(patterns: readonly string[]): WorkspacePatternSplit;
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFl
|
|
|
10
10
|
export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
|
|
11
11
|
export { readPackageVersion } from './readPackageVersion.js';
|
|
12
12
|
export type { GlyphSet, InvalidOutputStyle, OutputStyle, ResolveStreamStylesOptions, StatusGlyphName, StreamStyleResolution, StreamStyles, TruncateToWidthOptions, } from './terminal.js';
|
|
13
|
-
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
|
|
13
|
+
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
|
|
14
|
+
export type { ManagedFileOutcome, ManagedFileResult } from './updateManagedFile.js';
|
|
15
|
+
export { updateManagedFile } from './updateManagedFile.js';
|
|
14
16
|
export type { WriteOutcome, WriteResult } from './writeFileWithCheck.js';
|
|
15
17
|
export { writeFileWithCheck } from './writeFileWithCheck.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -6,5 +6,6 @@ export { hasErrnoCode } from "./hasErrnoCode.js";
|
|
|
6
6
|
export { hashWorkingTree, readHeadSha } from "./hashWorkingTree.js";
|
|
7
7
|
export { parseArgs, parseArgsOrExit, ParseError } from "./parseArgs.js";
|
|
8
8
|
export { readPackageVersion } from "./readPackageVersion.js";
|
|
9
|
-
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
|
|
9
|
+
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
|
|
10
|
+
export { updateManagedFile } from "./updateManagedFile.js";
|
|
10
11
|
export { writeFileWithCheck } from "./writeFileWithCheck.js";
|
package/dist/esm/parseArgs.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export interface FlagDefinition {
|
|
|
6
6
|
}
|
|
7
7
|
/** Map of camelCase property names to their flag definitions. */
|
|
8
8
|
export type FlagSchema = Record<string, FlagDefinition>;
|
|
9
|
-
/**
|
|
9
|
+
/** Infers the result type from a flag schema: booleans become `boolean`, strings become `string | undefined`. */
|
|
10
10
|
export type ParsedFlags<S extends FlagSchema> = {
|
|
11
11
|
[K in keyof S]: S[K]['type'] extends 'boolean' ? boolean : string | undefined;
|
|
12
12
|
};
|
|
@@ -20,12 +20,12 @@ export interface ParseArgsOptions {
|
|
|
20
20
|
/** When true, positionals are collected; otherwise an unexpected positional throws. Defaults to false. */
|
|
21
21
|
allowPositionals?: boolean;
|
|
22
22
|
}
|
|
23
|
-
/** Discriminates the failure modes `parseArgs` reports. */
|
|
23
|
+
/** Discriminates the failure modes that `parseArgs` reports. */
|
|
24
24
|
export type ParseErrorKind = 'unknown-flag' | 'missing-value' | 'unexpected-value' | 'unexpected-positional';
|
|
25
25
|
/**
|
|
26
26
|
* Error thrown by `parseArgs` on invalid input.
|
|
27
27
|
*
|
|
28
|
-
* Carries the failure `kind` and the offending token in `flag
|
|
28
|
+
* Carries the failure `kind` and the offending token in `flag`: a flag as the user typed it, or the
|
|
29
29
|
* positional value for `'unexpected-positional'`. Its `message` is composed from those fields, so error
|
|
30
30
|
* wording is uniform across every kind.
|
|
31
31
|
*/
|
|
@@ -35,17 +35,13 @@ export declare class ParseError extends Error {
|
|
|
35
35
|
constructor(kind: ParseErrorKind, flag: string);
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
38
|
-
*
|
|
38
|
+
* Parses a pre-sliced argv array against a flag schema.
|
|
39
39
|
*
|
|
40
40
|
* Delegates tokenizing to `node:util.parseArgs` (non-strict, with tokens) and validates the token
|
|
41
41
|
* stream against the schema. Throws `ParseError` on an unknown flag, a missing string-flag value, a
|
|
42
|
-
* value supplied to a boolean flag, or
|
|
42
|
+
* value supplied to a boolean flag, or (unless `options.allowPositionals` is set) an unexpected
|
|
43
43
|
* positional argument. Does not write output or exit.
|
|
44
44
|
*/
|
|
45
45
|
export declare function parseArgs<S extends FlagSchema>(argv: string[], schema: S, options?: ParseArgsOptions): ParsedArgs<S>;
|
|
46
|
-
/**
|
|
47
|
-
* Parse argv, or print a usage error to stderr and exit non-zero.
|
|
48
|
-
*
|
|
49
|
-
* The canonical "parse or die" entry point for CLI commands that terminate on invalid input.
|
|
50
|
-
*/
|
|
46
|
+
/** Parses argv, or prints a usage error to stderr and exits non-zero. */
|
|
51
47
|
export declare function parseArgsOrExit<S extends FlagSchema>(argv: string[], schema: S, options?: ParseArgsOptions): ParsedArgs<S>;
|
|
@@ -1,14 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Reads the `version` field from the nearest ancestor `package.json`, starting
|
|
3
3
|
* from the directory of the given `import.meta.url`.
|
|
4
4
|
*
|
|
5
|
-
* Composes `findPackageRoot` with a `package.json` read so callers get a
|
|
6
|
-
* depth-agnostic version lookup that works in source layouts (`src/...`),
|
|
7
|
-
* compiled layouts (`dist/esm/...`), and consumer layouts (npm-installed,
|
|
8
|
-
* `npx`).
|
|
9
|
-
*
|
|
10
5
|
* Throws if the located `package.json` lacks a string `version` field.
|
|
11
|
-
* Propagates `findPackageRoot`'s own error when
|
|
12
|
-
*
|
|
6
|
+
* Propagates `findPackageRoot`'s own error when it does not find an ancestor
|
|
7
|
+
* `package.json`.
|
|
13
8
|
*/
|
|
14
9
|
export declare function readPackageVersion(fromUrl: string): string;
|
package/dist/esm/terminal.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Writable } from 'node:stream';
|
|
2
2
|
import { type GlyphSet, type InvalidOutputStyle, type OutputStyle, type StatusGlyphName } from '@williamthorsen/toolbelt.terminal/candidate';
|
|
3
|
+
import type { ManagedFileResult } from './updateManagedFile.js';
|
|
3
4
|
import type { WriteResult } from './writeFileWithCheck.js';
|
|
4
5
|
export type { GlyphSet, InvalidOutputStyle, OutputStyle, StatusGlyphName, TruncateToWidthOptions, } from '@williamthorsen/toolbelt.terminal/candidate';
|
|
5
6
|
export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
|
|
@@ -7,7 +8,7 @@ export interface ResolveStreamStylesOptions {
|
|
|
7
8
|
/** Raw arguments in which to find `flag`; read only when `flag` is given. */
|
|
8
9
|
readonly argv?: readonly string[] | undefined;
|
|
9
10
|
readonly env: Readonly<Record<string, string | undefined>>;
|
|
10
|
-
/** The environment variable
|
|
11
|
+
/** The environment variable containing the caller's standing preference: `auto`, `plain`, or `rich`. */
|
|
11
12
|
readonly envVar: string;
|
|
12
13
|
/** The flag naming a style for one invocation, leading dashes included; it outranks `envVar`. */
|
|
13
14
|
readonly flag?: string | undefined;
|
|
@@ -15,7 +16,7 @@ export interface ResolveStreamStylesOptions {
|
|
|
15
16
|
readonly stdoutIsTty: boolean;
|
|
16
17
|
}
|
|
17
18
|
export interface StreamStyleResolution {
|
|
18
|
-
/** The first value of `flag` or `envVar` that
|
|
19
|
+
/** The first value of `flag` or `envVar` that does not name a setting; resolution continues with the next source. */
|
|
19
20
|
readonly invalid?: InvalidOutputStyle | undefined;
|
|
20
21
|
readonly styles: StreamStyles;
|
|
21
22
|
}
|
|
@@ -23,11 +24,7 @@ export interface StreamStyles {
|
|
|
23
24
|
readonly stderr: OutputStyle;
|
|
24
25
|
readonly stdout: OutputStyle;
|
|
25
26
|
}
|
|
26
|
-
/**
|
|
27
|
-
* Renders the canonical `Error: <message>` line (without a trailing newline) โ the single
|
|
28
|
-
* definition of this shape. Use it where the line is a value rather than a write target,
|
|
29
|
-
* e.g. a command that returns its message for the caller to print.
|
|
30
|
-
*/
|
|
27
|
+
/** Renders the canonical `Error: <message>` line, without a trailing newline, for a caller that needs it as a value. */
|
|
31
28
|
export declare function formatErrorLine(message: string): string;
|
|
32
29
|
/**
|
|
33
30
|
* Renders a glyph from `glyphs` and a message, omitting the separating space when the glyph's variant is
|
|
@@ -44,12 +41,13 @@ export declare function printSkip(message: string, style?: OutputStyle): void;
|
|
|
44
41
|
export declare function printStep(message: string): void;
|
|
45
42
|
/** Prints a success message to stdout, in the style detected for stdout unless one is given. */
|
|
46
43
|
export declare function printSuccess(message: string, style?: OutputStyle): void;
|
|
44
|
+
/** Writes the canonical `Error: <message>` line to `stream`, which an in-process CLI sets to its own `Writable`. */
|
|
45
|
+
export declare function reportError(message: string, stream?: Writable): void;
|
|
47
46
|
/**
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* route output through a `Writable` rather than touching `process.stderr` directly.
|
|
47
|
+
* Prints a status line for a managed-file result, followed by its diff indented beneath it: a failure to stderr,
|
|
48
|
+
* every other outcome to stdout.
|
|
51
49
|
*/
|
|
52
|
-
export declare function
|
|
50
|
+
export declare function reportTemplateUpdate(result: ManagedFileResult, dryRun: boolean, styles?: StreamStyles): void;
|
|
53
51
|
/**
|
|
54
52
|
* Prints a terminal message for a write result based on its outcome: a failure to stderr, every
|
|
55
53
|
* other outcome to stdout. Each message takes its own stream's style from `styles`; without
|
|
@@ -59,7 +57,7 @@ export declare function reportWriteResult(result: WriteResult, dryRun: boolean,
|
|
|
59
57
|
/**
|
|
60
58
|
* Resolves the style of each output stream: the flag when one is named, else the named environment
|
|
61
59
|
* variable, else detection from `CI`, the stream's terminal state, and `TERM`. Never throws; a value
|
|
62
|
-
* that
|
|
60
|
+
* that does not name a setting is returned in `invalid`, for the caller to report with
|
|
63
61
|
* `describeInvalidOutputStyle`.
|
|
64
62
|
*/
|
|
65
63
|
export declare function resolveStreamStyles(options: ResolveStreamStylesOptions): StreamStyleResolution;
|
package/dist/esm/terminal.js
CHANGED
|
@@ -29,6 +29,28 @@ export function printSuccess(message, style = detectStreamStyle(process.stdout))
|
|
|
29
29
|
export function reportError(message, stream = process.stderr) {
|
|
30
30
|
stream.write(`${formatErrorLine(message)}\n`);
|
|
31
31
|
}
|
|
32
|
+
export function reportTemplateUpdate(result, dryRun, styles) {
|
|
33
|
+
const style = styles?.stdout;
|
|
34
|
+
switch (result.outcome) {
|
|
35
|
+
case 'created':
|
|
36
|
+
printSuccess(dryRun ? `[dry-run] Would create ${result.filePath}` : `Created ${result.filePath}`, style);
|
|
37
|
+
break;
|
|
38
|
+
case 'updated':
|
|
39
|
+
printSuccess(dryRun ? `[dry-run] Would update ${result.filePath}` : `Updated ${result.filePath}`, style);
|
|
40
|
+
if (result.diff !== undefined && result.diff !== '') {
|
|
41
|
+
console.info(indentLines(result.diff, ' '.repeat(4)));
|
|
42
|
+
}
|
|
43
|
+
break;
|
|
44
|
+
case 'up-to-date':
|
|
45
|
+
printSuccess(`${result.filePath} (up to date)`, style);
|
|
46
|
+
break;
|
|
47
|
+
case 'failed': {
|
|
48
|
+
const detail = result.error === undefined ? '' : `: ${result.error}`;
|
|
49
|
+
printError(`Failed to update ${result.filePath}${detail}`, styles?.stderr);
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
32
54
|
export function reportWriteResult(result, dryRun, styles) {
|
|
33
55
|
const style = styles?.stdout;
|
|
34
56
|
switch (result.outcome) {
|
|
@@ -79,3 +101,9 @@ export function resolveStreamStyles(options) {
|
|
|
79
101
|
function detectStreamStyle(stream) {
|
|
80
102
|
return detectOutputStyle({ env: process.env, isTty: stream.isTTY === true });
|
|
81
103
|
}
|
|
104
|
+
function indentLines(text, indent) {
|
|
105
|
+
return text
|
|
106
|
+
.split('\n')
|
|
107
|
+
.map((line) => `${indent}${line}`)
|
|
108
|
+
.join('\n');
|
|
109
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Outcome of an `updateManagedFile` call. */
|
|
2
|
+
export type ManagedFileOutcome = 'created' | 'updated' | 'up-to-date' | 'failed';
|
|
3
|
+
/** Result returned by `updateManagedFile`. */
|
|
4
|
+
export interface ManagedFileResult {
|
|
5
|
+
filePath: string;
|
|
6
|
+
outcome: ManagedFileOutcome;
|
|
7
|
+
/** Hunks of a unified diff from the existing file to the rendered content; present only for `updated`. */
|
|
8
|
+
diff?: string;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Writes `content` to a file that a package renders from a template, when the file is missing or its bytes differ.
|
|
13
|
+
*
|
|
14
|
+
* With `dryRun`, returns the outcome and diff without writing. Returns a filesystem error in the result rather than
|
|
15
|
+
* throwing it.
|
|
16
|
+
*/
|
|
17
|
+
export declare function updateManagedFile(filePath: string, content: string, options: {
|
|
18
|
+
dryRun: boolean;
|
|
19
|
+
}): ManagedFileResult;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { describeError } from '@williamthorsen/toolbelt.errors';
|
|
4
|
+
import { structuredPatch } from 'diff';
|
|
5
|
+
export function updateManagedFile(filePath, content, options) {
|
|
6
|
+
let existing;
|
|
7
|
+
if (existsSync(filePath)) {
|
|
8
|
+
try {
|
|
9
|
+
existing = readFileSync(filePath, 'utf8');
|
|
10
|
+
}
|
|
11
|
+
catch (error) {
|
|
12
|
+
return { filePath, outcome: 'failed', error: describeError(error) };
|
|
13
|
+
}
|
|
14
|
+
if (existing === content) {
|
|
15
|
+
return { filePath, outcome: 'up-to-date' };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const result = existing === undefined
|
|
19
|
+
? { filePath, outcome: 'created' }
|
|
20
|
+
: { filePath, outcome: 'updated', diff: formatHunks(existing, content) };
|
|
21
|
+
if (options.dryRun) {
|
|
22
|
+
return result;
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
26
|
+
writeFileSync(filePath, content, 'utf8');
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
return { filePath, outcome: 'failed', error: describeError(error) };
|
|
30
|
+
}
|
|
31
|
+
return result;
|
|
32
|
+
}
|
|
33
|
+
function formatHunks(before, after) {
|
|
34
|
+
const { hunks } = structuredPatch('', '', before, after, undefined, undefined, { context: 3 });
|
|
35
|
+
return hunks
|
|
36
|
+
.flatMap((hunk) => [
|
|
37
|
+
`@@ -${String(hunk.oldStart)},${String(hunk.oldLines)} +${String(hunk.newStart)},${String(hunk.newLines)} @@`,
|
|
38
|
+
...hunk.lines.filter((line) => !line.startsWith('\\')),
|
|
39
|
+
])
|
|
40
|
+
.join('\n');
|
|
41
|
+
}
|
package/dist/esm/workspace.d.ts
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* The condition under which a workspace resolves to an empty set of package directories. Each calls for a
|
|
3
|
+
* different remedy:
|
|
4
|
+
*
|
|
5
|
+
* - `all-excluded`: The positive patterns match packages, and the exclusions remove every one.
|
|
6
|
+
* - `no-package`: The positive patterns do not match any package.
|
|
7
|
+
* - `no-packages-list`: The manifest does not declare a pattern list, which pnpm resolves to the root package alone.
|
|
8
|
+
* - `no-pattern`: The list does not contain a positive pattern, as with `!` entries and entries that YAML emptied.
|
|
9
|
+
* - `unreadable-manifest`: The manifest cannot be read or parsed, whatever patterns it may declare.
|
|
10
|
+
* - `unreadable-packages`: The `packages` value is not a list of strings.
|
|
11
|
+
*/
|
|
2
12
|
export type EmptyWorkspaceCause = 'all-excluded' | 'no-package' | 'no-packages-list' | 'no-pattern' | 'unreadable-manifest' | 'unreadable-packages';
|
|
3
13
|
/**
|
|
4
|
-
* What resolving a directory's workspace patterns produced:
|
|
5
|
-
* to a set of package directories, or it resolves to none and the cause says which condition emptied it.
|
|
14
|
+
* What resolving a directory's workspace patterns produced: The directory does not declare a workspace, it
|
|
15
|
+
* resolves to a set of package directories, or it resolves to none and the cause says which condition emptied it.
|
|
6
16
|
*
|
|
7
|
-
* The
|
|
8
|
-
*
|
|
9
|
-
* can see.
|
|
17
|
+
* The last two include the declared patterns because a message composed from one quotes them back to the reader.
|
|
18
|
+
* The patterns are empty when the manifest does not yield a pattern list.
|
|
10
19
|
*/
|
|
11
20
|
export type WorkspaceResolution = {
|
|
12
21
|
kind: 'empty';
|
|
@@ -20,49 +29,30 @@ export type WorkspaceResolution = {
|
|
|
20
29
|
patterns: string[];
|
|
21
30
|
};
|
|
22
31
|
/**
|
|
23
|
-
* Finds the monorepo root by walking up from `startDir`, defaulting to `process.cwd()`,
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* Returns nothing where the walk runs out of parent directories, which a CLI turns into whichever failure its
|
|
27
|
-
* own error boundary calls for.
|
|
32
|
+
* Finds the monorepo root by walking up from `startDir`, defaulting to `process.cwd()`, to the first directory
|
|
33
|
+
* containing `pnpm-workspace.yaml`, or returns `undefined` when the walk does not find one.
|
|
28
34
|
*/
|
|
29
35
|
export declare function findMonorepoRoot(startDir?: string): string | undefined;
|
|
30
36
|
/** Reports whether a directory is the monorepo root, which the workspace manifest's presence marks. */
|
|
31
37
|
export declare function isMonorepoRoot(dir: string): boolean;
|
|
32
38
|
/**
|
|
33
|
-
* Reads the `overrides` block from the monorepo root's `pnpm-workspace.yaml`, the site pnpm reads an
|
|
34
|
-
*
|
|
39
|
+
* Reads the `overrides` block from the monorepo root's `pnpm-workspace.yaml`, the site from which pnpm reads an
|
|
40
|
+
* override.
|
|
35
41
|
*
|
|
36
|
-
* Returns nothing when the manifest is missing, unreadable, unparseable, or
|
|
37
|
-
* entry whose value is not a string.
|
|
42
|
+
* Returns nothing when the manifest is missing, unreadable, unparseable, or does not declare the block, and drops
|
|
43
|
+
* an entry whose value is not a string.
|
|
38
44
|
*/
|
|
39
45
|
export declare function readWorkspaceOverrides(monorepoRoot: string): Record<string, string> | undefined;
|
|
40
46
|
/**
|
|
41
|
-
* Reads the manifest `name` each of the given package directories declares,
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* A directory whose manifest is missing, unparseable, or nameless contributes nothing. The sweep runs for a
|
|
45
|
-
* diagnostic's sake, so one malformed manifest elsewhere in the workspace must not replace the diagnostic the
|
|
46
|
-
* reader asked for with a failure of its own.
|
|
47
|
+
* Reads the manifest `name` that each of the given package directories declares, skipping a directory whose
|
|
48
|
+
* manifest is missing, unparseable, or nameless.
|
|
47
49
|
*/
|
|
48
50
|
export declare function readWorkspacePackageNames(packageDirs: readonly string[]): string[];
|
|
49
51
|
/**
|
|
50
|
-
* Resolves the workspace a directory
|
|
51
|
-
* exclusions
|
|
52
|
-
*
|
|
53
|
-
* Reaches the filesystem a second time for `all-excluded` alone, re-matching the positive patterns without the
|
|
54
|
-
* exclusion set. That runs only where a resolution has already come back empty.
|
|
55
|
-
*
|
|
56
|
-
* Three causes separate what a manifest declares from what the reader could make of it, because one remedy
|
|
57
|
-
* does not answer them all. `no-packages-list` is a manifest declaring nothing, an absent `packages` key or an
|
|
58
|
-
* empty list, which pnpm resolves to the root package alone; `unreadable-packages` is a `packages` value that
|
|
59
|
-
* is not a list of strings, which declares something the reader refused; and `no-pattern` is a list whose
|
|
60
|
-
* entries all fail to become a positive pattern, `!` entries and entries YAML emptied. A caller treating an
|
|
61
|
-
* empty resolution as a failure needs the first held apart from the other two, and a caller composing a
|
|
62
|
-
* message needs all three.
|
|
52
|
+
* Resolves the workspace declared by a directory, applying pnpm's pattern semantics (including `!`-prefixed
|
|
53
|
+
* exclusions) and reporting which condition left the result empty.
|
|
63
54
|
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
* one and a syntax error above it.
|
|
55
|
+
* Reaches the filesystem a second time only when the resolution is empty, re-matching the positive patterns
|
|
56
|
+
* without the exclusions to tell `all-excluded` from `no-package`.
|
|
67
57
|
*/
|
|
68
58
|
export declare function resolveWorkspace(monorepoRoot: string): WorkspaceResolution;
|
package/dist/esm/workspace.js
CHANGED
|
@@ -1,21 +1,12 @@
|
|
|
1
1
|
import { existsSync, readFileSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
+
import { findDirectoryChainMatch } from '@williamthorsen/toolbelt.filesystem';
|
|
3
4
|
import { parse } from 'yaml';
|
|
4
5
|
import { matchPackageDirs, resolvePackageDirs, splitWorkspacePatterns } from "./helpers/workspace-patterns.js";
|
|
5
6
|
const PACKAGE_MANIFEST = 'package.json';
|
|
6
7
|
const WORKSPACE_MANIFEST = 'pnpm-workspace.yaml';
|
|
7
8
|
export function findMonorepoRoot(startDir) {
|
|
8
|
-
|
|
9
|
-
for (;;) {
|
|
10
|
-
if (isMonorepoRoot(dir)) {
|
|
11
|
-
return dir;
|
|
12
|
-
}
|
|
13
|
-
const parent = path.dirname(dir);
|
|
14
|
-
if (parent === dir) {
|
|
15
|
-
return undefined;
|
|
16
|
-
}
|
|
17
|
-
dir = parent;
|
|
18
|
-
}
|
|
9
|
+
return findDirectoryChainMatch(startDir ?? process.cwd(), [WORKSPACE_MANIFEST])?.dir;
|
|
19
10
|
}
|
|
20
11
|
export function isMonorepoRoot(dir) {
|
|
21
12
|
return existsSync(path.join(dir, WORKSPACE_MANIFEST));
|
|
@@ -7,12 +7,11 @@ export interface WriteResult {
|
|
|
7
7
|
error?: string;
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
10
|
+
* Writes a file with existence and content checks, creating parent directories as needed.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* `{ outcome: 'failed' }` rather than thrown.
|
|
12
|
+
* Without `overwrite`, leaves an existing file alone and reports it `up-to-date` when its content matches up to
|
|
13
|
+
* trailing whitespace. With `dryRun`, returns the outcome without writing. Returns a filesystem error in the
|
|
14
|
+
* result rather than throwing it: `skipped` when the existing file cannot be read, `failed` when the write fails.
|
|
16
15
|
*/
|
|
17
16
|
export declare function writeFileWithCheck(filePath: string, content: string, options: {
|
|
18
17
|
dryRun: boolean;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@williamthorsen/nmr-core",
|
|
3
|
-
"version": "0.13.
|
|
3
|
+
"version": "0.13.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Shared utilities for node-monorepo-tools packages",
|
|
6
6
|
"keywords": [
|
|
@@ -39,14 +39,15 @@
|
|
|
39
39
|
"dist"
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@williamthorsen/toolbelt.errors": "0.8.
|
|
43
|
-
"@williamthorsen/toolbelt.
|
|
42
|
+
"@williamthorsen/toolbelt.errors": "0.8.2",
|
|
43
|
+
"@williamthorsen/toolbelt.filesystem": "0.9.2",
|
|
44
|
+
"@williamthorsen/toolbelt.terminal": "0.2.1",
|
|
45
|
+
"diff": "9.0.0",
|
|
44
46
|
"yaml": "2.9.1"
|
|
45
47
|
},
|
|
46
48
|
"devDependencies": {
|
|
47
|
-
"@williamthorsen/toolbelt.
|
|
48
|
-
"@williamthorsen/toolbelt.
|
|
49
|
-
"@williamthorsen/toolbelt.vitest": "0.10.1",
|
|
49
|
+
"@williamthorsen/toolbelt.testing": "0.6.2",
|
|
50
|
+
"@williamthorsen/toolbelt.vitest": "0.10.2",
|
|
50
51
|
"vitest": "4.1.11"
|
|
51
52
|
},
|
|
52
53
|
"engines": {
|