toolcrib 0.9.0 → 0.11.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/src/lib/git.js CHANGED
@@ -5,18 +5,48 @@ const execFileAsync = promisify(execFile);
5
5
  const isWindows = process.platform === 'win32';
6
6
 
7
7
  /** Base options applied to every spawned git process. */
8
- const baseOpts = (cwd) => ({
8
+ const baseOpts = (cwd, shell = false) => ({
9
9
  cwd,
10
10
  windowsHide: true, // belt-and-suspenders against any console flash on Windows
11
- shell: isWindows, // needed so Windows resolves the git.cmd shim correctly
11
+ shell,
12
12
  });
13
13
 
14
+ /**
15
+ * Git is run WITHOUT a shell first, on every platform. Windows resolves a
16
+ * bare `git` to git.exe through the normal PATH search, and with no shell
17
+ * there is nothing to interpret a path like `C:\a&b\x.patch`: a project
18
+ * directory containing `&` or `%` used to be handed to cmd.exe as command
19
+ * syntax (#831). Only if that fails with ENOENT (git reachable solely
20
+ * through a git.cmd shim) do we retry through a shell, with every argument
21
+ * double-quoted and anything cmd.exe would still expand rejected outright.
22
+ */
23
+ const shouldRetryWithShell = (err) => isWindows && err && err.code === 'ENOENT';
24
+
25
+ export function shellSafeArgs(args) {
26
+ for (const a of args) {
27
+ if (/["%\r\n]/.test(a)) {
28
+ throw new Error(`Refusing to pass an argument containing a quote, %, or newline through cmd.exe: ${a}`);
29
+ }
30
+ }
31
+ // A run of backslashes right before the closing quote would escape it
32
+ // under Windows argument parsing, so a trailing run is doubled.
33
+ return args.map((a) => `"${a.replace(/(\\+)$/, '$1$1')}"`);
34
+ }
35
+
14
36
  /** Quick, buffered checks — output isn't meant for the user, just a yes/no/value. */
15
37
  async function quietGit(args, cwd) {
16
38
  try {
17
39
  const { stdout } = await execFileAsync('git', args, baseOpts(cwd));
18
40
  return { ok: true, stdout: stdout.trim() };
19
41
  } catch (err) {
42
+ if (shouldRetryWithShell(err)) {
43
+ try {
44
+ const { stdout } = await execFileAsync('git', shellSafeArgs(args), baseOpts(cwd, true));
45
+ return { ok: true, stdout: stdout.trim() };
46
+ } catch (retryErr) {
47
+ return { ok: false, error: retryErr };
48
+ }
49
+ }
20
50
  return { ok: false, error: err };
21
51
  }
22
52
  }
@@ -33,16 +63,75 @@ export async function gitInit(cwd) {
33
63
  return quietGit(['init'], cwd);
34
64
  }
35
65
 
66
+ /**
67
+ * Runs `git merge-file -p ours base theirs` inside `dir` (three files already
68
+ * written there under those exact names) and returns the merged text plus the
69
+ * conflict count. git's exit status IS the conflict count (capped at 127);
70
+ * anything else (255 = error, e.g. a binary file) throws. No shell, per the
71
+ * policy at the top of this file; `merge.conflictStyle=merge` is forced so a
72
+ * user's global diff3/zdiff3 setting can't change the marker layout.
73
+ */
74
+ export async function gitMergeFile(dir, labels) {
75
+ const args = [
76
+ '-c',
77
+ 'merge.conflictStyle=merge',
78
+ 'merge-file',
79
+ '-p',
80
+ '-L',
81
+ labels.ours,
82
+ '-L',
83
+ labels.base,
84
+ '-L',
85
+ labels.theirs,
86
+ 'ours',
87
+ 'base',
88
+ 'theirs',
89
+ ];
90
+ const run = async (a, shell) => {
91
+ try {
92
+ const { stdout } = await execFileAsync('git', a, {
93
+ ...baseOpts(dir, shell),
94
+ encoding: 'utf8',
95
+ maxBuffer: 256 * 1024 * 1024,
96
+ });
97
+ return { conflicts: 0, merged: stdout };
98
+ } catch (err) {
99
+ if (typeof err.code === 'number' && err.code >= 1 && err.code <= 127) {
100
+ return { conflicts: err.code, merged: err.stdout };
101
+ }
102
+ throw err;
103
+ }
104
+ };
105
+ try {
106
+ return await run(args, false);
107
+ } catch (err) {
108
+ if (shouldRetryWithShell(err)) return run(shellSafeArgs(args), true);
109
+ throw err;
110
+ }
111
+ }
112
+
36
113
  /**
37
114
  * Streaming apply — the user should see git's own output live, especially
38
115
  * on failure (git apply's "patch does not apply" messages point at the
39
116
  * exact failing hunk, which is genuinely useful diagnostic info worth
40
117
  * surfacing rather than swallowing and reformatting).
41
118
  */
42
- export function gitApplyStreaming(patchPath, cwd) {
119
+ export async function gitApplyStreaming(patchPath, cwd) {
120
+ const first = await spawnApply(['apply', patchPath], cwd, false);
121
+ if (first.enoent && isWindows) {
122
+ try {
123
+ return await spawnApply(shellSafeArgs(['apply', patchPath]), cwd, true);
124
+ } catch (err) {
125
+ return { success: false, error: err.message };
126
+ }
127
+ }
128
+ return first;
129
+ }
130
+
131
+ function spawnApply(args, cwd, shell) {
43
132
  return new Promise((resolve) => {
44
- const proc = spawn('git', ['apply', patchPath], {
45
- ...baseOpts(cwd),
133
+ const proc = spawn('git', args, {
134
+ ...baseOpts(cwd, shell),
46
135
  stdio: ['ignore', 'pipe', 'pipe'],
47
136
  });
48
137
 
@@ -57,7 +146,7 @@ export function gitApplyStreaming(patchPath, cwd) {
57
146
  resolve(code === 0 ? { success: true } : { success: false, error: stderr.trim() });
58
147
  });
59
148
 
60
- proc.on('error', (err) => resolve({ success: false, error: err.message }));
149
+ proc.on('error', (err) => resolve({ success: false, error: err.message, enoent: err.code === 'ENOENT' }));
61
150
  });
62
151
  }
63
152
 
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Dependency-free import scanning, shared by the release build
3
+ * (scripts/build-release.js) and the CLI's own tooling so both see imports
4
+ * identically. Deliberately imports nothing: this file ships inside the
5
+ * published `toolcrib` npm package, and must work with zero dependencies.
6
+ *
7
+ * Pure string handling only. Not a parser: it will not see imports produced
8
+ * by macros, and an import-looking phrase inside a string literal is still
9
+ * matched (comments are the only thing stripped).
10
+ */
11
+
12
+ /**
13
+ * Remove `//` line comments and `/* *\/` block comments from JS/TS source,
14
+ * leaving string literals ('...', "...", `...`, with backslash escapes)
15
+ * untouched. Newlines inside removed block comments are kept so line
16
+ * structure is roughly preserved. Backslash escapes in code are skipped
17
+ * as a pair so a regex literal like `/\/\//` isn't mistaken for a comment.
18
+ *
19
+ * @param {string} source
20
+ * @returns {string}
21
+ */
22
+ export function stripComments(source) {
23
+ const n = source.length;
24
+ let out = '';
25
+ let i = 0;
26
+ while (i < n) {
27
+ const ch = source[i];
28
+ const next = source[i + 1];
29
+
30
+ if (ch === '/' && next === '/') {
31
+ i += 2;
32
+ while (i < n && source[i] !== '\n') i++;
33
+ continue;
34
+ }
35
+
36
+ if (ch === '/' && next === '*') {
37
+ i += 2;
38
+ while (i < n && !(source[i] === '*' && source[i + 1] === '/')) {
39
+ if (source[i] === '\n') out += '\n';
40
+ i++;
41
+ }
42
+ i += 2;
43
+ continue;
44
+ }
45
+
46
+ if (ch === '\\') {
47
+ out += source.slice(i, i + 2);
48
+ i += 2;
49
+ continue;
50
+ }
51
+
52
+ if (ch === '"' || ch === "'" || ch === '`') {
53
+ let j = i + 1;
54
+ while (j < n && source[j] !== ch) {
55
+ if (source[j] === '\\') {
56
+ j += 2;
57
+ continue;
58
+ }
59
+ // Single/double-quoted strings cannot span lines; stop at the newline
60
+ // so an apostrophe in JSX text can't swallow the rest of the file.
61
+ if (ch !== '`' && source[j] === '\n') break;
62
+ j++;
63
+ }
64
+ j = Math.min(j, n);
65
+ const closed = j < n && source[j] === ch;
66
+ const end = closed ? j + 1 : j;
67
+ out += source.slice(i, end);
68
+ i = end;
69
+ continue;
70
+ }
71
+
72
+ out += ch;
73
+ i++;
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /**
79
+ * Module specifiers referenced by a source file, in source order, after
80
+ * comments are stripped. Covers static `import`/`export ... from`, bare
81
+ * side-effect `import 'x'`, `import type`, `export * as ns from`, and
82
+ * dynamic `import('x')` with a string-literal argument.
83
+ *
84
+ * @param {string} source
85
+ * @returns {string[]}
86
+ */
87
+ export function extractImports(source) {
88
+ const code = stripComments(source);
89
+ const re = /\b(?:(?:import|export)\s+(?:[^'";]*?\sfrom\s+)?|import\s*\(\s*)['"]([^'"]+)['"]/g;
90
+ const specifiers = [];
91
+ let match;
92
+ while ((match = re.exec(code))) {
93
+ specifiers.push(match[1]);
94
+ }
95
+ return specifiers;
96
+ }
97
+
98
+ /**
99
+ * Resolve a relative import (`./` or `../` only) against the directory of
100
+ * the importing file, trying exact path, then the TS/JS extensions, then
101
+ * index files. Path handling is done by hand with forward slashes, never
102
+ * path.join/resolve, so the result is identical on Windows.
103
+ *
104
+ * @param {string} fromRelPath importing file, forward-slash, relative to the root (e.g. `components/Card/Card.tsx`)
105
+ * @param {string} specifier the import specifier as written
106
+ * @param {(relPath: string) => boolean} fileExists caller-supplied existence check, same root-relative form
107
+ * @returns {string | null} the first existing root-relative path, or null (non-relative, missing, or escaping the root)
108
+ */
109
+ export function resolveRelativeImport(fromRelPath, specifier, fileExists) {
110
+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) return null;
111
+
112
+ const segments = fromRelPath.split('/').slice(0, -1).filter((s) => s !== '');
113
+ for (const part of specifier.split('/')) {
114
+ if (part === '' || part === '.') continue;
115
+ if (part === '..') {
116
+ if (segments.length === 0) return null;
117
+ segments.pop();
118
+ } else {
119
+ segments.push(part);
120
+ }
121
+ }
122
+
123
+ const base = segments.join('/');
124
+ if (base === '') return null; // `./` alone names the root directory, not a file
125
+ const candidates = [
126
+ base,
127
+ `${base}.ts`,
128
+ `${base}.tsx`,
129
+ `${base}.js`,
130
+ `${base}.jsx`,
131
+ `${base}/index.ts`,
132
+ `${base}/index.tsx`,
133
+ `${base}/index.js`,
134
+ ];
135
+ for (const candidate of candidates) {
136
+ if (fileExists(candidate)) return candidate;
137
+ }
138
+ return null;
139
+ }
@@ -0,0 +1,190 @@
1
+ import fs from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { diffArrays } from 'diff';
6
+ import { gitMergeFile } from './git.js';
7
+
8
+ /**
9
+ * Line-level three-way merge for `toolcrib merge`.
10
+ *
11
+ * Two engines, same contract: `git merge-file -p` when git is available, and
12
+ * a pure-JS diff3 built on the `diff` package's Myers `diffArrays` otherwise.
13
+ * Both take LF-normalized text (callers normalize line endings first and
14
+ * restore the local file's EOL style afterwards) and return
15
+ * `{ merged, conflicts, engine }`, where `conflicts` is the number of
16
+ * conflict regions and `merged` carries standard markers
17
+ * (`<<<<<<< local` / `=======` / `>>>>>>> <newLabel>`) for each of them.
18
+ *
19
+ * The JS engine matches git on clean-vs-conflict outcome for ordinary edits:
20
+ * edits that touch or overlap conflict, identical edits on both sides
21
+ * resolve, and a conflicting region is refined down to the lines that
22
+ * actually differ (git's "zealous" behavior). It does not replicate git's
23
+ * extra heuristic of folding two conflicts separated by only a few
24
+ * non-alphanumeric lines into one, so marker granularity can differ from git
25
+ * in those rare layouts.
26
+ */
27
+
28
+ /** NUL byte, or bytes that are not valid UTF-8. Such content is never line-merged. */
29
+ export function isBinaryBuffer(buf) {
30
+ if (buf.includes(0)) return true;
31
+ try {
32
+ new TextDecoder('utf-8', { fatal: true }).decode(buf);
33
+ return false;
34
+ } catch {
35
+ return true;
36
+ }
37
+ }
38
+
39
+ /** 'crlf' when the text uses CRLF more than bare LF, else 'lf'. */
40
+ export function detectEol(text) {
41
+ const crlf = (text.match(/\r\n/g) || []).length;
42
+ const lf = (text.match(/\n/g) || []).length - crlf;
43
+ return crlf > lf ? 'crlf' : 'lf';
44
+ }
45
+
46
+ export function toEol(text, eol) {
47
+ return eol === 'crlf' ? text.replace(/\n/g, '\r\n') : text;
48
+ }
49
+
50
+ const splitLines = (text) => text.match(/[^\n]*\n|[^\n]+$/g) || [];
51
+ const ensureNl = (lines) =>
52
+ lines.length > 0 && !lines[lines.length - 1].endsWith('\n')
53
+ ? [...lines.slice(0, -1), lines[lines.length - 1] + '\n']
54
+ : lines;
55
+
56
+ /** Changed regions of `other` relative to `base`: [{ s, e, lines }] over base indexes [s, e). */
57
+ function hunks(base, other) {
58
+ const out = [];
59
+ let pos = 0;
60
+ let cur = null;
61
+ for (const part of diffArrays(base, other)) {
62
+ if (!part.added && !part.removed) {
63
+ if (cur) out.push(cur);
64
+ cur = null;
65
+ pos += part.value.length;
66
+ continue;
67
+ }
68
+ cur ??= { s: pos, e: pos, lines: [] };
69
+ if (part.removed) {
70
+ cur.e += part.value.length;
71
+ pos += part.value.length;
72
+ } else {
73
+ cur.lines.push(...part.value);
74
+ }
75
+ }
76
+ if (cur) out.push(cur);
77
+ return out;
78
+ }
79
+
80
+ function render(base, hs, start, end) {
81
+ const out = [];
82
+ let pos = start;
83
+ for (const h of hs) {
84
+ out.push(...base.slice(pos, h.s), ...h.lines);
85
+ pos = h.e;
86
+ }
87
+ out.push(...base.slice(pos, end));
88
+ return out;
89
+ }
90
+
91
+ const same = (a, b) => a.length === b.length && a.every((l, i) => l === b[i]);
92
+
93
+ export function mergeThreeWayJs(base, ours, theirs, labels) {
94
+ const b = splitLines(base);
95
+ const A = hunks(b, splitLines(ours));
96
+ const B = hunks(b, splitLines(theirs));
97
+ const out = [];
98
+ let conflicts = 0;
99
+ let pos = 0;
100
+ let i = 0;
101
+ let j = 0;
102
+
103
+ const conflictBlock = (o, t) => {
104
+ conflicts++;
105
+ out.push(`<<<<<<< ${labels.ours}\n`, ...ensureNl(o), '=======\n', ...ensureNl(t), `>>>>>>> ${labels.theirs}\n`);
106
+ };
107
+
108
+ while (i < A.length || j < B.length) {
109
+ const takeA = i < A.length && (j >= B.length || A[i].s <= B[j].s);
110
+ const first = takeA ? A[i++] : B[j++];
111
+ const gA = takeA ? [first] : [];
112
+ const gB = takeA ? [] : [first];
113
+ const start = first.s;
114
+ let end = first.e;
115
+ for (;;) {
116
+ if (i < A.length && A[i].s <= end) {
117
+ end = Math.max(end, A[i].e);
118
+ gA.push(A[i++]);
119
+ } else if (j < B.length && B[j].s <= end) {
120
+ end = Math.max(end, B[j].e);
121
+ gB.push(B[j++]);
122
+ } else break;
123
+ }
124
+
125
+ out.push(...b.slice(pos, start));
126
+ pos = end;
127
+
128
+ if (gB.length === 0) {
129
+ out.push(...render(b, gA, start, end));
130
+ } else if (gA.length === 0) {
131
+ out.push(...render(b, gB, start, end));
132
+ } else {
133
+ const o = render(b, gA, start, end);
134
+ const t = render(b, gB, start, end);
135
+ if (same(o, t)) {
136
+ out.push(...o);
137
+ } else {
138
+ // Refine: lines both sides agree on stay outside the markers.
139
+ let po = [];
140
+ let pt = [];
141
+ const flush = () => {
142
+ if (po.length || pt.length) conflictBlock(po, pt);
143
+ po = [];
144
+ pt = [];
145
+ };
146
+ for (const part of diffArrays(o, t)) {
147
+ if (part.removed) po.push(...part.value);
148
+ else if (part.added) pt.push(...part.value);
149
+ else {
150
+ flush();
151
+ out.push(...part.value);
152
+ }
153
+ }
154
+ flush();
155
+ }
156
+ }
157
+ }
158
+ out.push(...b.slice(pos));
159
+ return { merged: out.join(''), conflicts };
160
+ }
161
+
162
+ async function mergeWithGit(base, ours, theirs, labels) {
163
+ const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'toolcrib-merge-'));
164
+ try {
165
+ fs.writeFileSync(path.join(dir, 'ours'), ours);
166
+ fs.writeFileSync(path.join(dir, 'base'), base);
167
+ fs.writeFileSync(path.join(dir, 'theirs'), theirs);
168
+ const { merged, conflicts } = await gitMergeFile(dir, { ours: labels.ours, base: 'base', theirs: labels.theirs });
169
+ return { merged, conflicts };
170
+ } finally {
171
+ await fsp.rm(dir, { recursive: true, force: true }).catch(() => {});
172
+ }
173
+ }
174
+
175
+ /**
176
+ * @param {{base:string, ours:string, theirs:string}} texts - LF-normalized, BOM-free
177
+ * @param {{engine?: 'git'|'js', newLabel: string}} opts - `engine` defaults to 'js';
178
+ * a git failure on one file falls back to the JS engine for that file.
179
+ */
180
+ export async function mergeThreeWay({ base, ours, theirs }, { engine = 'js', newLabel }) {
181
+ const labels = { ours: 'local', theirs: newLabel };
182
+ if (engine === 'git') {
183
+ try {
184
+ return { ...(await mergeWithGit(base, ours, theirs, labels)), engine: 'git' };
185
+ } catch {
186
+ // fall through to the pure-JS engine
187
+ }
188
+ }
189
+ return { ...mergeThreeWayJs(base, ours, theirs, labels), engine: 'js' };
190
+ }
@@ -2,6 +2,7 @@ import fs from 'node:fs';
2
2
  import fsp from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { createTwoFilesPatch } from 'diff';
5
+ import { listFilesRecursive } from './zip.js';
5
6
 
6
7
  export const PATCH_DIR = './toolcrib-patches';
7
8
 
@@ -37,6 +38,45 @@ export function normalize(content) {
37
38
  return content.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
38
39
  }
39
40
 
41
+ function buildPatchInfo(relPath, currentContent, proposedContent, label) {
42
+ relPath = relPath.replace(/\\/g, '/');
43
+ // label defaults to the *normalized* relPath — a default parameter
44
+ // expression (`label = relPath`) would capture the pre-normalization
45
+ // value instead, since defaults evaluate before the function body runs.
46
+ if (label === undefined) label = relPath;
47
+ if (normalize(currentContent) === normalize(proposedContent)) return null; // no-op
48
+
49
+ const isNewFile = currentContent === '';
50
+ // Symmetric with isNewFile above: a deletion is just a patch whose
51
+ // *target* is /dev/null instead of its *source* — git apply (confirmed
52
+ // directly against a real repo, not assumed) recognizes this from a
53
+ // plain unified diff exactly the same way it recognizes a new file from
54
+ // an empty source, no git-extended `diff --git`/`deleted file mode`
55
+ // headers required. The `!isNewFile` guard only rules out the
56
+ // '' -> '' case, already caught by the no-op check above; kept for
57
+ // clarity that a file can't be simultaneously new and deleted.
58
+ const isDeletedFile = proposedContent === '' && !isNewFile;
59
+ const patch = createTwoFilesPatch(
60
+ isNewFile ? '/dev/null' : `a/${relPath}`,
61
+ isDeletedFile ? '/dev/null' : `b/${relPath}`,
62
+ currentContent,
63
+ proposedContent,
64
+ isNewFile ? undefined : `${label} (current)`,
65
+ isDeletedFile ? undefined : isNewFile ? `${label} (new file)` : `${label} (proposed)`
66
+ );
67
+ return { patch, isNewFile, isDeletedFile };
68
+ }
69
+
70
+ /**
71
+ * Pure patch-text construction shared by PendingChanges.propose() and the
72
+ * export-patches command. Returns the git-apply-compatible unified diff
73
+ * string, or null when the two contents are equal after line-ending
74
+ * normalization. '' as current means a new file; '' as proposed, a deletion.
75
+ */
76
+ export function buildPatch(relPath, currentContent, proposedContent, label) {
77
+ return buildPatchInfo(relPath, currentContent, proposedContent, label)?.patch ?? null;
78
+ }
79
+
40
80
  /**
41
81
  * Collects proposed file changes as unified diff patches. Nothing is ever
42
82
  * written directly to a pre-existing or ambiguous target — every mutation
@@ -53,6 +93,7 @@ export function normalize(content) {
53
93
  export class PendingChanges {
54
94
  constructor() {
55
95
  this.entries = [];
96
+ this.files = [];
56
97
  }
57
98
 
58
99
  /**
@@ -69,36 +110,23 @@ export class PendingChanges {
69
110
  */
70
111
  propose(relPath, currentContent, proposedContent, label) {
71
112
  relPath = relPath.replace(/\\/g, '/');
72
- // label defaults to the *normalized* relPath — a default parameter
73
- // expression (`label = relPath`) would capture the pre-normalization
74
- // value instead, since defaults evaluate before the function body runs.
75
- if (label === undefined) label = relPath;
76
- if (normalize(currentContent) === normalize(proposedContent)) return; // no-op, nothing to propose
77
-
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;
88
- const patch = createTwoFilesPatch(
89
- isNewFile ? '/dev/null' : `a/${relPath}`,
90
- isDeletedFile ? '/dev/null' : `b/${relPath}`,
91
- currentContent,
92
- proposedContent,
93
- isNewFile ? undefined : `${label} (current)`,
94
- isDeletedFile ? undefined : isNewFile ? `${label} (new file)` : `${label} (proposed)`
95
- );
96
-
97
- this.entries.push({ relPath, patch, isNewFile, isDeletedFile });
113
+ const built = buildPatchInfo(relPath, currentContent, proposedContent, label);
114
+ if (!built) return; // no-op, nothing to propose
115
+ this.entries.push({ relPath, patch: built.patch, isNewFile: built.isNewFile, isDeletedFile: built.isDeletedFile });
116
+ }
117
+
118
+ /**
119
+ * Stage a plain file (a conflict note, a binary upstream copy) next to the
120
+ * patches. It is never a `.patch`, so `apply` never writes it into the
121
+ * project. `relPath` is relative to the staging folder, forward-slash.
122
+ */
123
+ addStagedFile(relPath, content) {
124
+ relPath = relPath.replace(/\\/g, '/');
125
+ this.files.push({ relPath, content });
98
126
  }
99
127
 
100
128
  isEmpty() {
101
- return this.entries.length === 0;
129
+ return this.entries.length === 0 && this.files.length === 0;
102
130
  }
103
131
 
104
132
  count() {
@@ -126,6 +154,31 @@ export class PendingChanges {
126
154
  written.push(filePath);
127
155
  });
128
156
 
157
+ const resolvedDir = path.resolve(dir);
158
+ for (const file of this.files) {
159
+ const target = path.resolve(dir, ...file.relPath.split('/'));
160
+ // Defense in depth, same spirit as patchFallback: a staged file never leaves the staging folder.
161
+ if (!target.startsWith(resolvedDir + path.sep)) continue;
162
+ fs.mkdirSync(path.dirname(target), { recursive: true });
163
+ fs.writeFileSync(target, file.content);
164
+ }
165
+
129
166
  return written;
130
167
  }
131
168
  }
169
+
170
+ /**
171
+ * True when ./toolcrib-patches/ exists and holds anything at all. `merge` and
172
+ * `init` refuse to start over it: they clear the folder when they write, which
173
+ * would silently destroy unapplied patches and conflict notes.
174
+ */
175
+ export function hasStagedWork(projectRoot) {
176
+ const dir = path.join(projectRoot, PATCH_DIR);
177
+ // Files, not directory entries: once every note is resolved and deleted,
178
+ // the empty `conflicts/` subfolders left behind are not staged work.
179
+ return fs.existsSync(dir) && listFilesRecursive(dir).length > 0;
180
+ }
181
+
182
+ export const STAGED_WORK_MESSAGE =
183
+ './toolcrib-patches/ already holds staged work (unapplied patches or conflict notes). ' +
184
+ 'Run `toolcrib apply` to apply the patches, or delete the folder if you are done with it, then run this command again.';
@@ -46,6 +46,8 @@ export async function fetchRelease(version) {
46
46
  config,
47
47
  tempDir,
48
48
  readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
49
+ // Exact bytes, for binary detection and whole-file staging (readFile is lossy for non-UTF-8).
50
+ readBuffer: (relPath) => fs.readFileSync(path.join(tempDir, relPath)),
49
51
  allFiles: () => listFilesRecursive(tempDir).filter((f) => f !== 'toolcrib.config.json'),
50
52
  cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
51
53
  };
@@ -99,6 +101,7 @@ export async function fetchTestsRelease(version) {
99
101
  config,
100
102
  tempDir,
101
103
  readFile: (relPath) => stripBOM(fs.readFileSync(path.join(tempDir, relPath), 'utf-8')),
104
+ readBuffer: (relPath) => fs.readFileSync(path.join(tempDir, relPath)),
102
105
  allFiles: () => listFilesRecursive(tempDir).filter((f) => f !== 'toolcrib-tests.config.json'),
103
106
  cleanup: () => fsp.rm(tempDir, { recursive: true, force: true }),
104
107
  };