specshield 3.4.16 → 3.5.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/CHANGELOG.md +36 -6
- package/README.md +78 -12
- package/package.json +1 -1
- package/src/api/bdctClient.js +8 -0
- package/src/cli.js +4 -0
- package/src/commands/compare.js +2 -33
- package/src/commands/gate.js +307 -0
- package/src/commands/waivers.js +123 -0
- package/src/core/configLoader.js +34 -0
- package/src/core/gate/baseline.js +142 -0
- package/src/core/gate/git.js +44 -0
- package/src/core/gate/runGate.js +140 -0
- package/src/core/gate/waivers.js +270 -0
- package/src/core/usage/applyUsage.js +63 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
const chalk = require('chalk');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { loadConfig } = require('../core/configLoader');
|
|
7
|
+
const W = require('../core/gate/waivers');
|
|
8
|
+
const { plural } = require('../core/usage/format');
|
|
9
|
+
const logger = require('../utils/logger');
|
|
10
|
+
const exitAfterFlush = require('../utils/exitAfterFlush');
|
|
11
|
+
|
|
12
|
+
const DAY = 86400000;
|
|
13
|
+
|
|
14
|
+
async function settings(opts) {
|
|
15
|
+
const config = await loadConfig(opts.config);
|
|
16
|
+
const g = config.gate || {};
|
|
17
|
+
const maxDays = opts.maxDays !== undefined ? Number(opts.maxDays) : (g.maxWaiverDays || W.DEFAULT_MAX_DAYS);
|
|
18
|
+
if (!(maxDays >= 1)) throw new Error('--max-days must be a number ≥ 1');
|
|
19
|
+
return { file: opts.file || g.waivers || W.DEFAULT_FILE, maxDays };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const add = new Command('add')
|
|
23
|
+
.description('Accept a breaking change: add a waiver with an owner, a reason and an expiry')
|
|
24
|
+
.argument('<change>', 'Change type, e.g. response-field-removed (as printed by "specshield gate"); "*" with --operation for every change there')
|
|
25
|
+
.option('--operation <op>', 'Limit to an operation: "GET /pets/{id}"; * and ** glob path segments; "/pets/**" = any method')
|
|
26
|
+
.option('--field <name>', 'Limit to a field (name or dotted path suffix)')
|
|
27
|
+
.requiredOption('--owner <who>', 'Who answers for this waiver, e.g. @alice or team-payments')
|
|
28
|
+
.requiredOption('--reason <text>', 'Why this break is acceptable — what a reviewer needs to know')
|
|
29
|
+
.option('--days <n>', 'Expire after n days (default 30)')
|
|
30
|
+
.option('--expires <date>', 'Expire after this day (YYYY-MM-DD) instead of --days')
|
|
31
|
+
.option('--ticket <id>', 'A ticket or issue that tracks the follow-up')
|
|
32
|
+
.option('--file <path>', `Waiver file (default: ${W.DEFAULT_FILE})`)
|
|
33
|
+
.option('--max-days <n>', `Longest allowed waiver (default: gate.maxWaiverDays or ${W.DEFAULT_MAX_DAYS})`)
|
|
34
|
+
.option('--config <path>', 'Path to .specshield.yml')
|
|
35
|
+
.action(async (change, opts) => {
|
|
36
|
+
try {
|
|
37
|
+
const { file, maxDays } = await settings(opts);
|
|
38
|
+
if (opts.days && opts.expires) throw new Error('Use either --days or --expires, not both');
|
|
39
|
+
const created = W.today();
|
|
40
|
+
let expires = opts.expires;
|
|
41
|
+
if (!expires) {
|
|
42
|
+
const days = opts.days !== undefined ? Number(opts.days) : 30;
|
|
43
|
+
if (!(Number.isInteger(days) && days >= 1)) throw new Error('--days must be a whole number ≥ 1');
|
|
44
|
+
expires = new Date(Date.parse(created) + days * DAY).toISOString().slice(0, 10);
|
|
45
|
+
}
|
|
46
|
+
const waiver = { change, operation: opts.operation, field: opts.field, owner: opts.owner, reason: opts.reason, created, expires, ticket: opts.ticket };
|
|
47
|
+
const checked = W.validate(waiver, 0, { maxDays });
|
|
48
|
+
if (checked.errors.length) throw new Error(`Waiver not added: ${checked.errors.join('; ')}`);
|
|
49
|
+
await W.addWaiver(path.resolve(file), { ...waiver, change: checked.change, operation: checked.operation ? normalizeOp(checked.operation) : undefined });
|
|
50
|
+
process.stdout.write(chalk.green(`✔ Waiver added to ${file}`) + chalk.gray(` — ${[checked.change, checked.operation, checked.field].filter(Boolean).join(' ')}, ${checked.owner}, until ${expires}`) + '\n');
|
|
51
|
+
process.stdout.write(chalk.gray(' Commit it with the change it accepts, so the waiver is reviewed with the PR.') + '\n');
|
|
52
|
+
} catch (err) {
|
|
53
|
+
logger.error(`Error: ${err.message}`);
|
|
54
|
+
process.exit(2);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
function normalizeOp(op) {
|
|
59
|
+
const p = W.parseOperation(op);
|
|
60
|
+
return p.method === '*' ? p.path : `${p.method} ${p.path}`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const list = new Command('list')
|
|
64
|
+
.description('List waivers with their owner and expiry; --check fails on expired or invalid ones')
|
|
65
|
+
.option('--file <path>', `Waiver file (default: ${W.DEFAULT_FILE})`)
|
|
66
|
+
.option('--max-days <n>', `Longest allowed waiver (default: gate.maxWaiverDays or ${W.DEFAULT_MAX_DAYS})`)
|
|
67
|
+
.option('--check', 'Exit 1 when a waiver is expired or invalid (for a scheduled CI job)')
|
|
68
|
+
.option('--config <path>', 'Path to .specshield.yml')
|
|
69
|
+
.option('--json', 'Output machine-readable JSON')
|
|
70
|
+
.action(async (opts) => {
|
|
71
|
+
try {
|
|
72
|
+
const { file, maxDays } = await settings(opts);
|
|
73
|
+
const { exists, waivers } = await W.loadWaivers(path.resolve(file), { maxDays, file });
|
|
74
|
+
const rows = waivers.map((w) => ({ ...w, status: W.status(w), daysLeft: W.daysLeft(w) }));
|
|
75
|
+
const bad = rows.filter((w) => w.status === 'expired' || w.status === 'invalid');
|
|
76
|
+
if (opts.json) {
|
|
77
|
+
process.stdout.write(JSON.stringify({ file, exists, waivers: rows }, null, 2) + '\n');
|
|
78
|
+
} else {
|
|
79
|
+
process.stdout.write(renderList(file, exists, rows) + '\n');
|
|
80
|
+
}
|
|
81
|
+
exitAfterFlush(opts.check && bad.length ? 1 : 0);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
logger.error(`Error: ${err.message}`);
|
|
84
|
+
process.exit(2);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
function renderList(file, exists, rows) {
|
|
89
|
+
const lines = [''];
|
|
90
|
+
lines.push(chalk.bold(` Waivers — ${file}`));
|
|
91
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
92
|
+
if (!exists || rows.length === 0) {
|
|
93
|
+
lines.push(chalk.gray(` ${exists ? 'The file has no waivers.' : 'No waiver file yet.'} Add one with: specshield waivers add <change> --owner <you> --reason "<why>"`));
|
|
94
|
+
lines.push('');
|
|
95
|
+
return lines.join('\n');
|
|
96
|
+
}
|
|
97
|
+
const counts = rows.reduce((m, w) => ({ ...m, [w.status]: (m[w.status] || 0) + 1 }), {});
|
|
98
|
+
lines.push(` ${plural(rows.length, 'waiver')}` + ['active', 'expiring', 'expired', 'invalid']
|
|
99
|
+
.filter((s) => counts[s]).map((s) => ` · ${color(s)(`${counts[s]} ${s}`)}`).join(''));
|
|
100
|
+
for (const w of rows) {
|
|
101
|
+
lines.push('');
|
|
102
|
+
const what = [w.change || '?', w.operation, w.field].filter(Boolean).join(' ');
|
|
103
|
+
const when = w.status === 'invalid' ? 'invalid'
|
|
104
|
+
: w.status === 'expired' ? `expired ${w.expires}`
|
|
105
|
+
: `${w.daysLeft === 0 ? 'expires today' : `${plural(w.daysLeft, 'day')} left`} (${w.expires})`;
|
|
106
|
+
lines.push(` ${color(w.status)('●')} ${what} ${color(w.status)(when)}`);
|
|
107
|
+
if (w.owner || w.reason) lines.push(chalk.gray(` ${w.owner || 'no owner'}${w.ticket ? ` · ${w.ticket}` : ''}: ${w.reason || 'no reason'}`));
|
|
108
|
+
if (w.errors.length) lines.push(chalk.red(` ${w.errors.join('; ')}`));
|
|
109
|
+
}
|
|
110
|
+
lines.push('');
|
|
111
|
+
return lines.join('\n');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function color(status) {
|
|
115
|
+
return { active: chalk.green, expiring: chalk.yellow, expired: chalk.red, invalid: chalk.red }[status] || chalk.gray;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const waivers = new Command('waivers')
|
|
119
|
+
.description('Accepted breaking changes for "specshield gate": each with an owner, a reason and an expiry')
|
|
120
|
+
.addCommand(list, { isDefault: true })
|
|
121
|
+
.addCommand(add);
|
|
122
|
+
|
|
123
|
+
module.exports = waivers;
|
package/src/core/configLoader.js
CHANGED
|
@@ -142,6 +142,40 @@ function validateConfig(config, filePath) {
|
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
if (config.gate !== undefined && config.gate !== null) {
|
|
146
|
+
const g = config.gate;
|
|
147
|
+
if (typeof g !== 'object' || Array.isArray(g)) {
|
|
148
|
+
throw new Error(`Config error in "${filePath}": gate must be an object`);
|
|
149
|
+
}
|
|
150
|
+
if (g.mode !== undefined && !['blocking', 'shadow'].includes(g.mode)) {
|
|
151
|
+
throw new Error(`Config error in "${filePath}": gate.mode must be "blocking" or "shadow"`);
|
|
152
|
+
}
|
|
153
|
+
if (g.maxWaiverDays !== undefined && !(Number(g.maxWaiverDays) >= 1)) {
|
|
154
|
+
throw new Error(`Config error in "${filePath}": gate.maxWaiverDays must be a number ≥ 1`);
|
|
155
|
+
}
|
|
156
|
+
for (const key of ['spec', 'waivers', 'org']) {
|
|
157
|
+
if (g[key] !== undefined && typeof g[key] !== 'string') {
|
|
158
|
+
throw new Error(`Config error in "${filePath}": gate.${key} must be a string`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (g.upload !== undefined && typeof g.upload !== 'boolean') {
|
|
162
|
+
throw new Error(`Config error in "${filePath}": gate.upload must be a boolean`);
|
|
163
|
+
}
|
|
164
|
+
valid.gate = {
|
|
165
|
+
spec: g.spec,
|
|
166
|
+
mode: g.mode,
|
|
167
|
+
waivers: g.waivers,
|
|
168
|
+
maxWaiverDays: g.maxWaiverDays !== undefined ? Number(g.maxWaiverDays) : undefined,
|
|
169
|
+
upload: g.upload,
|
|
170
|
+
org: g.org,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// `specshield init` writes the spec path here; the gate falls back to it.
|
|
175
|
+
if (config.github && typeof config.github === 'object' && typeof config.github.specPath === 'string') {
|
|
176
|
+
valid.github = { specPath: config.github.specPath };
|
|
177
|
+
}
|
|
178
|
+
|
|
145
179
|
return valid;
|
|
146
180
|
}
|
|
147
181
|
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const G = require('./git');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Which spec a change is judged against.
|
|
8
|
+
*
|
|
9
|
+
* Always the merge base of the change and its target branch — the commit the
|
|
10
|
+
* branch started from — never the target branch's current tip and never what
|
|
11
|
+
* is deployed. Against the tip, a branch that is behind sees every change
|
|
12
|
+
* merged since it forked as "removed"; against production, a break that is
|
|
13
|
+
* already merged re-fires on every unrelated PR until it ships. Both make the
|
|
14
|
+
* check fail on PRs that didn't cause the failure, which is how a gate loses
|
|
15
|
+
* the team's trust.
|
|
16
|
+
*
|
|
17
|
+
* The baseline candidate comes from the CI event when there is one:
|
|
18
|
+
* GitHub pull_request the PR's base commit
|
|
19
|
+
* GitHub merge_group the merge queue's base (the PRs ahead in the queue)
|
|
20
|
+
* GitHub push the commit before the push
|
|
21
|
+
* GitLab MR CI_MERGE_REQUEST_DIFF_BASE_SHA (already a merge base)
|
|
22
|
+
* Bitbucket PR the destination branch
|
|
23
|
+
* anywhere else origin's default branch
|
|
24
|
+
* and --base overrides it.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const ZERO_SHA = /^0+$/;
|
|
28
|
+
|
|
29
|
+
function readEvent(env) {
|
|
30
|
+
if (!env.GITHUB_EVENT_PATH) return {};
|
|
31
|
+
try { return JSON.parse(fs.readFileSync(env.GITHUB_EVENT_PATH, 'utf8')) || {}; } catch { return {}; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** What CI (if any) this runs in, and the baseline candidates it offers, best first. */
|
|
35
|
+
function ciContext(env = process.env) {
|
|
36
|
+
if (env.GITHUB_ACTIONS === 'true') {
|
|
37
|
+
const event = env.GITHUB_EVENT_NAME || '';
|
|
38
|
+
const payload = readEvent(env);
|
|
39
|
+
const ctx = { provider: 'github', event, repo: env.GITHUB_REPOSITORY || null, pr: null, candidates: [] };
|
|
40
|
+
if (event === 'merge_group' && payload.merge_group) {
|
|
41
|
+
const mg = payload.merge_group;
|
|
42
|
+
const m = /\/pr-(\d+)-/.exec(mg.head_ref || '');
|
|
43
|
+
ctx.pr = m ? Number(m[1]) : null;
|
|
44
|
+
if (mg.base_sha) ctx.candidates.push({ ref: mg.base_sha, label: 'the merge queue base' });
|
|
45
|
+
if (mg.base_ref) ctx.candidates.push({ ref: `origin/${mg.base_ref.replace(/^refs\/heads\//, '')}`, label: 'the merge queue base branch', branch: mg.base_ref.replace(/^refs\/heads\//, '') });
|
|
46
|
+
} else if ((event === 'pull_request' || event === 'pull_request_target') && payload.pull_request) {
|
|
47
|
+
const pr = payload.pull_request;
|
|
48
|
+
ctx.pr = pr.number || null;
|
|
49
|
+
ctx.title = pr.title || null;
|
|
50
|
+
if (pr.base && pr.base.sha) ctx.candidates.push({ ref: pr.base.sha, label: `the PR's base (${pr.base.ref})` });
|
|
51
|
+
} else if (event === 'push' && payload.before && !ZERO_SHA.test(payload.before)) {
|
|
52
|
+
ctx.candidates.push({ ref: payload.before, label: 'the commit before this push' });
|
|
53
|
+
}
|
|
54
|
+
if (env.GITHUB_BASE_REF) ctx.candidates.push({ ref: `origin/${env.GITHUB_BASE_REF}`, label: `origin/${env.GITHUB_BASE_REF}`, branch: env.GITHUB_BASE_REF });
|
|
55
|
+
return ctx;
|
|
56
|
+
}
|
|
57
|
+
if (env.GITLAB_CI === 'true') {
|
|
58
|
+
const ctx = { provider: 'gitlab', event: env.CI_PIPELINE_SOURCE || '', repo: env.CI_PROJECT_PATH || null, pr: env.CI_MERGE_REQUEST_IID ? Number(env.CI_MERGE_REQUEST_IID) : null, title: env.CI_MERGE_REQUEST_TITLE || null, candidates: [] };
|
|
59
|
+
if (env.CI_MERGE_REQUEST_DIFF_BASE_SHA) ctx.candidates.push({ ref: env.CI_MERGE_REQUEST_DIFF_BASE_SHA, label: 'the merge request base' });
|
|
60
|
+
if (env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME) ctx.candidates.push({ ref: `origin/${env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`, label: `origin/${env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME}`, branch: env.CI_MERGE_REQUEST_TARGET_BRANCH_NAME });
|
|
61
|
+
if (!ctx.pr && env.CI_COMMIT_BEFORE_SHA && !ZERO_SHA.test(env.CI_COMMIT_BEFORE_SHA)) ctx.candidates.push({ ref: env.CI_COMMIT_BEFORE_SHA, label: 'the commit before this push' });
|
|
62
|
+
return ctx;
|
|
63
|
+
}
|
|
64
|
+
if (env.BITBUCKET_BUILD_NUMBER) {
|
|
65
|
+
const ctx = { provider: 'bitbucket', event: env.BITBUCKET_PR_ID ? 'pull_request' : 'push', repo: env.BITBUCKET_REPO_FULL_NAME || null, pr: env.BITBUCKET_PR_ID ? Number(env.BITBUCKET_PR_ID) : null, candidates: [] };
|
|
66
|
+
const b = env.BITBUCKET_PR_DESTINATION_BRANCH;
|
|
67
|
+
if (b) ctx.candidates.push({ ref: `origin/${b}`, label: `origin/${b}`, branch: b });
|
|
68
|
+
return ctx;
|
|
69
|
+
}
|
|
70
|
+
return { provider: env.CI ? 'ci' : 'local', event: null, repo: null, pr: null, candidates: [] };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Resolves the baseline commit. `fetch` lets it fetch a missing base commit
|
|
75
|
+
* and deepen a shallow clone (CI checkouts default to depth 1) until the
|
|
76
|
+
* merge base is reachable.
|
|
77
|
+
*
|
|
78
|
+
* Returns { sha, headSha, label, candidate, fetched: [..], ctx }.
|
|
79
|
+
*/
|
|
80
|
+
function resolveBaseline({ cwd, base, env = process.env, fetch = true } = {}) {
|
|
81
|
+
if (!G.toplevel(cwd)) throw new Error('specshield gate needs a git checkout (run it inside the repository)');
|
|
82
|
+
const headSha = G.commitOf('HEAD', cwd);
|
|
83
|
+
if (!headSha) throw new Error('The repository has no commits yet');
|
|
84
|
+
const ctx = ciContext(env);
|
|
85
|
+
const fetched = [];
|
|
86
|
+
|
|
87
|
+
let candidates = ctx.candidates;
|
|
88
|
+
if (base) candidates = [{ ref: base, label: base, branch: /^[0-9a-f]{7,40}$/i.test(base) ? null : base.replace(/^origin\//, '') }];
|
|
89
|
+
if (candidates.length === 0) {
|
|
90
|
+
const def = G.remoteDefaultBranch(cwd);
|
|
91
|
+
const guesses = def ? [def] : ['origin/main', 'origin/master', 'main', 'master'];
|
|
92
|
+
candidates = guesses.map((ref) => ({ ref, label: ref, branch: ref.replace(/^origin\//, '') }));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const tried = [];
|
|
96
|
+
for (const c of candidates) {
|
|
97
|
+
let sha = G.commitOf(c.ref, cwd);
|
|
98
|
+
if (!sha && fetch) {
|
|
99
|
+
sha = fetchRef(c, cwd, fetched);
|
|
100
|
+
}
|
|
101
|
+
if (!sha) { tried.push(`${c.ref} (not found)`); continue; }
|
|
102
|
+
|
|
103
|
+
let mb = G.mergeBase(sha, headSha, cwd);
|
|
104
|
+
if (!mb && fetch && G.isShallow(cwd)) mb = deepenUntil(() => G.mergeBase(sha, headSha, cwd), c, cwd, fetched);
|
|
105
|
+
if (!mb) { tried.push(`${c.ref} (no common history with HEAD)`); continue; }
|
|
106
|
+
return { sha: mb, headSha, label: c.label, candidate: c.ref, candidateSha: sha, fetched, ctx };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const shallow = G.isShallow(cwd);
|
|
110
|
+
throw new Error(`Could not find the commit this change started from. Tried: ${tried.join(', ')}.` +
|
|
111
|
+
(shallow ? ' The checkout is shallow — fetch full history (actions/checkout: fetch-depth: 0) or allow fetching (drop --no-fetch).' : '') +
|
|
112
|
+
' Pass --base <branch or sha> to choose the baseline.');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function fetchRef(c, cwd, fetched) {
|
|
116
|
+
const isSha = /^[0-9a-f]{7,40}$/i.test(c.ref);
|
|
117
|
+
const spec = isSha ? c.ref : c.branch ? `+refs/heads/${c.branch}:refs/remotes/origin/${c.branch}` : null;
|
|
118
|
+
if (!spec) return null;
|
|
119
|
+
if (G.git(['fetch', '--no-tags', '--quiet', 'origin', spec], { cwd, allowFail: true }) === null) return null;
|
|
120
|
+
fetched.push(isSha ? c.ref.slice(0, 12) : `origin/${c.branch}`);
|
|
121
|
+
return G.commitOf(c.ref, cwd);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Deepens a shallow clone step by step until `found()` succeeds, then unshallows as a last resort. */
|
|
125
|
+
function deepenUntil(found, c, cwd, fetched) {
|
|
126
|
+
const target = /^[0-9a-f]{7,40}$/i.test(c.ref) ? c.ref : c.branch ? `+refs/heads/${c.branch}:refs/remotes/origin/${c.branch}` : null;
|
|
127
|
+
for (const depth of [50, 250, 1000]) {
|
|
128
|
+
const args = ['fetch', '--no-tags', '--quiet', `--deepen=${depth}`, 'origin'];
|
|
129
|
+
if (target) args.push(target);
|
|
130
|
+
if (G.git(args, { cwd, allowFail: true }) === null) break;
|
|
131
|
+
fetched.push(`--deepen=${depth}`);
|
|
132
|
+
const mb = found();
|
|
133
|
+
if (mb) return mb;
|
|
134
|
+
}
|
|
135
|
+
if (G.isShallow(cwd) && G.git(['fetch', '--no-tags', '--quiet', '--unshallow', 'origin'], { cwd, allowFail: true }) !== null) {
|
|
136
|
+
fetched.push('--unshallow');
|
|
137
|
+
return found();
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = { resolveBaseline, ciContext };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { execFileSync } = require('child_process');
|
|
4
|
+
|
|
5
|
+
/** Runs git and returns trimmed stdout; throws with git's stderr. */
|
|
6
|
+
function git(args, { cwd, allowFail = false, raw = false } = {}) {
|
|
7
|
+
try {
|
|
8
|
+
const out = execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 256 * 1024 * 1024 });
|
|
9
|
+
return raw ? out : out.replace(/\n$/, '');
|
|
10
|
+
} catch (err) {
|
|
11
|
+
if (allowFail) return null;
|
|
12
|
+
const msg = (err.stderr && String(err.stderr).trim()) || err.message;
|
|
13
|
+
throw new Error(`git ${args.join(' ')} failed: ${msg}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function toplevel(cwd) {
|
|
18
|
+
return git(['rev-parse', '--show-toplevel'], { cwd, allowFail: true });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function commitOf(ref, cwd) {
|
|
22
|
+
return git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], { cwd, allowFail: true }) || null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function mergeBase(a, b, cwd) {
|
|
26
|
+
return git(['merge-base', a, b], { cwd, allowFail: true }) || null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function isShallow(cwd) {
|
|
30
|
+
return git(['rev-parse', '--is-shallow-repository'], { cwd, allowFail: true }) === 'true';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The file's content at a commit, or null when it doesn't exist there. */
|
|
34
|
+
function showFile(sha, relPath, cwd) {
|
|
35
|
+
return git(['show', `${sha}:${relPath}`], { cwd, allowFail: true, raw: true });
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** origin/HEAD's branch, e.g. "origin/main", or null. */
|
|
39
|
+
function remoteDefaultBranch(cwd) {
|
|
40
|
+
const ref = git(['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], { cwd, allowFail: true });
|
|
41
|
+
return ref ? ref.replace(/^refs\/remotes\//, '') : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = { git, toplevel, commitOf, mergeBase, isShallow, showFile, remoteDefaultBranch };
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const fsExtra = require('fs-extra');
|
|
6
|
+
const { parseSpec } = require('../parseSpec');
|
|
7
|
+
const { normalizeSpec } = require('../normalizeSpec');
|
|
8
|
+
const { diffSpecs } = require('../diffEngine');
|
|
9
|
+
const { classifyChanges } = require('../classifyChanges');
|
|
10
|
+
const { resolveBaseline } = require('./baseline');
|
|
11
|
+
const G = require('./git');
|
|
12
|
+
const W = require('./waivers');
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* One gate run: the spec at the merge base vs the spec in the working tree,
|
|
16
|
+
* minus changes no client uses (with usage data), minus waived changes.
|
|
17
|
+
*
|
|
18
|
+
* verdict pass nothing blocks
|
|
19
|
+
* block something blocks, mode blocking (exit 1)
|
|
20
|
+
* would-block something blocks, mode shadow (exit 0)
|
|
21
|
+
*/
|
|
22
|
+
async function runGate(opts) {
|
|
23
|
+
const {
|
|
24
|
+
spec, cwd = process.cwd(), base, env = process.env, fetch = true,
|
|
25
|
+
mode = 'blocking', waiversFile = W.DEFAULT_FILE, maxWaiverDays = W.DEFAULT_MAX_DAYS,
|
|
26
|
+
ignore = [], usage = null, now = Date.now(),
|
|
27
|
+
} = opts;
|
|
28
|
+
if (!['blocking', 'shadow'].includes(mode)) throw new Error(`mode must be "blocking" or "shadow", got "${mode}"`);
|
|
29
|
+
|
|
30
|
+
const baseline = resolveBaseline({ cwd, base, env, fetch });
|
|
31
|
+
const top = G.toplevel(cwd);
|
|
32
|
+
// git reports the toplevel with symlinks resolved (macOS /var → /private/var).
|
|
33
|
+
const rel = (p) => path.relative(real(top), real(path.resolve(cwd, p))).split(path.sep).join('/');
|
|
34
|
+
const specRel = rel(spec);
|
|
35
|
+
if (specRel.startsWith('..')) throw new Error(`${spec} is outside the repository`);
|
|
36
|
+
|
|
37
|
+
const specAbs = path.resolve(cwd, spec);
|
|
38
|
+
const headText = (await fsExtra.pathExists(specAbs)) ? await fsExtra.readFile(specAbs, 'utf8') : null;
|
|
39
|
+
const baseText = G.showFile(baseline.sha, specRel, cwd);
|
|
40
|
+
if (headText === null && baseText === null) {
|
|
41
|
+
throw new Error(`Spec not found: ${spec} (neither in the working tree nor at the baseline ${baseline.sha.slice(0, 12)})`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// A Windows checkout (core.autocrlf) has CRLF in the tree and LF in history.
|
|
45
|
+
const same = headText !== null && baseText !== null && headText.replace(/\r\n/g, '\n') === baseText.replace(/\r\n/g, '\n');
|
|
46
|
+
const out = {
|
|
47
|
+
version: 1,
|
|
48
|
+
mode,
|
|
49
|
+
spec: specRel,
|
|
50
|
+
baseline: { sha: baseline.sha, from: baseline.label, candidate: baseline.candidate, fetched: baseline.fetched },
|
|
51
|
+
head: { sha: baseline.headSha, dirty: isDirty(specRel, cwd) },
|
|
52
|
+
ci: { provider: baseline.ctx.provider, event: baseline.ctx.event, repo: baseline.ctx.repo, pr: baseline.ctx.pr, title: baseline.ctx.title || null },
|
|
53
|
+
specTouched: !same,
|
|
54
|
+
specStatus: baseText === null ? 'added' : headText === null ? 'deleted' : same ? 'unchanged' : 'changed',
|
|
55
|
+
breaking: [],
|
|
56
|
+
blocking: [],
|
|
57
|
+
waived: [],
|
|
58
|
+
unused: [],
|
|
59
|
+
ignored: [],
|
|
60
|
+
nonBreaking: 0,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// Waivers: the working tree's file applies; the baseline's tells which were added here.
|
|
64
|
+
const wAbs = path.resolve(cwd, waiversFile);
|
|
65
|
+
const wOpts = { maxDays: maxWaiverDays, now, file: waiversFile };
|
|
66
|
+
const headW = await W.loadWaivers(wAbs, wOpts);
|
|
67
|
+
const baseWText = G.showFile(baseline.sha, rel(waiversFile), cwd);
|
|
68
|
+
let baseW = [];
|
|
69
|
+
try { baseW = baseWText ? W.parseWaivers(baseWText, wOpts).waivers : []; } catch { /* the baseline's file may predate today's rules */ }
|
|
70
|
+
|
|
71
|
+
let breaking = [];
|
|
72
|
+
if (out.specStatus === 'deleted') {
|
|
73
|
+
breaking = [{ type: 'SPEC_REMOVED', path: null, method: null, field: null, severity: 'error', description: `The spec ${specRel} was deleted` }];
|
|
74
|
+
} else if (out.specStatus === 'changed') {
|
|
75
|
+
const baseDoc = parseSpec(baseText, specRel);
|
|
76
|
+
const headDoc = parseSpec(headText, specRel);
|
|
77
|
+
let result = classifyChanges(diffSpecs(normalizeSpec(baseDoc), normalizeSpec(headDoc)));
|
|
78
|
+
out.nonBreaking = result.additions.length + result.modifications.length + result.warnings.length;
|
|
79
|
+
if (ignore.length) {
|
|
80
|
+
const hit = (c) => ignore.some((p) => (c.description || '').includes(p));
|
|
81
|
+
out.ignored = result.breakingChanges.filter(hit);
|
|
82
|
+
result = { ...result, breakingChanges: result.breakingChanges.filter((c) => !hit(c)) };
|
|
83
|
+
}
|
|
84
|
+
if (usage && usage.usage) {
|
|
85
|
+
const { applyUsage } = require('../usage/applyUsage');
|
|
86
|
+
result = await applyUsage(result, baseDoc, usage, `${specRel} at ${baseline.sha.slice(0, 12)}`);
|
|
87
|
+
out.unused = result.unusedBreakingChanges || [];
|
|
88
|
+
out.usage = result.usage;
|
|
89
|
+
}
|
|
90
|
+
breaking = result.breakingChanges;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
out.breaking = breaking.map(withKey);
|
|
94
|
+
const { blocking, waived, used } = W.applyWaivers(out.breaking, headW.waivers, now);
|
|
95
|
+
out.blocking = blocking;
|
|
96
|
+
out.waived = waived;
|
|
97
|
+
|
|
98
|
+
const added = W.newSince(headW.waivers, baseW);
|
|
99
|
+
out.waivers = {
|
|
100
|
+
file: waiversFile,
|
|
101
|
+
exists: headW.exists,
|
|
102
|
+
total: headW.waivers.length,
|
|
103
|
+
counts: countBy(headW.waivers.map((w) => W.status(w, now))),
|
|
104
|
+
used: used.size,
|
|
105
|
+
invalid: headW.waivers.filter((w) => w.errors.length).map(summary),
|
|
106
|
+
expired: headW.waivers.filter((w) => W.status(w, now) === 'expired').map(summary),
|
|
107
|
+
expiring: headW.waivers.filter((w) => W.status(w, now) === 'expiring').map((w) => ({ ...summary(w), daysLeft: W.daysLeft(w, now) })),
|
|
108
|
+
added: added.map(summary),
|
|
109
|
+
// A waiver added in this change that matches nothing is almost always a typo.
|
|
110
|
+
unmatchedAdded: added.filter((w) => W.status(w, now) !== 'invalid' && W.status(w, now) !== 'expired' && !used.has(w.index)).map(summary),
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
out.verdict = blocking.length === 0 ? 'pass' : mode === 'shadow' ? 'would-block' : 'block';
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function withKey(c) {
|
|
118
|
+
const eps = W.endpointsOf(c);
|
|
119
|
+
return { ...c, change: W.changeId(c.type), operations: eps, key: [W.changeId(c.type), eps.join(','), c.field || ''].join('|') };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function summary(w) {
|
|
123
|
+
return { index: w.index, change: w.change, operation: w.operation, field: w.field, owner: w.owner, reason: w.reason, expires: w.expires, ticket: w.ticket, errors: w.errors };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function countBy(list) {
|
|
127
|
+
return list.reduce((m, k) => ({ ...m, [k]: (m[k] || 0) + 1 }), {});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** realpath for a path that may not exist yet (a deleted spec). */
|
|
131
|
+
function real(p) {
|
|
132
|
+
try { return fs.realpathSync(p); } catch { const d = path.dirname(p); return d === p ? p : path.join(real(d), path.basename(p)); }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function isDirty(rel, cwd) {
|
|
136
|
+
const s = G.git(['status', '--porcelain', '--', rel], { cwd, allowFail: true });
|
|
137
|
+
return Boolean(s);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { runGate };
|