toolcrib 0.8.0 → 0.10.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 +31 -0
- package/package.json +1 -1
- package/src/commands/exportPatches.js +283 -0
- package/src/commands/merge.js +66 -9
- package/src/index.js +11 -0
- package/src/lib/discussions.js +183 -0
- package/src/lib/exportFormat.js +224 -0
- package/src/lib/exportPatches.js +582 -0
- package/src/lib/git.js +48 -6
- package/src/lib/importScan.js +139 -0
- package/src/lib/patches.js +42 -26
- package/src/lib/zip.js +61 -0
package/README.md
CHANGED
|
@@ -231,6 +231,37 @@ toolcrib versions
|
|
|
231
231
|
Useful for picking an exact `--version` for `init` or `merge` instead of
|
|
232
232
|
always taking `latest`.
|
|
233
233
|
|
|
234
|
+
### `toolcrib export-patches`
|
|
235
|
+
|
|
236
|
+
Sends your changes to the vendored toolcrib source back upstream. It
|
|
237
|
+
compares `./toolcrib/` against the release recorded in
|
|
238
|
+
`toolcrib/.toolcrib-lock.json`, then writes one folder per contribution
|
|
239
|
+
to `./toolcrib-upstream/`. Each folder holds `git apply`-able patches
|
|
240
|
+
against toolcrib's own `src/` layout, plus a `SUMMARY.md`.
|
|
241
|
+
|
|
242
|
+
```bash
|
|
243
|
+
toolcrib export-patches # write folders to ./toolcrib-upstream/
|
|
244
|
+
toolcrib export-patches --out ./upstream # choose another folder
|
|
245
|
+
toolcrib export-patches --post # post each folder as a discussion (asks y/N)
|
|
246
|
+
toolcrib export-patches --post --yes # post without the prompt (needed outside a terminal)
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
- Only `components/`, `theme/`, `eventBus/`, and `observer/` changes are
|
|
250
|
+
exported. Changes to `ai-docs/`, `eslint-rules/`, and vendored tests are
|
|
251
|
+
listed as not exported. Edits to `index.ts` are expected and not
|
|
252
|
+
exported, since upstream regenerates it.
|
|
253
|
+
- Changes to shared files are split by contribution. A change that matches
|
|
254
|
+
no contribution is app-specific and not exported. A change that matches
|
|
255
|
+
two is ambiguous and not exported.
|
|
256
|
+
- Before posting, fill in each `SUMMARY.md`'s `intent:` lines
|
|
257
|
+
(`bug-fix`, `missing-feature`, or `customization`).
|
|
258
|
+
- `--post` creates a discussion in the **Consumer Patches** category of the
|
|
259
|
+
toolcrib repository, using your own `gh` login. It asks y/N first and
|
|
260
|
+
never posts without that answer or `--yes`. A folder that was already
|
|
261
|
+
posted (it has a `posted.json`) is skipped.
|
|
262
|
+
- The command never changes your project files. It only reads `./toolcrib/`
|
|
263
|
+
and writes the output folder.
|
|
264
|
+
|
|
234
265
|
## Reviewing and applying patches
|
|
235
266
|
|
|
236
267
|
After `init` or `merge`, you'll have a `./toolcrib-patches/` folder full of
|
package/package.json
CHANGED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import * as p from '@clack/prompts';
|
|
5
|
+
import { fetchRelease } from '../lib/release.js';
|
|
6
|
+
import { readLock } from '../lib/project.js';
|
|
7
|
+
import { listFilesRecursive } from '../lib/zip.js';
|
|
8
|
+
import { analyzeExport } from '../lib/exportPatches.js';
|
|
9
|
+
import {
|
|
10
|
+
contributionFolder,
|
|
11
|
+
patchFileName,
|
|
12
|
+
renderSummary,
|
|
13
|
+
renderReadme,
|
|
14
|
+
parseIntents,
|
|
15
|
+
INTENT_PLACEHOLDER,
|
|
16
|
+
} from '../lib/exportFormat.js';
|
|
17
|
+
import {
|
|
18
|
+
defaultRunGh,
|
|
19
|
+
ghLogin,
|
|
20
|
+
createDiscussion,
|
|
21
|
+
addDiscussionComment,
|
|
22
|
+
buildPostPlan,
|
|
23
|
+
CATEGORY_URL,
|
|
24
|
+
MAX_BODY,
|
|
25
|
+
} from '../lib/discussions.js';
|
|
26
|
+
|
|
27
|
+
const TOOLKIT_DIR = 'toolcrib';
|
|
28
|
+
const DEFAULT_OUT = './toolcrib-upstream';
|
|
29
|
+
const MARKER = '.toolcrib-export';
|
|
30
|
+
// Meta-configuration the CLI itself writes, never toolkit source.
|
|
31
|
+
const SKIP_LOCAL = new Set(['.toolcrib-lock.json', '.toolcrib-tests-config.json']);
|
|
32
|
+
|
|
33
|
+
const cliVersion = JSON.parse(fs.readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
|
|
34
|
+
|
|
35
|
+
function readLocalFiles(projectRoot) {
|
|
36
|
+
const root = path.join(projectRoot, TOOLKIT_DIR);
|
|
37
|
+
const files = new Map();
|
|
38
|
+
for (const relPath of listFilesRecursive(root)) {
|
|
39
|
+
if (SKIP_LOCAL.has(relPath)) continue;
|
|
40
|
+
files.set(relPath, fs.readFileSync(path.join(root, relPath), 'utf-8'));
|
|
41
|
+
}
|
|
42
|
+
return files;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Refuse to clear a directory this command didn't create. Returns an error string, or null when safe. */
|
|
46
|
+
function checkOutDir(outDir) {
|
|
47
|
+
if (!fs.existsSync(outDir)) return null;
|
|
48
|
+
if (!fs.statSync(outDir).isDirectory()) return `${outDir} exists and is not a directory.`;
|
|
49
|
+
const entries = fs.readdirSync(outDir);
|
|
50
|
+
if (entries.length > 0 && !entries.includes(MARKER)) {
|
|
51
|
+
return `${outDir} is not empty and was not created by \`toolcrib export-patches\` (no ${MARKER} marker). Choose another --out, or remove it yourself.`;
|
|
52
|
+
}
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Upstream path of a patch, from its `+++ b/` header (or `--- a/` for a deletion). */
|
|
57
|
+
function upstreamPathOf(patchText) {
|
|
58
|
+
const plus = /^\+\+\+ b\/(.+)$/m.exec(patchText);
|
|
59
|
+
if (plus) return plus[1].trim();
|
|
60
|
+
const minus = /^--- a\/(.+)$/m.exec(patchText);
|
|
61
|
+
return minus ? minus[1].trim() : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function postExport(options) {
|
|
65
|
+
const projectRoot = process.cwd();
|
|
66
|
+
const runGh = options.runGh ?? defaultRunGh;
|
|
67
|
+
const confirm = options.confirm ?? p.confirm;
|
|
68
|
+
const isTTY = options.isTTY ?? Boolean(process.stdin.isTTY);
|
|
69
|
+
p.intro('toolcrib export-patches --post');
|
|
70
|
+
|
|
71
|
+
const outDir = path.resolve(projectRoot, options.out ?? DEFAULT_OUT);
|
|
72
|
+
if (!fs.existsSync(path.join(outDir, MARKER))) {
|
|
73
|
+
p.log.error(`No export found at ${outDir}; run \`toolcrib export-patches\` first.`);
|
|
74
|
+
process.exitCode = 1;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const folders = fs
|
|
79
|
+
.readdirSync(outDir, { withFileTypes: true })
|
|
80
|
+
.filter((d) => d.isDirectory())
|
|
81
|
+
.map((d) => d.name)
|
|
82
|
+
.sort();
|
|
83
|
+
const plans = [];
|
|
84
|
+
for (const folder of folders) {
|
|
85
|
+
const dir = path.join(outDir, folder);
|
|
86
|
+
const postedFile = path.join(dir, 'posted.json');
|
|
87
|
+
if (fs.existsSync(postedFile)) {
|
|
88
|
+
let url = '';
|
|
89
|
+
try {
|
|
90
|
+
url = JSON.parse(fs.readFileSync(postedFile, 'utf8')).url ?? '';
|
|
91
|
+
} catch {
|
|
92
|
+
// unreadable record: still treat as posted
|
|
93
|
+
}
|
|
94
|
+
p.log.info(`${folder}: already posted${url ? ` (${url})` : ''}; skipping.`);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const summaryPath = path.join(dir, 'SUMMARY.md');
|
|
98
|
+
if (!fs.existsSync(summaryPath)) continue;
|
|
99
|
+
const summaryText = fs.readFileSync(summaryPath, 'utf8');
|
|
100
|
+
const patches = fs
|
|
101
|
+
.readdirSync(dir)
|
|
102
|
+
.filter((f) => f.endsWith('.patch'))
|
|
103
|
+
.sort()
|
|
104
|
+
.map((fileName) => {
|
|
105
|
+
const text = fs.readFileSync(path.join(dir, fileName), 'utf8');
|
|
106
|
+
return { fileName, upstreamPath: upstreamPathOf(text) ?? fileName, text };
|
|
107
|
+
});
|
|
108
|
+
plans.push({ folder, dir, summaryText, plan: buildPostPlan({ summaryText, patches }) });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (plans.length === 0) {
|
|
112
|
+
p.outro('Nothing to post.');
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const unspecified = plans.filter((x) => parseIntents(x.summaryText).includes(INTENT_PLACEHOLDER));
|
|
117
|
+
if (unspecified.length) {
|
|
118
|
+
p.log.warn(
|
|
119
|
+
`These contributions still have \`intent: ${INTENT_PLACEHOLDER}\` in SUMMARY.md: ${unspecified.map((x) => x.folder).join(', ')}`
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const login = ghLogin(runGh);
|
|
124
|
+
if (!login) {
|
|
125
|
+
p.log.info(
|
|
126
|
+
`gh CLI not found or not logged in. To post by hand: open ${CATEGORY_URL}, start a new discussion, use the title below and paste SUMMARY.md as the body (and each patch as a comment if the body is over ${MAX_BODY.toLocaleString('en-US')} characters).\n` +
|
|
127
|
+
plans.map((x) => ` ${x.folder}: ${x.plan.title}`).join('\n')
|
|
128
|
+
);
|
|
129
|
+
p.outro('Not posted.');
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
p.log.info(
|
|
134
|
+
plans
|
|
135
|
+
.map((x) => `${x.plan.title}\n body ${x.plan.body.length} chars, ${x.plan.comments.length} comment(s)`)
|
|
136
|
+
.join('\n') + `\nPosting as @${login} to escape-llc/toolcrib → Consumer Patches`
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
if (!options.yes) {
|
|
140
|
+
if (!isTTY) {
|
|
141
|
+
p.log.info('Not an interactive terminal; re-run with --yes to post.');
|
|
142
|
+
p.outro('Not posted.');
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const answer = await confirm({ message: `Post ${plans.length} discussion(s)?`, initialValue: false });
|
|
146
|
+
if (p.isCancel(answer) || !answer) {
|
|
147
|
+
p.outro('Not posted.');
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'toolcrib-post-'));
|
|
153
|
+
try {
|
|
154
|
+
let n = 0;
|
|
155
|
+
for (const { folder, dir, plan } of plans) {
|
|
156
|
+
try {
|
|
157
|
+
const write = (text) => {
|
|
158
|
+
const file = path.join(tmp, `${++n}.md`);
|
|
159
|
+
fs.writeFileSync(file, text);
|
|
160
|
+
return file;
|
|
161
|
+
};
|
|
162
|
+
const { id, url } = createDiscussion(runGh, { title: plan.title, bodyFile: write(plan.body) });
|
|
163
|
+
const commentUrls = [];
|
|
164
|
+
for (const c of plan.comments) {
|
|
165
|
+
commentUrls.push(addDiscussionComment(runGh, { discussionId: id, bodyFile: write(c) }));
|
|
166
|
+
}
|
|
167
|
+
fs.writeFileSync(
|
|
168
|
+
path.join(dir, 'posted.json'),
|
|
169
|
+
JSON.stringify({ url, id, postedAt: new Date().toISOString(), comments: commentUrls }, null, 2) + '\n'
|
|
170
|
+
);
|
|
171
|
+
p.log.success(`${folder}: ${url}`);
|
|
172
|
+
} catch (err) {
|
|
173
|
+
p.log.error(`${folder}: ${err.message}`);
|
|
174
|
+
process.exitCode = 1;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
} finally {
|
|
178
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
179
|
+
}
|
|
180
|
+
p.outro(process.exitCode === 1 ? 'Finished with errors.' : 'Posted.');
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export async function exportPatchesCommand(options = {}) {
|
|
184
|
+
if (options.post) return postExport(options);
|
|
185
|
+
const projectRoot = process.cwd();
|
|
186
|
+
p.intro('toolcrib export-patches');
|
|
187
|
+
|
|
188
|
+
const lock = readLock(projectRoot);
|
|
189
|
+
if (!lock) {
|
|
190
|
+
p.log.error('No toolcrib install found (missing .toolcrib-lock.json). Run `toolcrib init` first.');
|
|
191
|
+
process.exitCode = 1;
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const outDir = path.resolve(projectRoot, options.out ?? DEFAULT_OUT);
|
|
196
|
+
const outError = checkOutDir(outDir);
|
|
197
|
+
if (outError) {
|
|
198
|
+
p.log.error(outError);
|
|
199
|
+
process.exitCode = 1;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const spinner = p.spinner();
|
|
204
|
+
spinner.start(`Fetching installed release (v${lock.version})`);
|
|
205
|
+
let release;
|
|
206
|
+
try {
|
|
207
|
+
release = await fetchRelease(lock.version);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
spinner.stop('Failed to fetch release');
|
|
210
|
+
throw err;
|
|
211
|
+
}
|
|
212
|
+
spinner.stop(`Comparing ./${TOOLKIT_DIR}/ against v${release.version}`);
|
|
213
|
+
|
|
214
|
+
let analysis;
|
|
215
|
+
try {
|
|
216
|
+
const releaseFiles = new Map();
|
|
217
|
+
for (const relPath of release.allFiles()) releaseFiles.set(relPath, release.readFile(relPath));
|
|
218
|
+
analysis = analyzeExport({ releaseFiles, localFiles: readLocalFiles(projectRoot) });
|
|
219
|
+
} finally {
|
|
220
|
+
await release.cleanup();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (!analysis.hasChanges) {
|
|
224
|
+
p.log.info('No changes to vendored toolkit source.');
|
|
225
|
+
p.outro('Nothing to export.');
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const baseVersion = release.version;
|
|
230
|
+
const entries = analysis.contributions.map((contribution, i) => ({
|
|
231
|
+
folder: contributionFolder(i, contribution.name),
|
|
232
|
+
contribution,
|
|
233
|
+
}));
|
|
234
|
+
|
|
235
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
236
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
237
|
+
fs.writeFileSync(path.join(outDir, MARKER), 'Created by `toolcrib export-patches`; safe to replace.\n');
|
|
238
|
+
|
|
239
|
+
for (const { folder, contribution } of entries) {
|
|
240
|
+
const dir = path.join(outDir, folder);
|
|
241
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
242
|
+
const patches = contribution.files
|
|
243
|
+
.filter((f) => f.patch)
|
|
244
|
+
.map((file, i) => ({ file, fileName: patchFileName(i, file.upstreamPath) }));
|
|
245
|
+
for (const { file, fileName } of patches) fs.writeFileSync(path.join(dir, fileName), file.patch);
|
|
246
|
+
fs.writeFileSync(
|
|
247
|
+
path.join(dir, 'SUMMARY.md'),
|
|
248
|
+
renderSummary({
|
|
249
|
+
contribution,
|
|
250
|
+
baseVersion,
|
|
251
|
+
cliVersion,
|
|
252
|
+
notExported: analysis.notExported,
|
|
253
|
+
regeneratedUpstream: analysis.regeneratedUpstream,
|
|
254
|
+
patches,
|
|
255
|
+
})
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
fs.writeFileSync(
|
|
259
|
+
path.join(outDir, 'README.md'),
|
|
260
|
+
renderReadme({
|
|
261
|
+
baseVersion,
|
|
262
|
+
entries,
|
|
263
|
+
notExported: analysis.notExported,
|
|
264
|
+
regeneratedUpstream: analysis.regeneratedUpstream,
|
|
265
|
+
appSpecific: analysis.appSpecific,
|
|
266
|
+
ambiguous: analysis.ambiguous,
|
|
267
|
+
})
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
p.log.success(
|
|
271
|
+
`${entries.length} contribution(s) written to ${outDir}` +
|
|
272
|
+
`\n ${analysis.notExported.length} file(s) not exported` +
|
|
273
|
+
`\n ${analysis.appSpecific.length} app-specific shared-file hunk(s)` +
|
|
274
|
+
`\n ${analysis.ambiguous.length} ambiguous shared-file hunk(s)`
|
|
275
|
+
);
|
|
276
|
+
// Commander always fills in --out's default, so compare resolved paths
|
|
277
|
+
// rather than checking whether the option was set.
|
|
278
|
+
const isDefaultOut = outDir === path.resolve(projectRoot, DEFAULT_OUT);
|
|
279
|
+
const outArg = isDefaultOut ? '' : ` --out ${options.out}`;
|
|
280
|
+
p.outro(
|
|
281
|
+
`Fill in each contribution's \`intent:\` lines in its SUMMARY.md, review, then run \`toolcrib export-patches --post${outArg}\`.`
|
|
282
|
+
);
|
|
283
|
+
}
|
package/src/commands/merge.js
CHANGED
|
@@ -3,7 +3,7 @@ import * as p from '@clack/prompts';
|
|
|
3
3
|
import { fetchRelease, fetchTestsRelease } from '../lib/release.js';
|
|
4
4
|
import { resolveVersion } from '../lib/github.js';
|
|
5
5
|
import { PendingChanges, normalize, joinPatchPath } from '../lib/patches.js';
|
|
6
|
-
import { mergeImportsField } from '../lib/deps.js';
|
|
6
|
+
import { resolveDependencyDecisions, buildProposedPackageJson, mergeImportsField } from '../lib/deps.js';
|
|
7
7
|
import { fileExists, readJsonIfExists, readLock, readTextIfExists, proposeLockUpdate } from '../lib/project.js';
|
|
8
8
|
import { MANAGED_DOCS, KNOWN_TARGET_FILES, listManagedBlocks, upsertManagedBlock } from '../lib/managedDocs.js';
|
|
9
9
|
|
|
@@ -20,6 +20,9 @@ const TOOLKIT_IMPORTS_ENTRY = { '#toolcrib': './toolcrib/index.ts' };
|
|
|
20
20
|
*
|
|
21
21
|
* All three are read fresh, on demand, every time — nothing here trusts
|
|
22
22
|
* a previously-cached hash (see design notes on why that was dropped).
|
|
23
|
+
*
|
|
24
|
+
* Returns one of five outcomes: 'unchanged', 'safe-update', 'keep-local',
|
|
25
|
+
* 'conflict', or 'converged' (both sides changed to identical content).
|
|
23
26
|
*/
|
|
24
27
|
function classify(original, local, updated) {
|
|
25
28
|
const localModified = normalize(local) !== normalize(original);
|
|
@@ -28,6 +31,9 @@ function classify(original, local, updated) {
|
|
|
28
31
|
if (!localModified && !upstreamChanged) return 'unchanged';
|
|
29
32
|
if (!localModified && upstreamChanged) return 'safe-update';
|
|
30
33
|
if (localModified && !upstreamChanged) return 'keep-local';
|
|
34
|
+
// Both sides changed, but to the same content (e.g. upstream adopted the
|
|
35
|
+
// consumer's own fix): nothing to propose and nothing to resolve.
|
|
36
|
+
if (normalize(local) === normalize(updated)) return 'converged';
|
|
31
37
|
return 'conflict';
|
|
32
38
|
}
|
|
33
39
|
|
|
@@ -76,6 +82,11 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
|
|
|
76
82
|
changes.propose(joinPatchPath(TOOLKIT_DIR, relPath), local, updated, relPath);
|
|
77
83
|
updatedCount++;
|
|
78
84
|
break;
|
|
85
|
+
case 'converged':
|
|
86
|
+
// Local already matches the new release, so there's nothing to
|
|
87
|
+
// propose; it still counts as updated, not as a conflict.
|
|
88
|
+
updatedCount++;
|
|
89
|
+
break;
|
|
79
90
|
case 'keep-local':
|
|
80
91
|
keptCount++;
|
|
81
92
|
break;
|
|
@@ -86,8 +97,8 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
|
|
|
86
97
|
}
|
|
87
98
|
|
|
88
99
|
// A file present in oldRelease but absent from newRelease was removed
|
|
89
|
-
// upstream — e.g. useAnimatedMount.ts when Drawer moved to
|
|
90
|
-
//
|
|
100
|
+
// upstream — e.g. useAnimatedMount.ts when Drawer moved to a Presence
|
|
101
|
+
// primitive in v0.10.0. Without this pass, a vendored copy of a file
|
|
91
102
|
// upstream no longer ships just sits there forever, unreferenced but
|
|
92
103
|
// never cleaned up, since the loop above only ever visits paths that
|
|
93
104
|
// still exist in the *new* release. classify(original, local, '')
|
|
@@ -123,7 +134,10 @@ function diffReleaseFiles(projectRoot, oldRelease, newRelease, changes, conflict
|
|
|
123
134
|
break;
|
|
124
135
|
// 'unchanged'/'keep-local' can't occur here: original is always
|
|
125
136
|
// non-empty (relPath came from oldRelease.allFiles()) and updated is
|
|
126
|
-
// always '', so upstreamChanged is unconditionally true.
|
|
137
|
+
// always '', so upstreamChanged is unconditionally true. 'converged'
|
|
138
|
+
// only happens for a locally-emptied file (local === updated === ''),
|
|
139
|
+
// which this switch deliberately has no case for: nothing is
|
|
140
|
+
// proposed, so the empty file is left on disk as-is.
|
|
127
141
|
}
|
|
128
142
|
}
|
|
129
143
|
|
|
@@ -190,8 +204,13 @@ async function mergeManagedBlocks(projectRoot, oldRelease, newRelease, changes,
|
|
|
190
204
|
switch (status) {
|
|
191
205
|
case 'unchanged':
|
|
192
206
|
case 'safe-update':
|
|
207
|
+
case 'converged':
|
|
208
|
+
// 'converged': the block's content already matches the new doc, but
|
|
209
|
+
// its version= attribute still names the old version. It must be
|
|
210
|
+
// advanced anyway, or the next merge treats the old version's doc as
|
|
211
|
+
// the "original" and misclassifies this block.
|
|
193
212
|
proposedFileContent = upsertManagedBlock(proposedFileContent, block.docId, newRelease.version, updatedDocContent);
|
|
194
|
-
fileChanged = fileChanged || status
|
|
213
|
+
fileChanged = fileChanged || status !== 'unchanged';
|
|
195
214
|
updatedCount++;
|
|
196
215
|
break;
|
|
197
216
|
case 'keep-local':
|
|
@@ -305,13 +324,36 @@ export async function mergeCommand(options) {
|
|
|
305
324
|
|
|
306
325
|
await cleanupAll();
|
|
307
326
|
|
|
308
|
-
//
|
|
309
|
-
//
|
|
327
|
+
// package.json: the target release's peerDependencies the project doesn't
|
|
328
|
+
// have yet (a release can introduce new ones -- e.g. the Base UI switch
|
|
329
|
+
// added @base-ui/react), plus installs from before the "imports" subpath
|
|
330
|
+
// entry existed. One combined patch, same reason as init.js: two propose()
|
|
331
|
+
// calls for the same relPath would both diff against the original file.
|
|
310
332
|
const pkgPath = path.join(projectRoot, 'package.json');
|
|
311
333
|
const userPkg = readJsonIfExists(pkgPath);
|
|
334
|
+
let depConflicts = [];
|
|
335
|
+
let removedPeers = [];
|
|
312
336
|
if (userPkg) {
|
|
313
|
-
const
|
|
314
|
-
|
|
337
|
+
const depDecisions = resolveDependencyDecisions(userPkg, newRelease.config?.peerDependencies ?? {});
|
|
338
|
+
const pkgWithDeps = depDecisions.toAdd.length > 0
|
|
339
|
+
? buildProposedPackageJson(userPkg, depDecisions.toAdd)
|
|
340
|
+
: userPkg;
|
|
341
|
+
// The vendored tests' own peers are dev tooling, so devDependencies, as in init.
|
|
342
|
+
const testsDepDecisions = newTestsRelease
|
|
343
|
+
? resolveDependencyDecisions(pkgWithDeps, newTestsRelease.config?.peerDependencies ?? {})
|
|
344
|
+
: null;
|
|
345
|
+
const pkgWithAllDeps = testsDepDecisions?.toAdd.length > 0
|
|
346
|
+
? buildProposedPackageJson(pkgWithDeps, testsDepDecisions.toAdd, 'devDependencies')
|
|
347
|
+
: pkgWithDeps;
|
|
348
|
+
depConflicts = [...depDecisions.conflicts, ...(testsDepDecisions?.conflicts ?? [])];
|
|
349
|
+
// Peers the old release needed and the new one doesn't: reported, never
|
|
350
|
+
// removed -- the project may use them itself.
|
|
351
|
+
const newPeers = newRelease.config?.peerDependencies ?? {};
|
|
352
|
+
removedPeers = Object.keys(oldRelease.config?.peerDependencies ?? {}).filter(
|
|
353
|
+
(name) => !(name in newPeers) && (userPkg.dependencies?.[name] || userPkg.devDependencies?.[name])
|
|
354
|
+
);
|
|
355
|
+
const importsResult = mergeImportsField(pkgWithAllDeps, TOOLKIT_IMPORTS_ENTRY);
|
|
356
|
+
if (depDecisions.toAdd.length > 0 || testsDepDecisions?.toAdd.length > 0 || importsResult.changed) {
|
|
315
357
|
changes.propose(
|
|
316
358
|
'package.json',
|
|
317
359
|
readTextIfExists(pkgPath),
|
|
@@ -381,6 +423,21 @@ export async function mergeCommand(options) {
|
|
|
381
423
|
);
|
|
382
424
|
}
|
|
383
425
|
|
|
426
|
+
if (depConflicts.length > 0) {
|
|
427
|
+
process.exitCode = 1;
|
|
428
|
+
p.log.warn(
|
|
429
|
+
`${depConflicts.length} dependency conflict(s) — not staged, needs your decision:\n` +
|
|
430
|
+
depConflicts
|
|
431
|
+
.map((d) => ` ${d.name}: you have ${d.userRange}, toolcrib needs ${d.requiredRange} (${d.reason})`)
|
|
432
|
+
.join('\n')
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
if (removedPeers.length > 0) {
|
|
436
|
+
p.log.info(
|
|
437
|
+
`No longer required by toolcrib (left in package.json; remove them if your own code doesn't use them): ${removedPeers.join(', ')}`
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
|
|
384
441
|
p.outro(changes.isEmpty() ? 'No changes to apply.' : 'Review ./toolcrib-patches/, then run `toolcrib apply`.');
|
|
385
442
|
}
|
|
386
443
|
|
package/src/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { mergeCommand } from './commands/merge.js';
|
|
|
6
6
|
import { applyCommand } from './commands/apply.js';
|
|
7
7
|
import { doctorCommand } from './commands/doctor.js';
|
|
8
8
|
import { versionsCommand } from './commands/versions.js';
|
|
9
|
+
import { exportPatchesCommand } from './commands/exportPatches.js';
|
|
9
10
|
|
|
10
11
|
// Read at runtime instead of a JSON import assertion: `assert { type: 'json' }`
|
|
11
12
|
// vs `with { type: 'json' }` differs across the Node 18-22 range this CLI's
|
|
@@ -89,6 +90,16 @@ program
|
|
|
89
90
|
await doctorCommand(options).catch(fail);
|
|
90
91
|
});
|
|
91
92
|
|
|
93
|
+
program
|
|
94
|
+
.command('export-patches')
|
|
95
|
+
.description('Export your changes to vendored toolkit source as patches for upstream (read-only)')
|
|
96
|
+
.option('--out <dir>', 'output directory', './toolcrib-upstream')
|
|
97
|
+
.option('--post', 'post an existing export to the toolcrib Consumer Patches discussions')
|
|
98
|
+
.option('--yes', 'with --post: skip the confirmation prompt')
|
|
99
|
+
.action(async (options) => {
|
|
100
|
+
await exportPatchesCommand(options).catch(fail);
|
|
101
|
+
});
|
|
102
|
+
|
|
92
103
|
program
|
|
93
104
|
.command('versions')
|
|
94
105
|
.description('List available toolkit releases')
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Posting `toolcrib export-patches` output to GitHub Discussions via the `gh`
|
|
3
|
+
* CLI. Everything that touches `gh` takes an injectable `runGh(args)` so it is
|
|
4
|
+
* testable without any network; the plan builder is pure.
|
|
5
|
+
*/
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
|
|
8
|
+
// Cached GraphQL node ids for escape-llc/toolcrib and its "Consumer Patches"
|
|
9
|
+
// discussion category. If a mutation fails with a not-found error, re-fetch
|
|
10
|
+
// them via `repository.discussionCategories` and update these.
|
|
11
|
+
export const REPO_ID = 'R_kgDOTwhGaA';
|
|
12
|
+
export const CATEGORY_ID = 'DIC_kwDOTwhGaM4DKwRA';
|
|
13
|
+
export const MAX_BODY = 65536;
|
|
14
|
+
export const CATEGORY_URL = 'https://github.com/escape-llc/toolcrib/discussions/categories/consumer-patches';
|
|
15
|
+
|
|
16
|
+
const CREATE_MUTATION =
|
|
17
|
+
'mutation($repo:ID!,$cat:ID!,$title:String!,$body:String!){createDiscussion(input:{repositoryId:$repo,categoryId:$cat,title:$title,body:$body}){discussion{id url}}}';
|
|
18
|
+
const COMMENT_MUTATION =
|
|
19
|
+
'mutation($id:ID!,$body:String!){addDiscussionComment(input:{discussionId:$id,body:$body}){comment{url}}}';
|
|
20
|
+
|
|
21
|
+
/** Run `gh` directly (no shell: gh.exe resolves on Windows). */
|
|
22
|
+
export function defaultRunGh(args) {
|
|
23
|
+
const r = spawnSync('gh', args, { encoding: 'utf8' });
|
|
24
|
+
return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '', error: r.error };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The authenticated GitHub login, or null when gh is missing or not logged in. */
|
|
28
|
+
export function ghLogin(runGh) {
|
|
29
|
+
const r = runGh(['api', 'user', '--jq', '.login']);
|
|
30
|
+
if (r.error || r.status !== 0) return null;
|
|
31
|
+
const login = String(r.stdout ?? '').trim();
|
|
32
|
+
return login || null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function runGraphql(runGh, query, vars, bodyFile) {
|
|
36
|
+
const args = ['api', 'graphql', '-f', `query=${query}`];
|
|
37
|
+
for (const [k, v] of Object.entries(vars)) args.push('-f', `${k}=${v}`);
|
|
38
|
+
args.push('-F', `body=@${bodyFile}`);
|
|
39
|
+
const r = runGh(args);
|
|
40
|
+
if (r.error) throw new Error(`gh failed to run: ${r.error.message}`);
|
|
41
|
+
if (r.status !== 0) throw new Error(`gh api graphql failed (exit ${r.status}): ${String(r.stderr).trim()}`);
|
|
42
|
+
let json;
|
|
43
|
+
try {
|
|
44
|
+
json = JSON.parse(r.stdout);
|
|
45
|
+
} catch {
|
|
46
|
+
throw new Error(`gh api graphql returned non-JSON output: ${String(r.stdout).slice(0, 200)}`);
|
|
47
|
+
}
|
|
48
|
+
if (json.errors?.length) {
|
|
49
|
+
throw new Error(`GitHub GraphQL error: ${json.errors.map((e) => e.message).join('; ')}`);
|
|
50
|
+
}
|
|
51
|
+
return json.data;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function createDiscussion(runGh, { title, bodyFile }) {
|
|
55
|
+
const data = runGraphql(runGh, CREATE_MUTATION, { repo: REPO_ID, cat: CATEGORY_ID, title }, bodyFile);
|
|
56
|
+
const d = data?.createDiscussion?.discussion;
|
|
57
|
+
if (!d?.id) throw new Error('GitHub returned no discussion for createDiscussion.');
|
|
58
|
+
return { id: d.id, url: d.url };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function addDiscussionComment(runGh, { discussionId, bodyFile }) {
|
|
62
|
+
const data = runGraphql(runGh, COMMENT_MUTATION, { id: discussionId }, bodyFile);
|
|
63
|
+
const url = data?.addDiscussionComment?.comment?.url;
|
|
64
|
+
if (!url) throw new Error('GitHub returned no comment for addDiscussionComment.');
|
|
65
|
+
return url;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function yamlValue(summaryText, key) {
|
|
69
|
+
const block = /```yaml\r?\n([\s\S]*?)\r?\n```/.exec(summaryText);
|
|
70
|
+
if (!block) return undefined;
|
|
71
|
+
const m = new RegExp(`^${key}:\\s*(.*)$`, 'm').exec(block[1]);
|
|
72
|
+
if (!m) return undefined;
|
|
73
|
+
let v = m[1].replace(/\s+#.*$/, '').trim();
|
|
74
|
+
const q = /^"((?:[^"\\]|\\.)*)"$/.exec(v);
|
|
75
|
+
if (q) v = q[1].replace(/\\(.)/g, '$1');
|
|
76
|
+
return v;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function fenceFor(text) {
|
|
80
|
+
const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
|
|
81
|
+
return '`'.repeat(longest + 1);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Slice an over-long string into pieces of at most `size` characters. */
|
|
85
|
+
function sliceBy(text, size) {
|
|
86
|
+
const out = [];
|
|
87
|
+
for (let i = 0; i < text.length; i += size) out.push(text.slice(i, i + size));
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Split a patch into text chunks each at most `budget` characters, at hunk
|
|
93
|
+
* boundaries, repeating the file header at the top of every chunk.
|
|
94
|
+
*/
|
|
95
|
+
function splitPatch(text, budget) {
|
|
96
|
+
if (text.length <= budget) return [text];
|
|
97
|
+
const lines = text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
98
|
+
const firstHunk = lines.findIndex((l) => l.startsWith('@@ '));
|
|
99
|
+
const header = firstHunk === -1 ? '' : lines.slice(0, firstHunk).join('');
|
|
100
|
+
const body = firstHunk === -1 ? lines : lines.slice(firstHunk);
|
|
101
|
+
const hunks = [];
|
|
102
|
+
for (const line of body) {
|
|
103
|
+
if (line.startsWith('@@ ') || hunks.length === 0) hunks.push(line);
|
|
104
|
+
else hunks[hunks.length - 1] += line;
|
|
105
|
+
}
|
|
106
|
+
const room = budget - header.length;
|
|
107
|
+
if (room < 1000) throw new Error('A patch header is too large to split into discussion comments.');
|
|
108
|
+
|
|
109
|
+
// Break any hunk that cannot fit by itself, at line boundaries.
|
|
110
|
+
const units = [];
|
|
111
|
+
for (const h of hunks) {
|
|
112
|
+
if (h.length <= room) {
|
|
113
|
+
units.push(h);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
let cur = '';
|
|
117
|
+
for (const line of h.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
|
|
118
|
+
for (const piece of line.length > room ? sliceBy(line, room) : [line]) {
|
|
119
|
+
if (cur.length + piece.length > room) {
|
|
120
|
+
units.push(cur);
|
|
121
|
+
cur = '';
|
|
122
|
+
}
|
|
123
|
+
cur += piece;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (cur) units.push(cur);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const chunks = [];
|
|
130
|
+
let cur = '';
|
|
131
|
+
for (const u of units) {
|
|
132
|
+
if (cur && cur.length + u.length > room) {
|
|
133
|
+
chunks.push(header + cur);
|
|
134
|
+
cur = '';
|
|
135
|
+
}
|
|
136
|
+
cur += u;
|
|
137
|
+
}
|
|
138
|
+
if (cur) chunks.push(header + cur);
|
|
139
|
+
return chunks;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Pure: turn a SUMMARY.md and its patches into a discussion title, body, and
|
|
144
|
+
* (when the whole thing exceeds MAX_BODY) the follow-up comments carrying the
|
|
145
|
+
* patches. Every returned body/comment is at most MAX_BODY characters.
|
|
146
|
+
*
|
|
147
|
+
* @param {{ summaryText: string, patches: { fileName: string, upstreamPath: string, text: string }[] }} input
|
|
148
|
+
*/
|
|
149
|
+
export function buildPostPlan({ summaryText, patches }) {
|
|
150
|
+
const contribution = yamlValue(summaryText, 'contribution') ?? 'unnamed';
|
|
151
|
+
const type = yamlValue(summaryText, 'type') ?? 'unknown';
|
|
152
|
+
const base = yamlValue(summaryText, 'base_version') ?? 'unknown';
|
|
153
|
+
const title = `[consumer-patch] ${contribution} (${type}, base v${base})`;
|
|
154
|
+
|
|
155
|
+
if (summaryText.length <= MAX_BODY) return { title, body: summaryText, comments: [] };
|
|
156
|
+
|
|
157
|
+
const idx = summaryText.search(/^### Patches\s*$/m);
|
|
158
|
+
const prefix = idx === -1 ? summaryText.replace(/\s*$/, '\n\n') : summaryText.slice(0, idx);
|
|
159
|
+
|
|
160
|
+
// Comment overhead: heading, blank line, two fences, "diff", and a part suffix.
|
|
161
|
+
const comments = [];
|
|
162
|
+
for (const { upstreamPath, text } of patches) {
|
|
163
|
+
const body = text.replace(/\n$/, '');
|
|
164
|
+
const fence = fenceFor(body);
|
|
165
|
+
const title0 = `#### ${upstreamPath}`;
|
|
166
|
+
const reserve = title0.length + 2 * (fence.length + 2) + 8 + 24;
|
|
167
|
+
const chunks = splitPatch(body, MAX_BODY - reserve);
|
|
168
|
+
chunks.forEach((chunk, i) => {
|
|
169
|
+
const t = chunks.length > 1 ? `${title0} (part ${i + 1}/${chunks.length})` : title0;
|
|
170
|
+
comments.push(`${t}\n\n${fence}diff\n${chunk}\n${fence}`);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const n = comments.length;
|
|
175
|
+
const body = `${prefix}### Patches\n\nPosted as ${n} comment(s) below, in order.\n`;
|
|
176
|
+
if (body.length > MAX_BODY) {
|
|
177
|
+
throw new Error(`SUMMARY.md is too large to post even without its patches (${body.length} > ${MAX_BODY} characters).`);
|
|
178
|
+
}
|
|
179
|
+
for (const c of comments) {
|
|
180
|
+
if (c.length > MAX_BODY) throw new Error('Internal error: a patch comment exceeds the size limit.');
|
|
181
|
+
}
|
|
182
|
+
return { title, body, comments };
|
|
183
|
+
}
|