@osdlc/repo-cleaner 0.20.5 → 0.24.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 +92 -0
- package/README.md +562 -167
- package/dist/approval.d.ts +91 -0
- package/dist/approval.js +233 -0
- package/dist/archive.d.ts +87 -0
- package/dist/archive.js +252 -0
- package/dist/branches.d.ts +4 -4
- package/dist/branches.js +56 -43
- package/dist/candidates.d.ts +42 -0
- package/dist/candidates.js +42 -0
- package/dist/clean.d.ts +66 -70
- package/dist/clean.js +386 -218
- package/dist/cli.d.ts +16 -10
- package/dist/cli.js +273 -102
- package/dist/discover.d.ts +28 -7
- package/dist/discover.js +185 -42
- package/dist/index.d.ts +12 -5
- package/dist/index.js +11 -4
- package/dist/landing.d.ts +10 -5
- package/dist/landing.js +15 -16
- package/dist/plan.d.ts +18 -11
- package/dist/plan.js +33 -13
- package/dist/processes.d.ts +19 -9
- package/dist/processes.js +51 -25
- package/dist/providers/github.d.ts +21 -3
- package/dist/providers/github.js +149 -27
- package/dist/providers/gitlab.js +37 -17
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.js +1 -1
- package/dist/providers/types.d.ts +15 -2
- package/dist/prs.d.ts +19 -10
- package/dist/prs.js +21 -13
- package/dist/receipt.d.ts +68 -3
- package/dist/receipt.js +30 -3
- package/dist/reference.d.ts +1 -1
- package/dist/reference.js +99 -51
- package/dist/remote-mirror.d.ts +2 -1
- package/dist/remote-mirror.js +3 -14
- package/dist/render.d.ts +17 -2
- package/dist/render.js +81 -14
- package/dist/resolve.d.ts +12 -1
- package/dist/resolve.js +15 -3
- package/dist/scope.d.ts +15 -0
- package/dist/scope.js +125 -0
- package/dist/size.d.ts +20 -0
- package/dist/size.js +34 -0
- package/dist/status-line.js +1 -0
- package/dist/step-board.js +6 -4
- package/dist/sweep.d.ts +50 -18
- package/dist/sweep.js +152 -127
- package/dist/types.d.ts +89 -10
- package/dist/types.js +50 -6
- package/dist/util.d.ts +2 -0
- package/dist/util.js +25 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.js +1 -1
- package/dist/worktrees.js +87 -11
- package/package.json +6 -5
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a person approved for a clean, and resolving it against a plan: the
|
|
3
|
+
* rows selected or picked, the rows spared, and the risks allowed. `checkApproval`
|
|
4
|
+
* refuses what can be refused before anything is swept; `resolveApproval`
|
|
5
|
+
* names each reference's one plan row.
|
|
6
|
+
*/
|
|
7
|
+
import type { Plan } from './plan.ts';
|
|
8
|
+
import { type Kind, type Risk, type RowId, type SweptWith } from './types.ts';
|
|
9
|
+
/** A risk allowed for every row (`row` absent), or for one row. */
|
|
10
|
+
export interface Allow {
|
|
11
|
+
risk: Risk;
|
|
12
|
+
/** A row id or bare name, resolved as a pick is, or a row already resolved. */
|
|
13
|
+
row?: string | Resolved | undefined;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* What a person approved. Rows are named by id (`branch:feat/x`), or by a
|
|
17
|
+
* bare name or path when only one plan row has it.
|
|
18
|
+
*
|
|
19
|
+
* `select` work on exactly these rows, whatever their verdict, instead of
|
|
20
|
+
* the default: every `delete` row. For a checklist (`-i`) or a host
|
|
21
|
+
* that chose the rows itself.
|
|
22
|
+
* `pick` also run these rows: a `review` row, or a `keep` row with an
|
|
23
|
+
* action, runs only when picked or selected.
|
|
24
|
+
* `spare` leave these rows alone: a row id; a bare name, which is every
|
|
25
|
+
* row of that name, the remote branches and worktrees of that
|
|
26
|
+
* branch included, and nothing where no row has it; or a glob
|
|
27
|
+
* (`release/*`, `remote:origin/tmp-*`) matched against row names
|
|
28
|
+
* and the branch a remote row or worktree is of. A remote branch
|
|
29
|
+
* named in full (`remote:origin/x` or `origin/x`) is still checked,
|
|
30
|
+
* and the run stops if it moved or is gone since the plan.
|
|
31
|
+
* `allow` the risks a row's action may carry.
|
|
32
|
+
*/
|
|
33
|
+
export interface Approval {
|
|
34
|
+
/** Row names, or rows already resolved: a checklist names each by its repository. */
|
|
35
|
+
select?: readonly (string | Resolved)[] | undefined;
|
|
36
|
+
pick?: readonly string[] | undefined;
|
|
37
|
+
spare?: readonly string[] | undefined;
|
|
38
|
+
allow?: readonly (Risk | Allow)[] | undefined;
|
|
39
|
+
}
|
|
40
|
+
/** A row reference resolved to one plan row. */
|
|
41
|
+
export interface Resolved {
|
|
42
|
+
repo: string;
|
|
43
|
+
id: RowId;
|
|
44
|
+
}
|
|
45
|
+
/** An approval with every row resolved to its plan row. */
|
|
46
|
+
export interface ResolvedApproval {
|
|
47
|
+
/** Null for the default selection: every `delete` row. */
|
|
48
|
+
select: Resolved[] | null;
|
|
49
|
+
pick: Resolved[];
|
|
50
|
+
/** Spared by name; a remote branch among them has its tip checked. */
|
|
51
|
+
spare: Resolved[];
|
|
52
|
+
/** Spared by a glob: left alone, nothing checked. */
|
|
53
|
+
spareMatched: Resolved[];
|
|
54
|
+
allow: {
|
|
55
|
+
risk: Risk;
|
|
56
|
+
row: Resolved | null;
|
|
57
|
+
}[];
|
|
58
|
+
}
|
|
59
|
+
/** Whether a `spare` entry is a glob rather than a row. */
|
|
60
|
+
export declare function isGlob(text: string): boolean;
|
|
61
|
+
/** A row reference as typed: a kind and a name, or a bare name (`kind: null`). */
|
|
62
|
+
export interface RowRef {
|
|
63
|
+
kind: Kind | null;
|
|
64
|
+
name: string;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* `kind:name`, or a bare name. A word before a colon that is not a kind is an
|
|
68
|
+
* error (a typo such as `wt:x`), but a path is a bare name whatever colons it
|
|
69
|
+
* holds: a prefix with a path separator in it is never a kind.
|
|
70
|
+
*/
|
|
71
|
+
export declare function parseRowRef(text: string): RowRef;
|
|
72
|
+
/** `<risk>` for every row, or `<risk>=<row>` for one. */
|
|
73
|
+
export declare function parseAllow(text: string): Allow;
|
|
74
|
+
/**
|
|
75
|
+
* What can be refused of `approval` before anything is swept: a malformed
|
|
76
|
+
* row or risk, a row a sweep with `options` could never hold, and a row
|
|
77
|
+
* picked and spared as written. A row named two ways, and an `allow` for a
|
|
78
|
+
* spared or unpicked row, are found when the approval is resolved against
|
|
79
|
+
* the plan.
|
|
80
|
+
*/
|
|
81
|
+
export declare function checkApproval(options: Pick<SweptWith, 'only' | 'branch'>, approval: Approval): void;
|
|
82
|
+
export declare const keyOf: (r: Resolved) => string;
|
|
83
|
+
export declare const same: (a: Resolved, b: Resolved) => boolean;
|
|
84
|
+
export declare const uniq: (rows: Resolved[]) => Resolved[];
|
|
85
|
+
/**
|
|
86
|
+
* `approval` resolved against `plan`, or a {@link RepoCleanerError} for one
|
|
87
|
+
* that contradicts itself or names rows the plan does not have.
|
|
88
|
+
*/
|
|
89
|
+
export declare function resolveApproval(plan: Plan, approval: Approval, cwd: string): ResolvedApproval;
|
|
90
|
+
/** Whether `allow` grants `risk` for the row `at`. */
|
|
91
|
+
export declare function allowed(allow: ResolvedApproval['allow'], at: Resolved, risk: Risk): boolean;
|
package/dist/approval.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a person approved for a clean, and resolving it against a plan: the
|
|
3
|
+
* rows selected or picked, the rows spared, and the risks allowed. `checkApproval`
|
|
4
|
+
* refuses what can be refused before anything is swept; `resolveApproval`
|
|
5
|
+
* names each reference's one plan row.
|
|
6
|
+
*/
|
|
7
|
+
import { realpathSync } from 'node:fs';
|
|
8
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
9
|
+
import { KINDS, RISKS, RepoCleanerError, parseRowId, } from "./types.js";
|
|
10
|
+
import { globRegExp } from "./util.js";
|
|
11
|
+
/** Whether a `spare` entry is a glob rather than a row. */
|
|
12
|
+
export function isGlob(text) {
|
|
13
|
+
return /[*?]/.test(text);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* `kind:name`, or a bare name. A word before a colon that is not a kind is an
|
|
17
|
+
* error (a typo such as `wt:x`), but a path is a bare name whatever colons it
|
|
18
|
+
* holds: a prefix with a path separator in it is never a kind.
|
|
19
|
+
*/
|
|
20
|
+
export function parseRowRef(text) {
|
|
21
|
+
if (text === '')
|
|
22
|
+
throw new RepoCleanerError('bad-input', 'an empty row');
|
|
23
|
+
const id = parseRowId(text);
|
|
24
|
+
if (id !== null) {
|
|
25
|
+
if (id.name === '')
|
|
26
|
+
throw new RepoCleanerError('bad-input', `bad row ${JSON.stringify(text)}: no name`);
|
|
27
|
+
return id;
|
|
28
|
+
}
|
|
29
|
+
const colon = text.indexOf(':');
|
|
30
|
+
if (colon > 1 && !/[\\/]/.test(text.slice(0, colon))) {
|
|
31
|
+
throw new RepoCleanerError('bad-input', `bad row ${JSON.stringify(text)}: expected <kind>:<name> with kind one of ${KINDS.join(', ')}, or a bare name`);
|
|
32
|
+
}
|
|
33
|
+
return { kind: null, name: text };
|
|
34
|
+
}
|
|
35
|
+
/** `<risk>` for every row, or `<risk>=<row>` for one. */
|
|
36
|
+
export function parseAllow(text) {
|
|
37
|
+
const eq = text.indexOf('=');
|
|
38
|
+
const risk = eq < 0 ? text : text.slice(0, eq);
|
|
39
|
+
checkRisk(risk);
|
|
40
|
+
if (eq < 0)
|
|
41
|
+
return { risk };
|
|
42
|
+
const row = text.slice(eq + 1);
|
|
43
|
+
if (row === '')
|
|
44
|
+
throw new RepoCleanerError('bad-input', `--allow ${text} names no row`);
|
|
45
|
+
return { risk, row };
|
|
46
|
+
}
|
|
47
|
+
function checkRisk(risk) {
|
|
48
|
+
if (!RISKS.includes(risk)) {
|
|
49
|
+
throw new RepoCleanerError('bad-input', `unknown risk ${JSON.stringify(risk)}: expected one of ${RISKS.join(', ')}`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** A conflict for a reference no sweep with `options` could hold: a kind it left out, or a row outside its `--branch`. */
|
|
53
|
+
function checkScope(options, ref, flag, text) {
|
|
54
|
+
const { only, branch } = options;
|
|
55
|
+
if (ref.kind !== null && !only.includes(ref.kind)) {
|
|
56
|
+
throw new RepoCleanerError('conflict', `${flag} ${text}: the sweep has no ${ref.kind} rows (it sweeps ${only.join(', ')})`);
|
|
57
|
+
}
|
|
58
|
+
const outside = branch !== null &&
|
|
59
|
+
((ref.kind === 'branch' && ref.name !== branch) ||
|
|
60
|
+
(ref.kind === 'remote' && !ref.name.endsWith(`/${branch}`)));
|
|
61
|
+
if (outside) {
|
|
62
|
+
throw new RepoCleanerError('conflict', `${flag} ${text} is not a row of --branch ${branch}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* What can be refused of `approval` before anything is swept: a malformed
|
|
67
|
+
* row or risk, a row a sweep with `options` could never hold, and a row
|
|
68
|
+
* picked and spared as written. A row named two ways, and an `allow` for a
|
|
69
|
+
* spared or unpicked row, are found when the approval is resolved against
|
|
70
|
+
* the plan.
|
|
71
|
+
*/
|
|
72
|
+
export function checkApproval(options, approval) {
|
|
73
|
+
const refs = [
|
|
74
|
+
...(approval.select ?? [])
|
|
75
|
+
.filter((t) => typeof t === 'string')
|
|
76
|
+
.map((t) => ['--select', t]),
|
|
77
|
+
...(approval.pick ?? []).map((t) => ['--pick', t]),
|
|
78
|
+
...(approval.spare ?? [])
|
|
79
|
+
.filter((t) => !isGlob(t))
|
|
80
|
+
.map((t) => ['--spare', t]),
|
|
81
|
+
];
|
|
82
|
+
for (const glob of (approval.spare ?? []).filter(isGlob))
|
|
83
|
+
parseRowRef(glob);
|
|
84
|
+
for (const a of approval.allow ?? []) {
|
|
85
|
+
const { risk, row } = typeof a === 'string' ? { risk: a, row: undefined } : a;
|
|
86
|
+
checkRisk(risk);
|
|
87
|
+
if (typeof row === 'string')
|
|
88
|
+
refs.push(['--allow', row]);
|
|
89
|
+
}
|
|
90
|
+
for (const [flag, text] of refs)
|
|
91
|
+
checkScope(options, parseRowRef(text), flag, text);
|
|
92
|
+
const chosen = [...(approval.select ?? []), ...(approval.pick ?? [])];
|
|
93
|
+
const both = chosen.find((p) => typeof p === 'string' && (approval.spare ?? []).includes(p));
|
|
94
|
+
if (both !== undefined)
|
|
95
|
+
throw new RepoCleanerError('conflict', `${both} is both picked and spared`);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The rows one `spare` entry leaves alone: `named`, a remote branch among
|
|
99
|
+
* which gets the tip check, and `matched`, which do not. A row id is named. A
|
|
100
|
+
* bare name names the rows it names exactly (a worktree's path, a local
|
|
101
|
+
* branch, `<remote>/<branch>`), and matches every remote branch of that name
|
|
102
|
+
* and every worktree that has it checked out, so `--spare staging` keeps
|
|
103
|
+
* `staging` everywhere; one that hits nothing spares nothing. A glob matches;
|
|
104
|
+
* see {@link matchGlob}.
|
|
105
|
+
*/
|
|
106
|
+
function spareRows(plan, text, cwd) {
|
|
107
|
+
if (isGlob(text))
|
|
108
|
+
return { named: [], matched: matchGlob(plan, text) };
|
|
109
|
+
const ref = parseRowRef(text);
|
|
110
|
+
if (ref.kind !== null)
|
|
111
|
+
return { named: [resolveRef(plan, text, '--spare', cwd)], matched: [] };
|
|
112
|
+
checkScope(plan.options, ref, '--spare', text);
|
|
113
|
+
const paths = pathForms(ref.name, cwd);
|
|
114
|
+
const named = [];
|
|
115
|
+
const matched = [];
|
|
116
|
+
for (const e of planEntries(plan)) {
|
|
117
|
+
if (e.kind === 'worktree' ? paths.has(e.name) : e.name === ref.name)
|
|
118
|
+
named.push(rowOf(e));
|
|
119
|
+
else if (e.branch === ref.name)
|
|
120
|
+
matched.push(rowOf(e));
|
|
121
|
+
}
|
|
122
|
+
// A branch some repositories lack spares nothing there, as a glob does.
|
|
123
|
+
return { named, matched };
|
|
124
|
+
}
|
|
125
|
+
/** The plan rows `glob` matches; see {@link Approval.spare}. */
|
|
126
|
+
function matchGlob(plan, glob) {
|
|
127
|
+
const ref = parseRowRef(glob);
|
|
128
|
+
const re = globRegExp(ref.name);
|
|
129
|
+
return planEntries(plan)
|
|
130
|
+
.filter((e) => ref.kind === null || ref.kind === e.kind)
|
|
131
|
+
.filter((e) => re.test(e.name) || (e.branch !== null && re.test(e.branch)))
|
|
132
|
+
.map(rowOf);
|
|
133
|
+
}
|
|
134
|
+
/** Every row of `plan`, with its repository. */
|
|
135
|
+
function planEntries(plan) {
|
|
136
|
+
return plan.repos.flatMap((repo) => repo.rows.map((row) => {
|
|
137
|
+
const { kind, name } = parseRowId(row.id);
|
|
138
|
+
const held = row.fingerprint['branch'];
|
|
139
|
+
const branch = kind === 'remote'
|
|
140
|
+
? name.slice(name.indexOf('/') + 1)
|
|
141
|
+
: kind === 'worktree' && typeof held === 'string'
|
|
142
|
+
? held
|
|
143
|
+
: null;
|
|
144
|
+
return { repo: repo.root, id: row.id, kind, name, branch };
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
const rowOf = (e) => ({ repo: e.repo, id: e.id });
|
|
148
|
+
/** The names a worktree reference may match: as written, against `cwd`, and resolved through symlinks. */
|
|
149
|
+
function pathForms(name, cwd) {
|
|
150
|
+
const abs = isAbsolute(name) ? name : resolve(cwd, name);
|
|
151
|
+
const forms = new Set([name, abs]);
|
|
152
|
+
try {
|
|
153
|
+
forms.add(realpathSync(abs));
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
// A gone worktree has no real path; the plan names it as git did.
|
|
157
|
+
}
|
|
158
|
+
return forms;
|
|
159
|
+
}
|
|
160
|
+
/** The plan row `text` names, its scope checked first so a row the plan could never hold is a conflict, not a miss. */
|
|
161
|
+
function resolveRef(plan, text, flag, cwd) {
|
|
162
|
+
if (typeof text !== 'string') {
|
|
163
|
+
if (!planEntries(plan).some((e) => same(e, text))) {
|
|
164
|
+
throw new RepoCleanerError('not-found', `${flag} ${text.id} in ${text.repo}: no such row in the plan`);
|
|
165
|
+
}
|
|
166
|
+
return { repo: text.repo, id: text.id };
|
|
167
|
+
}
|
|
168
|
+
const ref = parseRowRef(text);
|
|
169
|
+
checkScope(plan.options, ref, flag, text);
|
|
170
|
+
const paths = ref.kind === null || ref.kind === 'worktree' ? pathForms(ref.name, cwd) : null;
|
|
171
|
+
const hits = planEntries(plan)
|
|
172
|
+
.filter((e) => ref.kind === null || ref.kind === e.kind)
|
|
173
|
+
.filter((e) => (e.kind === 'worktree' ? paths.has(e.name) : ref.name === e.name))
|
|
174
|
+
.map(rowOf);
|
|
175
|
+
if (hits.length === 0) {
|
|
176
|
+
throw new RepoCleanerError('not-found', `${flag} ${text}: no such row in the plan`);
|
|
177
|
+
}
|
|
178
|
+
if (hits.length > 1) {
|
|
179
|
+
const where = [...new Set(hits.map((h) => `${h.id} in ${h.repo}`))].join(', ');
|
|
180
|
+
throw new RepoCleanerError('ambiguous', `${flag} ${text} matches ${hits.length} rows (${where}); sweep or plan only the repository it is in${ref.kind === null ? ', or name it by its full id' : ''}`);
|
|
181
|
+
}
|
|
182
|
+
return hits[0];
|
|
183
|
+
}
|
|
184
|
+
export const keyOf = (r) => `${r.repo}\0${r.id}`;
|
|
185
|
+
export const same = (a, b) => a.repo === b.repo && a.id === b.id;
|
|
186
|
+
export const uniq = (rows) => [
|
|
187
|
+
...new Map(rows.map((r) => [keyOf(r), r])).values(),
|
|
188
|
+
];
|
|
189
|
+
/**
|
|
190
|
+
* `approval` resolved against `plan`, or a {@link RepoCleanerError} for one
|
|
191
|
+
* that contradicts itself or names rows the plan does not have.
|
|
192
|
+
*/
|
|
193
|
+
export function resolveApproval(plan, approval, cwd) {
|
|
194
|
+
checkApproval(plan.options, approval);
|
|
195
|
+
const select = approval.select === undefined
|
|
196
|
+
? null
|
|
197
|
+
: uniq(approval.select.map((t) => resolveRef(plan, t, '--select', cwd)));
|
|
198
|
+
const pick = uniq((approval.pick ?? []).map((t) => resolveRef(plan, t, '--pick', cwd)));
|
|
199
|
+
const spares = (approval.spare ?? []).map((t) => spareRows(plan, t, cwd));
|
|
200
|
+
const spare = uniq(spares.flatMap((s) => s.named));
|
|
201
|
+
const spareMatched = uniq(spares.flatMap((s) => s.matched));
|
|
202
|
+
const chosen = [...(select ?? []), ...pick];
|
|
203
|
+
const picked = new Set(chosen.map(keyOf));
|
|
204
|
+
const spared = new Set([...spare, ...spareMatched].map(keyOf));
|
|
205
|
+
const both = chosen.find((p) => spared.has(keyOf(p)));
|
|
206
|
+
if (both !== undefined)
|
|
207
|
+
throw new RepoCleanerError('conflict', `${both.id} is both picked and spared`);
|
|
208
|
+
const allow = (approval.allow ?? []).map((a) => {
|
|
209
|
+
const { risk, row } = typeof a === 'string' ? { risk: a, row: undefined } : a;
|
|
210
|
+
if (row === undefined)
|
|
211
|
+
return { risk, row: null };
|
|
212
|
+
const at = resolveRef(plan, row, '--allow', cwd);
|
|
213
|
+
const named = typeof row === 'string' ? row : row.id;
|
|
214
|
+
if (spared.has(keyOf(at))) {
|
|
215
|
+
throw new RepoCleanerError('conflict', `--allow ${risk}=${named}: ${at.id} is spared`);
|
|
216
|
+
}
|
|
217
|
+
if (select !== null && !picked.has(keyOf(at))) {
|
|
218
|
+
throw new RepoCleanerError('conflict', `--allow ${risk}=${named}: ${at.id} is not selected`);
|
|
219
|
+
}
|
|
220
|
+
return { risk, row: at };
|
|
221
|
+
});
|
|
222
|
+
return {
|
|
223
|
+
select,
|
|
224
|
+
pick,
|
|
225
|
+
spare,
|
|
226
|
+
spareMatched: spareMatched.filter((r) => !spare.some((s) => same(s, r))),
|
|
227
|
+
allow,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/** Whether `allow` grants `risk` for the row `at`. */
|
|
231
|
+
export function allowed(allow, at, risk) {
|
|
232
|
+
return allow.some((a) => a.risk === risk && (a.row === null || same(a.row, at)));
|
|
233
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Archiving unlanded work to the remote before `run` deletes it.
|
|
3
|
+
*
|
|
4
|
+
* With the `archive` option, a run's first step per repository builds one
|
|
5
|
+
* commit whose tree is the remote default branch's and whose parents are that
|
|
6
|
+
* branch's tip plus the work about to be lost, and pushes it to
|
|
7
|
+
* `refs/heads/archive/<repo>-local-<date>`. A row whose work the archive holds
|
|
8
|
+
* carries `discard-archived` in place of `abandon-unmerged` and
|
|
9
|
+
* `discard-changes`.
|
|
10
|
+
*
|
|
11
|
+
* A worktree's uncommitted files go in a snapshot commit built in a temporary
|
|
12
|
+
* index (`GIT_INDEX_FILE`), so the worktree's own index and files are not
|
|
13
|
+
* touched. Left out of a snapshot: ignored files, secret-shaped files, files
|
|
14
|
+
* matching `exclude`, and files over `maxFileBytes`. Not held at all:
|
|
15
|
+
* submodule commits, files and stashes.
|
|
16
|
+
*/
|
|
17
|
+
import type { Git } from '@osdlc/typed-git';
|
|
18
|
+
import type { ArchiveRecord } from './receipt.ts';
|
|
19
|
+
import type { Risk, Row, RowId } from './types.ts';
|
|
20
|
+
/** What the `archive` option takes. */
|
|
21
|
+
export interface ArchiveOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Globs of files left out of a snapshot, besides the secret-shaped ones. A
|
|
24
|
+
* glob without a `/` matches a file or directory name anywhere; one with a `/` matches
|
|
25
|
+
* the path from the worktree root. `*` stays inside a directory, `**` does not.
|
|
26
|
+
*/
|
|
27
|
+
exclude?: readonly string[] | undefined;
|
|
28
|
+
/** Files larger than this many bytes are left out of a snapshot. Default {@link DEFAULT_MAX_FILE_BYTES}. */
|
|
29
|
+
maxFileBytes?: number | undefined;
|
|
30
|
+
}
|
|
31
|
+
/** A snapshot leaves out a file over 10 MiB. */
|
|
32
|
+
export declare const DEFAULT_MAX_FILE_BYTES: number;
|
|
33
|
+
/** A file left out of a snapshot, and why. */
|
|
34
|
+
export interface LeftOut {
|
|
35
|
+
path: string;
|
|
36
|
+
reason: 'secret' | 'excluded' | 'too-large';
|
|
37
|
+
}
|
|
38
|
+
/** The reason `path` stays out of a snapshot, or null. `root` is where `path` is read for its size. */
|
|
39
|
+
export declare function leftOutReason(path: string, root: string, opts: ArchiveOptions): LeftOut['reason'] | null;
|
|
40
|
+
/**
|
|
41
|
+
* The modified, staged and untracked files of the worktree `git` is at that a
|
|
42
|
+
* snapshot would leave out.
|
|
43
|
+
*/
|
|
44
|
+
export declare function snapshotLeftOut(git: Git, opts: ArchiveOptions): LeftOut[];
|
|
45
|
+
/** What the archive holds of a row, and so which of its risks `discard-archived` replaces. */
|
|
46
|
+
export interface Coverage {
|
|
47
|
+
covers: Risk[];
|
|
48
|
+
leftOut: LeftOut[];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Which of `row`'s risks an archive covers. A branch's or remote branch's
|
|
52
|
+
* unlanded commits are. A worktree's unpushed commits and files are, except
|
|
53
|
+
* submodule work, which the archive does not hold, a worktree whose directory
|
|
54
|
+
* is gone, and, for its files, a snapshot that would leave one out.
|
|
55
|
+
*
|
|
56
|
+
* @param git The client for reading a worktree's files; unused for a branch.
|
|
57
|
+
*/
|
|
58
|
+
export declare function coverageOf(row: Row, opts: ArchiveOptions, git: (path: string) => Git): Coverage;
|
|
59
|
+
/** True when a row could put something in an archive. */
|
|
60
|
+
export declare function mayContribute(row: Row): boolean;
|
|
61
|
+
/** One row's work in an archive. */
|
|
62
|
+
export interface ArchiveRowJob {
|
|
63
|
+
id: RowId;
|
|
64
|
+
row: Row;
|
|
65
|
+
/** `discard-changes` was allowed for the row itself, so a snapshot may leave files out. */
|
|
66
|
+
discardAllowed: boolean;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* What a worktree held when it was archived: its HEAD and, with `files`, its
|
|
70
|
+
* snapshot tree. The remove step compares it again, so work added after the
|
|
71
|
+
* archive is not deleted on the strength of an archive that lacks it.
|
|
72
|
+
*/
|
|
73
|
+
export declare function worktreeStamp(git: Git, opts: ArchiveOptions, files: boolean): string;
|
|
74
|
+
/**
|
|
75
|
+
* Build the archive of `jobs` and push it, then confirm the remote has it.
|
|
76
|
+
* Returns null when there was nothing to hold, else the receipt record and each archived worktree's {@link worktreeStamp}.
|
|
77
|
+
*
|
|
78
|
+
* @param git The client at the repository's root.
|
|
79
|
+
* @param defaultRef The remote default branch, `<remote>/<branch>`.
|
|
80
|
+
* @throws when the default branch cannot be read, a snapshot would leave out a
|
|
81
|
+
* file nobody allowed to lose, the push is refused, or the remote does not
|
|
82
|
+
* list the archive afterwards. Nothing has been deleted.
|
|
83
|
+
*/
|
|
84
|
+
export declare function pushArchive(git: Git, remote: string, defaultRef: string, jobs: readonly ArchiveRowJob[], opts: ArchiveOptions, now: Date): {
|
|
85
|
+
record: ArchiveRecord;
|
|
86
|
+
stamps: Map<RowId, string>;
|
|
87
|
+
} | null;
|
package/dist/archive.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Archiving unlanded work to the remote before `run` deletes it.
|
|
3
|
+
*
|
|
4
|
+
* With the `archive` option, a run's first step per repository builds one
|
|
5
|
+
* commit whose tree is the remote default branch's and whose parents are that
|
|
6
|
+
* branch's tip plus the work about to be lost, and pushes it to
|
|
7
|
+
* `refs/heads/archive/<repo>-local-<date>`. A row whose work the archive holds
|
|
8
|
+
* carries `discard-archived` in place of `abandon-unmerged` and
|
|
9
|
+
* `discard-changes`.
|
|
10
|
+
*
|
|
11
|
+
* A worktree's uncommitted files go in a snapshot commit built in a temporary
|
|
12
|
+
* index (`GIT_INDEX_FILE`), so the worktree's own index and files are not
|
|
13
|
+
* touched. Left out of a snapshot: ignored files, secret-shaped files, files
|
|
14
|
+
* matching `exclude`, and files over `maxFileBytes`. Not held at all:
|
|
15
|
+
* submodule commits, files and stashes.
|
|
16
|
+
*/
|
|
17
|
+
import { lstatSync, mkdtempSync, rmSync } from 'node:fs';
|
|
18
|
+
import { tmpdir } from 'node:os';
|
|
19
|
+
import { basename, join } from 'node:path';
|
|
20
|
+
import { globRegExp } from "./util.js";
|
|
21
|
+
/** A snapshot leaves out a file over 10 MiB. */
|
|
22
|
+
export const DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;
|
|
23
|
+
/** File names that look like secrets. */
|
|
24
|
+
const SECRET_NAME = /^(\.env.*|.*\.pem|.*\.key|.*\.p12|.*\.pfx|id_rsa.*|id_ed25519.*|\.npmrc|\.netrc|credentials(\..*)?)$/i;
|
|
25
|
+
/** The reason `path` stays out of a snapshot, or null. `root` is where `path` is read for its size. */
|
|
26
|
+
export function leftOutReason(path, root, opts) {
|
|
27
|
+
const name = basename(path);
|
|
28
|
+
if (SECRET_NAME.test(name))
|
|
29
|
+
return 'secret';
|
|
30
|
+
const segments = path.split('/');
|
|
31
|
+
for (const glob of opts.exclude ?? []) {
|
|
32
|
+
const re = globRegExp(glob);
|
|
33
|
+
// A glob without a `/` matches a file or directory name anywhere on the path.
|
|
34
|
+
if (glob.includes('/') ? re.test(path) : segments.some((seg) => re.test(seg))) {
|
|
35
|
+
return 'excluded';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
if (lstatSync(join(root, path)).size > (opts.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES)) {
|
|
40
|
+
return 'too-large';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// A deleted file has no size; it is archived as a deletion.
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The modified, staged and untracked files of the worktree `git` is at that a
|
|
50
|
+
* snapshot would leave out.
|
|
51
|
+
*/
|
|
52
|
+
export function snapshotLeftOut(git, opts) {
|
|
53
|
+
const out = [];
|
|
54
|
+
for (const entry of git.statusEntries()) {
|
|
55
|
+
const reason = leftOutReason(entry.path, git.cwd, opts);
|
|
56
|
+
if (reason !== null)
|
|
57
|
+
out.push({ path: entry.path, reason });
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Which of `row`'s risks an archive covers. A branch's or remote branch's
|
|
63
|
+
* unlanded commits are. A worktree's unpushed commits and files are, except
|
|
64
|
+
* submodule work, which the archive does not hold, a worktree whose directory
|
|
65
|
+
* is gone, and, for its files, a snapshot that would leave one out.
|
|
66
|
+
*
|
|
67
|
+
* @param git The client for reading a worktree's files; unused for a branch.
|
|
68
|
+
*/
|
|
69
|
+
export function coverageOf(row, opts, git) {
|
|
70
|
+
const covers = [];
|
|
71
|
+
let leftOut = [];
|
|
72
|
+
if (row.kind !== 'worktree') {
|
|
73
|
+
if (row.risks.includes('abandon-unmerged'))
|
|
74
|
+
covers.push('abandon-unmerged');
|
|
75
|
+
return { covers, leftOut };
|
|
76
|
+
}
|
|
77
|
+
const e = row.evidence;
|
|
78
|
+
if (e.onDisk === false)
|
|
79
|
+
return { covers, leftOut };
|
|
80
|
+
const submodules = e.submodules ?? [];
|
|
81
|
+
const submoduleWork = submodules.some((s) => s.unpushedCommits > 0 || s.stashes > 0);
|
|
82
|
+
if (row.risks.includes('abandon-unmerged') && !submoduleWork)
|
|
83
|
+
covers.push('abandon-unmerged');
|
|
84
|
+
if (row.risks.includes('discard-changes')) {
|
|
85
|
+
leftOut = snapshotLeftOut(git(row.name), opts);
|
|
86
|
+
const submoduleDirty = submodules.some((s) => s.dirtyFiles > 0);
|
|
87
|
+
if (leftOut.length === 0 && !submoduleDirty)
|
|
88
|
+
covers.push('discard-changes');
|
|
89
|
+
}
|
|
90
|
+
return { covers, leftOut };
|
|
91
|
+
}
|
|
92
|
+
/** True when a row could put something in an archive. */
|
|
93
|
+
export function mayContribute(row) {
|
|
94
|
+
return row.risks.includes('abandon-unmerged') || row.risks.includes('discard-changes');
|
|
95
|
+
}
|
|
96
|
+
/** The tree of the worktree's files as a snapshot holds them, built in a temporary index. */
|
|
97
|
+
function snapshotTree(git, leftOut) {
|
|
98
|
+
const dir = mkdtempSync(join(tmpdir(), 'repo-cleaner-archive-'));
|
|
99
|
+
try {
|
|
100
|
+
const env = { GIT_INDEX_FILE: join(dir, 'index') };
|
|
101
|
+
git.readTree('HEAD', { env });
|
|
102
|
+
// An excluded pathspec leaves the file as HEAD has it.
|
|
103
|
+
git.add(['.', ...leftOut.map((f) => `:(exclude,literal)${f.path}`)], { all: true, env });
|
|
104
|
+
return git.writeTree({ env });
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
rmSync(dir, { recursive: true, force: true });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* What a worktree held when it was archived: its HEAD and, with `files`, its
|
|
112
|
+
* snapshot tree. The remove step compares it again, so work added after the
|
|
113
|
+
* archive is not deleted on the strength of an archive that lacks it.
|
|
114
|
+
*/
|
|
115
|
+
export function worktreeStamp(git, opts, files) {
|
|
116
|
+
const tree = files ? snapshotTree(git, snapshotLeftOut(git, opts)) : '';
|
|
117
|
+
return `${git.resolveRef('HEAD') ?? ''}:${tree}`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Commit the worktree `git` is at, uncommitted files included, without
|
|
121
|
+
* touching its index or files. `sha` is null when nothing differs from HEAD;
|
|
122
|
+
* `unheld` is true when something is dirty that a snapshot cannot hold, such
|
|
123
|
+
* as a staged change the working file has since been reverted from.
|
|
124
|
+
*/
|
|
125
|
+
function snapshot(git, opts) {
|
|
126
|
+
const head = git.resolveRef('HEAD');
|
|
127
|
+
if (head === null)
|
|
128
|
+
return { sha: null, leftOut: [], unheld: false };
|
|
129
|
+
const leftOut = snapshotLeftOut(git, opts);
|
|
130
|
+
const tree = snapshotTree(git, leftOut);
|
|
131
|
+
if (tree === git.resolveRef('HEAD^{tree}')) {
|
|
132
|
+
return { sha: null, leftOut, unheld: git.statusEntries().length > leftOut.length };
|
|
133
|
+
}
|
|
134
|
+
const sha = git.commitTree(tree, { parents: [head], message: `snapshot of ${git.cwd}\n\nuncommitted files on top of ${head}` }, { env: identityEnv(git) });
|
|
135
|
+
return { sha, leftOut, unheld: false };
|
|
136
|
+
}
|
|
137
|
+
/** `<repo>-local-<YYYY-MM-DD>`, the branch name after `archive/`. */
|
|
138
|
+
function branchBase(root, now) {
|
|
139
|
+
const repo = basename(root).replace(/[^A-Za-z0-9._-]/g, '-') || 'repo';
|
|
140
|
+
return `archive/${repo}-local-${now.toISOString().slice(0, 10)}`;
|
|
141
|
+
}
|
|
142
|
+
/** An identity for `commit-tree` when git has none configured. */
|
|
143
|
+
function identityEnv(git) {
|
|
144
|
+
if (git.configGet('user.name') !== null && git.configGet('user.email') !== null)
|
|
145
|
+
return undefined;
|
|
146
|
+
return {
|
|
147
|
+
GIT_AUTHOR_NAME: 'repo-cleaner',
|
|
148
|
+
GIT_AUTHOR_EMAIL: 'repo-cleaner@localhost',
|
|
149
|
+
GIT_COMMITTER_NAME: 'repo-cleaner',
|
|
150
|
+
GIT_COMMITTER_EMAIL: 'repo-cleaner@localhost',
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Build the archive of `jobs` and push it, then confirm the remote has it.
|
|
155
|
+
* Returns null when there was nothing to hold, else the receipt record and each archived worktree's {@link worktreeStamp}.
|
|
156
|
+
*
|
|
157
|
+
* @param git The client at the repository's root.
|
|
158
|
+
* @param defaultRef The remote default branch, `<remote>/<branch>`.
|
|
159
|
+
* @throws when the default branch cannot be read, a snapshot would leave out a
|
|
160
|
+
* file nobody allowed to lose, the push is refused, or the remote does not
|
|
161
|
+
* list the archive afterwards. Nothing has been deleted.
|
|
162
|
+
*/
|
|
163
|
+
export function pushArchive(git, remote, defaultRef, jobs, opts, now) {
|
|
164
|
+
const defaultTip = git.resolveRef(defaultRef);
|
|
165
|
+
const tree = git.resolveRef(`${defaultRef}^{tree}`);
|
|
166
|
+
if (defaultTip === null || tree === null)
|
|
167
|
+
throw new Error(`cannot read ${defaultRef}`);
|
|
168
|
+
const held = new Map();
|
|
169
|
+
const hold = (sha, source, row, leftOut = []) => {
|
|
170
|
+
if (sha === defaultTip)
|
|
171
|
+
return;
|
|
172
|
+
const was = held.get(sha);
|
|
173
|
+
if (was === undefined)
|
|
174
|
+
held.set(sha, { sha, source, rows: [row], leftOut });
|
|
175
|
+
else {
|
|
176
|
+
was.rows.push(row);
|
|
177
|
+
was.source += `, ${source}`;
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
for (const { row, discardAllowed } of jobs) {
|
|
181
|
+
if (row.kind !== 'worktree') {
|
|
182
|
+
if (row.risks.includes('abandon-unmerged'))
|
|
183
|
+
hold(row.evidence.sha, row.id, row.id);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
if (row.evidence.onDisk === false)
|
|
187
|
+
continue;
|
|
188
|
+
const at = git.at(row.name);
|
|
189
|
+
if (row.risks.includes('discard-changes')) {
|
|
190
|
+
const snap = snapshot(at, opts);
|
|
191
|
+
if ((snap.leftOut.length > 0 || snap.unheld) && !discardAllowed) {
|
|
192
|
+
throw new Error(`refused: ${row.name} has changes the archive cannot hold (${snap.leftOut.map((f) => f.path).join(', ') || 'staged changes the files no longer show'}); allow discard-changes for it`);
|
|
193
|
+
}
|
|
194
|
+
if (snap.sha !== null) {
|
|
195
|
+
hold(snap.sha, row.id, row.id, snap.leftOut);
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
const head = row.risks.includes('abandon-unmerged') ? at.resolveRef('HEAD') : null;
|
|
200
|
+
if (head !== null)
|
|
201
|
+
hold(head, row.id, row.id);
|
|
202
|
+
}
|
|
203
|
+
if (held.size === 0)
|
|
204
|
+
return null;
|
|
205
|
+
const stamps = new Map(jobs.flatMap(({ row }) => row.kind === 'worktree' && row.evidence.onDisk !== false
|
|
206
|
+
? [
|
|
207
|
+
[
|
|
208
|
+
row.id,
|
|
209
|
+
worktreeStamp(git.at(row.name), opts, row.risks.includes('discard-changes')),
|
|
210
|
+
],
|
|
211
|
+
]
|
|
212
|
+
: []));
|
|
213
|
+
const parents = [...held.values()];
|
|
214
|
+
const lines = [
|
|
215
|
+
`repo-cleaner archive of local work, ${now.toISOString()}`,
|
|
216
|
+
'',
|
|
217
|
+
`parent 1: ${defaultTip} ${defaultRef}`,
|
|
218
|
+
...parents.flatMap((p, i) => [
|
|
219
|
+
`parent ${i + 2}: ${p.sha} ${p.source}`,
|
|
220
|
+
...p.leftOut.map((f) => ` left out (${f.reason}): ${f.path}`),
|
|
221
|
+
]),
|
|
222
|
+
'',
|
|
223
|
+
'Not archived: ignored files, submodule commits and files, stashes.',
|
|
224
|
+
];
|
|
225
|
+
const sha = git.commitTree(tree, { parents: [defaultTip, ...parents.map((p) => p.sha)], message: lines.join('\n') }, { env: identityEnv(git) });
|
|
226
|
+
const base = branchBase(git.cwd, now);
|
|
227
|
+
let ref = `refs/heads/${base}`;
|
|
228
|
+
for (let n = 2; git.lsRemote(remote, ref).some((r) => r.ref === ref); n++) {
|
|
229
|
+
ref = `refs/heads/${base}-${n}`;
|
|
230
|
+
}
|
|
231
|
+
const report = git.push(remote, `${sha}:${ref}`);
|
|
232
|
+
const refused = report.refs.find((r) => r.flag === '!');
|
|
233
|
+
if (refused !== undefined) {
|
|
234
|
+
throw new Error(`push of the archive to ${remote} refused: ${refused.summary}`);
|
|
235
|
+
}
|
|
236
|
+
if (git.lsRemote(remote, ref).find((r) => r.ref === ref)?.sha !== sha) {
|
|
237
|
+
throw new Error(`${remote} does not list ${ref} at ${sha} after the push`);
|
|
238
|
+
}
|
|
239
|
+
const record = {
|
|
240
|
+
remote,
|
|
241
|
+
ref,
|
|
242
|
+
sha,
|
|
243
|
+
parents: parents.map((p, i) => ({
|
|
244
|
+
parent: i + 2,
|
|
245
|
+
sha: p.sha,
|
|
246
|
+
source: p.source,
|
|
247
|
+
rows: p.rows,
|
|
248
|
+
leftOut: p.leftOut,
|
|
249
|
+
})),
|
|
250
|
+
};
|
|
251
|
+
return { record, stamps };
|
|
252
|
+
}
|