@kirill.konshin/lint 0.5.2 → 0.5.4
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 +1 -1
- package/dist/lintPrepare.d.ts +9 -8
- package/dist/lintPrepare.d.ts.map +1 -1
- package/dist/lintPrepare.js +20 -14
- package/package.json +5 -3
- package/rules/github.md +0 -76
- package/rules/gitlab.md +0 -72
- package/rules/nextjs.md +2 -55
- package/rules/openspec.md +12 -0
- package/rules/storybook.md +2 -0
- package/rules/tailwind.md +1 -1
- package/rules/testing.md +1 -0
- package/rules/webstorm.md +6 -214
- package/skills/lint-github/SKILL.md +78 -0
- package/skills/lint-gitlab/SKILL.md +76 -0
- package/skills/lint-nextjs/SKILL.md +59 -0
- package/skills/{lint-repo.md → lint-repo/SKILL.md} +1 -1
- package/skills/lint-webstorm/SKILL.md +201 -0
- package/skills/lint-worktree/SKILL.md +28 -0
- package/skills/spec-steward/SKILL.md +76 -0
- package/skills/spec-steward/references/apply.md +18 -0
- package/skills/spec-steward/references/audit.md +57 -0
- package/skills/spec-steward/references/contract.md +186 -0
- package/skills/spec-steward/references/criteria.md +59 -0
- package/skills/spec-steward/references/model.md +71 -0
- package/skills/spec-steward/references/review-format.md +61 -0
- package/skills/spec-steward/references/wiring.md +19 -0
- package/skills/spec-steward/scripts/lib/align.mjs +126 -0
- package/skills/spec-steward/scripts/lib/checks.mjs +584 -0
- package/skills/spec-steward/scripts/lib/citations.mjs +156 -0
- package/skills/spec-steward/scripts/lib/corpus.mjs +259 -0
- package/skills/spec-steward/scripts/lib/coverage.mjs +124 -0
- package/skills/spec-steward/scripts/lib/evidence.mjs +335 -0
- package/skills/spec-steward/scripts/lib/git.mjs +138 -0
- package/skills/spec-steward/scripts/lib/review.mjs +347 -0
- package/skills/spec-steward/scripts/lib/scan.mjs +364 -0
- package/skills/spec-steward/scripts/lib/util.mjs +161 -0
- package/skills/spec-steward/scripts/lib/wire.mjs +331 -0
- package/skills/spec-steward/scripts/steward.mjs +350 -0
- package/skills/spec-steward/workflows/audit.js +539 -0
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Evidence for an audit, assembled mechanically so a reader judges instead of searching. For every requirement: the
|
|
4
|
+
* tests bound to it and its scenarios, and where its own terms occur in the sources with comments stripped. Code
|
|
5
|
+
* citations are optional pointers, listed when present and never evidence. Every excerpt keeps its file's own line
|
|
6
|
+
* numbers. Two shapes: per-capability Markdown bundles (`evidence --out`) and one JSON model (`evidence --json`).
|
|
7
|
+
*/
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
|
|
11
|
+
import { isTestFile } from './citations.mjs';
|
|
12
|
+
import { allRequirements } from './corpus.mjs';
|
|
13
|
+
import { listFiles } from './git.mjs';
|
|
14
|
+
import { stripComments } from './scan.mjs';
|
|
15
|
+
import { codeTokens, jaccard, sentences, words } from './util.mjs';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {import('./corpus.mjs').Corpus} Corpus
|
|
19
|
+
* @typedef {import('./corpus.mjs').Requirement} Requirement
|
|
20
|
+
* @typedef {import('./citations.mjs').Citation} Citation
|
|
21
|
+
* @typedef {{ file: string, text: string, lines: string[] }} Source text has its comments blanked; lines are as written
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|ya?ml|json|sh|py|go|conf|toml|sql|tpl|Dockerfile)$|(?:^|\/)Dockerfile[^/]*$/;
|
|
25
|
+
const SOURCE_SKIP =
|
|
26
|
+
/(?:^|\/)(?:node_modules|dist|build|coverage|\.nx|\.yarn|\.yalc|\.git|docs\/build|\.docusaurus)(?:\/|$)|^openspec\/|(?:^|\/)(?:yarn\.lock|package-lock\.json|pnpm-lock\.yaml)$/;
|
|
27
|
+
const COMMON = new Set([
|
|
28
|
+
'true',
|
|
29
|
+
'false',
|
|
30
|
+
'null',
|
|
31
|
+
'undefined',
|
|
32
|
+
'string',
|
|
33
|
+
'number',
|
|
34
|
+
'object',
|
|
35
|
+
'id',
|
|
36
|
+
'url',
|
|
37
|
+
'name',
|
|
38
|
+
'type',
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/** Lines `[from, to]` of a file with their numbers. @param {string[]} lines @param {number} from @param {number} to */
|
|
42
|
+
const numbered = (lines, from, to) =>
|
|
43
|
+
lines
|
|
44
|
+
.slice(from - 1, to)
|
|
45
|
+
.map((l, i) => `${String(from + i).padStart(5)}│ ${l}`)
|
|
46
|
+
.join('\n');
|
|
47
|
+
|
|
48
|
+
/** @param {string} file */
|
|
49
|
+
const fence = (file) =>
|
|
50
|
+
/\.(?:[cm]?[jt]sx?)$/.test(file) ? 'ts' : /\.ya?ml$/.test(file) ? 'yaml' : /\.json$/.test(file) ? 'json' : '';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The non-test source files of a repository, read once, comments blanked for searching.
|
|
54
|
+
* @param {string} root
|
|
55
|
+
* @returns {Source[]}
|
|
56
|
+
*/
|
|
57
|
+
export function sourceIndex(root) {
|
|
58
|
+
return (listFiles(root) ?? [])
|
|
59
|
+
.filter((f) => SOURCE_EXT.test(f) && !SOURCE_SKIP.test(f) && !isTestFile(f))
|
|
60
|
+
.flatMap((file) => {
|
|
61
|
+
try {
|
|
62
|
+
const raw = fs.readFileSync(path.join(root, file), 'utf8');
|
|
63
|
+
return raw.length < 400_000 && !raw.includes('\0')
|
|
64
|
+
? [{ file, text: stripComments(file, raw), lines: raw.split('\n') }]
|
|
65
|
+
: [];
|
|
66
|
+
} catch {
|
|
67
|
+
return [];
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Terms worth searching for: the identifiers a requirement names in backticks. @param {Requirement} r */
|
|
73
|
+
export const searchTerms = (r) =>
|
|
74
|
+
[...new Set(codeTokens(r.block))].filter(
|
|
75
|
+
(t) => t.length >= 3 && /^[\w$.@/:<>-]+$/.test(t) && !COMMON.has(t.toLowerCase()),
|
|
76
|
+
);
|
|
77
|
+
|
|
78
|
+
/** A term as a pattern: an identifier-like end never matches inside a longer identifier. @param {string} term */
|
|
79
|
+
const termPattern = (term) =>
|
|
80
|
+
new RegExp(
|
|
81
|
+
`${/^[\w$]/.test(term) ? '(?<![\\w$])' : ''}${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}${/[\w$]$/.test(term) ? '(?![\\w$])' : ''}`,
|
|
82
|
+
'g',
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Every line of a source the term occurs on, comments stripped.
|
|
87
|
+
* @param {string} term
|
|
88
|
+
* @param {Source[]} sources
|
|
89
|
+
* @returns {{ file: string, line: number }[]}
|
|
90
|
+
*/
|
|
91
|
+
export function termHits(term, sources) {
|
|
92
|
+
const re = termPattern(term);
|
|
93
|
+
const hits = [];
|
|
94
|
+
for (const s of sources) {
|
|
95
|
+
let line = 1;
|
|
96
|
+
let from = 0;
|
|
97
|
+
let last = -1;
|
|
98
|
+
for (const m of s.text.matchAll(re)) {
|
|
99
|
+
for (let i = s.text.indexOf('\n', from); i >= 0 && i < (m.index ?? 0); i = s.text.indexOf('\n', i + 1)) {
|
|
100
|
+
line++;
|
|
101
|
+
from = i + 1;
|
|
102
|
+
}
|
|
103
|
+
if (line !== last) hits.push({ file: s.file, line });
|
|
104
|
+
last = line;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return hits;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Requirements sharing terms or wording with `r`, strongest first.
|
|
112
|
+
* @param {Requirement} r
|
|
113
|
+
* @param {{ corpus: Corpus, requirement: Requirement }[]} everywhere
|
|
114
|
+
* @param {Corpus} corpus
|
|
115
|
+
*/
|
|
116
|
+
function relatedOf(r, everywhere, corpus) {
|
|
117
|
+
const mine = new Set(searchTerms(r));
|
|
118
|
+
const myWords = words(r.statement);
|
|
119
|
+
return everywhere
|
|
120
|
+
.filter((x) => x.requirement.id !== r.id || x.corpus.name !== corpus.name)
|
|
121
|
+
.map((x) => {
|
|
122
|
+
const shared = searchTerms(x.requirement).filter((t) => mine.has(t));
|
|
123
|
+
return { x, shared, score: shared.length + jaccard(myWords, words(x.requirement.statement)) * 3 };
|
|
124
|
+
})
|
|
125
|
+
.filter((y) => y.shared.length || y.score >= 1.2)
|
|
126
|
+
.sort((a, b) => b.score - a.score)
|
|
127
|
+
.slice(0, 5);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The citations of a requirement's anchors. @param {Requirement} r @param {Citation[]} citations */
|
|
131
|
+
function citationsOf(r, citations) {
|
|
132
|
+
const anchors = new Set([`${r.file}#${r.slug}`, ...r.scenarios.map((s) => `${r.file}#${s.slug}`)]);
|
|
133
|
+
return citations.filter((c) => c.anchor && c.resolves && anchors.has(`${c.target}#${c.anchor}`));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The audit's evidence model for one repository, `spec-evidence.json`.
|
|
138
|
+
* @param {Corpus} corpus
|
|
139
|
+
* @param {Citation[]} citations
|
|
140
|
+
* @param {Source[]} sources
|
|
141
|
+
*/
|
|
142
|
+
export function evidenceModel(corpus, citations, sources) {
|
|
143
|
+
const everywhere = allRequirements(corpus).map((requirement) => ({ corpus, requirement }));
|
|
144
|
+
/** @type {Map<string, { file: string, line: number }[]>} */
|
|
145
|
+
const hitsByTerm = new Map();
|
|
146
|
+
const hitsOf = (/** @type {string} */ term) => {
|
|
147
|
+
if (!hitsByTerm.has(term)) hitsByTerm.set(term, termHits(term, sources));
|
|
148
|
+
return /** @type {{ file: string, line: number }[]} */ (hitsByTerm.get(term));
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
version: 1,
|
|
152
|
+
root: corpus.name,
|
|
153
|
+
requirements: allRequirements(corpus).map((r) => {
|
|
154
|
+
const cites = citationsOf(r, citations);
|
|
155
|
+
const bound = new Set(cites.filter((c) => c.binding).map((c) => c.anchor));
|
|
156
|
+
return {
|
|
157
|
+
id: r.id,
|
|
158
|
+
capability: r.capability,
|
|
159
|
+
file: r.file,
|
|
160
|
+
line: r.line,
|
|
161
|
+
end: r.end,
|
|
162
|
+
block: r.block,
|
|
163
|
+
class: r.advisory ? 'advisory' : 'required',
|
|
164
|
+
gaps: r.gaps.map((g) => ({
|
|
165
|
+
tracker: g.tracker,
|
|
166
|
+
text: g.text,
|
|
167
|
+
line: g.line,
|
|
168
|
+
scenario: g.scenario,
|
|
169
|
+
exempts: g.exempts,
|
|
170
|
+
})),
|
|
171
|
+
scenarios: r.scenarios.map((s) => ({
|
|
172
|
+
slug: s.slug,
|
|
173
|
+
line: s.line,
|
|
174
|
+
end: s.end,
|
|
175
|
+
block: s.block,
|
|
176
|
+
bound: bound.has(s.slug) || (r.scenarios.length === 1 && bound.has(r.slug)),
|
|
177
|
+
})),
|
|
178
|
+
bindings: cites
|
|
179
|
+
.filter((c) => c.binding)
|
|
180
|
+
.map((c) => ({
|
|
181
|
+
file: c.file,
|
|
182
|
+
line: c.line,
|
|
183
|
+
anchor: c.anchor,
|
|
184
|
+
kind: c.binding,
|
|
185
|
+
title: c.testTitle ?? null,
|
|
186
|
+
window: c.window,
|
|
187
|
+
})),
|
|
188
|
+
pointers: cites
|
|
189
|
+
.filter((c) => !c.binding)
|
|
190
|
+
.map((c) => ({
|
|
191
|
+
file: c.file,
|
|
192
|
+
line: c.line,
|
|
193
|
+
anchor: c.anchor,
|
|
194
|
+
kind: c.kind === 'doc' ? 'doc' : 'code',
|
|
195
|
+
})),
|
|
196
|
+
terms: searchTerms(r).map((term) => ({ term, hits: hitsOf(term) })),
|
|
197
|
+
related: relatedOf(r, everywhere, corpus).map(({ x, shared }) => ({ id: x.requirement.id, shared })),
|
|
198
|
+
};
|
|
199
|
+
}),
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* One capability's evidence, as markdown.
|
|
205
|
+
* @param {Corpus} corpus
|
|
206
|
+
* @param {import('./corpus.mjs').Capability} cap
|
|
207
|
+
* @param {Citation[]} citations
|
|
208
|
+
* @param {Source[]} sources
|
|
209
|
+
* @param {{ corpus: Corpus, requirement: Requirement }[]} everywhere every requirement of every corpus in the run
|
|
210
|
+
*/
|
|
211
|
+
export function capabilityEvidence(corpus, cap, citations, sources, everywhere) {
|
|
212
|
+
const specLines = fs.readFileSync(path.join(corpus.path, cap.file), 'utf8').split('\n');
|
|
213
|
+
const fileLines = new Map();
|
|
214
|
+
const linesOf = (/** @type {string} */ f) => {
|
|
215
|
+
if (!fileLines.has(f)) fileLines.set(f, fs.readFileSync(path.join(corpus.path, f), 'utf8').split('\n'));
|
|
216
|
+
return fileLines.get(f);
|
|
217
|
+
};
|
|
218
|
+
const out = [
|
|
219
|
+
`# ${corpus.name} \`${cap.capability}\` — evidence`,
|
|
220
|
+
'',
|
|
221
|
+
`Spec \`${cap.file}\` in ${corpus.name} (\`${corpus.path}\`). Generated by spec-steward; every excerpt keeps its file's own line numbers. Bound tests come first: a test block, type assertion or lint entry citing a scenario is the binding that matters. Code citations are optional pointers, never evidence; "where its terms occur" is a search of comment-stripped sources, a lead to read, not a verdict.`,
|
|
222
|
+
'',
|
|
223
|
+
'## Purpose',
|
|
224
|
+
'',
|
|
225
|
+
cap.purpose || '_(none)_',
|
|
226
|
+
'',
|
|
227
|
+
];
|
|
228
|
+
for (const r of cap.requirements) {
|
|
229
|
+
const cites = citationsOf(r, citations);
|
|
230
|
+
const tests = cites.filter((c) => c.binding);
|
|
231
|
+
const code = cites.filter((c) => !c.binding);
|
|
232
|
+
out.push(
|
|
233
|
+
'---',
|
|
234
|
+
'',
|
|
235
|
+
`## \`${r.id}\` — \`${r.file}:${r.line}\`${r.advisory ? ' — ⚠️ Advisory' : ''}`,
|
|
236
|
+
'',
|
|
237
|
+
'```md',
|
|
238
|
+
numbered(specLines, r.line, r.end),
|
|
239
|
+
'```',
|
|
240
|
+
'',
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
out.push(`### Bound tests (${tests.length})`, '');
|
|
244
|
+
if (!tests.length) out.push('_Nothing binds this requirement or its scenarios._', '');
|
|
245
|
+
for (const t of tests) {
|
|
246
|
+
const lines = linesOf(t.file);
|
|
247
|
+
const [from, to] = [Math.max(1, t.window[0]), Math.min(lines.length, t.window[1], t.window[0] + 70)];
|
|
248
|
+
out.push(
|
|
249
|
+
`\`${t.file}:${t.line}\` → \`#${t.anchor}\`${t.testTitle ? ` — "${t.testTitle}"` : ''}${to < t.window[1] ? ' (window cut)' : ''}`,
|
|
250
|
+
'',
|
|
251
|
+
'```' + fence(t.file),
|
|
252
|
+
numbered(lines, from, to),
|
|
253
|
+
'```',
|
|
254
|
+
'',
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
if (code.length) {
|
|
258
|
+
out.push(`### Pointers (${code.length}) — code citations, not evidence`, '');
|
|
259
|
+
for (const c of code) {
|
|
260
|
+
const lines = linesOf(c.file);
|
|
261
|
+
out.push(
|
|
262
|
+
`\`${c.file}:${c.line}\``,
|
|
263
|
+
'',
|
|
264
|
+
'```' + fence(c.file),
|
|
265
|
+
numbered(lines, Math.max(1, c.line - 2), Math.min(lines.length, c.line + 20)),
|
|
266
|
+
'```',
|
|
267
|
+
'',
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const terms = searchTerms(r);
|
|
272
|
+
const hits = [];
|
|
273
|
+
for (const term of terms.slice(0, 8)) {
|
|
274
|
+
const found = termHits(term, sources).slice(0, 3);
|
|
275
|
+
for (const h of found) {
|
|
276
|
+
const src = sources.find((s) => s.file === h.file);
|
|
277
|
+
const text = (src?.lines[h.line - 1] ?? '').trim().slice(0, 160).replace(/`/g, "'");
|
|
278
|
+
hits.push(`- \`${term}\` — \`${h.file}:${h.line}\`: \`${text}\``);
|
|
279
|
+
}
|
|
280
|
+
if (!found.length) hits.push(`- \`${term}\` — no source contains it`);
|
|
281
|
+
}
|
|
282
|
+
out.push('### Where its terms occur', '', hits.length ? hits.join('\n') : '_It names no code terms._', '');
|
|
283
|
+
|
|
284
|
+
const related = relatedOf(r, everywhere, corpus);
|
|
285
|
+
if (related.length) {
|
|
286
|
+
out.push('### Related requirements', '');
|
|
287
|
+
for (const { x, shared } of related)
|
|
288
|
+
out.push(
|
|
289
|
+
`- ${x.corpus.name} \`${x.requirement.id}\` (\`${x.requirement.file}:${x.requirement.line}\`)${
|
|
290
|
+
shared.length
|
|
291
|
+
? ` — shares ${shared
|
|
292
|
+
.slice(0, 4)
|
|
293
|
+
.map((t) => `\`${t}\``)
|
|
294
|
+
.join(', ')}`
|
|
295
|
+
: ''
|
|
296
|
+
}: ${(sentences(x.requirement.statement)[0] ?? '').slice(0, 220)}`,
|
|
297
|
+
);
|
|
298
|
+
out.push('');
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return out.join('\n');
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Balanced parts for parallel readers; same-named capabilities across repositories stay in one part.
|
|
306
|
+
* @param {{ corpus: string, capability: string, file: string, bytes: number, requirementIds: string[] }[]} bundles
|
|
307
|
+
* @param {number} parts
|
|
308
|
+
*/
|
|
309
|
+
export function partition(bundles, parts) {
|
|
310
|
+
const groups = new Map();
|
|
311
|
+
for (const b of bundles) {
|
|
312
|
+
const key = b.capability.split('/').pop();
|
|
313
|
+
groups.set(key, [...(groups.get(key) ?? []), b]);
|
|
314
|
+
}
|
|
315
|
+
const bins = Array.from({ length: Math.max(1, parts) }, (_, i) => ({
|
|
316
|
+
part: i + 1,
|
|
317
|
+
bytes: 0,
|
|
318
|
+
files: /** @type {string[]} */ ([]),
|
|
319
|
+
capabilities: /** @type {string[]} */ ([]),
|
|
320
|
+
requirementIds: /** @type {string[]} */ ([]),
|
|
321
|
+
}));
|
|
322
|
+
const sorted = [...groups.values()].sort(
|
|
323
|
+
(a, b) => b.reduce((s, x) => s + x.bytes, 0) - a.reduce((s, x) => s + x.bytes, 0),
|
|
324
|
+
);
|
|
325
|
+
for (const group of sorted) {
|
|
326
|
+
const bin = bins.reduce((min, x) => (x.bytes < min.bytes ? x : min));
|
|
327
|
+
for (const b of group) {
|
|
328
|
+
bin.bytes += b.bytes;
|
|
329
|
+
bin.files.push(b.file);
|
|
330
|
+
bin.capabilities.push(`${b.corpus}:${b.capability}`);
|
|
331
|
+
bin.requirementIds.push(...b.requirementIds.map((id) => `${b.corpus}:${id}`));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return bins.filter((b) => b.files.length);
|
|
335
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/** The few git reads steward needs; every one degrades to "nothing" outside a repository. */
|
|
3
|
+
import { execFileSync } from 'node:child_process';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @param {string} cwd
|
|
7
|
+
* @param {string[]} args
|
|
8
|
+
* @returns {string | null} stdout, or null when git fails
|
|
9
|
+
*/
|
|
10
|
+
export function git(cwd, args) {
|
|
11
|
+
try {
|
|
12
|
+
return execFileSync('git', args, {
|
|
13
|
+
cwd,
|
|
14
|
+
encoding: 'utf8',
|
|
15
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
16
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
17
|
+
});
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Answers a process asks more than once (git can be slow on a large or busy worktree). */
|
|
24
|
+
const memo = new Map();
|
|
25
|
+
/** @template T @param {string} key @param {() => T} read @returns {T} */
|
|
26
|
+
const once = (key, read) => {
|
|
27
|
+
if (!memo.has(key)) memo.set(key, read());
|
|
28
|
+
return memo.get(key);
|
|
29
|
+
};
|
|
30
|
+
/** Forget what git answered, before a run that must see the tree as it is now. */
|
|
31
|
+
export const forget = () => memo.clear();
|
|
32
|
+
|
|
33
|
+
/** Repository root containing `dir`, or null. @param {string} dir */
|
|
34
|
+
export const toplevel = (dir) =>
|
|
35
|
+
once(`toplevel:${dir}`, () => git(dir, ['rev-parse', '--show-toplevel'])?.trim() || null);
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Tracked plus untracked-but-not-ignored files, repository-relative; null when git cannot list them.
|
|
39
|
+
* @param {string} root
|
|
40
|
+
* @returns {string[] | null}
|
|
41
|
+
*/
|
|
42
|
+
export function listFiles(root) {
|
|
43
|
+
return once(`files:${root}`, () => {
|
|
44
|
+
const out = git(root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']);
|
|
45
|
+
return out === null ? null : [...new Set(out.split('\0').filter(Boolean))];
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A file's content at a ref, or null when it did not exist there. @param {string} root @param {string} ref @param {string} file */
|
|
50
|
+
export const show = (root, ref, file) => git(root, ['show', `${ref}:${file}`]);
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Many files' contents at a ref in one git process; a file absent there maps to null.
|
|
54
|
+
* @param {string} root
|
|
55
|
+
* @param {string} ref
|
|
56
|
+
* @param {string[]} files
|
|
57
|
+
* @returns {Map<string, string | null>}
|
|
58
|
+
*/
|
|
59
|
+
export function showMany(root, ref, files) {
|
|
60
|
+
const out = new Map(files.map((f) => [f, /** @type {string | null} */ (null)]));
|
|
61
|
+
if (!files.length) return out;
|
|
62
|
+
let buf;
|
|
63
|
+
try {
|
|
64
|
+
buf = execFileSync('git', ['cat-file', '--batch'], {
|
|
65
|
+
cwd: root,
|
|
66
|
+
input: files.map((f) => `${ref}:${f}\n`).join(''),
|
|
67
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
68
|
+
stdio: ['pipe', 'pipe', 'ignore'],
|
|
69
|
+
});
|
|
70
|
+
} catch {
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
let at = 0;
|
|
74
|
+
for (const file of files) {
|
|
75
|
+
const eol = buf.indexOf(10, at);
|
|
76
|
+
if (eol < 0) break;
|
|
77
|
+
const header = buf.subarray(at, eol).toString('utf8');
|
|
78
|
+
at = eol + 1;
|
|
79
|
+
const size = /^[0-9a-f]+ blob (\d+)$/.exec(header)?.[1];
|
|
80
|
+
if (size === undefined) continue;
|
|
81
|
+
out.set(file, buf.subarray(at, at + Number(size)).toString('utf8'));
|
|
82
|
+
at += Number(size) + 1;
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The commit a ref names, or null when the repository has no such object. @param {string} root @param {string} ref */
|
|
88
|
+
export const commitOf = (root, ref) =>
|
|
89
|
+
git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])?.trim() || null;
|
|
90
|
+
|
|
91
|
+
/** The merge base of `ref` and HEAD — what a branch is compared against — or `ref` itself when there is none. */
|
|
92
|
+
export const mergeBase = (/** @type {string} */ root, /** @type {string} */ ref) =>
|
|
93
|
+
git(root, ['merge-base', ref, 'HEAD'])?.trim() || ref;
|
|
94
|
+
|
|
95
|
+
/** Files under `dir` at `ref`. @param {string} root @param {string} ref @param {string} dir */
|
|
96
|
+
export function filesAt(root, ref, dir) {
|
|
97
|
+
const out = git(root, ['ls-tree', '-r', '--name-only', '-z', ref, '--', dir]);
|
|
98
|
+
return out ? out.split('\0').filter(Boolean) : [];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Files the working tree changes against `ref`: tracked edits, additions, deletions and renames, plus untracked files.
|
|
103
|
+
* @param {string} root
|
|
104
|
+
* @param {string} ref
|
|
105
|
+
*/
|
|
106
|
+
export function changedFiles(root, ref) {
|
|
107
|
+
const tracked = git(root, ['diff', '--name-only', '-z', ref, '--']) ?? '';
|
|
108
|
+
const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '-z']) ?? '';
|
|
109
|
+
return new Set([...tracked.split('\0'), ...untracked.split('\0')].filter(Boolean));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The base `--base` names (R-004): a merge request's diff base in CI, nothing in another CI pipeline, the merge base
|
|
114
|
+
* with `origin/HEAD` (or `origin/main`) locally; an explicit ref is compared through its merge base with HEAD.
|
|
115
|
+
* @param {string} root
|
|
116
|
+
* @param {string | true} given `auto`, a ref, or true when the flag had no value
|
|
117
|
+
* @param {Record<string, string | undefined>} env
|
|
118
|
+
* @returns {{ ref: string | null, how: string } | { error: string }}
|
|
119
|
+
*/
|
|
120
|
+
export function resolveBase(root, given, env = process.env) {
|
|
121
|
+
if (given !== 'auto') {
|
|
122
|
+
if (given === true || !given) return { error: '--base needs a ref, or auto' };
|
|
123
|
+
if (!commitOf(root, given)) return { error: `base ref ${given} not found — git fetch origin` };
|
|
124
|
+
return { ref: mergeBase(root, given), how: `merge base of ${given}` };
|
|
125
|
+
}
|
|
126
|
+
const sha = env.CI_MERGE_REQUEST_DIFF_BASE_SHA;
|
|
127
|
+
if (sha) {
|
|
128
|
+
if (!commitOf(root, sha)) return { error: `CI_MERGE_REQUEST_DIFF_BASE_SHA ${sha} is not in this clone` };
|
|
129
|
+
return { ref: sha, how: 'the merge request diff base' };
|
|
130
|
+
}
|
|
131
|
+
if (env.CI) return { ref: null, how: 'none — a CI pipeline outside a merge request' };
|
|
132
|
+
for (const upstream of ['origin/HEAD', 'origin/main']) {
|
|
133
|
+
if (!commitOf(root, upstream)) continue;
|
|
134
|
+
const ref = git(root, ['merge-base', upstream, 'HEAD'])?.trim();
|
|
135
|
+
if (ref) return { ref, how: `merge base of ${upstream}` };
|
|
136
|
+
}
|
|
137
|
+
return { error: 'no origin/HEAD or origin/main to compare against — git fetch origin' };
|
|
138
|
+
}
|