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.
@@ -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
+ }