@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/sweep.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * The sweep itself: one repository, or many.
3
+ *
4
+ * Every item carries the command that would act on it, and running that
5
+ * command is the caller's decision. The only write is the optional fetch,
6
+ * which updates remote-tracking refs and nothing else.
7
+ */
8
+ import { Git } from '@osdlc/typed-git';
9
+ import { Gh } from '@osdlc/typed-gh';
10
+ import { gatherLocalBranches, gatherRemoteBranches } from "./branches.js";
11
+ import { DiscoveryFailed, discoverRepo } from "./discover.js";
12
+ import { defaultProcessProbe } from "./processes.js";
13
+ import { fetchPrs } from "./prs.js";
14
+ import { resolveEntries } from "./resolve.js";
15
+ import { ALL_SCOPES, findDuplicateCheckouts, } from "./types.js";
16
+ import { gatherWorktrees } from "./worktrees.js";
17
+ function scopeSet(scope) {
18
+ return new Set(scope === undefined ? ALL_SCOPES : [...scope]);
19
+ }
20
+ function clients(path, opts) {
21
+ return {
22
+ git: new Git(path, { runner: opts.git }),
23
+ gh: new Gh(path, { runner: opts.gh }),
24
+ };
25
+ }
26
+ /**
27
+ * Inventory one repository.
28
+ *
29
+ * Never throws for a repository that cannot be read: the failure is returned
30
+ * as `error`, because a fan-out must not end on its first bad entry. A
31
+ * single-repository caller checks that field.
32
+ */
33
+ export function sweepRepo(path, opts = {}) {
34
+ const scope = scopeSet(opts.scope);
35
+ const { git, gh } = clients(path, opts);
36
+ const only = opts.branch;
37
+ let repo;
38
+ try {
39
+ repo = discoverRepo(path, {
40
+ remote: opts.remote ?? null,
41
+ allowGh: opts.noGh !== true,
42
+ git,
43
+ gh,
44
+ });
45
+ }
46
+ catch (err) {
47
+ if (err instanceof DiscoveryFailed)
48
+ return { repo: null, path, items: [], error: err.message };
49
+ return { repo: null, path, items: [], error: err instanceof Error ? err.message : String(err) };
50
+ }
51
+ if (only === repo.mainBranch) {
52
+ return { repo, path, items: [], error: `refusing to clean up the default branch \`${only}\`` };
53
+ }
54
+ const cwd = only === undefined ? (opts.cwd ?? process.cwd()) : repo.root;
55
+ if (opts.fetch === true && repo.remote !== null) {
56
+ const fetched = git
57
+ .at(repo.root)
58
+ .try.fetch(repo.remote, undefined, { prune: true, quiet: true, noWriteFetchHead: true });
59
+ if (!fetched.ok) {
60
+ return {
61
+ repo,
62
+ path,
63
+ items: [],
64
+ error: `fetch failed: ${fetched.error.detail || fetched.error.message}`,
65
+ };
66
+ }
67
+ repo = { ...repo, fetched: true };
68
+ }
69
+ try {
70
+ const prs = fetchPrs(repo, gh, only);
71
+ const items = [];
72
+ // Worktrees are gathered whenever local branches are, even if they are not
73
+ // reported: a branch checked out in one must not be judged on its own.
74
+ let worktreeItems = [];
75
+ let worktreeBranches = new Set();
76
+ if (scope.has('worktrees') || scope.has('local-branches')) {
77
+ ;
78
+ [worktreeItems, worktreeBranches] = gatherWorktrees(repo, prs, cwd, git, only, opts.probe ?? defaultProcessProbe());
79
+ }
80
+ if (scope.has('worktrees'))
81
+ items.push(...worktreeItems);
82
+ let localBranchNames = new Set();
83
+ if (scope.has('local-branches') || scope.has('remote-branches')) {
84
+ const pinned = only === undefined
85
+ ? worktreeBranches
86
+ : new Set(worktreeItems
87
+ .filter((item) => !item.deletable)
88
+ .map((item) => String(item.facts['branch'])));
89
+ const localItems = gatherLocalBranches(repo, prs, pinned, git, only);
90
+ localBranchNames = new Set(localItems.map((item) => item.id));
91
+ if (scope.has('local-branches'))
92
+ items.push(...localItems);
93
+ }
94
+ if (scope.has('remote-branches')) {
95
+ items.push(...gatherRemoteBranches(repo, prs, localBranchNames, git, only));
96
+ }
97
+ return { repo, path, items, error: null };
98
+ }
99
+ catch (err) {
100
+ return {
101
+ repo,
102
+ path,
103
+ items: [],
104
+ error: err instanceof Error ? err.message : String(err),
105
+ };
106
+ }
107
+ }
108
+ /**
109
+ * Resolve `entries` and inventory every repository they name.
110
+ *
111
+ * Entries may be checkouts or directories containing checkouts; see
112
+ * {@link resolveEntries}. A repository that fails discovery becomes an error
113
+ * row and the sweep continues.
114
+ */
115
+ export function sweepRepos(entries, opts = {}) {
116
+ const probe = new Git(opts.baseDir ?? process.cwd(), { runner: opts.git });
117
+ const resolution = resolveEntries(entries, {
118
+ git: probe,
119
+ ...(opts.baseDir === undefined ? {} : { baseDir: opts.baseDir }),
120
+ ...(opts.onWarn === undefined ? {} : { onWarn: opts.onWarn }),
121
+ });
122
+ const repos = resolution.repos.map((root) => sweepRepo(root, opts));
123
+ return {
124
+ repos,
125
+ unresolved: resolution.unresolved,
126
+ scan: resolution.scan,
127
+ duplicates: findDuplicateCheckouts(repos.map((sweep) => sweep.repo)),
128
+ };
129
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The inventory a sweep produces, and the vocabulary it is described in.
3
+ *
4
+ * One shape serves every category. A caller that wants only worktrees filters
5
+ * by `category` rather than reading a different type, and a host that adds its
6
+ * own knowledge (an issue tracker's linkage, say) rewrites rows in place.
7
+ */
8
+ /** What the sweep concluded about an item. */
9
+ export type Classification = 'safe-to-delete' | 'safe-to-keep' | 'needs-investigation';
10
+ /** The kinds of thing a sweep inventories. */
11
+ export type Category = 'local_branch' | 'worktree' | 'remote_branch';
12
+ /** Which categories to gather. */
13
+ export declare const ALL_SCOPES: readonly ["local-branches", "worktrees", "remote-branches"];
14
+ export type Scope = (typeof ALL_SCOPES)[number];
15
+ /**
16
+ * A risk a delete or remove carries, which the user approves by name:
17
+ * `abandon-unmerged` drops commits not on the default branch or a merged PR
18
+ * `discard-changes` drops a worktree's modified, staged or untracked files
19
+ * `confirm-open-pr` the branch has an open PR; deleting the remote branch closes it
20
+ */
21
+ export declare const AUTHORIZATIONS: readonly ["abandon-unmerged", "discard-changes", "confirm-open-pr"];
22
+ export type Authorization = (typeof AUTHORIZATIONS)[number];
23
+ /** The authorizations whose flag is set, in canonical order. */
24
+ export declare function authorizationsFor(flags: Partial<Record<Authorization, boolean>>): Authorization[];
25
+ /** What the sweep learned about a repository before inventorying it. */
26
+ export interface RepoInfo {
27
+ /** The main checkout's root, even when the sweep was pointed at a worktree. */
28
+ root: string;
29
+ /** `owner/name` when the remote is a recognisable host coordinate. */
30
+ slug: string | null;
31
+ mainBranch: string;
32
+ remote: string | null;
33
+ currentBranch: string;
34
+ hasGh: boolean;
35
+ ghAuthenticated: boolean;
36
+ /** True when the sweep fetched the remote before classifying. */
37
+ fetched: boolean;
38
+ }
39
+ /** The ref a branch must reach to count as landed: `<remote>/<default>`, or the local default without a remote. */
40
+ export declare function landedRef(repo: RepoInfo): string;
41
+ /** True when the repository has a remote the sweep did not fetch, so its refs may be stale. */
42
+ export declare function isUnfetched(repo: RepoInfo): boolean;
43
+ /** A pull request, reduced to what classification consults. */
44
+ export interface PRInfo {
45
+ number: number;
46
+ state: string;
47
+ mergedAt: string | null;
48
+ headRef: string;
49
+ /** The PR's head commit; null when `gh` did not report one. */
50
+ headOid: string | null;
51
+ /** The branch the PR targets. */
52
+ baseRef: string;
53
+ title: string;
54
+ url: string;
55
+ }
56
+ export interface SweepItem {
57
+ category: Category;
58
+ id: string;
59
+ classification: Classification;
60
+ action: string;
61
+ /** One line, already phrased for a report. */
62
+ reason: string;
63
+ /** The evidence behind the verdict. A host re-ranking a row reads these. */
64
+ facts: Record<string, unknown>;
65
+ /** Literal commands that would carry out `action`. Never run by this library. */
66
+ commands: string[];
67
+ /**
68
+ * Sentences explaining what is unclear, for a `needs-investigation` row.
69
+ *
70
+ * Parts rather than one string: a host with knowledge this library does not
71
+ * have appends its own sentence before anything is rendered. Empty for a row
72
+ * that needs no investigation.
73
+ */
74
+ investigationParts: string[];
75
+ /** What deleting or removing this row would need approved. */
76
+ requires: Authorization[];
77
+ /**
78
+ * False for a row kept for structure, such as the default branch, and for a
79
+ * blocked worktree. Never offered for deletion.
80
+ */
81
+ deletable: boolean;
82
+ }
83
+ /** One repository's inventory, or the reason there is none. */
84
+ export interface RepoSweep {
85
+ /** Present when the repository could be read. */
86
+ repo: RepoInfo | null;
87
+ /** The path the sweep was pointed at, whether or not it could be read. */
88
+ path: string;
89
+ items: SweepItem[];
90
+ /** Why this repository produced no inventory. Null on success. */
91
+ error: string | null;
92
+ }
93
+ /** An entry that named no repository. */
94
+ export interface UnresolvedEntry {
95
+ entry: string;
96
+ reason: string;
97
+ }
98
+ /**
99
+ * What resolving the entries cost. An entry that is itself a checkout costs
100
+ * nothing to find; a container is walked, and a person who points one at the
101
+ * wrong directory deserves to be told how much was read.
102
+ */
103
+ export interface ScanStats {
104
+ /** Entries that had to be searched, rather than naming a checkout outright. */
105
+ containers: number;
106
+ /** Directories read across those searches. */
107
+ directoriesScanned: number;
108
+ /** Directories left unopened because the depth cap stopped the walk. */
109
+ depthLimited: number;
110
+ /** Checkouts found by those searches, worktrees included, before de-duplication. */
111
+ checkoutsFound: number;
112
+ }
113
+ /** One remote checked out as two or more separate main checkouts. */
114
+ export interface DuplicateCheckout {
115
+ slug: string;
116
+ /** Main-checkout paths, sorted. */
117
+ roots: string[];
118
+ }
119
+ /** Every repository swept in one run, plus the entries that named none. */
120
+ export interface SweepResult {
121
+ repos: RepoSweep[];
122
+ unresolved: UnresolvedEntry[];
123
+ scan: ScanStats;
124
+ duplicates: DuplicateCheckout[];
125
+ }
126
+ /**
127
+ * Slugs shared by two or more of `repos`, roots sorted. A null entry or a
128
+ * repository without a slug is left out.
129
+ */
130
+ export declare function findDuplicateCheckouts(repos: readonly ({
131
+ root: string;
132
+ slug: string | null;
133
+ } | null)[]): DuplicateCheckout[];
134
+ export declare function emptyScan(): ScanStats;
135
+ export interface SummaryBucket {
136
+ total: number;
137
+ 'safe-to-delete': number;
138
+ 'safe-to-keep': number;
139
+ 'needs-investigation': number;
140
+ }
141
+ export declare function emptyBucket(): SummaryBucket;
142
+ /** Per-category counts over `items`. */
143
+ export declare function summarize(items: readonly SweepItem[]): Record<string, SummaryBucket>;
144
+ type Defaulted = 'facts' | 'commands' | 'investigationParts' | 'requires' | 'deletable';
145
+ /** Build an item, defaulting the collection fields and `deletable: true`. */
146
+ export declare function makeItem(partial: Omit<SweepItem, Defaulted> & Partial<Pick<SweepItem, Defaulted>>): SweepItem;
147
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The inventory a sweep produces, and the vocabulary it is described in.
3
+ *
4
+ * One shape serves every category. A caller that wants only worktrees filters
5
+ * by `category` rather than reading a different type, and a host that adds its
6
+ * own knowledge (an issue tracker's linkage, say) rewrites rows in place.
7
+ */
8
+ /** Which categories to gather. */
9
+ export const ALL_SCOPES = ['local-branches', 'worktrees', 'remote-branches'];
10
+ /**
11
+ * A risk a delete or remove carries, which the user approves by name:
12
+ * `abandon-unmerged` drops commits not on the default branch or a merged PR
13
+ * `discard-changes` drops a worktree's modified, staged or untracked files
14
+ * `confirm-open-pr` the branch has an open PR; deleting the remote branch closes it
15
+ */
16
+ export const AUTHORIZATIONS = ['abandon-unmerged', 'discard-changes', 'confirm-open-pr'];
17
+ /** The authorizations whose flag is set, in canonical order. */
18
+ export function authorizationsFor(flags) {
19
+ return AUTHORIZATIONS.filter((name) => flags[name] === true);
20
+ }
21
+ /** The ref a branch must reach to count as landed: `<remote>/<default>`, or the local default without a remote. */
22
+ export function landedRef(repo) {
23
+ return repo.remote === null ? repo.mainBranch : `${repo.remote}/${repo.mainBranch}`;
24
+ }
25
+ /** True when the repository has a remote the sweep did not fetch, so its refs may be stale. */
26
+ export function isUnfetched(repo) {
27
+ return repo.remote !== null && !repo.fetched;
28
+ }
29
+ /**
30
+ * Slugs shared by two or more of `repos`, roots sorted. A null entry or a
31
+ * repository without a slug is left out.
32
+ */
33
+ export function findDuplicateCheckouts(repos) {
34
+ const bySlug = new Map();
35
+ for (const repo of repos) {
36
+ if (repo?.slug == null)
37
+ continue;
38
+ const roots = bySlug.get(repo.slug) ?? new Set();
39
+ roots.add(repo.root);
40
+ bySlug.set(repo.slug, roots);
41
+ }
42
+ return [...bySlug]
43
+ .filter(([, roots]) => roots.size > 1)
44
+ .map(([slug, roots]) => ({ slug, roots: [...roots].sort() }))
45
+ .sort((a, b) => a.slug.localeCompare(b.slug));
46
+ }
47
+ export function emptyScan() {
48
+ return { containers: 0, directoriesScanned: 0, depthLimited: 0, checkoutsFound: 0 };
49
+ }
50
+ export function emptyBucket() {
51
+ return { total: 0, 'safe-to-delete': 0, 'safe-to-keep': 0, 'needs-investigation': 0 };
52
+ }
53
+ /** Per-category counts over `items`. */
54
+ export function summarize(items) {
55
+ const out = {};
56
+ for (const item of items) {
57
+ const bucket = (out[item.category] ??= emptyBucket());
58
+ bucket.total += 1;
59
+ bucket[item.classification] += 1;
60
+ }
61
+ return out;
62
+ }
63
+ /** Build an item, defaulting the collection fields and `deletable: true`. */
64
+ export function makeItem(partial) {
65
+ return {
66
+ category: partial.category,
67
+ id: partial.id,
68
+ classification: partial.classification,
69
+ action: partial.action,
70
+ reason: partial.reason,
71
+ facts: partial.facts ?? {},
72
+ commands: partial.commands ?? [],
73
+ investigationParts: partial.investigationParts ?? [],
74
+ requires: partial.requires ?? [],
75
+ deletable: partial.deletable ?? true,
76
+ };
77
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Worktrees: gather them, then decide what each one is.
3
+ *
4
+ * A worktree is a directory with work in it, so it is judged more cautiously
5
+ * than a branch. Anything uncommitted or unpushed stops the verdict cold —
6
+ * losing an hour of someone's work costs more than any amount of clutter.
7
+ */
8
+ import type { Git } from '@osdlc/typed-git';
9
+ import { type ProcessProbe } from './processes.ts';
10
+ import { type PRInfo, type RepoInfo, type SweepItem } from './types.ts';
11
+ /** The command line, not run, that removes the worktree at `path`. */
12
+ export declare function worktreeRemoveCommand(root: string, path: string, opts?: {
13
+ force?: boolean;
14
+ }): string;
15
+ /** The command line, not run, that unlocks the worktree at `path`. */
16
+ export declare function worktreeUnlockCommand(root: string, path: string): string;
17
+ /** The command line, not run, that drops registrations of worktrees whose directories are gone. */
18
+ export declare function worktreePruneCommand(root: string): string;
19
+ /** A condition that rules out removing a worktree, whatever its branch says. */
20
+ export type WorktreeBlocker = 'locked-worktree' | 'live-process' | 'process-probe-failed' | 'hidden-index-flags' | 'nested-repository' | 'branch-in-other-worktree';
21
+ /** True for a worktree row held back by `facts.blockers`. */
22
+ export declare function hasBlockers(item: Pick<SweepItem, 'facts'>): boolean;
23
+ /**
24
+ * Every worktree of `repo`, and the set of branches they hold.
25
+ *
26
+ * The branch set is returned because a local branch checked out in a worktree
27
+ * must not be judged on its own: the worktree is what a person would act on.
28
+ */
29
+ export declare function gatherWorktrees(repo: RepoInfo, prs: Map<string, PRInfo>, cwd: string, git: Git, only: string | undefined, probe: ProcessProbe): [SweepItem[], Set<string>];
30
+ export declare function classifyWorktree(opts: {
31
+ path: string;
32
+ branch: string;
33
+ /** The worktree's HEAD commit; null when git reported none. */
34
+ head: string | null;
35
+ isBare: boolean;
36
+ isDetached: boolean;
37
+ isPrimary: boolean;
38
+ locked: boolean;
39
+ lockReason: string | null;
40
+ /** Other worktrees with the same branch checked out. */
41
+ otherWorktrees: string[];
42
+ repo: RepoInfo;
43
+ prs: Map<string, PRInfo>;
44
+ cwd: string;
45
+ git: Git;
46
+ /** Answers lock-owner and working-directory questions. One per sweep: it caches the process table. */
47
+ probe: ProcessProbe;
48
+ }): SweepItem;