toolcrib 0.3.0 → 0.5.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/README.md +12 -0
- package/package.json +5 -2
- package/src/commands/doctor.js +7 -5
- package/src/commands/merge.js +56 -2
- package/src/index.js +17 -1
- package/src/lib/github.js +74 -38
- package/src/lib/patchFallback.js +17 -1
- package/src/lib/patches.js +16 -5
- package/src/lib/project.js +19 -7
package/README.md
CHANGED
|
@@ -29,6 +29,18 @@ toolcrib <command>
|
|
|
29
29
|
Run every command from your project's root — the same directory as your
|
|
30
30
|
`package.json`.
|
|
31
31
|
|
|
32
|
+
**Two version numbers, completely unrelated — never try to align them.**
|
|
33
|
+
`npx toolcrib` (or `npm install -g toolcrib`) always resolves to the CLI's
|
|
34
|
+
own latest npm release; there's no reason to ever pin it (`npx
|
|
35
|
+
toolcrib@1.2.3`), and doing so has nothing to do with which toolkit content
|
|
36
|
+
you get. The toolkit itself — the components, `ai-docs/`, everything
|
|
37
|
+
`init`/`merge` actually download — is versioned completely separately, as
|
|
38
|
+
GitHub Releases. That's what `init`/`merge`'s own `--version` flag targets
|
|
39
|
+
(see [Commands](#commands) below), and it already defaults to `latest` on
|
|
40
|
+
its own. These two numbers will essentially never match each other, by
|
|
41
|
+
design — don't infer one from the other, and don't specify either unless
|
|
42
|
+
you have a specific reason to pin a particular release.
|
|
43
|
+
|
|
32
44
|
## The lifecycle, at a glance
|
|
33
45
|
|
|
34
46
|
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toolcrib",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Bootstrap the toolcrib UI toolkit into your project",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
},
|
|
21
21
|
"scripts": {
|
|
22
22
|
"test": "vitest run",
|
|
23
|
-
"test:watch": "vitest"
|
|
23
|
+
"test:watch": "vitest",
|
|
24
|
+
"coverage:unit": "vitest run --coverage"
|
|
24
25
|
},
|
|
25
26
|
"dependencies": {
|
|
26
27
|
"@clack/prompts": "^1.7.0",
|
|
@@ -29,6 +30,8 @@
|
|
|
29
30
|
"semver": "^7.6.0"
|
|
30
31
|
},
|
|
31
32
|
"devDependencies": {
|
|
33
|
+
"@vitest/coverage-v8": "^4.1.10",
|
|
34
|
+
"cross-spawn": "^7.0.6",
|
|
32
35
|
"vitest": "^4.1.10"
|
|
33
36
|
}
|
|
34
37
|
}
|
package/src/commands/doctor.js
CHANGED
|
@@ -3,7 +3,7 @@ import * as p from '@clack/prompts';
|
|
|
3
3
|
import { fetchRelease } from '../lib/release.js';
|
|
4
4
|
import { normalize } from '../lib/patches.js';
|
|
5
5
|
import { readJsonIfExists, readLock, readTextIfExists, fileExists } from '../lib/project.js';
|
|
6
|
-
import {
|
|
6
|
+
import { fetchLatestVersion } from '../lib/github.js';
|
|
7
7
|
import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks } from '../lib/managedDocs.js';
|
|
8
8
|
import { detectBundler } from '../lib/bundler.js';
|
|
9
9
|
import { checkRootProviderWired } from '../lib/rootProvider.js';
|
|
@@ -224,10 +224,12 @@ export async function doctorCommand(options = {}) {
|
|
|
224
224
|
}
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
227
|
+
// fetchLatestVersion (GitHub's dedicated /releases/latest endpoint), not
|
|
228
|
+
// listVersions — doctor only ever needs the single newest release to
|
|
229
|
+
// compare against what's installed, not every release's full metadata.
|
|
230
|
+
const newestVersion = await fetchLatestVersion();
|
|
231
|
+
if (newestVersion !== lock.version) {
|
|
232
|
+
p.log.info(`A newer version is available: v${newestVersion} (installed: v${lock.version}). Run 'toolcrib merge'.`);
|
|
231
233
|
} else {
|
|
232
234
|
p.log.info('You are on the latest release.');
|
|
233
235
|
}
|
package/src/commands/merge.js
CHANGED
|
@@ -3,7 +3,7 @@ import * as p from '@clack/prompts';
|
|
|
3
3
|
import { fetchRelease } from '../lib/release.js';
|
|
4
4
|
import { PendingChanges, normalize, joinPatchPath } from '../lib/patches.js';
|
|
5
5
|
import { mergeImportsField } from '../lib/deps.js';
|
|
6
|
-
import { readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
|
|
6
|
+
import { fileExists, readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
|
|
7
7
|
import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks, upsertManagedBlock } from '../lib/managedDocs.js';
|
|
8
8
|
|
|
9
9
|
const TOOLKIT_DIR = './toolcrib';
|
|
@@ -155,6 +155,7 @@ export async function mergeCommand(options) {
|
|
|
155
155
|
const conflicts = [];
|
|
156
156
|
let updatedCount = 0;
|
|
157
157
|
let keptCount = 0;
|
|
158
|
+
let deletedCount = 0;
|
|
158
159
|
|
|
159
160
|
for (const relPath of newRelease.allFiles()) {
|
|
160
161
|
const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
|
|
@@ -180,6 +181,48 @@ export async function mergeCommand(options) {
|
|
|
180
181
|
}
|
|
181
182
|
}
|
|
182
183
|
|
|
184
|
+
// A file present in oldRelease but absent from newRelease was removed
|
|
185
|
+
// upstream — e.g. useAnimatedMount.ts when Drawer moved to Radix
|
|
186
|
+
// Presence in v0.10.0. Without this pass, a vendored copy of a file
|
|
187
|
+
// upstream no longer ships just sits there forever, unreferenced but
|
|
188
|
+
// never cleaned up, since the loop above only ever visits paths that
|
|
189
|
+
// still exist in the *new* release. classify(original, local, '')
|
|
190
|
+
// reuses the same four-way logic as the update loop, treating "removed
|
|
191
|
+
// upstream" as updated content of '': local unmodified from original ->
|
|
192
|
+
// safe to delete; local modified -> a real conflict (don't silently
|
|
193
|
+
// discard someone's customization just because upstream dropped the
|
|
194
|
+
// file), same as any other conflicting edit.
|
|
195
|
+
for (const relPath of oldRelease.allFiles()) {
|
|
196
|
+
if (newRelease.allFiles().includes(relPath)) continue;
|
|
197
|
+
|
|
198
|
+
const targetPath = path.join(projectRoot, TOOLKIT_DIR, relPath);
|
|
199
|
+
if (!fileExists(targetPath)) continue; // already absent locally — nothing to propose
|
|
200
|
+
const local = readTextIfExists(targetPath);
|
|
201
|
+
|
|
202
|
+
const original = oldRelease.readFile(relPath);
|
|
203
|
+
const status = classify(original, local, '');
|
|
204
|
+
|
|
205
|
+
switch (status) {
|
|
206
|
+
case 'safe-update':
|
|
207
|
+
changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, '', relPath);
|
|
208
|
+
deletedCount++;
|
|
209
|
+
break;
|
|
210
|
+
case 'conflict':
|
|
211
|
+
conflicts.push({
|
|
212
|
+
relPath,
|
|
213
|
+
patchPath: joinPatchPath(TOOLKIT_DIR, relPath),
|
|
214
|
+
original,
|
|
215
|
+
local,
|
|
216
|
+
updated: '',
|
|
217
|
+
removedUpstream: true,
|
|
218
|
+
});
|
|
219
|
+
break;
|
|
220
|
+
// 'unchanged'/'keep-local' can't occur here: original is always
|
|
221
|
+
// non-empty (relPath came from oldRelease.allFiles()) and updated is
|
|
222
|
+
// always '', so upstreamChanged is unconditionally true.
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
183
226
|
const managedBlockCounts = await mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes, conflicts);
|
|
184
227
|
updatedCount += managedBlockCounts.updatedCount;
|
|
185
228
|
keptCount += managedBlockCounts.keptCount;
|
|
@@ -230,7 +273,11 @@ export async function mergeCommand(options) {
|
|
|
230
273
|
await changes.writeAll(projectRoot);
|
|
231
274
|
}
|
|
232
275
|
|
|
233
|
-
p.log.success(
|
|
276
|
+
p.log.success(
|
|
277
|
+
`${updatedCount} file(s) updated cleanly, ${keptCount} local edit(s) preserved untouched` +
|
|
278
|
+
(deletedCount > 0 ? `, ${deletedCount} file(s) removed upstream and proposed for deletion` : '') +
|
|
279
|
+
'.'
|
|
280
|
+
);
|
|
234
281
|
if (conflicts.length > 0) {
|
|
235
282
|
p.log.warn(
|
|
236
283
|
`${conflicts.length} conflict(s) — both local and upstream changed:\n` +
|
|
@@ -243,6 +290,13 @@ export async function mergeCommand(options) {
|
|
|
243
290
|
}
|
|
244
291
|
|
|
245
292
|
function buildConflictNote(conflict) {
|
|
293
|
+
if (conflict.removedUpstream) {
|
|
294
|
+
return (
|
|
295
|
+
`This file was modified locally, but removed upstream in the new version.\n` +
|
|
296
|
+
`Automatic deletion was skipped — review manually or ask your AI assistant:\n` +
|
|
297
|
+
`"reconcile my local changes to ${conflict.relPath}, which was removed upstream"\n`
|
|
298
|
+
);
|
|
299
|
+
}
|
|
246
300
|
return (
|
|
247
301
|
`This file was modified locally AND changed upstream.\n` +
|
|
248
302
|
`Automatic merge was skipped — review manually or ask your AI assistant:\n` +
|
package/src/index.js
CHANGED
|
@@ -29,7 +29,23 @@ program.enablePositionalOptions();
|
|
|
29
29
|
program
|
|
30
30
|
.name('toolcrib')
|
|
31
31
|
.description('Bootstrap and maintain the toolcrib UI toolkit in your project')
|
|
32
|
-
|
|
32
|
+
// Commander auto-adds -V/--version at the top level; without a custom
|
|
33
|
+
// description it just says "output the version number" with no
|
|
34
|
+
// indication of WHICH version. This is a real, confirmed source of
|
|
35
|
+
// confusion: an agent runs `toolcrib --version`, gets this CLI package's
|
|
36
|
+
// own npm version (e.g. "0.4.0"), and has no reason to suspect that
|
|
37
|
+
// number is unrelated to the toolkit content release `init`/`merge`'s
|
|
38
|
+
// own --version flag targets (a completely separate, independently-
|
|
39
|
+
// versioned GitHub Release) -- then reuses the wrong number there. The
|
|
40
|
+
// *parsing* collision between these two same-named flags was already
|
|
41
|
+
// fixed via enablePositionalOptions() above; this is the remaining
|
|
42
|
+
// *semantic* one -- disambiguated right in the text an agent actually
|
|
43
|
+
// reads when it checks.
|
|
44
|
+
.version(
|
|
45
|
+
packageJson.version,
|
|
46
|
+
'-V, --version',
|
|
47
|
+
"output this CLI tool's own npm package version -- unrelated to the toolkit content version (see `toolcrib init --version`/`toolcrib versions`)"
|
|
48
|
+
);
|
|
33
49
|
|
|
34
50
|
program
|
|
35
51
|
.command('init')
|
package/src/lib/github.js
CHANGED
|
@@ -11,40 +11,48 @@ const CHECKSUM_ASSET_NAME = 'toolcrib.zip.sha256';
|
|
|
11
11
|
const API_BASE = process.env.TOOLCRIB_API_BASE || 'https://api.github.com';
|
|
12
12
|
const RELEASES_BASE = process.env.TOOLCRIB_RELEASES_BASE || `https://github.com/${REPO}/releases`;
|
|
13
13
|
|
|
14
|
+
// GitHub's unauthenticated rate limit (60/hr, shared across every caller on
|
|
15
|
+
// the same IP — e.g. a shared CI runner or sandbox) surfaces as a plain 403,
|
|
16
|
+
// indistinguishable from a real auth/network failure unless the response
|
|
17
|
+
// headers are inspected. Left as a generic error, this sends whoever/
|
|
18
|
+
// whatever hits it down a diagnostic path (checking headers, retrying with
|
|
19
|
+
// curl, poking at User-Agent) to rediscover a fix (`toolcrib init --version
|
|
20
|
+
// <x.y.z>`) that already exists and is documented — see CLI README. Checked
|
|
21
|
+
// here so the message states the real cause and the real fix directly,
|
|
22
|
+
// instead of a bare status code. Shared by every GitHub API call in this
|
|
23
|
+
// file (not just listVersions' original one) since the failure mode and fix
|
|
24
|
+
// are identical regardless of which endpoint hit it.
|
|
25
|
+
function throwGitHubApiError(res, context) {
|
|
26
|
+
const remaining = res.status === 403 ? res.headers?.get?.('x-ratelimit-remaining') : null;
|
|
27
|
+
if (res.status === 403 && remaining === '0') {
|
|
28
|
+
const resetHeader = res.headers?.get?.('x-ratelimit-reset');
|
|
29
|
+
const resetAt = resetHeader ? new Date(Number(resetHeader) * 1000).toLocaleTimeString() : 'unknown';
|
|
30
|
+
throw new Error(
|
|
31
|
+
`GitHub's unauthenticated API rate limit (60 requests/hour, shared by IP) is exhausted — ` +
|
|
32
|
+
`resets around ${resetAt}. This only affects version *discovery* ("latest" resolution); it ` +
|
|
33
|
+
`does not affect release downloads themselves. Fix: run \`toolcrib init --version <x.y.z>\` ` +
|
|
34
|
+
`(or \`apply\`/\`merge\` with an explicit version) with a version you already know, which skips ` +
|
|
35
|
+
`this call entirely.`
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
throw new Error(`Failed to fetch ${context}: ${res.status} ${res.statusText}`);
|
|
39
|
+
}
|
|
40
|
+
|
|
14
41
|
/**
|
|
15
42
|
* List published (non-draft) releases from the GitHub API, newest first.
|
|
16
43
|
* No auth needed for public repos; subject to the standard 60/hr
|
|
17
44
|
* unauthenticated rate limit, which is fine for occasional CLI use.
|
|
45
|
+
*
|
|
46
|
+
* Only `versionsCommand` (`toolcrib versions`, which prints every release)
|
|
47
|
+
* actually needs this full list — resolving "latest" doesn't, see
|
|
48
|
+
* fetchLatestVersion below.
|
|
18
49
|
*/
|
|
19
50
|
export async function listVersions() {
|
|
20
51
|
const res = await fetch(`${API_BASE}/repos/${REPO}/releases`, {
|
|
21
52
|
headers: { Accept: 'application/vnd.github+json' },
|
|
22
53
|
});
|
|
23
54
|
|
|
24
|
-
if (!res.ok)
|
|
25
|
-
// GitHub's unauthenticated rate limit (60/hr, shared across every caller
|
|
26
|
-
// on the same IP — e.g. a shared CI runner or sandbox) surfaces as a
|
|
27
|
-
// plain 403, indistinguishable from a real auth/network failure unless
|
|
28
|
-
// the response headers are inspected. Left as a generic error, this
|
|
29
|
-
// sends whoever/whatever hits it down a diagnostic path (checking
|
|
30
|
-
// headers, retrying with curl, poking at User-Agent) to rediscover a
|
|
31
|
-
// fix (`toolcrib init --version <x.y.z>`) that already exists and is
|
|
32
|
-
// documented — see CLI README. Checked here so the message states the
|
|
33
|
-
// real cause and the real fix directly, instead of a bare status code.
|
|
34
|
-
const remaining = res.status === 403 ? res.headers?.get?.('x-ratelimit-remaining') : null;
|
|
35
|
-
if (res.status === 403 && remaining === '0') {
|
|
36
|
-
const resetHeader = res.headers?.get?.('x-ratelimit-reset');
|
|
37
|
-
const resetAt = resetHeader ? new Date(Number(resetHeader) * 1000).toLocaleTimeString() : 'unknown';
|
|
38
|
-
throw new Error(
|
|
39
|
-
`GitHub's unauthenticated API rate limit (60 requests/hour, shared by IP) is exhausted — ` +
|
|
40
|
-
`resets around ${resetAt}. This only affects version *discovery* ("latest" resolution); it ` +
|
|
41
|
-
`does not affect release downloads themselves. Fix: run \`toolcrib init --version <x.y.z>\` ` +
|
|
42
|
-
`(or \`apply\`/\`merge\` with an explicit version) with a version you already know, which skips ` +
|
|
43
|
-
`this call entirely.`
|
|
44
|
-
);
|
|
45
|
-
}
|
|
46
|
-
throw new Error(`Failed to fetch release list: ${res.status} ${res.statusText}`);
|
|
47
|
-
}
|
|
55
|
+
if (!res.ok) throwGitHubApiError(res, 'release list');
|
|
48
56
|
|
|
49
57
|
const releases = await res.json();
|
|
50
58
|
|
|
@@ -57,6 +65,29 @@ export async function listVersions() {
|
|
|
57
65
|
}));
|
|
58
66
|
}
|
|
59
67
|
|
|
68
|
+
/**
|
|
69
|
+
* Resolve "latest" to a concrete version string via GitHub's own dedicated
|
|
70
|
+
* `/releases/latest` endpoint — "the most recent non-prerelease, non-draft
|
|
71
|
+
* release" by GitHub's own definition, matching exactly what resolveVersion
|
|
72
|
+
* used to compute client-side (`listVersions().find(v => !v.prerelease)`)
|
|
73
|
+
* after fetching *every* release's full metadata just to find the first
|
|
74
|
+
* one. Same 60/hr quota cost either way (one request either way), but a
|
|
75
|
+
* much smaller response and the semantically-correct endpoint for this
|
|
76
|
+
* exact question. 404 means no qualifying release exists yet, per GitHub's
|
|
77
|
+
* own documented behavior for this endpoint.
|
|
78
|
+
*/
|
|
79
|
+
export async function fetchLatestVersion() {
|
|
80
|
+
const res = await fetch(`${API_BASE}/repos/${REPO}/releases/latest`, {
|
|
81
|
+
headers: { Accept: 'application/vnd.github+json' },
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
if (res.status === 404) throw new Error('No published releases found.');
|
|
85
|
+
if (!res.ok) throwGitHubApiError(res, 'the latest release');
|
|
86
|
+
|
|
87
|
+
const release = await res.json();
|
|
88
|
+
return release.tag_name.replace(/^v/, '');
|
|
89
|
+
}
|
|
90
|
+
|
|
60
91
|
function assetUrl(version, assetName) {
|
|
61
92
|
return version === 'latest'
|
|
62
93
|
? `${RELEASES_BASE}/latest/download/${assetName}`
|
|
@@ -71,10 +102,7 @@ function assetUrl(version, assetName) {
|
|
|
71
102
|
*/
|
|
72
103
|
export async function resolveVersion(version) {
|
|
73
104
|
if (version !== 'latest') return version;
|
|
74
|
-
|
|
75
|
-
const newest = versions.find((v) => !v.prerelease);
|
|
76
|
-
if (!newest) throw new Error('No published releases found.');
|
|
77
|
-
return newest.version;
|
|
105
|
+
return fetchLatestVersion();
|
|
78
106
|
}
|
|
79
107
|
|
|
80
108
|
async function fetchText(url) {
|
|
@@ -98,6 +126,11 @@ function sha256(buffer) {
|
|
|
98
126
|
* and return the raw buffer. Throws on mismatch (corrupted/truncated
|
|
99
127
|
* download, or a tampered file at rest — see design notes on what a
|
|
100
128
|
* checksum does and doesn't guarantee against a compromised source).
|
|
129
|
+
*
|
|
130
|
+
* Every published release has shipped a .sha256 sibling since this
|
|
131
|
+
* mechanism was introduced — a failed fetch of it (missing, network
|
|
132
|
+
* error, or an on-path actor blocking just that request) is treated
|
|
133
|
+
* as an integrity failure, not tolerated as an older-release gap.
|
|
101
134
|
*/
|
|
102
135
|
export async function downloadReleaseZip(version) {
|
|
103
136
|
const zipUrl = assetUrl(version, ASSET_NAME);
|
|
@@ -105,18 +138,21 @@ export async function downloadReleaseZip(version) {
|
|
|
105
138
|
|
|
106
139
|
const [zipBuffer, checksumText] = await Promise.all([
|
|
107
140
|
fetchBuffer(zipUrl),
|
|
108
|
-
fetchText(checksumUrl).catch(() =>
|
|
109
|
-
]);
|
|
110
|
-
|
|
111
|
-
if (checksumText) {
|
|
112
|
-
const expected = checksumText.trim().split(/\s+/)[0];
|
|
113
|
-
const actual = sha256(zipBuffer);
|
|
114
|
-
if (actual !== expected) {
|
|
141
|
+
fetchText(checksumUrl).catch((err) => {
|
|
115
142
|
throw new Error(
|
|
116
|
-
`
|
|
117
|
-
`
|
|
143
|
+
`Failed to fetch checksum for ${ASSET_NAME} (${err.message}). ` +
|
|
144
|
+
`Refusing to install an unverified download.`
|
|
118
145
|
);
|
|
119
|
-
}
|
|
146
|
+
}),
|
|
147
|
+
]);
|
|
148
|
+
|
|
149
|
+
const expected = checksumText.trim().split(/\s+/)[0];
|
|
150
|
+
const actual = sha256(zipBuffer);
|
|
151
|
+
if (actual !== expected) {
|
|
152
|
+
throw new Error(
|
|
153
|
+
`Checksum mismatch for ${ASSET_NAME} (expected ${expected}, got ${actual}). ` +
|
|
154
|
+
`The download may be corrupted or incomplete — try again.`
|
|
155
|
+
);
|
|
120
156
|
}
|
|
121
157
|
|
|
122
158
|
return zipBuffer;
|
package/src/lib/patchFallback.js
CHANGED
|
@@ -13,7 +13,13 @@ export function applyPatchFallback(patchPath, projectRoot) {
|
|
|
13
13
|
const patchText = fs.readFileSync(patchPath, 'utf-8');
|
|
14
14
|
const [parsed] = parsePatch(patchText);
|
|
15
15
|
|
|
16
|
-
const
|
|
16
|
+
const isDeletedFile = parsed.newFileName === '/dev/null';
|
|
17
|
+
// A deletion's real target is its *source* name (oldFileName) — newFileName
|
|
18
|
+
// is /dev/null itself for a deletion, so falling through to the same
|
|
19
|
+
// newFileName-based path resolution used for create/update would target
|
|
20
|
+
// a literal "/dev/null" path inside the project instead of the file
|
|
21
|
+
// actually being removed.
|
|
22
|
+
const targetRelPath = (isDeletedFile ? parsed.oldFileName : parsed.newFileName).replace(/^[ab]\//, '');
|
|
17
23
|
const targetPath = path.join(projectRoot, targetRelPath);
|
|
18
24
|
|
|
19
25
|
// Defense in depth: every relPath this CLI itself writes into a patch
|
|
@@ -31,6 +37,16 @@ export function applyPatchFallback(patchPath, projectRoot) {
|
|
|
31
37
|
return { success: false, error: `Refusing to apply patch: target path "${targetRelPath}" resolves outside the project root.` };
|
|
32
38
|
}
|
|
33
39
|
|
|
40
|
+
if (isDeletedFile) {
|
|
41
|
+
if (!fs.existsSync(targetPath)) {
|
|
42
|
+
// Already gone (e.g. a re-run after a partial previous apply) —
|
|
43
|
+
// the end state this patch wants is already true, not a failure.
|
|
44
|
+
return { success: true };
|
|
45
|
+
}
|
|
46
|
+
fs.rmSync(targetPath);
|
|
47
|
+
return { success: true };
|
|
48
|
+
}
|
|
49
|
+
|
|
34
50
|
const isNewFile = parsed.oldFileName === '/dev/null';
|
|
35
51
|
const currentContent = isNewFile ? '' : fs.readFileSync(targetPath, 'utf-8');
|
|
36
52
|
|
package/src/lib/patches.js
CHANGED
|
@@ -62,7 +62,9 @@ export class PendingChanges {
|
|
|
62
62
|
* built, regardless of whether the caller already went through
|
|
63
63
|
* joinPatchPath() or constructed relPath some other way.
|
|
64
64
|
* @param {string} currentContent - '' if the file doesn't exist yet
|
|
65
|
-
* @param {string} proposedContent -
|
|
65
|
+
* @param {string} proposedContent - '' to propose deleting the file
|
|
66
|
+
* (only meaningful when currentContent is non-empty — '' vs '' is
|
|
67
|
+
* already a no-op via the check below)
|
|
66
68
|
* @param {string} [label] - display label for the patch header
|
|
67
69
|
*/
|
|
68
70
|
propose(relPath, currentContent, proposedContent, label) {
|
|
@@ -74,16 +76,25 @@ export class PendingChanges {
|
|
|
74
76
|
if (normalize(currentContent) === normalize(proposedContent)) return; // no-op, nothing to propose
|
|
75
77
|
|
|
76
78
|
const isNewFile = currentContent === '';
|
|
79
|
+
// Symmetric with isNewFile above: a deletion is just a patch whose
|
|
80
|
+
// *target* is /dev/null instead of its *source* — git apply (confirmed
|
|
81
|
+
// directly against a real repo, not assumed) recognizes this from a
|
|
82
|
+
// plain unified diff exactly the same way it recognizes a new file from
|
|
83
|
+
// an empty source, no git-extended `diff --git`/`deleted file mode`
|
|
84
|
+
// headers required. The `!isNewFile` guard only rules out the
|
|
85
|
+
// '' -> '' case, already caught by the no-op check above; kept for
|
|
86
|
+
// clarity that a file can't be simultaneously new and deleted.
|
|
87
|
+
const isDeletedFile = proposedContent === '' && !isNewFile;
|
|
77
88
|
const patch = createTwoFilesPatch(
|
|
78
89
|
isNewFile ? '/dev/null' : `a/${relPath}`,
|
|
79
|
-
`b/${relPath}`,
|
|
90
|
+
isDeletedFile ? '/dev/null' : `b/${relPath}`,
|
|
80
91
|
currentContent,
|
|
81
92
|
proposedContent,
|
|
82
93
|
isNewFile ? undefined : `${label} (current)`,
|
|
83
|
-
isNewFile ? `${label} (new file)` : `${label} (proposed)`
|
|
94
|
+
isDeletedFile ? undefined : isNewFile ? `${label} (new file)` : `${label} (proposed)`
|
|
84
95
|
);
|
|
85
96
|
|
|
86
|
-
this.entries.push({ relPath, patch, isNewFile });
|
|
97
|
+
this.entries.push({ relPath, patch, isNewFile, isDeletedFile });
|
|
87
98
|
}
|
|
88
99
|
|
|
89
100
|
isEmpty() {
|
|
@@ -96,7 +107,7 @@ export class PendingChanges {
|
|
|
96
107
|
|
|
97
108
|
summarize() {
|
|
98
109
|
return this.entries
|
|
99
|
-
.map((e) => ` ${e.isNewFile ? '+ (new) ' : '~ '}${e.relPath}`)
|
|
110
|
+
.map((e) => ` ${e.isDeletedFile ? '- (deleted) ' : e.isNewFile ? '+ (new) ' : '~ '}${e.relPath}`)
|
|
100
111
|
.join('\n');
|
|
101
112
|
}
|
|
102
113
|
|
package/src/lib/project.js
CHANGED
|
@@ -13,12 +13,9 @@ const GITIGNORE_FENCE_ID = 'gitignore';
|
|
|
13
13
|
// literal at the start of the string. Left in place, it breaks
|
|
14
14
|
// JSON.parse() outright ("Unexpected token" — a real, well-known Node
|
|
15
15
|
// gotcha, not hypothetical: package.json/tsconfig.json saved by some
|
|
16
|
-
// Windows editors carry one)
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
// corrupting any byte-for-byte comparison against BOM-less content. Strip
|
|
20
|
-
// it at the read chokepoint, once, rather than defending against it at
|
|
21
|
-
// every call site.
|
|
16
|
+
// Windows editors carry one). readJsonIfExists strips it for exactly that
|
|
17
|
+
// reason, at the read chokepoint, once, rather than defending against it
|
|
18
|
+
// at every JSON.parse call site.
|
|
22
19
|
function stripBOM(text) {
|
|
23
20
|
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
24
21
|
}
|
|
@@ -28,8 +25,23 @@ export function readJsonIfExists(filePath) {
|
|
|
28
25
|
return JSON.parse(stripBOM(fs.readFileSync(filePath, 'utf-8')));
|
|
29
26
|
}
|
|
30
27
|
|
|
28
|
+
// Deliberately does NOT strip a BOM, unlike readJsonIfExists above --
|
|
29
|
+
// confirmed as a real, previously-shipped bug (found via
|
|
30
|
+
// cli/integration-test/run-windows-integration.mjs, not assumed): every
|
|
31
|
+
// call site of this function feeds `changes.propose()`'s "current"
|
|
32
|
+
// argument, which becomes the literal "before" context in a real diff/
|
|
33
|
+
// patch that `git apply` later matches byte-for-byte against the real
|
|
34
|
+
// file on disk. Stripping the BOM here made that comparison start from
|
|
35
|
+
// content that no longer matches what's actually in the file -- so a
|
|
36
|
+
// project with a BOM'd package.json (PowerShell's `Out-File`/`>`
|
|
37
|
+
// redirection adds one by default) got `error: patch does not apply` on
|
|
38
|
+
// the very first line, and the patch was silently discarded, every time.
|
|
39
|
+
// The BOM in the file itself is still handled correctly elsewhere: the
|
|
40
|
+
// *new* content computed from readJsonIfExists (which does strip it) is
|
|
41
|
+
// always BOM-free, so applying the resulting patch also naturally cleans
|
|
42
|
+
// up a pre-existing BOM going forward.
|
|
31
43
|
export function readTextIfExists(filePath) {
|
|
32
|
-
return fs.existsSync(filePath) ?
|
|
44
|
+
return fs.existsSync(filePath) ? fs.readFileSync(filePath, 'utf-8') : '';
|
|
33
45
|
}
|
|
34
46
|
|
|
35
47
|
/**
|