@osdlc/repo-cleaner 0.0.0-stage → 0.5.2

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/dist/cli.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * `repo-cleaner` — what has been merged, and what can go away.
3
+ *
4
+ * Two commands. A bare invocation sweeps: it inventories, fetching each
5
+ * remote first unless `--no-fetch`, and writes nothing but an optional plan.
6
+ * `repo-cleaner apply` deletes the rows of a plan that were selected and
7
+ * authorized. Scope is opt-in: the sweep covers the repository you are
8
+ * standing in unless `--all` or a path says otherwise.
9
+ *
10
+ * Exit codes:
11
+ * 0 swept; or every selected row was applied or dropped with a reason
12
+ * 1 failed against the state it found
13
+ * 2 cannot run as typed
14
+ * 10 nothing to sweep: no entry named a repository
15
+ * 11 apply stopped at a failed step; the receipt says which
16
+ */
17
+ import { type CliContext } from '@osdlc/cli-tool';
18
+ /** `main(argv, ctx)`: returns an exit code, never exits. */
19
+ export declare function main(argv: readonly string[], ctx: CliContext): number;
package/dist/cli.js ADDED
@@ -0,0 +1,298 @@
1
+ /**
2
+ * `repo-cleaner` — what has been merged, and what can go away.
3
+ *
4
+ * Two commands. A bare invocation sweeps: it inventories, fetching each
5
+ * remote first unless `--no-fetch`, and writes nothing but an optional plan.
6
+ * `repo-cleaner apply` deletes the rows of a plan that were selected and
7
+ * authorized. Scope is opt-in: the sweep covers the repository you are
8
+ * standing in unless `--all` or a path says otherwise.
9
+ *
10
+ * Exit codes:
11
+ * 0 swept; or every selected row was applied or dropped with a reason
12
+ * 1 failed against the state it found
13
+ * 2 cannot run as typed
14
+ * 10 nothing to sweep: no entry named a repository
15
+ * 11 apply stopped at a failed step; the receipt says which
16
+ */
17
+ import { resolve } from 'node:path';
18
+ import { EXIT, TieredDirs, defineCli } from '@osdlc/cli-tool';
19
+ import { Git } from '@osdlc/typed-git';
20
+ import { resolveBranch } from "./branches.js";
21
+ import { ApplyArgumentError, applyPlan, parseGrant, parseRowRef } from "./apply.js";
22
+ import { CONFIG_ENV, TOOL, VENDOR_DIRS, clearConfigCache, configPath, configuredRepos, } from "./config.js";
23
+ import { PLAN_VERSION, planRepo, readPlan, stampedPath, writePlan } from "./plan.js";
24
+ import { proposedCommands, renderJson, renderReceipt, renderText } from "./render.js";
25
+ import { sweepRepos } from "./sweep.js";
26
+ import { ALL_SCOPES } from "./types.js";
27
+ const EXIT_NOTHING_TO_SWEEP = 10;
28
+ const EXIT_STEP_FAILED = 11;
29
+ /** `<durable-home>/repo-cleaner/<kind>`, where plans and receipts go by default. */
30
+ function stateDir(ctx, kind) {
31
+ return resolve(TieredDirs.fromEnv(VENDOR_DIRS.vendor, VENDOR_DIRS.envVars, { env: ctx.env })
32
+ .standalone(TOOL)
33
+ .durable().path, kind);
34
+ }
35
+ /** Built per run: the help names the config path as the environment has it then. */
36
+ const sweepCli = () => defineCli({
37
+ name: 'repo-cleaner',
38
+ summary: 'Inventory branches, worktrees and remote branches, and say which have been merged into ' +
39
+ 'the default branch. Fetches each remote first; writes nothing but an optional plan.',
40
+ positionals: [
41
+ {
42
+ name: 'path',
43
+ variadic: true,
44
+ help: 'a checkout, or a directory containing checkouts (default: the one you are in)',
45
+ },
46
+ ],
47
+ flags: {
48
+ all: { kind: 'boolean', help: 'sweep the repositories in the config file' },
49
+ config: { kind: 'string', valueName: 'path', help: 'config file to read' },
50
+ scope: {
51
+ kind: 'list',
52
+ valueName: 'list',
53
+ help: `comma-separated: ${ALL_SCOPES.join(', ')}`,
54
+ },
55
+ remote: {
56
+ kind: 'string',
57
+ valueName: 'name',
58
+ help: 'remote to measure against (default: origin)',
59
+ },
60
+ gh: { kind: 'boolean', negatable: true, help: 'classify on git evidence alone' },
61
+ fetch: {
62
+ kind: 'boolean',
63
+ negatable: true,
64
+ help: 'classify on the remote-tracking refs already on disk',
65
+ },
66
+ keep: { kind: 'boolean', help: 'include safe-to-keep rows in the report' },
67
+ commands: { kind: 'boolean', help: 'print the proposed commands only' },
68
+ branch: {
69
+ kind: 'string',
70
+ valueName: 'name|HEAD',
71
+ help: 'sweep only this branch of this repository: its worktree, local and remote branch',
72
+ },
73
+ writePlan: { kind: 'boolean', help: 'write the deletable rows as a plan for `apply`' },
74
+ planOut: {
75
+ kind: 'string',
76
+ valueName: 'path',
77
+ help: 'write the plan here; implies --write-plan',
78
+ },
79
+ output: {
80
+ kind: 'enum',
81
+ choices: ['text', 'json'],
82
+ valueName: 'form',
83
+ default: 'text',
84
+ help: 'report format',
85
+ },
86
+ },
87
+ epilogue: `commands:
88
+ repo-cleaner apply --help delete the approved rows of a plan
89
+
90
+ A checkout directory named "apply" is swept as ./apply.
91
+
92
+ config: ${configPath()}
93
+ plans: <durable home>/repo-cleaner/plans/ unless --plan-out`,
94
+ });
95
+ const applyCli = () => defineCli({
96
+ name: 'repo-cleaner apply',
97
+ summary: 'Apply approved rows of a plan: re-check them, delete compare-and-swap, verify each step, ' +
98
+ 'and write a receipt.',
99
+ flags: {
100
+ plan: {
101
+ kind: 'string',
102
+ valueName: 'path',
103
+ required: true,
104
+ help: 'plan file from `repo-cleaner --write-plan`',
105
+ },
106
+ row: {
107
+ kind: 'list',
108
+ valueName: 'category:id',
109
+ default: [],
110
+ commaSeparated: false,
111
+ help: 'row to apply, e.g. local_branch:feat/x; repeatable',
112
+ },
113
+ authorize: {
114
+ kind: 'list',
115
+ valueName: 'name[=category:id]',
116
+ default: [],
117
+ commaSeparated: false,
118
+ help: 'authorization for every row, or for one row; repeatable',
119
+ },
120
+ repoRoot: {
121
+ kind: 'string',
122
+ valueName: 'path',
123
+ help: 'apply only the plan repository rooted here',
124
+ },
125
+ receiptDir: { kind: 'string', valueName: 'dir', help: 'write the receipt here' },
126
+ dryRun: { kind: 'boolean', help: 're-check and print the steps; delete nothing' },
127
+ output: {
128
+ kind: 'enum',
129
+ choices: ['text', 'json'],
130
+ valueName: 'form',
131
+ default: 'text',
132
+ help: 'report format',
133
+ },
134
+ },
135
+ epilogue: 'receipts: <durable home>/repo-cleaner/receipts/ unless --receipt-dir',
136
+ });
137
+ function usageError(ctx, name, message) {
138
+ ctx.io.stderr(`${name}: ${message}\n`);
139
+ return EXIT.usage;
140
+ }
141
+ function failure(ctx, err) {
142
+ ctx.io.stderr(`repo-cleaner: ${err instanceof Error ? err.message : String(err)}\n`);
143
+ return EXIT.error;
144
+ }
145
+ /** Runs `fn` with the shared loader pointed at `path`, then restores it. */
146
+ function withConfigFile(path, fn) {
147
+ if (path === undefined)
148
+ return fn();
149
+ const prior = process.env[CONFIG_ENV];
150
+ process.env[CONFIG_ENV] = path;
151
+ clearConfigCache();
152
+ try {
153
+ return fn();
154
+ }
155
+ finally {
156
+ if (prior === undefined)
157
+ delete process.env[CONFIG_ENV];
158
+ else
159
+ process.env[CONFIG_ENV] = prior;
160
+ clearConfigCache();
161
+ }
162
+ }
163
+ function runSweep(argv, ctx) {
164
+ const parsed = sweepCli().parse(argv, ctx.io);
165
+ if (parsed.status === 'help')
166
+ return EXIT.ok;
167
+ if (parsed.status === 'error')
168
+ return usageError(ctx, 'repo-cleaner', parsed.message);
169
+ const v = parsed.values;
170
+ const paths = parsed.positionals;
171
+ const scope = v.scope?.filter((s) => s !== '');
172
+ const unknown = (scope ?? []).filter((s) => !ALL_SCOPES.includes(s));
173
+ if (unknown.length > 0) {
174
+ return usageError(ctx, 'repo-cleaner', `unknown scope(s): ${unknown.join(', ')}`);
175
+ }
176
+ if (v.branch !== undefined && (v.all || paths.length > 0)) {
177
+ return usageError(ctx, 'repo-cleaner', '--branch sweeps this repository only; drop --all and paths');
178
+ }
179
+ if (v.config !== undefined && !v.all) {
180
+ return usageError(ctx, 'repo-cleaner', '--config is read only with --all');
181
+ }
182
+ let branch;
183
+ try {
184
+ branch = v.branch === undefined ? undefined : resolveBranch(v.branch, new Git(ctx.cwd));
185
+ }
186
+ catch (err) {
187
+ return failure(ctx, err);
188
+ }
189
+ const entries = [...paths];
190
+ if (v.all) {
191
+ try {
192
+ entries.push(...withConfigFile(v.config, () => configuredRepos(undefined, ctx.cwd)));
193
+ }
194
+ catch (err) {
195
+ return failure(ctx, err);
196
+ }
197
+ }
198
+ if (entries.length === 0)
199
+ entries.push(ctx.cwd);
200
+ const options = {
201
+ baseDir: ctx.cwd,
202
+ cwd: ctx.cwd,
203
+ noGh: !v.gh,
204
+ fetch: v.fetch,
205
+ branch,
206
+ // Mid-walk, while the wait is happening — the summary comes too late to
207
+ // explain why the tool appeared to hang.
208
+ onWarn: (message) => ctx.io.stderr(`repo-cleaner: ${message}\n`),
209
+ ...(scope === undefined ? {} : { scope }),
210
+ ...(v.remote === undefined ? {} : { remote: v.remote }),
211
+ };
212
+ const result = sweepRepos(entries, options);
213
+ if (branch !== undefined && result.repos.length > 1) {
214
+ return failure(ctx, new Error(`--branch sweeps one repository; ${result.repos.length} found under ${ctx.cwd}`));
215
+ }
216
+ const refused = branch === undefined ? null : (result.repos[0]?.error ?? null);
217
+ if (refused !== null)
218
+ return failure(ctx, new Error(refused));
219
+ if (result.repos.length === 0) {
220
+ ctx.io.stdout(v.output === 'json' ? renderJson(result) : renderText(result));
221
+ return EXIT_NOTHING_TO_SWEEP;
222
+ }
223
+ let planPath = null;
224
+ if (v.writePlan || v.planOut !== undefined) {
225
+ const now = new Date();
226
+ planPath =
227
+ v.planOut !== undefined
228
+ ? resolve(ctx.cwd, v.planOut)
229
+ : stampedPath(stateDir(ctx, 'plans'), now);
230
+ const planOpts = { remote: v.remote ?? null, noGh: !v.gh, branch: branch ?? null };
231
+ writePlan(planPath, {
232
+ version: PLAN_VERSION,
233
+ created_at: now.toISOString(),
234
+ repos: result.repos.flatMap((sweep) => sweep.repo === null ? [] : [planRepo(sweep.repo.root, planOpts, sweep.items)]),
235
+ });
236
+ }
237
+ if (v.commands) {
238
+ const commands = proposedCommands(result);
239
+ if (commands.length > 0)
240
+ ctx.io.stdout(commands.join('\n') + '\n');
241
+ }
242
+ else if (v.output === 'json') {
243
+ ctx.io.stdout(renderJson(result, planPath === null ? {} : { plan_path: planPath }));
244
+ }
245
+ else {
246
+ ctx.io.stdout(renderText(result, { keep: v.keep }));
247
+ }
248
+ if (planPath !== null && v.output !== 'json')
249
+ ctx.io.stderr(`plan: ${planPath}\n`);
250
+ return EXIT.ok;
251
+ }
252
+ function runApply(argv, ctx) {
253
+ const name = 'repo-cleaner apply';
254
+ const parsed = applyCli().parse(argv, ctx.io);
255
+ if (parsed.status === 'help')
256
+ return EXIT.ok;
257
+ if (parsed.status === 'error')
258
+ return usageError(ctx, name, parsed.message);
259
+ const v = parsed.values;
260
+ let rows;
261
+ let grants;
262
+ try {
263
+ rows = v.row.map(parseRowRef);
264
+ grants = v.authorize.map(parseGrant);
265
+ }
266
+ catch (err) {
267
+ if (err instanceof ApplyArgumentError)
268
+ return usageError(ctx, name, err.message);
269
+ throw err;
270
+ }
271
+ const planPath = resolve(ctx.cwd, v.plan);
272
+ const repoRoot = v.repoRoot === undefined ? undefined : resolve(ctx.cwd, v.repoRoot);
273
+ const receiptDir = v.receiptDir === undefined ? stateDir(ctx, 'receipts') : resolve(ctx.cwd, v.receiptDir);
274
+ const receiptPath = stampedPath(receiptDir, new Date());
275
+ let receipt;
276
+ try {
277
+ receipt = applyPlan(readPlan(planPath), rows, grants, {
278
+ callerCwd: ctx.cwd,
279
+ dryRun: v.dryRun,
280
+ receiptPath,
281
+ planPath,
282
+ repoRoot,
283
+ });
284
+ }
285
+ catch (err) {
286
+ return failure(ctx, err);
287
+ }
288
+ const shownPath = v.dryRun ? null : receiptPath;
289
+ ctx.io.stdout(v.output === 'json'
290
+ ? `${JSON.stringify({ receiptPath: shownPath, receipt }, null, 2)}\n`
291
+ : renderReceipt(receipt, shownPath));
292
+ return receipt.status === 'failed' ? EXIT_STEP_FAILED : EXIT.ok;
293
+ }
294
+ /** `main(argv, ctx)`: returns an exit code, never exits. */
295
+ export function main(argv, ctx) {
296
+ const [sub, ...rest] = argv;
297
+ return sub === 'apply' ? runApply(rest, ctx) : runSweep(argv, ctx);
298
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The standalone tool's own configuration file.
3
+ *
4
+ * Only the CLI reads it. The library takes repositories as an argument, so a
5
+ * host that already knows where its repositories are passes them in and never touches this file.
6
+ *
7
+ * Shape, location and loading are `@osdlc/config-layers`'s machine file:
8
+ * `<config-home>/repo-cleaner/config.yaml` over `@osdlc/tiered-dirs`'
9
+ * standalone tier, Zod as the single source of truth, never throws, degrades
10
+ * to the defaults, memoised. Standalone, not suite or vendor, because a
11
+ * general tool must not write a company namespace onto someone else's
12
+ * machine.
13
+ */
14
+ import { z } from 'zod';
15
+ /** The tool's name, and so its config directory segment. */
16
+ export declare const TOOL = "repo-cleaner";
17
+ /** Env var that relocates the config file, for tests and one-off runs. */
18
+ export declare const CONFIG_ENV = "REPO_CLEANER_MACHINE_CONFIG";
19
+ export declare const RepoCleanerConfigSchema: z.ZodObject<{
20
+ paths: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
21
+ repos: z.ZodDefault<z.ZodArray<z.ZodString>>;
22
+ }, z.core.$strict>;
23
+ export type RepoCleanerConfig = z.infer<typeof RepoCleanerConfigSchema>;
24
+ /**
25
+ * Whose directories the config file, plans and receipts live under: vendor
26
+ * `repo-cleaner`, moved by the `REPO_CLEANER_*` override variables.
27
+ */
28
+ export declare const VENDOR_DIRS: {
29
+ vendor: string;
30
+ envVars: import("@osdlc/tiered-dirs").EnvVars;
31
+ };
32
+ export declare const DEFAULT_CONFIG: RepoCleanerConfig;
33
+ /** `<config-home>/repo-cleaner/config.yaml`, unless {@link CONFIG_ENV} says otherwise. */
34
+ export declare const configPath: () => string;
35
+ /**
36
+ * The config, defaults filled.
37
+ *
38
+ * Never throws. A missing file, unreadable file, malformed YAML or wrong
39
+ * shape all degrade to the defaults: a person running the tool in a
40
+ * repository should not be stopped by a config file they never wrote.
41
+ */
42
+ export declare const loadConfig: () => RepoCleanerConfig;
43
+ /** Drop the memoised value. Call from tests between runs. */
44
+ export declare const clearConfigCache: () => void;
45
+ /**
46
+ * The configured entries with their `{name}` path names substituted against
47
+ * `paths:`, relative entries resolved against `baseDir`.
48
+ *
49
+ * A name nothing defines is an error rather than an empty string — a
50
+ * `repos:` entry that quietly becomes `/dev` would sweep whatever happens to
51
+ * be there.
52
+ */
53
+ export declare function configuredRepos(config?: RepoCleanerConfig, baseDir?: string): string[];
package/dist/config.js ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The standalone tool's own configuration file.
3
+ *
4
+ * Only the CLI reads it. The library takes repositories as an argument, so a
5
+ * host that already knows where its repositories are passes them in and never touches this file.
6
+ *
7
+ * Shape, location and loading are `@osdlc/config-layers`'s machine file:
8
+ * `<config-home>/repo-cleaner/config.yaml` over `@osdlc/tiered-dirs`'
9
+ * standalone tier, Zod as the single source of truth, never throws, degrades
10
+ * to the defaults, memoised. Standalone, not suite or vendor, because a
11
+ * general tool must not write a company namespace onto someone else's
12
+ * machine.
13
+ */
14
+ import { envVars } from '@osdlc/cli-tool';
15
+ import { machineConfigFile, pathNames, pathsSchema, substitutePathNames, } from '@osdlc/config-layers';
16
+ import { z } from 'zod';
17
+ /** The tool's name, and so its config directory segment. */
18
+ export const TOOL = 'repo-cleaner';
19
+ /** Env var that relocates the config file, for tests and one-off runs. */
20
+ export const CONFIG_ENV = 'REPO_CLEANER_MACHINE_CONFIG';
21
+ export const RepoCleanerConfigSchema = z
22
+ .object({
23
+ paths: pathsSchema()
24
+ .default({})
25
+ .describe('Named directories; a `repos:` entry refers to one as `{name}`.'),
26
+ repos: z
27
+ .array(z.string().trim().min(1))
28
+ .default([])
29
+ .describe('Checkouts, or directories containing checkouts at any depth.'),
30
+ })
31
+ .strict();
32
+ /**
33
+ * Whose directories the config file, plans and receipts live under: vendor
34
+ * `repo-cleaner`, moved by the `REPO_CLEANER_*` override variables.
35
+ */
36
+ export const VENDOR_DIRS = { vendor: TOOL, envVars: envVars('REPO_CLEANER') };
37
+ const file = machineConfigFile({
38
+ tool: TOOL,
39
+ schema: RepoCleanerConfigSchema,
40
+ vendorDirs: VENDOR_DIRS,
41
+ env: CONFIG_ENV,
42
+ });
43
+ export const DEFAULT_CONFIG = RepoCleanerConfigSchema.parse({});
44
+ /** `<config-home>/repo-cleaner/config.yaml`, unless {@link CONFIG_ENV} says otherwise. */
45
+ export const configPath = () => file.path();
46
+ /**
47
+ * The config, defaults filled.
48
+ *
49
+ * Never throws. A missing file, unreadable file, malformed YAML or wrong
50
+ * shape all degrade to the defaults: a person running the tool in a
51
+ * repository should not be stopped by a config file they never wrote.
52
+ */
53
+ export const loadConfig = () => file.load();
54
+ /** Drop the memoised value. Call from tests between runs. */
55
+ export const clearConfigCache = () => file.clearCache();
56
+ /**
57
+ * The configured entries with their `{name}` path names substituted against
58
+ * `paths:`, relative entries resolved against `baseDir`.
59
+ *
60
+ * A name nothing defines is an error rather than an empty string — a
61
+ * `repos:` entry that quietly becomes `/dev` would sweep whatever happens to
62
+ * be there.
63
+ */
64
+ export function configuredRepos(config = loadConfig(), baseDir = process.cwd()) {
65
+ const names = pathNames(baseDir, config.paths, {});
66
+ return config.repos.map((entry) => substitutePathNames(entry, names, 'repos:'));
67
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What the sweep must know about a repository before it can classify anything:
3
+ * where its main checkout is, what its default branch is called, which remote
4
+ * to measure against, and whether `gh` can be asked about pull requests.
5
+ */
6
+ import type { Git } from '@osdlc/typed-git';
7
+ import { type Gh } from '@osdlc/typed-gh';
8
+ import type { RepoInfo } from './types.ts';
9
+ /**
10
+ * Thrown when a path names no repository, or names one whose default branch
11
+ * cannot be determined. A single-repository caller lets it propagate; a
12
+ * fan-out catches it and records an error row, because one unreadable
13
+ * repository must not end the sweep.
14
+ */
15
+ export declare class DiscoveryFailed extends Error {
16
+ constructor(message: string);
17
+ }
18
+ /**
19
+ * Read `hint`'s repository.
20
+ *
21
+ * The root is normalised through `--git-common-dir`, so pointing the sweep at
22
+ * a linked worktree inventories the repository that worktree belongs to. The
23
+ * default branch comes from the remote's own HEAD, falling back to probing
24
+ * `main` then `master` — a remote whose HEAD was never set is an ordinary
25
+ * state, not a failure.
26
+ */
27
+ export declare function discoverRepo(hint: string, opts: {
28
+ remote?: string | null;
29
+ allowGh?: boolean;
30
+ git: Git;
31
+ gh: Gh;
32
+ }): RepoInfo;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What the sweep must know about a repository before it can classify anything:
3
+ * where its main checkout is, what its default branch is called, which remote
4
+ * to measure against, and whether `gh` can be asked about pull requests.
5
+ */
6
+ import { ownerRepoSlug } from '@osdlc/typed-gh';
7
+ /**
8
+ * Thrown when a path names no repository, or names one whose default branch
9
+ * cannot be determined. A single-repository caller lets it propagate; a
10
+ * fan-out catches it and records an error row, because one unreadable
11
+ * repository must not end the sweep.
12
+ */
13
+ export class DiscoveryFailed extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = 'DiscoveryFailed';
17
+ }
18
+ }
19
+ /**
20
+ * Read `hint`'s repository.
21
+ *
22
+ * The root is normalised through `--git-common-dir`, so pointing the sweep at
23
+ * a linked worktree inventories the repository that worktree belongs to. The
24
+ * default branch comes from the remote's own HEAD, falling back to probing
25
+ * `main` then `master` — a remote whose HEAD was never set is an ordinary
26
+ * state, not a failure.
27
+ */
28
+ export function discoverRepo(hint, opts) {
29
+ const { git, gh } = opts;
30
+ const remoteHint = opts.remote ?? null;
31
+ const allowGh = opts.allowGh ?? true;
32
+ // `topLevel()` answers null for exit 128 only — "this is not a repository",
33
+ // which is the answer to the question. Any other git failure throws.
34
+ const top = git.at(hint).topLevel();
35
+ if (top === null)
36
+ throw new DiscoveryFailed(`not a git repository: ${hint}`);
37
+ // Pointing the sweep at a linked worktree inventories the repository that
38
+ // worktree belongs to, not the worktree alone.
39
+ const root = git.at(top).mainCheckout() ?? top;
40
+ // We are provably inside a repository by now, so a failure here is a
41
+ // failure, not "no remotes".
42
+ const remotes = git.at(root).remote();
43
+ let remote = null;
44
+ if (remoteHint !== null && remotes.includes(remoteHint))
45
+ remote = remoteHint;
46
+ if (remote === null) {
47
+ if (remotes.includes('origin'))
48
+ remote = 'origin';
49
+ else if (remotes.length > 0)
50
+ remote = remotes[0];
51
+ }
52
+ let mainBranch = '';
53
+ if (remote !== null) {
54
+ // Null when the remote's HEAD was never set — an ordinary state, not a
55
+ // failure; fall through to the main/master probe.
56
+ const head = git.at(root).symbolicRef(`refs/remotes/${remote}/HEAD`);
57
+ const prefix = `refs/remotes/${remote}/`;
58
+ if (head?.startsWith(prefix))
59
+ mainBranch = head.slice(prefix.length);
60
+ }
61
+ if (!mainBranch) {
62
+ for (const candidate of ['main', 'master']) {
63
+ if (git.at(root).resolveRef(candidate) !== null) {
64
+ mainBranch = candidate;
65
+ break;
66
+ }
67
+ }
68
+ }
69
+ if (!mainBranch)
70
+ throw new DiscoveryFailed(`could not determine the default branch of ${root}`);
71
+ // `owner/name` for the report's header, so a fan-out over long paths stays
72
+ // readable. A remote that is not a recognisable host coordinate answers null.
73
+ const slug = remote === null ? null : ownerRepoSlugOf(git.at(root).try.remoteGetUrl(remote), gh, root);
74
+ const currentBranch = git.at(root).headRef() ?? '';
75
+ // The two halves separately, not `ready()`: the report says "gh not
76
+ // available" and "gh not authenticated" differently, because they send a
77
+ // person somewhere different.
78
+ const hasGh = allowGh && gh.at(root).installed();
79
+ const ghAuthenticated = hasGh && gh.at(root).authenticated();
80
+ return { root, slug, mainBranch, remote, currentBranch, hasGh, ghAuthenticated, fetched: false };
81
+ }
82
+ /** `owner/name` from a remote URL outcome, or null when it is not one. */
83
+ function ownerRepoSlugOf(url, gh, root) {
84
+ if (!url.ok || url.value === undefined || url.value === null)
85
+ return null;
86
+ const coord = gh.at(root).ownerRepo(url.value);
87
+ return coord === null ? null : ownerRepoSlug(coord);
88
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * What a host may supply that this package cannot know for itself.
3
+ *
4
+ * A standalone run passes none; a host passes `annotate` so its verdicts
5
+ * survive `applyPlan`'s re-sweep.
6
+ */
7
+ import type { RepoInfo, SweepItem } from './types.ts';
8
+ /**
9
+ * Re-rank a repository's swept rows with what the host knows. Runs after the
10
+ * sweep, on its output; it never reaches into classification.
11
+ */
12
+ export type Annotate = (repo: RepoInfo, items: SweepItem[]) => SweepItem[];
13
+ export interface HostHooks {
14
+ annotate?: Annotate | undefined;
15
+ }
package/dist/hooks.js ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * What a host may supply that this package cannot know for itself.
3
+ *
4
+ * A standalone run passes none; a host passes `annotate` so its verdicts
5
+ * survive `applyPlan`'s re-sweep.
6
+ */
7
+ export {};
@@ -0,0 +1,30 @@
1
+ /**
2
+ * `@osdlc/repo-cleaner` — what has been merged into the default branch, and
3
+ * what can go away.
4
+ *
5
+ * Point it at a repository and it inventories the local branches, worktrees
6
+ * and remote branches, classifying each as safe-to-delete, safe-to-keep or
7
+ * needs-investigation, with the evidence behind the verdict and the literal
8
+ * command that would act on it. The sweep never deletes anything; `applyPlan`
9
+ * deletes the rows of a plan a person approved.
10
+ *
11
+ * Two signals settle most items — a merged pull request, and ancestry of the
12
+ * default branch — and either alone is enough. A host that knows more than
13
+ * git does (an issue tracker, say) re-ranks the returned rows
14
+ * rather than reaching into classification, which is why every row carries
15
+ * its facts and why `investigationParts` is a list rather than a sentence.
16
+ */
17
+ export { classifyLocalBranch, classifyRemoteBranch, gatherLocalBranches, gatherRemoteBranches, localDeleteCommand, remoteDeleteCommand, resolveBranch, } from './branches.ts';
18
+ export { classifyWorktree, gatherWorktrees, hasBlockers, worktreePruneCommand, worktreeRemoveCommand, worktreeUnlockCommand, type WorktreeBlocker, } from './worktrees.ts';
19
+ export { DiscoveryFailed, discoverRepo } from './discover.ts';
20
+ export { ApplyArgumentError, applyPlan, parseGrant, parseRowRef, type ApplyOptions, type Grant, } from './apply.ts';
21
+ export type { Annotate, HostHooks } from './hooks.ts';
22
+ export { PLAN_VERSION, PlanReadError, planRepo, readPlan, stampedPath, writePlan, type Plan, type PlanRepo, type PlannableRow, } from './plan.ts';
23
+ export { ReceiptSchema, type Dropped, type Receipt, type RowRef, type Step } from './receipt.ts';
24
+ export { defaultProcessProbe, isIdleShell, parseLockOwner, parseLsofCwd, type DefaultProbeOptions, type LockOwner, type ProcessHolder, type ProcessProbe, } from './processes.ts';
25
+ export { fetchPrs } from './prs.ts';
26
+ export { expandTilde, isCheckoutRoot, resolveEntries, type Resolution, type ResolveOptions, } from './resolve.ts';
27
+ export { sweepRepo, sweepRepos, type SweepOptions, type SweepReposOptions } from './sweep.ts';
28
+ export { proposedCommands, renderJson, renderReceipt, renderRepo, renderScan, renderSummary, renderText, requiresNote, } from './render.ts';
29
+ export { CONFIG_ENV, DEFAULT_CONFIG, RepoCleanerConfigSchema, TOOL, clearConfigCache, configPath, configuredRepos, loadConfig, type RepoCleanerConfig, } from './config.ts';
30
+ export { ALL_SCOPES, AUTHORIZATIONS, authorizationsFor, emptyBucket, emptyScan, findDuplicateCheckouts, isUnfetched, makeItem, summarize, type Authorization, type Category, type Classification, type DuplicateCheckout, type PRInfo, type RepoInfo, type RepoSweep, type ScanStats, type Scope, type SummaryBucket, type SweepItem, type SweepResult, type UnresolvedEntry, } from './types.ts';
package/dist/index.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `@osdlc/repo-cleaner` — what has been merged into the default branch, and
3
+ * what can go away.
4
+ *
5
+ * Point it at a repository and it inventories the local branches, worktrees
6
+ * and remote branches, classifying each as safe-to-delete, safe-to-keep or
7
+ * needs-investigation, with the evidence behind the verdict and the literal
8
+ * command that would act on it. The sweep never deletes anything; `applyPlan`
9
+ * deletes the rows of a plan a person approved.
10
+ *
11
+ * Two signals settle most items — a merged pull request, and ancestry of the
12
+ * default branch — and either alone is enough. A host that knows more than
13
+ * git does (an issue tracker, say) re-ranks the returned rows
14
+ * rather than reaching into classification, which is why every row carries
15
+ * its facts and why `investigationParts` is a list rather than a sentence.
16
+ */
17
+ export { classifyLocalBranch, classifyRemoteBranch, gatherLocalBranches, gatherRemoteBranches, localDeleteCommand, remoteDeleteCommand, resolveBranch, } from "./branches.js";
18
+ export { classifyWorktree, gatherWorktrees, hasBlockers, worktreePruneCommand, worktreeRemoveCommand, worktreeUnlockCommand, } from "./worktrees.js";
19
+ export { DiscoveryFailed, discoverRepo } from "./discover.js";
20
+ export { ApplyArgumentError, applyPlan, parseGrant, parseRowRef, } from "./apply.js";
21
+ export { PLAN_VERSION, PlanReadError, planRepo, readPlan, stampedPath, writePlan, } from "./plan.js";
22
+ export { ReceiptSchema } from "./receipt.js";
23
+ export { defaultProcessProbe, isIdleShell, parseLockOwner, parseLsofCwd, } from "./processes.js";
24
+ export { fetchPrs } from "./prs.js";
25
+ export { expandTilde, isCheckoutRoot, resolveEntries, } from "./resolve.js";
26
+ export { sweepRepo, sweepRepos } from "./sweep.js";
27
+ export { proposedCommands, renderJson, renderReceipt, renderRepo, renderScan, renderSummary, renderText, requiresNote, } from "./render.js";
28
+ export { CONFIG_ENV, DEFAULT_CONFIG, RepoCleanerConfigSchema, TOOL, clearConfigCache, configPath, configuredRepos, loadConfig, } from "./config.js";
29
+ export { ALL_SCOPES, AUTHORIZATIONS, authorizationsFor, emptyBucket, emptyScan, findDuplicateCheckouts, isUnfetched, makeItem, summarize, } from "./types.js";