@williamthorsen/nmr-core 0.13.6 โ 0.15.0
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 +56 -0
- package/CHANGELOG.md +22 -0
- package/README.md +7 -1
- package/dist/esm/UserError.d.ts +9 -0
- package/dist/esm/UserError.js +6 -0
- package/dist/esm/cache-store.d.ts +11 -0
- package/dist/esm/cache-store.js +27 -9
- package/dist/esm/collectChangedPaths.js +6 -6
- package/dist/esm/gitObjects.js +11 -11
- package/dist/esm/gitOutputLimit.d.ts +1 -1
- package/dist/esm/gitOutputLimit.js +1 -1
- package/dist/esm/hashWorkingTree.js +34 -34
- package/dist/esm/helpers/workspace-patterns.js +6 -6
- package/dist/esm/index.d.ts +5 -3
- package/dist/esm/index.js +5 -3
- package/dist/esm/parseArgs.d.ts +2 -1
- package/dist/esm/parseArgs.js +12 -9
- package/dist/esm/runGit.js +2 -2
- package/dist/esm/terminal.d.ts +12 -2
- package/dist/esm/terminal.js +29 -10
- package/dist/esm/timer.d.ts +5 -0
- package/dist/esm/timer.js +4 -0
- package/dist/esm/updateManagedFile.d.ts +2 -2
- package/dist/esm/updateManagedFile.js +8 -8
- package/dist/esm/workspace.js +18 -18
- package/dist/esm/writeFileWithCheck.d.ts +4 -4
- package/dist/esm/writeFileWithCheck.js +7 -7
- package/package.json +9 -8
package/.meta/changelog.json
CHANGED
|
@@ -1,4 +1,60 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.15.0",
|
|
4
|
+
"date": "2026-11-05",
|
|
5
|
+
"sections": [
|
|
6
|
+
{
|
|
7
|
+
"title": "๐ Features",
|
|
8
|
+
"audience": "all",
|
|
9
|
+
"items": [
|
|
10
|
+
{
|
|
11
|
+
"description": "Adds `reportCrash` to `@williamthorsen/nmr-core`, which writes `<bin>: internal error: <message>` followed by the error's stack frames, so that a CLI can report a crash differently from a handled error written by `reportError`. (#1153)",
|
|
12
|
+
"hash": "0289c032b00438984efcf7466f2b3055b4dbc546",
|
|
13
|
+
"entry": 3
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"title": "๐๏ธ Internal features",
|
|
19
|
+
"audience": "dev",
|
|
20
|
+
"items": [
|
|
21
|
+
{
|
|
22
|
+
"description": "Adds `UserError` and `reportFailure` to `@williamthorsen/nmr-core` so that a CLI's last-resort handler prints an anticipated failure as `Error: <message>` and anything else as an internal error, and makes `ParseError` extend `UserError`. (#1157)",
|
|
23
|
+
"hash": "ef1ed5f50bf0b01f19b6d6fe82a40322a8286002",
|
|
24
|
+
"entry": 3
|
|
25
|
+
}
|
|
26
|
+
]
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
"version": "0.14.0",
|
|
32
|
+
"date": "2026-10-27",
|
|
33
|
+
"sections": [
|
|
34
|
+
{
|
|
35
|
+
"title": "๐ Features",
|
|
36
|
+
"audience": "all",
|
|
37
|
+
"items": [
|
|
38
|
+
{
|
|
39
|
+
"description": "Report the time that a build-cache hit saved (#1112)",
|
|
40
|
+
"body": "Adds the time that a build-cache hit saved to the skip line printed by `nmr-compile`, as in `Skipping build, saved ~2.1s.`, when the skipped emit took at least a second. The change also measures the durations that nmr reports on the monotonic clock, so that an adjustment of the system clock during a run no longer shortens or negates them.",
|
|
41
|
+
"hash": "ead0549c50d886ef371cb03d979883e027b051c2"
|
|
42
|
+
}
|
|
43
|
+
]
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"title": "โป๏ธ Refactoring",
|
|
47
|
+
"audience": "dev",
|
|
48
|
+
"items": [
|
|
49
|
+
{
|
|
50
|
+
"description": "Renames nmr-core's identifiers to follow the naming conventions, changing the exported option keys `dryRun` and `overwrite` to `isDryRun` and `shouldOverwrite` and the constant `GIT_OUTPUT_LIMIT` to `GIT_OUTPUT_LIMIT_BYTES`, and updates their call sites in nmr, release-kit, and v11y-check. (#1125)",
|
|
51
|
+
"hash": "2cb60f628512ed6ec2273a219a7b6c71aa35b1bf",
|
|
52
|
+
"entry": 1
|
|
53
|
+
}
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
]
|
|
57
|
+
},
|
|
2
58
|
{
|
|
3
59
|
"version": "0.13.6",
|
|
4
60
|
"date": "2026-10-24",
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,28 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## 0.15.0 โ 2026-11-05
|
|
6
|
+
|
|
7
|
+
### ๐ Features
|
|
8
|
+
|
|
9
|
+
- Adds `reportCrash` to `@williamthorsen/nmr-core`, which writes `<bin>: internal error: <message>` followed by the error's stack frames, so that a CLI can report a crash differently from a handled error written by `reportError`. (#1153)
|
|
10
|
+
|
|
11
|
+
### ๐๏ธ Internal features
|
|
12
|
+
|
|
13
|
+
- Adds `UserError` and `reportFailure` to `@williamthorsen/nmr-core` so that a CLI's last-resort handler prints an anticipated failure as `Error: <message>` and anything else as an internal error, and makes `ParseError` extend `UserError`. (#1157)
|
|
14
|
+
|
|
15
|
+
## 0.14.0 โ 2026-10-27
|
|
16
|
+
|
|
17
|
+
### ๐ Features
|
|
18
|
+
|
|
19
|
+
- Report the time that a build-cache hit saved (#1112)
|
|
20
|
+
|
|
21
|
+
Adds the time that a build-cache hit saved to the skip line printed by `nmr-compile`, as in `Skipping build, saved ~2.1s.`, when the skipped emit took at least a second. The change also measures the durations that nmr reports on the monotonic clock, so that an adjustment of the system clock during a run no longer shortens or negates them.
|
|
22
|
+
|
|
23
|
+
### โป๏ธ Refactoring
|
|
24
|
+
|
|
25
|
+
- Renames nmr-core's identifiers to follow the naming conventions, changing the exported option keys `dryRun` and `overwrite` to `isDryRun` and `shouldOverwrite` and the constant `GIT_OUTPUT_LIMIT` to `GIT_OUTPUT_LIMIT_BYTES`, and updates their call sites in nmr, release-kit, and v11y-check. (#1125)
|
|
26
|
+
|
|
5
27
|
## 0.13.6 โ 2026-10-24
|
|
6
28
|
|
|
7
29
|
### ๐งช Tests
|
package/README.md
CHANGED
|
@@ -6,7 +6,13 @@ 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
|
|
9
|
+
<!-- section:release-notes -->
|
|
10
|
+
## Release notes โ v0.15.0 (2026-11-05)
|
|
11
|
+
|
|
12
|
+
### ๐ Features
|
|
13
|
+
|
|
14
|
+
- Adds `reportCrash` to `@williamthorsen/nmr-core`, which writes `<bin>: internal error: <message>` followed by the error's stack frames, so that a CLI can report a crash differently from a handled error written by `reportError`. (#1153)
|
|
15
|
+
<!-- /section:release-notes -->
|
|
10
16
|
|
|
11
17
|
## Installation
|
|
12
18
|
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A failure that the tool anticipated -- in the user's input, config, or environment, including a failed external
|
|
3
|
+
* command -- rather than a fault in the tool.
|
|
4
|
+
*
|
|
5
|
+
* A CLI's last-resort handler prints one of these as `Error: <message>` and anything else as an internal error.
|
|
6
|
+
*/
|
|
7
|
+
export declare class UserError extends Error {
|
|
8
|
+
constructor(message: string, options?: ErrorOptions);
|
|
9
|
+
}
|
|
@@ -27,6 +27,12 @@ export interface CacheEntryRef extends CacheDirRef {
|
|
|
27
27
|
* miss, never an error: The caller's fallback is to do the work again, which is always correct.
|
|
28
28
|
*/
|
|
29
29
|
export declare function readCacheEntry(entryPath: string): Promise<string | undefined>;
|
|
30
|
+
/**
|
|
31
|
+
* Reads the value that `writeGuardedCacheEntry` recorded under `token`, or `undefined` when the entry is missing,
|
|
32
|
+
* unreadable, recorded under another token, or holds a value that `isValidValue` rejects. A token that no longer
|
|
33
|
+
* matches means that the value describes inputs other than the current ones.
|
|
34
|
+
*/
|
|
35
|
+
export declare function readGuardedCacheEntry<T>(entryPath: string, token: string, isValidValue: (value: unknown) => value is T): Promise<T | undefined>;
|
|
30
36
|
/**
|
|
31
37
|
* Reads a JSON entry and narrows it with `isValidEntry`, returning `undefined` when the entry is missing,
|
|
32
38
|
* unparseable, or of the wrong shape. Content written in an older format therefore reads as a miss rather than
|
|
@@ -57,3 +63,8 @@ export declare function resolveCacheEntryPath(ref: CacheEntryRef): string;
|
|
|
57
63
|
* for whom a failed cache write is not worth failing over catches it.
|
|
58
64
|
*/
|
|
59
65
|
export declare function writeCacheEntry(entryPath: string, content: string): Promise<void>;
|
|
66
|
+
/**
|
|
67
|
+
* Writes `value` with the token under which `readGuardedCacheEntry` returns it, atomically as `writeCacheEntry`
|
|
68
|
+
* does. Throws when the write cannot be completed.
|
|
69
|
+
*/
|
|
70
|
+
export declare function writeGuardedCacheEntry(entryPath: string, token: string, value: unknown): Promise<void>;
|
package/dist/esm/cache-store.js
CHANGED
|
@@ -3,7 +3,7 @@ import { readFile, rm } from 'node:fs/promises';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { findDirectoryChainMatch } from '@williamthorsen/toolbelt.filesystem';
|
|
5
5
|
import { writeAtomic } from '@williamthorsen/toolbelt.filesystem/candidate';
|
|
6
|
-
const
|
|
6
|
+
const DIGEST_LENGTH_CHARS = 8;
|
|
7
7
|
export async function readCacheEntry(entryPath) {
|
|
8
8
|
try {
|
|
9
9
|
return await readFile(entryPath, 'utf8');
|
|
@@ -12,19 +12,26 @@ export async function readCacheEntry(entryPath) {
|
|
|
12
12
|
return undefined;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
+
export async function readGuardedCacheEntry(entryPath, token, isValidValue) {
|
|
16
|
+
const entry = await readJsonCacheEntry(entryPath, isGuardedEntry);
|
|
17
|
+
if (entry?.token !== token) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
return isValidValue(entry.value) ? entry.value : undefined;
|
|
21
|
+
}
|
|
15
22
|
export async function readJsonCacheEntry(entryPath, isValidEntry) {
|
|
16
|
-
const
|
|
17
|
-
if (
|
|
23
|
+
const rawContent = await readCacheEntry(entryPath);
|
|
24
|
+
if (rawContent === undefined) {
|
|
18
25
|
return undefined;
|
|
19
26
|
}
|
|
20
|
-
let
|
|
27
|
+
let parsedValue;
|
|
21
28
|
try {
|
|
22
|
-
|
|
29
|
+
parsedValue = JSON.parse(rawContent);
|
|
23
30
|
}
|
|
24
31
|
catch {
|
|
25
32
|
return undefined;
|
|
26
33
|
}
|
|
27
|
-
return isValidEntry(
|
|
34
|
+
return isValidEntry(parsedValue) ? parsedValue : undefined;
|
|
28
35
|
}
|
|
29
36
|
export async function removeCacheDir(ref) {
|
|
30
37
|
await rm(resolveCacheDir(ref), { force: true, recursive: true });
|
|
@@ -35,17 +42,28 @@ export async function removeCacheEntry(entryPath) {
|
|
|
35
42
|
export function resolveCacheDir(ref) {
|
|
36
43
|
const absoluteScopeDir = path.resolve(ref.scopeDir);
|
|
37
44
|
const stopAtDir = ref.stopAtDir === undefined ? undefined : path.resolve(ref.stopAtDir);
|
|
38
|
-
const
|
|
39
|
-
return path.join(
|
|
45
|
+
const homeDir = findDirectoryChainMatch(absoluteScopeDir, ['node_modules'], { stopAtDir })?.dir ?? absoluteScopeDir;
|
|
46
|
+
return path.join(homeDir, 'node_modules', '.cache', ref.tool);
|
|
40
47
|
}
|
|
41
48
|
export function resolveCacheEntryPath(ref) {
|
|
42
49
|
const absoluteScopeDir = path.resolve(ref.scopeDir);
|
|
43
50
|
const digest = createHash('sha256')
|
|
44
51
|
.update([absoluteScopeDir, ...(ref.discriminators ?? [])].join('\0'))
|
|
45
52
|
.digest('hex')
|
|
46
|
-
.slice(0,
|
|
53
|
+
.slice(0, DIGEST_LENGTH_CHARS);
|
|
47
54
|
return path.join(resolveCacheDir(ref), `${ref.slug}-${digest}${ref.extension}`);
|
|
48
55
|
}
|
|
49
56
|
export async function writeCacheEntry(entryPath, content) {
|
|
50
57
|
await writeAtomic(entryPath, content);
|
|
51
58
|
}
|
|
59
|
+
export async function writeGuardedCacheEntry(entryPath, token, value) {
|
|
60
|
+
const entry = { token, value };
|
|
61
|
+
await writeCacheEntry(entryPath, JSON.stringify(entry));
|
|
62
|
+
}
|
|
63
|
+
function isGuardedEntry(value) {
|
|
64
|
+
return (typeof value === 'object' &&
|
|
65
|
+
value !== null &&
|
|
66
|
+
'token' in value &&
|
|
67
|
+
typeof value.token === 'string' &&
|
|
68
|
+
'value' in value);
|
|
69
|
+
}
|
|
@@ -46,13 +46,13 @@ function extractField(record, fieldIndex) {
|
|
|
46
46
|
}
|
|
47
47
|
function extractPath(record, precedingFieldCount) {
|
|
48
48
|
let index = 0;
|
|
49
|
-
for (let
|
|
50
|
-
const
|
|
51
|
-
if (
|
|
49
|
+
for (let fieldIndex = 0; fieldIndex < precedingFieldCount; fieldIndex++) {
|
|
50
|
+
const separatorIndex = record.indexOf(' ', index);
|
|
51
|
+
if (separatorIndex === -1) {
|
|
52
52
|
return undefined;
|
|
53
53
|
}
|
|
54
|
-
index =
|
|
54
|
+
index = separatorIndex + 1;
|
|
55
55
|
}
|
|
56
|
-
const
|
|
57
|
-
return
|
|
56
|
+
const extractedPath = record.slice(index);
|
|
57
|
+
return extractedPath === '' ? undefined : extractedPath;
|
|
58
58
|
}
|
package/dist/esm/gitObjects.js
CHANGED
|
@@ -7,27 +7,27 @@ export function parseObjectFormat(value) {
|
|
|
7
7
|
return value === 'sha1' || value === 'sha256' ? value : undefined;
|
|
8
8
|
}
|
|
9
9
|
export function parseTreeObject(format, content) {
|
|
10
|
-
const
|
|
10
|
+
const idLengthBytes = format === 'sha1' ? 20 : 32;
|
|
11
11
|
const entries = [];
|
|
12
12
|
let offset = 0;
|
|
13
13
|
while (offset < content.length) {
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
if (
|
|
14
|
+
const spaceIndex = content.indexOf(0x20, offset);
|
|
15
|
+
const nulIndex = content.indexOf(0, spaceIndex + 1);
|
|
16
|
+
if (spaceIndex === -1 || nulIndex === -1 || nulIndex + 1 + idLengthBytes > content.length) {
|
|
17
17
|
return undefined;
|
|
18
18
|
}
|
|
19
19
|
entries.push({
|
|
20
|
-
id: content.subarray(
|
|
21
|
-
mode: content.toString('latin1', offset,
|
|
22
|
-
name: content.toString('latin1',
|
|
20
|
+
id: content.subarray(nulIndex + 1, nulIndex + 1 + idLengthBytes),
|
|
21
|
+
mode: content.toString('latin1', offset, spaceIndex),
|
|
22
|
+
name: content.toString('latin1', spaceIndex + 1, nulIndex),
|
|
23
23
|
});
|
|
24
|
-
offset =
|
|
24
|
+
offset = nulIndex + 1 + idLengthBytes;
|
|
25
25
|
}
|
|
26
26
|
return entries;
|
|
27
27
|
}
|
|
28
28
|
export function serializeTreeObject(entries) {
|
|
29
|
-
const
|
|
30
|
-
return Buffer.concat(
|
|
29
|
+
const sortedEntries = [...entries].toSorted((left, right) => compareStrings(getSortKey(left), getSortKey(right)));
|
|
30
|
+
return Buffer.concat(sortedEntries.flatMap((entry) => [Buffer.from(`${entry.mode} ${entry.name}\0`, 'latin1'), entry.id]));
|
|
31
31
|
}
|
|
32
32
|
function compareStrings(left, right) {
|
|
33
33
|
if (left === right) {
|
|
@@ -35,6 +35,6 @@ function compareStrings(left, right) {
|
|
|
35
35
|
}
|
|
36
36
|
return left < right ? -1 : 1;
|
|
37
37
|
}
|
|
38
|
-
function
|
|
38
|
+
function getSortKey(entry) {
|
|
39
39
|
return entry.mode === TREE_MODE ? `${entry.name}/` : entry.name;
|
|
40
40
|
}
|
|
@@ -5,4 +5,4 @@
|
|
|
5
5
|
* Past the limit, Node kills the child and reports `ENOBUFS`, an error that names the spawned program rather than
|
|
6
6
|
* the output that overflowed. A call site that omits the option fails this way only once its repo has grown enough.
|
|
7
7
|
*/
|
|
8
|
-
export declare const
|
|
8
|
+
export declare const GIT_OUTPUT_LIMIT_BYTES: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const
|
|
1
|
+
export const GIT_OUTPUT_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
@@ -76,7 +76,7 @@ function buildTreeId(options) {
|
|
|
76
76
|
const { trees } = treesResult;
|
|
77
77
|
for (const [changedPath, entry] of changes) {
|
|
78
78
|
const { name, parent } = splitPath(changedPath);
|
|
79
|
-
const tree =
|
|
79
|
+
const tree = ensureEntries(trees, parent);
|
|
80
80
|
if (entry === undefined) {
|
|
81
81
|
tree.delete(name);
|
|
82
82
|
}
|
|
@@ -84,14 +84,14 @@ function buildTreeId(options) {
|
|
|
84
84
|
tree.set(name, { ...entry, name });
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
-
const
|
|
88
|
-
for (const directory of
|
|
87
|
+
const deepestFirstDirectories = [...directories].toSorted((left, right) => measureDepth(right) - measureDepth(left));
|
|
88
|
+
for (const directory of deepestFirstDirectories) {
|
|
89
89
|
if (directory === '') {
|
|
90
90
|
continue;
|
|
91
91
|
}
|
|
92
92
|
const { name, parent } = splitPath(directory);
|
|
93
|
-
const parentTree =
|
|
94
|
-
const tree =
|
|
93
|
+
const parentTree = ensureEntries(trees, parent);
|
|
94
|
+
const tree = ensureEntries(trees, directory);
|
|
95
95
|
if (tree.size === 0) {
|
|
96
96
|
if (parentTree.get(name)?.mode === TREE_MODE) {
|
|
97
97
|
parentTree.delete(name);
|
|
@@ -104,13 +104,13 @@ function buildTreeId(options) {
|
|
|
104
104
|
name,
|
|
105
105
|
});
|
|
106
106
|
}
|
|
107
|
-
const rootId = hashGitObject(format, 'tree', serializeTreeObject(
|
|
107
|
+
const rootId = hashGitObject(format, 'tree', serializeTreeObject(ensureEntries(trees, '').values()));
|
|
108
108
|
return { ok: true, treeId: rootId.toString('hex') };
|
|
109
109
|
}
|
|
110
|
-
function
|
|
110
|
+
function measureDepth(directory) {
|
|
111
111
|
return directory === '' ? 0 : directory.split('/').length;
|
|
112
112
|
}
|
|
113
|
-
function
|
|
113
|
+
function ensureEntries(trees, directory) {
|
|
114
114
|
let entries = trees.get(directory);
|
|
115
115
|
if (entries === undefined) {
|
|
116
116
|
entries = new Map();
|
|
@@ -130,20 +130,20 @@ function hasSymlinkLeadingPath(toplevel, relativePath) {
|
|
|
130
130
|
});
|
|
131
131
|
}
|
|
132
132
|
function quotePath(relativePath) {
|
|
133
|
-
let
|
|
133
|
+
let quotedPath = '"';
|
|
134
134
|
for (const character of relativePath) {
|
|
135
135
|
const codePoint = character.codePointAt(0) ?? 0;
|
|
136
136
|
if (character === '"' || character === '\\') {
|
|
137
|
-
|
|
137
|
+
quotedPath += `\\${character}`;
|
|
138
138
|
}
|
|
139
139
|
else if (codePoint < 0x20 || codePoint === 0x7f) {
|
|
140
|
-
|
|
140
|
+
quotedPath += `\\${codePoint.toString(8).padStart(3, '0')}`;
|
|
141
141
|
}
|
|
142
142
|
else {
|
|
143
|
-
|
|
143
|
+
quotedPath += character;
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
|
-
return `${
|
|
146
|
+
return `${quotedPath}"`;
|
|
147
147
|
}
|
|
148
148
|
function readChangedEntries(toplevel, paths, format) {
|
|
149
149
|
const changes = new Map();
|
|
@@ -191,8 +191,8 @@ function readChangedEntries(toplevel, paths, format) {
|
|
|
191
191
|
}
|
|
192
192
|
function readHeadTrees(options) {
|
|
193
193
|
const { directories, format, headSha, headTreeId, toplevel } = options;
|
|
194
|
-
const
|
|
195
|
-
const input =
|
|
194
|
+
const orderedDirectories = [...directories];
|
|
195
|
+
const input = orderedDirectories
|
|
196
196
|
.map((directory) => (directory === '' ? `${headTreeId}\0` : `${headSha}:${directory}\0`))
|
|
197
197
|
.join('');
|
|
198
198
|
const batchResult = runGitForBytes(['cat-file', '--batch', '-z'], toplevel, Buffer.from(input, 'latin1'));
|
|
@@ -200,33 +200,33 @@ function readHeadTrees(options) {
|
|
|
200
200
|
return { ok: false, reason: `git cat-file failed: ${batchResult.error}` };
|
|
201
201
|
}
|
|
202
202
|
const output = batchResult.stdout;
|
|
203
|
-
const
|
|
203
|
+
const malformedResult = { ok: false, reason: 'git cat-file reported a malformed object' };
|
|
204
204
|
const trees = new Map();
|
|
205
205
|
let offset = 0;
|
|
206
|
-
for (const directory of
|
|
207
|
-
const
|
|
208
|
-
if (
|
|
209
|
-
return
|
|
206
|
+
for (const directory of orderedDirectories) {
|
|
207
|
+
const lineEndOffset = output.indexOf(0x0a, offset);
|
|
208
|
+
if (lineEndOffset === -1) {
|
|
209
|
+
return malformedResult;
|
|
210
210
|
}
|
|
211
|
-
const header = output.toString('latin1', offset,
|
|
212
|
-
offset =
|
|
211
|
+
const header = output.toString('latin1', offset, lineEndOffset);
|
|
212
|
+
offset = lineEndOffset + 1;
|
|
213
213
|
if (header.endsWith(' missing')) {
|
|
214
214
|
trees.set(directory, new Map());
|
|
215
215
|
continue;
|
|
216
216
|
}
|
|
217
217
|
const [, type, sizeText] = header.split(' ', 3);
|
|
218
218
|
if (sizeText === undefined) {
|
|
219
|
-
return
|
|
219
|
+
return malformedResult;
|
|
220
220
|
}
|
|
221
|
-
const
|
|
222
|
-
if (!Number.isSafeInteger(
|
|
223
|
-
return
|
|
221
|
+
const sizeBytes = Number(sizeText);
|
|
222
|
+
if (!Number.isSafeInteger(sizeBytes) || offset + sizeBytes > output.length) {
|
|
223
|
+
return malformedResult;
|
|
224
224
|
}
|
|
225
|
-
const content = output.subarray(offset, offset +
|
|
226
|
-
offset +=
|
|
225
|
+
const content = output.subarray(offset, offset + sizeBytes);
|
|
226
|
+
offset += sizeBytes + 1;
|
|
227
227
|
const entries = type === 'tree' ? parseTreeObject(format, content) : [];
|
|
228
228
|
if (entries === undefined) {
|
|
229
|
-
return
|
|
229
|
+
return malformedResult;
|
|
230
230
|
}
|
|
231
231
|
trees.set(directory, new Map(entries.map((entry) => [entry.name, entry])));
|
|
232
232
|
}
|
|
@@ -252,8 +252,8 @@ function readPathState(toplevel, relativePath, format) {
|
|
|
252
252
|
}
|
|
253
253
|
if (stats.isSymbolicLink()) {
|
|
254
254
|
try {
|
|
255
|
-
const
|
|
256
|
-
return { ok: true, kind: 'link', id: hashGitObject(format, 'blob',
|
|
255
|
+
const targetPath = readlinkSync(absolutePath, { encoding: 'buffer' });
|
|
256
|
+
return { ok: true, kind: 'link', id: hashGitObject(format, 'blob', targetPath) };
|
|
257
257
|
}
|
|
258
258
|
catch (error) {
|
|
259
259
|
return { ok: false, reason: `could not read ${relativePath}: ${describeError(error)}` };
|
|
@@ -262,8 +262,8 @@ function readPathState(toplevel, relativePath, format) {
|
|
|
262
262
|
return { ok: false, reason: `${relativePath} is neither a file nor a symlink, so its content is not hashable` };
|
|
263
263
|
}
|
|
264
264
|
function splitPath(fullPath) {
|
|
265
|
-
const
|
|
266
|
-
return
|
|
265
|
+
const separatorIndex = fullPath.lastIndexOf('/');
|
|
266
|
+
return separatorIndex === -1
|
|
267
267
|
? { name: fullPath, parent: '' }
|
|
268
|
-
: { name: fullPath.slice(
|
|
268
|
+
: { name: fullPath.slice(separatorIndex + 1), parent: fullPath.slice(0, separatorIndex) };
|
|
269
269
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { globSync } from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
const
|
|
4
|
-
const
|
|
3
|
+
const MANIFEST_FILENAME = 'package.json';
|
|
4
|
+
const ALWAYS_EXCLUDED_PATTERNS = ['**/node_modules/**'];
|
|
5
5
|
export function matchPackageDirs(monorepoRoot, includedPatterns, excludedPatterns) {
|
|
6
6
|
const options = {
|
|
7
7
|
cwd: monorepoRoot,
|
|
8
|
-
exclude: [...excludedPatterns, ...
|
|
8
|
+
exclude: [...excludedPatterns, ...ALWAYS_EXCLUDED_PATTERNS],
|
|
9
9
|
followSymlinks: true,
|
|
10
10
|
};
|
|
11
11
|
const matches = globSync([...includedPatterns], options);
|
|
@@ -26,11 +26,11 @@ export function splitWorkspacePatterns(patterns) {
|
|
|
26
26
|
if (pattern.trim() === '')
|
|
27
27
|
continue;
|
|
28
28
|
const isNegated = pattern.startsWith('!');
|
|
29
|
-
const
|
|
30
|
-
|
|
29
|
+
const targetPatterns = isNegated ? excludedPatterns : includedPatterns;
|
|
30
|
+
targetPatterns.push(buildManifestPattern(isNegated ? pattern.slice(1) : pattern));
|
|
31
31
|
}
|
|
32
32
|
return { excludedPatterns, includedPatterns };
|
|
33
33
|
}
|
|
34
34
|
function buildManifestPattern(pattern) {
|
|
35
|
-
return `${pattern.replace(/\/?$/, '')}/${
|
|
35
|
+
return `${pattern.replace(/\/?$/, '')}/${MANIFEST_FILENAME}`;
|
|
36
36
|
}
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
export declare const PACKAGE_NAME = "@williamthorsen/nmr-core";
|
|
2
2
|
export type { CacheDirRef, CacheEntryRef } from './cache-store.js';
|
|
3
|
-
export { readCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, } from './cache-store.js';
|
|
4
|
-
export {
|
|
3
|
+
export { readCacheEntry, readGuardedCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, writeGuardedCacheEntry, } from './cache-store.js';
|
|
4
|
+
export { GIT_OUTPUT_LIMIT_BYTES } from './gitOutputLimit.js';
|
|
5
5
|
export { hasErrnoCode } from './hasErrnoCode.js';
|
|
6
6
|
export type { WorkingTreeHashResult } from './hashWorkingTree.js';
|
|
7
7
|
export { hashWorkingTree, readHeadSha } from './hashWorkingTree.js';
|
|
8
8
|
export type { FlagDefinition, FlagSchema, ParseArgsOptions, ParsedArgs, ParsedFlags, ParseErrorKind, } from './parseArgs.js';
|
|
9
9
|
export { parseArgs, parseArgsOrExit, ParseError } from './parseArgs.js';
|
|
10
10
|
export type { GlyphSet, InvalidOutputStyle, OutputStyle, ResolveStreamStylesOptions, StatusGlyphName, StreamStyleResolution, StreamStyles, TruncateToWidthOptions, } from './terminal.js';
|
|
11
|
-
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
|
|
11
|
+
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportCrash, reportError, reportFailure, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from './terminal.js';
|
|
12
|
+
export { startTimer } from './timer.js';
|
|
12
13
|
export type { ManagedFileOutcome, ManagedFileResult } from './updateManagedFile.js';
|
|
13
14
|
export { updateManagedFile } from './updateManagedFile.js';
|
|
15
|
+
export { UserError } from './UserError.js';
|
|
14
16
|
export type { WriteOutcome, WriteResult } from './writeFileWithCheck.js';
|
|
15
17
|
export { writeFileWithCheck } from './writeFileWithCheck.js';
|
|
16
18
|
export { findPackageRoot, resolveSelfVersion } from '@williamthorsen/toolbelt.packaging/candidate';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
export const PACKAGE_NAME = '@williamthorsen/nmr-core';
|
|
2
|
-
export { readCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, } from "./cache-store.js";
|
|
3
|
-
export {
|
|
2
|
+
export { readCacheEntry, readGuardedCacheEntry, readJsonCacheEntry, removeCacheDir, removeCacheEntry, resolveCacheDir, resolveCacheEntryPath, writeCacheEntry, writeGuardedCacheEntry, } from "./cache-store.js";
|
|
3
|
+
export { GIT_OUTPUT_LIMIT_BYTES } from "./gitOutputLimit.js";
|
|
4
4
|
export { hasErrnoCode } from "./hasErrnoCode.js";
|
|
5
5
|
export { hashWorkingTree, readHeadSha } from "./hashWorkingTree.js";
|
|
6
6
|
export { parseArgs, parseArgsOrExit, ParseError } from "./parseArgs.js";
|
|
7
|
-
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportError, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
|
|
7
|
+
export { defineGlyphSet, describeInvalidOutputStyle, formatErrorLine, formatGlyphLine, formatStatusLine, measureGlyphColumn, measureWidth, printError, printSkip, printStep, printSuccess, reportCrash, reportError, reportFailure, reportTemplateUpdate, reportWriteResult, resolveStreamStyles, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from "./terminal.js";
|
|
8
|
+
export { startTimer } from "./timer.js";
|
|
8
9
|
export { updateManagedFile } from "./updateManagedFile.js";
|
|
10
|
+
export { UserError } from "./UserError.js";
|
|
9
11
|
export { writeFileWithCheck } from "./writeFileWithCheck.js";
|
|
10
12
|
export { findPackageRoot, resolveSelfVersion } from '@williamthorsen/toolbelt.packaging/candidate';
|
package/dist/esm/parseArgs.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { UserError } from './UserError.js';
|
|
1
2
|
/** Schema entry describing a single CLI flag. */
|
|
2
3
|
export interface FlagDefinition {
|
|
3
4
|
long: string;
|
|
@@ -29,7 +30,7 @@ export type ParseErrorKind = 'unknown-flag' | 'missing-value' | 'unexpected-valu
|
|
|
29
30
|
* positional value for `'unexpected-positional'`. Its `message` is composed from those fields, so error
|
|
30
31
|
* wording is uniform across every kind.
|
|
31
32
|
*/
|
|
32
|
-
export declare class ParseError extends
|
|
33
|
+
export declare class ParseError extends UserError {
|
|
33
34
|
readonly kind: ParseErrorKind;
|
|
34
35
|
readonly flag: string;
|
|
35
36
|
constructor(kind: ParseErrorKind, flag: string);
|
package/dist/esm/parseArgs.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import process from 'node:process';
|
|
2
2
|
import { parseArgs as nodeParseArgs } from 'node:util';
|
|
3
3
|
import { reportError } from "./terminal.js";
|
|
4
|
+
import { UserError } from "./UserError.js";
|
|
4
5
|
const initialFlagValues = { boolean: false, string: undefined };
|
|
5
|
-
export class ParseError extends
|
|
6
|
+
export class ParseError extends UserError {
|
|
6
7
|
kind;
|
|
7
8
|
flag;
|
|
8
9
|
constructor(kind, flag) {
|
|
@@ -14,14 +15,16 @@ export class ParseError extends Error {
|
|
|
14
15
|
}
|
|
15
16
|
export function parseArgs(argv, schema, options = {}) {
|
|
16
17
|
const nodeOptions = {};
|
|
17
|
-
const
|
|
18
|
+
const entriesByName = new Map();
|
|
18
19
|
const flags = {};
|
|
19
|
-
for (const [key,
|
|
20
|
-
const name =
|
|
20
|
+
for (const [key, definition] of Object.entries(schema)) {
|
|
21
|
+
const name = definition.long.replace(/^--/, '');
|
|
21
22
|
nodeOptions[name] =
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
definition.short === undefined
|
|
24
|
+
? { type: definition.type }
|
|
25
|
+
: { type: definition.type, short: definition.short.replace(/^-/, '') };
|
|
26
|
+
entriesByName.set(name, { key, definition });
|
|
27
|
+
flags[key] = initialFlagValues[definition.type];
|
|
25
28
|
}
|
|
26
29
|
const { tokens } = nodeParseArgs({
|
|
27
30
|
args: argv,
|
|
@@ -42,11 +45,11 @@ export function parseArgs(argv, schema, options = {}) {
|
|
|
42
45
|
if (token.kind !== 'option') {
|
|
43
46
|
continue;
|
|
44
47
|
}
|
|
45
|
-
const entry =
|
|
48
|
+
const entry = entriesByName.get(token.name);
|
|
46
49
|
if (entry === undefined) {
|
|
47
50
|
throw new ParseError('unknown-flag', token.rawName);
|
|
48
51
|
}
|
|
49
|
-
if (entry.
|
|
52
|
+
if (entry.definition.type === 'boolean') {
|
|
50
53
|
if (token.value !== undefined) {
|
|
51
54
|
throw new ParseError('unexpected-value', token.rawName);
|
|
52
55
|
}
|
package/dist/esm/runGit.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { GIT_OUTPUT_LIMIT_BYTES } from "./gitOutputLimit.js";
|
|
3
3
|
export function runGit(args, cwd, input) {
|
|
4
4
|
const result = runGitForBytes(args, cwd, input === undefined ? undefined : Buffer.from(input, 'utf8'));
|
|
5
5
|
return result.ok ? { ok: true, stdout: result.stdout.toString('utf8') } : result;
|
|
@@ -9,7 +9,7 @@ export function runGitForBytes(args, cwd, input) {
|
|
|
9
9
|
cwd,
|
|
10
10
|
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
|
|
11
11
|
input,
|
|
12
|
-
maxBuffer:
|
|
12
|
+
maxBuffer: GIT_OUTPUT_LIMIT_BYTES,
|
|
13
13
|
});
|
|
14
14
|
if (result.error) {
|
|
15
15
|
return { ok: false, error: result.error.message };
|
package/dist/esm/terminal.d.ts
CHANGED
|
@@ -41,19 +41,29 @@ export declare function printSkip(message: string, style?: OutputStyle): void;
|
|
|
41
41
|
export declare function printStep(message: string): void;
|
|
42
42
|
/** Prints a success message to stdout, in the style detected for stdout unless one is given. */
|
|
43
43
|
export declare function printSuccess(message: string, style?: OutputStyle): void;
|
|
44
|
+
/**
|
|
45
|
+
* Writes an unexpected crash, a bug in the tool, as `<bin>: internal error: <message>` followed by the error's stack
|
|
46
|
+
* frames. A handled error goes through `reportError` instead, so that a reader can tell the two apart.
|
|
47
|
+
*/
|
|
48
|
+
export declare function reportCrash(bin: string, error: unknown, stream?: Writable): void;
|
|
44
49
|
/** Writes the canonical `Error: <message>` line to `stream`, which an in-process CLI sets to its own `Writable`. */
|
|
45
50
|
export declare function reportError(message: string, stream?: Writable): void;
|
|
51
|
+
/**
|
|
52
|
+
* Writes a failure that reached a CLI's last-resort handler: a `UserError` as `Error: <message>`, and anything else
|
|
53
|
+
* as an internal error through `reportCrash`.
|
|
54
|
+
*/
|
|
55
|
+
export declare function reportFailure(bin: string, error: unknown, stream?: Writable): void;
|
|
46
56
|
/**
|
|
47
57
|
* Prints a status line for a managed-file result, followed by its diff indented beneath it: a failure to stderr,
|
|
48
58
|
* every other outcome to stdout.
|
|
49
59
|
*/
|
|
50
|
-
export declare function reportTemplateUpdate(result: ManagedFileResult,
|
|
60
|
+
export declare function reportTemplateUpdate(result: ManagedFileResult, isDryRun: boolean, styles?: StreamStyles): void;
|
|
51
61
|
/**
|
|
52
62
|
* Prints a terminal message for a write result based on its outcome: a failure to stderr, every
|
|
53
63
|
* other outcome to stdout. Each message takes its own stream's style from `styles`; without
|
|
54
64
|
* `styles`, it takes the style detected for that stream.
|
|
55
65
|
*/
|
|
56
|
-
export declare function reportWriteResult(result: WriteResult,
|
|
66
|
+
export declare function reportWriteResult(result: WriteResult, isDryRun: boolean, styles?: StreamStyles): void;
|
|
57
67
|
/**
|
|
58
68
|
* Resolves the style of each output stream: the flag when one is named, else the named environment
|
|
59
69
|
* variable, else detection from `CI`, the stream's terminal state, and `TERM`. Never throws; a value
|
package/dist/esm/terminal.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import process from 'node:process';
|
|
2
|
+
import { describeError, isError } from '@williamthorsen/toolbelt.errors';
|
|
2
3
|
import { detectOutputStyle, measureGlyphColumn, resolveOutputStyle, STATUS_GLYPHS, } from '@williamthorsen/toolbelt.terminal/candidate';
|
|
4
|
+
import { UserError } from "./UserError.js";
|
|
3
5
|
export { defineGlyphSet, describeInvalidOutputStyle, measureGlyphColumn, measureWidth, STATUS_GLYPHS, truncateToWidth, wrapToWidth, } from '@williamthorsen/toolbelt.terminal/candidate';
|
|
4
6
|
export function formatErrorLine(message) {
|
|
5
7
|
return `Error: ${message}`;
|
|
@@ -26,17 +28,29 @@ export function printStep(message) {
|
|
|
26
28
|
export function printSuccess(message, style = detectStreamStyle(process.stdout)) {
|
|
27
29
|
console.info(` ${formatStatusLine(style, 'passed', message)}`);
|
|
28
30
|
}
|
|
31
|
+
export function reportCrash(bin, error, stream = process.stderr) {
|
|
32
|
+
const frames = isError(error) && error.stack !== undefined ? extractStackFrames(error.stack) : '';
|
|
33
|
+
const header = `${bin}: internal error: ${describeError(error)}\n`;
|
|
34
|
+
stream.write(frames === '' ? header : `${header}${frames}\n`);
|
|
35
|
+
}
|
|
29
36
|
export function reportError(message, stream = process.stderr) {
|
|
30
37
|
stream.write(`${formatErrorLine(message)}\n`);
|
|
31
38
|
}
|
|
32
|
-
export function
|
|
39
|
+
export function reportFailure(bin, error, stream = process.stderr) {
|
|
40
|
+
if (error instanceof UserError) {
|
|
41
|
+
reportError(describeError(error), stream);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
reportCrash(bin, error, stream);
|
|
45
|
+
}
|
|
46
|
+
export function reportTemplateUpdate(result, isDryRun, styles) {
|
|
33
47
|
const style = styles?.stdout;
|
|
34
48
|
switch (result.outcome) {
|
|
35
49
|
case 'created':
|
|
36
|
-
printSuccess(
|
|
50
|
+
printSuccess(isDryRun ? `[dry-run] Would create ${result.filePath}` : `Created ${result.filePath}`, style);
|
|
37
51
|
break;
|
|
38
52
|
case 'updated':
|
|
39
|
-
printSuccess(
|
|
53
|
+
printSuccess(isDryRun ? `[dry-run] Would update ${result.filePath}` : `Updated ${result.filePath}`, style);
|
|
40
54
|
if (result.diff !== undefined && result.diff !== '') {
|
|
41
55
|
console.info(indentLines(result.diff, ' '.repeat(4)));
|
|
42
56
|
}
|
|
@@ -51,11 +65,11 @@ export function reportTemplateUpdate(result, dryRun, styles) {
|
|
|
51
65
|
}
|
|
52
66
|
}
|
|
53
67
|
}
|
|
54
|
-
export function reportWriteResult(result,
|
|
68
|
+
export function reportWriteResult(result, isDryRun, styles) {
|
|
55
69
|
const style = styles?.stdout;
|
|
56
70
|
switch (result.outcome) {
|
|
57
71
|
case 'created':
|
|
58
|
-
if (
|
|
72
|
+
if (isDryRun) {
|
|
59
73
|
printSuccess(`[dry-run] Would create ${result.filePath}`, style);
|
|
60
74
|
}
|
|
61
75
|
else {
|
|
@@ -63,7 +77,7 @@ export function reportWriteResult(result, dryRun, styles) {
|
|
|
63
77
|
}
|
|
64
78
|
break;
|
|
65
79
|
case 'overwritten':
|
|
66
|
-
if (
|
|
80
|
+
if (isDryRun) {
|
|
67
81
|
printSuccess(`[dry-run] Would overwrite ${result.filePath}`, style);
|
|
68
82
|
}
|
|
69
83
|
else {
|
|
@@ -93,14 +107,19 @@ export function reportWriteResult(result, dryRun, styles) {
|
|
|
93
107
|
}
|
|
94
108
|
export function resolveStreamStyles(options) {
|
|
95
109
|
const { argv = [], env, envVar, flag, stderrIsTty, stdoutIsTty } = options;
|
|
96
|
-
const
|
|
97
|
-
const
|
|
98
|
-
const styles = { stderr:
|
|
99
|
-
return
|
|
110
|
+
const stderrResolution = resolveOutputStyle({ argv, env, envVar, flag, isTty: stderrIsTty });
|
|
111
|
+
const stdoutResolution = resolveOutputStyle({ argv, env, envVar, flag, isTty: stdoutIsTty });
|
|
112
|
+
const styles = { stderr: stderrResolution.style, stdout: stdoutResolution.style };
|
|
113
|
+
return stdoutResolution.invalid === undefined ? { styles } : { invalid: stdoutResolution.invalid, styles };
|
|
100
114
|
}
|
|
101
115
|
function detectStreamStyle(stream) {
|
|
102
116
|
return detectOutputStyle({ env: process.env, isTty: stream.isTTY === true });
|
|
103
117
|
}
|
|
118
|
+
function extractStackFrames(stack) {
|
|
119
|
+
const lines = stack.split('\n');
|
|
120
|
+
const firstFrameIndex = lines.findIndex((line) => /^\s+at /.test(line));
|
|
121
|
+
return firstFrameIndex === -1 ? '' : lines.slice(firstFrameIndex).join('\n');
|
|
122
|
+
}
|
|
104
123
|
function indentLines(text, indent) {
|
|
105
124
|
return text
|
|
106
125
|
.split('\n')
|
|
@@ -11,9 +11,9 @@ export interface ManagedFileResult {
|
|
|
11
11
|
/**
|
|
12
12
|
* Writes `content` to a file that a package renders from a template, when the file is missing or its bytes differ.
|
|
13
13
|
*
|
|
14
|
-
* With `
|
|
14
|
+
* With `isDryRun`, returns the outcome and diff without writing. Returns a filesystem error in the result rather than
|
|
15
15
|
* throwing it.
|
|
16
16
|
*/
|
|
17
17
|
export declare function updateManagedFile(filePath: string, content: string, options: {
|
|
18
|
-
|
|
18
|
+
isDryRun: boolean;
|
|
19
19
|
}): ManagedFileResult;
|
|
@@ -3,22 +3,22 @@ import { dirname } from 'node:path';
|
|
|
3
3
|
import { describeError } from '@williamthorsen/toolbelt.errors';
|
|
4
4
|
import { structuredPatch } from 'diff';
|
|
5
5
|
export function updateManagedFile(filePath, content, options) {
|
|
6
|
-
let
|
|
6
|
+
let existingContent;
|
|
7
7
|
if (existsSync(filePath)) {
|
|
8
8
|
try {
|
|
9
|
-
|
|
9
|
+
existingContent = readFileSync(filePath, 'utf8');
|
|
10
10
|
}
|
|
11
11
|
catch (error) {
|
|
12
12
|
return { filePath, outcome: 'failed', error: describeError(error) };
|
|
13
13
|
}
|
|
14
|
-
if (
|
|
14
|
+
if (existingContent === content) {
|
|
15
15
|
return { filePath, outcome: 'up-to-date' };
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
|
-
const result =
|
|
18
|
+
const result = existingContent === undefined
|
|
19
19
|
? { filePath, outcome: 'created' }
|
|
20
|
-
: { filePath, outcome: 'updated', diff: formatHunks(
|
|
21
|
-
if (options.
|
|
20
|
+
: { filePath, outcome: 'updated', diff: formatHunks(existingContent, content) };
|
|
21
|
+
if (options.isDryRun) {
|
|
22
22
|
return result;
|
|
23
23
|
}
|
|
24
24
|
try {
|
|
@@ -30,8 +30,8 @@ export function updateManagedFile(filePath, content, options) {
|
|
|
30
30
|
}
|
|
31
31
|
return result;
|
|
32
32
|
}
|
|
33
|
-
function formatHunks(
|
|
34
|
-
const { hunks } = structuredPatch('', '',
|
|
33
|
+
function formatHunks(oldContent, newContent) {
|
|
34
|
+
const { hunks } = structuredPatch('', '', oldContent, newContent, undefined, undefined, { context: 3 });
|
|
35
35
|
return hunks
|
|
36
36
|
.flatMap((hunk) => [
|
|
37
37
|
`@@ -${String(hunk.oldStart)},${String(hunk.oldLines)} +${String(hunk.newStart)},${String(hunk.newLines)} @@`,
|
package/dist/esm/workspace.js
CHANGED
|
@@ -3,20 +3,20 @@ import path from 'node:path';
|
|
|
3
3
|
import { findDirectoryChainMatch } from '@williamthorsen/toolbelt.filesystem';
|
|
4
4
|
import { parse } from 'yaml';
|
|
5
5
|
import { matchPackageDirs, resolvePackageDirs, splitWorkspacePatterns } from "./helpers/workspace-patterns.js";
|
|
6
|
-
const
|
|
7
|
-
const
|
|
6
|
+
const PACKAGE_MANIFEST_FILENAME = 'package.json';
|
|
7
|
+
const WORKSPACE_MANIFEST_FILENAME = 'pnpm-workspace.yaml';
|
|
8
8
|
export function findMonorepoRoot(startDir) {
|
|
9
|
-
return findDirectoryChainMatch(startDir ?? process.cwd(), [
|
|
9
|
+
return findDirectoryChainMatch(startDir ?? process.cwd(), [WORKSPACE_MANIFEST_FILENAME])?.dir;
|
|
10
10
|
}
|
|
11
11
|
export function isMonorepoRoot(dir) {
|
|
12
|
-
return existsSync(path.join(dir,
|
|
12
|
+
return existsSync(path.join(dir, WORKSPACE_MANIFEST_FILENAME));
|
|
13
13
|
}
|
|
14
14
|
export function readWorkspaceOverrides(monorepoRoot) {
|
|
15
|
-
const
|
|
16
|
-
if (
|
|
15
|
+
const manifestReadResult = readWorkspaceManifest(monorepoRoot);
|
|
16
|
+
if (manifestReadResult.kind !== 'parsed' || !isObject(manifestReadResult.value)) {
|
|
17
17
|
return undefined;
|
|
18
18
|
}
|
|
19
|
-
const overrides =
|
|
19
|
+
const overrides = manifestReadResult.value['overrides'];
|
|
20
20
|
return isObject(overrides) ? readStringValues(overrides) : undefined;
|
|
21
21
|
}
|
|
22
22
|
export function readWorkspacePackageNames(packageDirs) {
|
|
@@ -24,7 +24,7 @@ export function readWorkspacePackageNames(packageDirs) {
|
|
|
24
24
|
for (const dir of packageDirs) {
|
|
25
25
|
let parsedManifest;
|
|
26
26
|
try {
|
|
27
|
-
parsedManifest = JSON.parse(readFileSync(path.join(dir,
|
|
27
|
+
parsedManifest = JSON.parse(readFileSync(path.join(dir, PACKAGE_MANIFEST_FILENAME), 'utf8'));
|
|
28
28
|
}
|
|
29
29
|
catch {
|
|
30
30
|
continue;
|
|
@@ -36,19 +36,19 @@ export function readWorkspacePackageNames(packageDirs) {
|
|
|
36
36
|
return names;
|
|
37
37
|
}
|
|
38
38
|
export function resolveWorkspace(monorepoRoot) {
|
|
39
|
-
const
|
|
40
|
-
if (
|
|
39
|
+
const manifestReadResult = readWorkspaceManifest(monorepoRoot);
|
|
40
|
+
if (manifestReadResult.kind === 'absent') {
|
|
41
41
|
return { kind: 'not-a-workspace' };
|
|
42
42
|
}
|
|
43
|
-
if (
|
|
43
|
+
if (manifestReadResult.kind === 'unreadable') {
|
|
44
44
|
return { cause: 'unreadable-manifest', kind: 'empty', patterns: [] };
|
|
45
45
|
}
|
|
46
|
-
const
|
|
47
|
-
if (
|
|
48
|
-
const cause =
|
|
46
|
+
const packagesReadResult = readDeclaredPackages(manifestReadResult.value);
|
|
47
|
+
if (packagesReadResult.kind !== 'patterns') {
|
|
48
|
+
const cause = packagesReadResult.kind === 'absent' ? 'no-packages-list' : 'unreadable-packages';
|
|
49
49
|
return { cause, kind: 'empty', patterns: [] };
|
|
50
50
|
}
|
|
51
|
-
const { patterns } =
|
|
51
|
+
const { patterns } = packagesReadResult;
|
|
52
52
|
const packageDirs = resolvePackageDirs(monorepoRoot, patterns);
|
|
53
53
|
if (packageDirs.length > 0) {
|
|
54
54
|
return { kind: 'packages', packageDirs, patterns };
|
|
@@ -89,12 +89,12 @@ function readStringValues(record) {
|
|
|
89
89
|
return result;
|
|
90
90
|
}
|
|
91
91
|
function readWorkspaceManifest(monorepoRoot) {
|
|
92
|
-
const
|
|
93
|
-
if (!existsSync(
|
|
92
|
+
const workspaceManifestPath = path.join(monorepoRoot, WORKSPACE_MANIFEST_FILENAME);
|
|
93
|
+
if (!existsSync(workspaceManifestPath)) {
|
|
94
94
|
return { kind: 'absent' };
|
|
95
95
|
}
|
|
96
96
|
try {
|
|
97
|
-
return { kind: 'parsed', value: parse(readFileSync(
|
|
97
|
+
return { kind: 'parsed', value: parse(readFileSync(workspaceManifestPath, 'utf8')) };
|
|
98
98
|
}
|
|
99
99
|
catch {
|
|
100
100
|
return { kind: 'unreadable' };
|
|
@@ -9,11 +9,11 @@ export interface WriteResult {
|
|
|
9
9
|
/**
|
|
10
10
|
* Writes a file with existence and content checks, creating parent directories as needed.
|
|
11
11
|
*
|
|
12
|
-
* Without `
|
|
13
|
-
* trailing whitespace. With `
|
|
12
|
+
* Without `shouldOverwrite`, leaves an existing file alone and reports it `up-to-date` when its content matches up to
|
|
13
|
+
* trailing whitespace. With `isDryRun`, returns the outcome without writing. Returns a filesystem error in the
|
|
14
14
|
* result rather than throwing it: `skipped` when the existing file cannot be read, `failed` when the write fails.
|
|
15
15
|
*/
|
|
16
16
|
export declare function writeFileWithCheck(filePath: string, content: string, options: {
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
isDryRun: boolean;
|
|
18
|
+
shouldOverwrite: boolean;
|
|
19
19
|
}): WriteResult;
|
|
@@ -9,12 +9,12 @@ function normalizeTrailingWhitespace(content) {
|
|
|
9
9
|
.trimEnd();
|
|
10
10
|
}
|
|
11
11
|
export function writeFileWithCheck(filePath, content, options) {
|
|
12
|
-
const {
|
|
13
|
-
const
|
|
14
|
-
if (
|
|
12
|
+
const { isDryRun, shouldOverwrite } = options;
|
|
13
|
+
const doesFileExist = existsSync(filePath);
|
|
14
|
+
if (doesFileExist && !shouldOverwrite) {
|
|
15
15
|
try {
|
|
16
|
-
const
|
|
17
|
-
if (normalizeTrailingWhitespace(
|
|
16
|
+
const existingContent = readFileSync(filePath, 'utf8');
|
|
17
|
+
if (normalizeTrailingWhitespace(existingContent) === normalizeTrailingWhitespace(content)) {
|
|
18
18
|
return { filePath, outcome: 'up-to-date' };
|
|
19
19
|
}
|
|
20
20
|
}
|
|
@@ -24,8 +24,8 @@ export function writeFileWithCheck(filePath, content, options) {
|
|
|
24
24
|
}
|
|
25
25
|
return { filePath, outcome: 'skipped' };
|
|
26
26
|
}
|
|
27
|
-
const outcome =
|
|
28
|
-
if (
|
|
27
|
+
const outcome = doesFileExist ? 'overwritten' : 'created';
|
|
28
|
+
if (isDryRun) {
|
|
29
29
|
return { filePath, outcome };
|
|
30
30
|
}
|
|
31
31
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@williamthorsen/nmr-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Shared utilities for node-monorepo-tools packages",
|
|
6
6
|
"keywords": [
|
|
@@ -39,17 +39,18 @@
|
|
|
39
39
|
"dist"
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@williamthorsen/toolbelt.
|
|
43
|
-
"@williamthorsen/toolbelt.
|
|
44
|
-
"@williamthorsen/toolbelt.
|
|
45
|
-
"@williamthorsen/toolbelt.
|
|
42
|
+
"@williamthorsen/toolbelt.datetime": "4.1.0",
|
|
43
|
+
"@williamthorsen/toolbelt.errors": "0.9.0",
|
|
44
|
+
"@williamthorsen/toolbelt.filesystem": "0.10.0",
|
|
45
|
+
"@williamthorsen/toolbelt.packaging": "0.7.0",
|
|
46
|
+
"@williamthorsen/toolbelt.terminal": "0.3.0",
|
|
46
47
|
"diff": "9.0.0",
|
|
47
48
|
"yaml": "2.9.1"
|
|
48
49
|
},
|
|
49
50
|
"devDependencies": {
|
|
50
|
-
"@williamthorsen/toolbelt.testing": "0.
|
|
51
|
-
"@williamthorsen/toolbelt.vitest": "0.
|
|
52
|
-
"vitest": "5.0
|
|
51
|
+
"@williamthorsen/toolbelt.testing": "0.8.0",
|
|
52
|
+
"@williamthorsen/toolbelt.vitest": "0.13.1",
|
|
53
|
+
"vitest": "5.1.0"
|
|
53
54
|
},
|
|
54
55
|
"engines": {
|
|
55
56
|
"node": ">=24.16.0"
|