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.
@@ -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
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Pure rendering for `toolcrib export-patches`: the per-contribution
3
+ * SUMMARY.md (whose YAML metadata block is parsed back later, so its shape is
4
+ * machine-stable), the top-level README.md index, and patch file naming.
5
+ * No fs, no network.
6
+ */
7
+
8
+ export const INTENT_PLACEHOLDER = 'unspecified';
9
+ const INTENT_COMMENT = 'bug-fix | missing-feature | customization';
10
+
11
+ /** Folder name for contribution `index` (0-based) — `NN-<name>`, NN 1-based. */
12
+ export function contributionFolder(index, name) {
13
+ const safe = name.replace(/[^A-Za-z0-9._-]/g, '-');
14
+ return `${String(index + 1).padStart(2, '0')}-${safe}`;
15
+ }
16
+
17
+ /** Patch file name: `NNNN-<upstream path with / replaced by ->.patch`. */
18
+ export function patchFileName(index, upstreamPath) {
19
+ return `${String(index + 1).padStart(4, '0')}-${upstreamPath.replace(/[/\\]/g, '-')}.patch`;
20
+ }
21
+
22
+ /**
23
+ * Emit a YAML scalar, double-quoted when a plain scalar would be misread:
24
+ * empty, contains `: ` / `#` / flow punctuation, starts with an indicator
25
+ * character, has edge whitespace, or would parse as a non-string.
26
+ */
27
+ export function yamlScalar(value) {
28
+ const s = String(value);
29
+ const needsQuote =
30
+ s === '' ||
31
+ /: |#|[,[\]{}]/.test(s) ||
32
+ /:$/.test(s) ||
33
+ /^[&*!|>'"%@`]/.test(s) ||
34
+ /^[-?:](\s|$)/.test(s) ||
35
+ /^\s|\s$/.test(s) ||
36
+ /^(?:true|false|null|yes|no|on|off|~)$/i.test(s) ||
37
+ /^[-+]?(?:\d[\d_]*\.?\d*|\.\d+)(?:e[-+]?\d+)?$/i.test(s);
38
+ return needsQuote ? `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"` : s;
39
+ }
40
+
41
+ function yamlFlowList(items) {
42
+ return items.length === 0 ? '[]' : `[${items.map(yamlScalar).join(', ')}]`;
43
+ }
44
+
45
+ /** Backtick fence long enough that the content can't close it early. */
46
+ function fenceFor(text) {
47
+ const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
48
+ return '`'.repeat(longest + 1);
49
+ }
50
+
51
+ function describeContribution(c, baseVersion) {
52
+ const count = (change) => c.files.filter((f) => f.change === change && f.hunks === undefined).length;
53
+ const shared = c.files.filter((f) => f.hunks !== undefined);
54
+ const parts = [];
55
+ const added = count('added');
56
+ const modified = count('modified');
57
+ const deleted = count('deleted');
58
+ const fileBits = [];
59
+ if (added) fileBits.push(`${added} file(s) added`);
60
+ if (modified) fileBits.push(`${modified} file(s) modified`);
61
+ if (deleted) fileBits.push(`${deleted} file(s) deleted`);
62
+ if (fileBits.length) parts.push(`${fileBits.join(', ')}.`);
63
+ if (shared.length) {
64
+ parts.push(
65
+ `Shared-file hunks: ${shared.map((f) => `${f.relPath} (${f.hunks})`).join(', ')}.`
66
+ );
67
+ }
68
+ if (c.dependsOn.length) parts.push(`Depends on contribution(s): ${c.dependsOn.join(', ')}.`);
69
+ if (c.missingDependencies.length) {
70
+ parts.push(
71
+ `Missing dependencies (changed locally but not exportable, so this will not compile upstream without them): ${c.missingDependencies.join(', ')}.`
72
+ );
73
+ }
74
+ return parts.join(' ');
75
+ }
76
+
77
+ /**
78
+ * @param {object} args
79
+ * @param {object} args.contribution one entry of analyzeExport().contributions
80
+ * @param {string} args.baseVersion installed toolkit version the patches apply to
81
+ * @param {string} args.cliVersion this CLI's own package version
82
+ * @param {{relPath:string}[]} args.notExported
83
+ * @param {string[]} args.regeneratedUpstream
84
+ * @param {{ file: object, fileName: string }[]} args.patches the contribution's exported patch files, in order
85
+ */
86
+ export function renderSummary({ contribution: c, baseVersion, cliVersion, notExported, regeneratedUpstream, patches }) {
87
+ const yaml = [
88
+ 'kind: consumer-patch',
89
+ 'schema: 1',
90
+ `base_version: ${yamlScalar(baseVersion)}`,
91
+ `cli_version: ${yamlScalar(cliVersion)}`,
92
+ `contribution: ${yamlScalar(c.name)}`,
93
+ `type: ${c.type}`,
94
+ 'files:',
95
+ ];
96
+ for (const f of c.files) {
97
+ yaml.push(` - path: ${yamlScalar(f.upstreamPath)}`);
98
+ yaml.push(` change: ${f.change}`);
99
+ if (f.hunks !== undefined) yaml.push(` hunks: ${f.hunks}`);
100
+ yaml.push(` intent: ${INTENT_PLACEHOLDER} # ${INTENT_COMMENT}`);
101
+ }
102
+ yaml.push(`depends_on: ${yamlFlowList(c.dependsOn)}`);
103
+ yaml.push(`missing_dependencies: ${yamlFlowList(c.missingDependencies)}`);
104
+ yaml.push(`not_exported: ${yamlFlowList(notExported.map((n) => n.relPath))}`);
105
+ yaml.push(`regenerated_upstream: ${yamlFlowList(regeneratedUpstream)}`);
106
+ yaml.push('checklist:');
107
+ for (const [key, { status }] of Object.entries(c.checklist)) yaml.push(` ${key}: ${status}`);
108
+
109
+ const lines = [
110
+ '<details><summary>Patch metadata</summary>',
111
+ '',
112
+ '```yaml',
113
+ ...yaml,
114
+ '```',
115
+ '',
116
+ '</details>',
117
+ '',
118
+ `## ${c.name} (${c.type}, base v${baseVersion})`,
119
+ '',
120
+ describeContribution(c, baseVersion),
121
+ '',
122
+ '### Readiness checklist',
123
+ '',
124
+ '| Check | Result | Details |',
125
+ '|---|---|---|',
126
+ ];
127
+ for (const [key, { status, details }] of Object.entries(c.checklist)) {
128
+ // Escape backslashes before pipes, or a detail containing `\|` would
129
+ // become `\\|`: an escaped backslash followed by a live column break.
130
+ const cell = details.map((d) => d.replace(/\\/g, '\\\\').replace(/\|/g, '\\|')).join('; ');
131
+ lines.push(cell ? `| ${key} | ${status} | ${cell} |` : `| ${key} | ${status} | |`);
132
+ }
133
+ lines.push('', '### Patches', '');
134
+ for (const { file } of patches) {
135
+ const fence = fenceFor(file.patch);
136
+ lines.push(`#### ${file.upstreamPath}`, '', `${fence}diff`, file.patch.replace(/\n$/, ''), fence, '');
137
+ }
138
+ return lines.join('\n');
139
+ }
140
+
141
+ /** Read the `intent:` values back out of a SUMMARY.md's YAML block, in file order. */
142
+ export function parseIntents(summaryText) {
143
+ const block = /```yaml\r?\n([\s\S]*?)\r?\n```/.exec(summaryText);
144
+ if (!block) return [];
145
+ const intents = [];
146
+ for (const line of block[1].split(/\r?\n/)) {
147
+ const m = /^\s+intent:\s*(.*)$/.exec(line);
148
+ if (!m) continue;
149
+ let value = m[1];
150
+ const quoted = /^"((?:[^"\\]|\\.)*)"/.exec(value);
151
+ if (quoted) value = quoted[1].replace(/\\(.)/g, '$1');
152
+ else value = value.replace(/\s+#.*$/, '').trim();
153
+ intents.push(value);
154
+ }
155
+ return intents;
156
+ }
157
+
158
+ function diffBlock(text) {
159
+ const fence = fenceFor(text);
160
+ return `${fence}diff\n${text}\n${fence}`;
161
+ }
162
+
163
+ /**
164
+ * @param {object} args
165
+ * @param {string} args.baseVersion
166
+ * @param {{ folder: string, contribution: object }[]} args.entries
167
+ * @param {{relPath:string, change:string}[]} args.notExported
168
+ * @param {string[]} args.regeneratedUpstream
169
+ * @param {{relPath:string, hunkText:string}[]} args.appSpecific
170
+ * @param {{relPath:string, hunkText:string, candidates:string[]}[]} args.ambiguous
171
+ */
172
+ export function renderReadme({ baseVersion, entries, notExported, regeneratedUpstream, appSpecific, ambiguous }) {
173
+ const lines = [
174
+ '# toolcrib upstream export',
175
+ '',
176
+ `Base version: v${baseVersion}. Each contribution folder's patches apply with \`git apply\` to a checkout of the \`v${baseVersion}\` tag, independently of the others.`,
177
+ '',
178
+ "Fill in each contribution's `intent:` lines in its SUMMARY.md before posting.",
179
+ '',
180
+ '## Contributions',
181
+ '',
182
+ ];
183
+ if (entries.length === 0) lines.push('None.', '');
184
+ else {
185
+ lines.push('| Folder | Name | Type | Files |', '|---|---|---|---|');
186
+ for (const { folder, contribution: c } of entries) {
187
+ lines.push(`| ${folder} | ${c.name} | ${c.type} | ${c.files.length} |`);
188
+ }
189
+ lines.push('');
190
+ }
191
+
192
+ lines.push('## Not exported', '');
193
+ if (notExported.length === 0) lines.push('None.', '');
194
+ else {
195
+ lines.push('Changed outside the exportable directories (components, theme, eventBus, observer), or a shared file that was added or deleted:', '');
196
+ for (const n of notExported) lines.push(`- ${n.relPath} (${n.change})`);
197
+ lines.push('');
198
+ }
199
+
200
+ lines.push('## Regenerated upstream', '');
201
+ if (regeneratedUpstream.length === 0) lines.push('None.', '');
202
+ else {
203
+ lines.push('Generated upstream from source tags, so your edit is expected and not exported:', '');
204
+ for (const r of regeneratedUpstream) lines.push(`- ${r}`);
205
+ lines.push('');
206
+ }
207
+
208
+ lines.push('## App-specific shared-file changes', '');
209
+ if (appSpecific.length === 0) lines.push('None.', '');
210
+ else {
211
+ lines.push('Hunks in shared files that no contribution owns. Not exported.', '');
212
+ for (const a of appSpecific) lines.push(`### ${a.relPath}`, '', diffBlock(a.hunkText), '');
213
+ }
214
+
215
+ lines.push('## Ambiguous shared-file changes', '');
216
+ if (ambiguous.length === 0) lines.push('None.', '');
217
+ else {
218
+ lines.push('Hunks that more than one contribution could own. Not exported; split them by hand.', '');
219
+ for (const a of ambiguous) {
220
+ lines.push(`### ${a.relPath}`, '', `Candidates: ${a.candidates.join(', ')}`, '', diffBlock(a.hunkText), '');
221
+ }
222
+ }
223
+ return lines.join('\n');
224
+ }