@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/CHANGELOG.md +191 -0
- package/CONTRIBUTING.md +59 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +301 -2
- package/SECURITY.md +21 -0
- package/bin/repo-cleaner.js +8 -0
- package/dist/apply.d.ts +62 -0
- package/dist/apply.js +316 -0
- package/dist/branches.d.ts +61 -0
- package/dist/branches.js +303 -0
- package/dist/cli.d.ts +19 -0
- package/dist/cli.js +298 -0
- package/dist/config.d.ts +53 -0
- package/dist/config.js +67 -0
- package/dist/discover.d.ts +32 -0
- package/dist/discover.js +88 -0
- package/dist/hooks.d.ts +15 -0
- package/dist/hooks.js +7 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +29 -0
- package/dist/plan.d.ts +101 -0
- package/dist/plan.js +107 -0
- package/dist/processes.d.ts +103 -0
- package/dist/processes.js +189 -0
- package/dist/prs.d.ts +26 -0
- package/dist/prs.js +82 -0
- package/dist/receipt.d.ts +114 -0
- package/dist/receipt.js +35 -0
- package/dist/render.d.ts +43 -0
- package/dist/render.js +219 -0
- package/dist/resolve.d.ts +46 -0
- package/dist/resolve.js +90 -0
- package/dist/sweep.d.ts +68 -0
- package/dist/sweep.js +129 -0
- package/dist/types.d.ts +147 -0
- package/dist/types.js +77 -0
- package/dist/worktrees.d.ts +48 -0
- package/dist/worktrees.js +338 -0
- package/dist/write-json.d.ts +6 -0
- package/dist/write-json.js +40 -0
- package/package.json +77 -3
package/dist/plan.d.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cleanup plan: the deletable rows of a sweep, each with a fingerprint of
|
|
3
|
+
* the facts its verdict rests on. `applyPlan` re-sweeps and drops any row
|
|
4
|
+
* whose fingerprint no longer matches.
|
|
5
|
+
*/
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { type SweepItem } from './types.ts';
|
|
8
|
+
export declare const PLAN_VERSION = 1;
|
|
9
|
+
/** The categories a plan can hold, in the order apply runs them. */
|
|
10
|
+
export declare const PLAN_CATEGORIES: readonly ["worktree", "local_branch", "remote_branch"];
|
|
11
|
+
export type PlanCategory = (typeof PLAN_CATEGORIES)[number];
|
|
12
|
+
export declare const PlanRowSchema: z.ZodObject<{
|
|
13
|
+
category: z.ZodEnum<{
|
|
14
|
+
local_branch: "local_branch";
|
|
15
|
+
worktree: "worktree";
|
|
16
|
+
remote_branch: "remote_branch";
|
|
17
|
+
}>;
|
|
18
|
+
id: z.ZodString;
|
|
19
|
+
requires: z.ZodArray<z.ZodEnum<{
|
|
20
|
+
"abandon-unmerged": "abandon-unmerged";
|
|
21
|
+
"discard-changes": "discard-changes";
|
|
22
|
+
"confirm-open-pr": "confirm-open-pr";
|
|
23
|
+
}>>;
|
|
24
|
+
fingerprint: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
25
|
+
}, z.core.$strip>;
|
|
26
|
+
export type PlanRow = z.infer<typeof PlanRowSchema>;
|
|
27
|
+
export declare const PlanRepoSchema: z.ZodObject<{
|
|
28
|
+
root: z.ZodString;
|
|
29
|
+
remote: z.ZodNullable<z.ZodString>;
|
|
30
|
+
no_gh: z.ZodBoolean;
|
|
31
|
+
branch: z.ZodDefault<z.ZodNullable<z.ZodString>>;
|
|
32
|
+
rows: z.ZodArray<z.ZodObject<{
|
|
33
|
+
category: z.ZodEnum<{
|
|
34
|
+
local_branch: "local_branch";
|
|
35
|
+
worktree: "worktree";
|
|
36
|
+
remote_branch: "remote_branch";
|
|
37
|
+
}>;
|
|
38
|
+
id: z.ZodString;
|
|
39
|
+
requires: z.ZodArray<z.ZodEnum<{
|
|
40
|
+
"abandon-unmerged": "abandon-unmerged";
|
|
41
|
+
"discard-changes": "discard-changes";
|
|
42
|
+
"confirm-open-pr": "confirm-open-pr";
|
|
43
|
+
}>>;
|
|
44
|
+
fingerprint: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
45
|
+
}, z.core.$strip>>;
|
|
46
|
+
}, z.core.$strip>;
|
|
47
|
+
export type PlanRepo = z.infer<typeof PlanRepoSchema>;
|
|
48
|
+
export declare const PlanSchema: z.ZodObject<{
|
|
49
|
+
version: z.ZodLiteral<1>;
|
|
50
|
+
created_at: z.ZodString;
|
|
51
|
+
repos: z.ZodArray<z.ZodObject<{
|
|
52
|
+
root: z.ZodString;
|
|
53
|
+
remote: z.ZodNullable<z.ZodString>;
|
|
54
|
+
no_gh: z.ZodBoolean;
|
|
55
|
+
branch: z.ZodDefault<z.ZodNullable<z.ZodString>>;
|
|
56
|
+
rows: z.ZodArray<z.ZodObject<{
|
|
57
|
+
category: z.ZodEnum<{
|
|
58
|
+
local_branch: "local_branch";
|
|
59
|
+
worktree: "worktree";
|
|
60
|
+
remote_branch: "remote_branch";
|
|
61
|
+
}>;
|
|
62
|
+
id: z.ZodString;
|
|
63
|
+
requires: z.ZodArray<z.ZodEnum<{
|
|
64
|
+
"abandon-unmerged": "abandon-unmerged";
|
|
65
|
+
"discard-changes": "discard-changes";
|
|
66
|
+
"confirm-open-pr": "confirm-open-pr";
|
|
67
|
+
}>>;
|
|
68
|
+
fingerprint: z.ZodRecord<z.ZodString, z.ZodUnknown>;
|
|
69
|
+
}, z.core.$strip>>;
|
|
70
|
+
}, z.core.$strip>>;
|
|
71
|
+
}, z.core.$strip>;
|
|
72
|
+
export type Plan = z.infer<typeof PlanSchema>;
|
|
73
|
+
/** What planning reads off a row. A host's own row type plans the same way. */
|
|
74
|
+
export type PlannableRow = Pick<SweepItem, 'id' | 'facts' | 'requires' | 'deletable'> & {
|
|
75
|
+
category: string;
|
|
76
|
+
};
|
|
77
|
+
export declare function isPlanCategory(category: string): category is PlanCategory;
|
|
78
|
+
/**
|
|
79
|
+
* The facts a row's verdict rests on. A branch: its sha and its PR's number
|
|
80
|
+
* and state. A worktree: HEAD, branch, how much unlanded work it holds and
|
|
81
|
+
* whether its lock was stale, so a lock taken or revived after planning drops
|
|
82
|
+
* the row.
|
|
83
|
+
*/
|
|
84
|
+
export declare function fingerprint(item: PlannableRow): Record<string, unknown>;
|
|
85
|
+
/** Equal fingerprints, treating a missing key as null. */
|
|
86
|
+
export declare function sameFingerprint(a: Record<string, unknown>, b: Record<string, unknown>): boolean;
|
|
87
|
+
/** One repository's plan entry: its deletable rows. */
|
|
88
|
+
export declare function planRepo(root: string, opts: {
|
|
89
|
+
remote: string | null;
|
|
90
|
+
noGh: boolean;
|
|
91
|
+
branch?: string | null;
|
|
92
|
+
}, items: readonly PlannableRow[]): PlanRepo;
|
|
93
|
+
/** A UTC timestamp safe in a file name, e.g. `2026-10-04T12-30-05-123Z`. */
|
|
94
|
+
export declare function fileStamp(d: Date): string;
|
|
95
|
+
export declare function stampedPath(dir: string, d: Date): string;
|
|
96
|
+
export declare function writePlan(path: string, plan: Plan): void;
|
|
97
|
+
/** A plan file that cannot be read or does not match {@link PlanSchema}. */
|
|
98
|
+
export declare class PlanReadError extends Error {
|
|
99
|
+
}
|
|
100
|
+
/** @throws PlanReadError */
|
|
101
|
+
export declare function readPlan(path: string): Plan;
|
package/dist/plan.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cleanup plan: the deletable rows of a sweep, each with a fingerprint of
|
|
3
|
+
* the facts its verdict rests on. `applyPlan` re-sweeps and drops any row
|
|
4
|
+
* whose fingerprint no longer matches.
|
|
5
|
+
*/
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { AUTHORIZATIONS } from "./types.js";
|
|
10
|
+
import { writeJsonAtomic } from "./write-json.js";
|
|
11
|
+
export const PLAN_VERSION = 1;
|
|
12
|
+
/** The categories a plan can hold, in the order apply runs them. */
|
|
13
|
+
export const PLAN_CATEGORIES = ['worktree', 'local_branch', 'remote_branch'];
|
|
14
|
+
export const PlanRowSchema = z.object({
|
|
15
|
+
category: z.enum(PLAN_CATEGORIES),
|
|
16
|
+
id: z.string(),
|
|
17
|
+
requires: z.array(z.enum(AUTHORIZATIONS)),
|
|
18
|
+
fingerprint: z.record(z.string(), z.unknown()),
|
|
19
|
+
});
|
|
20
|
+
export const PlanRepoSchema = z.object({
|
|
21
|
+
root: z.string(),
|
|
22
|
+
/** The `remote` the sweep ran with; the re-sweep uses the same. */
|
|
23
|
+
remote: z.string().nullable(),
|
|
24
|
+
no_gh: z.boolean(),
|
|
25
|
+
/** The `branch` the sweep was narrowed to; the re-sweep uses the same. */
|
|
26
|
+
branch: z.string().nullable().default(null),
|
|
27
|
+
rows: z.array(PlanRowSchema),
|
|
28
|
+
});
|
|
29
|
+
export const PlanSchema = z.object({
|
|
30
|
+
version: z.literal(PLAN_VERSION),
|
|
31
|
+
created_at: z.string(),
|
|
32
|
+
repos: z.array(PlanRepoSchema),
|
|
33
|
+
});
|
|
34
|
+
export function isPlanCategory(category) {
|
|
35
|
+
return PLAN_CATEGORIES.includes(category);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The facts a row's verdict rests on. A branch: its sha and its PR's number
|
|
39
|
+
* and state. A worktree: HEAD, branch, how much unlanded work it holds and
|
|
40
|
+
* whether its lock was stale, so a lock taken or revived after planning drops
|
|
41
|
+
* the row.
|
|
42
|
+
*/
|
|
43
|
+
export function fingerprint(item) {
|
|
44
|
+
const f = item.facts;
|
|
45
|
+
if (item.category === 'worktree') {
|
|
46
|
+
return {
|
|
47
|
+
head: f['head'] ?? null,
|
|
48
|
+
branch: f['branch'] ?? null,
|
|
49
|
+
dirty_files: f['dirty_files'] ?? null,
|
|
50
|
+
unpushed_commits: f['unpushed_commits'] ?? null,
|
|
51
|
+
stale_lock: f['stale_lock'] ?? null,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const pr = f['pr'];
|
|
55
|
+
return { sha: f['sha'] ?? null, pr_number: pr?.number ?? null, pr_state: pr?.state ?? null };
|
|
56
|
+
}
|
|
57
|
+
/** Equal fingerprints, treating a missing key as null. */
|
|
58
|
+
export function sameFingerprint(a, b) {
|
|
59
|
+
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
60
|
+
for (const key of keys) {
|
|
61
|
+
if (JSON.stringify(a[key] ?? null) !== JSON.stringify(b[key] ?? null))
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
/** One repository's plan entry: its deletable rows. */
|
|
67
|
+
export function planRepo(root, opts, items) {
|
|
68
|
+
const rows = [];
|
|
69
|
+
for (const item of items) {
|
|
70
|
+
if (!item.deletable || !isPlanCategory(item.category))
|
|
71
|
+
continue;
|
|
72
|
+
rows.push({
|
|
73
|
+
category: item.category,
|
|
74
|
+
id: item.id,
|
|
75
|
+
requires: item.requires,
|
|
76
|
+
fingerprint: fingerprint(item),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return { root, remote: opts.remote, no_gh: opts.noGh, branch: opts.branch ?? null, rows };
|
|
80
|
+
}
|
|
81
|
+
/** A UTC timestamp safe in a file name, e.g. `2026-10-04T12-30-05-123Z`. */
|
|
82
|
+
export function fileStamp(d) {
|
|
83
|
+
return d.toISOString().replace(/[:.]/g, '-');
|
|
84
|
+
}
|
|
85
|
+
export function stampedPath(dir, d) {
|
|
86
|
+
return join(dir, `${fileStamp(d)}.json`);
|
|
87
|
+
}
|
|
88
|
+
export function writePlan(path, plan) {
|
|
89
|
+
writeJsonAtomic(path, plan);
|
|
90
|
+
}
|
|
91
|
+
/** A plan file that cannot be read or does not match {@link PlanSchema}. */
|
|
92
|
+
export class PlanReadError extends Error {
|
|
93
|
+
}
|
|
94
|
+
/** @throws PlanReadError */
|
|
95
|
+
export function readPlan(path) {
|
|
96
|
+
let raw;
|
|
97
|
+
try {
|
|
98
|
+
raw = JSON.parse(readFileSync(path, 'utf-8'));
|
|
99
|
+
}
|
|
100
|
+
catch (err) {
|
|
101
|
+
throw new PlanReadError(`cannot read plan ${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
102
|
+
}
|
|
103
|
+
const parsed = PlanSchema.safeParse(raw);
|
|
104
|
+
if (!parsed.success)
|
|
105
|
+
throw new PlanReadError(`bad plan ${path}: ${parsed.error.message}`);
|
|
106
|
+
return parsed.data;
|
|
107
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process liveness: is the owner of a worktree lock still running, and which
|
|
3
|
+
* processes work inside a directory.
|
|
4
|
+
*
|
|
5
|
+
* These are facts about a worktree, next to "is it dirty" and "is it locked".
|
|
6
|
+
* The engine reads one generic token from a lock reason, `pid <N>`, with an
|
|
7
|
+
* optional `start <time>` after it to guard against pid reuse. It parses no
|
|
8
|
+
* other part of the reason and names no tool.
|
|
9
|
+
*
|
|
10
|
+
* The questions go through a {@link ProcessProbe}, so a test or a host can
|
|
11
|
+
* answer them without a process table. The default probe runs `ps` and `lsof`
|
|
12
|
+
* through the command seam.
|
|
13
|
+
*/
|
|
14
|
+
import { type CommandRunner } from '@osdlc/command-seam';
|
|
15
|
+
/** A process whose working directory is inside a directory. */
|
|
16
|
+
export interface ProcessHolder {
|
|
17
|
+
pid: number;
|
|
18
|
+
/** The command name as the OS reports it, without a path. */
|
|
19
|
+
command: string;
|
|
20
|
+
/**
|
|
21
|
+
* Whether the process has child processes. Read only for shells: a shell
|
|
22
|
+
* counts as idle only when this is `false`; absent means unknown, which is
|
|
23
|
+
* not idle.
|
|
24
|
+
*/
|
|
25
|
+
hasChildren?: boolean | undefined;
|
|
26
|
+
}
|
|
27
|
+
/** What the engine asks of the process table. */
|
|
28
|
+
export interface ProcessProbe {
|
|
29
|
+
/**
|
|
30
|
+
* Whether `pid` is running. With `startedAt`, the process counts only if it
|
|
31
|
+
* also started at that time: a pid reused by a newer process is not the
|
|
32
|
+
* owner. `startedAt` is the text the lock gave; a probe that cannot read it
|
|
33
|
+
* as a time must answer "alive" (the owner cannot be ruled out).
|
|
34
|
+
*/
|
|
35
|
+
alive(pid: number, startedAt?: string): boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Processes whose current directory is `path` or below it. Throws when the
|
|
38
|
+
* process table cannot be read; the caller must treat that as "unknown".
|
|
39
|
+
* With `fresh`, a probe that caches its table reads it again.
|
|
40
|
+
*/
|
|
41
|
+
holders(path: string, opts?: {
|
|
42
|
+
fresh?: boolean;
|
|
43
|
+
}): ProcessHolder[];
|
|
44
|
+
}
|
|
45
|
+
/** The owner a lock reason claims. */
|
|
46
|
+
export interface LockOwner {
|
|
47
|
+
pid: number;
|
|
48
|
+
/** The text after `start`, when the reason gave one. */
|
|
49
|
+
startedAt?: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The owner claimed by a lock reason, or null when it carries no `pid <N>`
|
|
53
|
+
* token. The token reads `pid <digits>`, optionally followed by
|
|
54
|
+
* `start <text>` running to a closing parenthesis or the end of the reason.
|
|
55
|
+
*/
|
|
56
|
+
export declare function parseLockOwner(reason: string | null): LockOwner | null;
|
|
57
|
+
/**
|
|
58
|
+
* True when `command` is the name of a shell (`sh`, `bash`, `zsh`, `fish`); a
|
|
59
|
+
* login shell's leading `-` is ignored. The name alone does not make a shell
|
|
60
|
+
* idle: see {@link busyHolders}. Not for names longer than lsof's 9 characters.
|
|
61
|
+
*/
|
|
62
|
+
export declare function isIdleShell(command: string): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Whether a holder is a shell with nothing running under it. A shell whose
|
|
65
|
+
* children are unknown, or that has any, is not idle: it may be running a script.
|
|
66
|
+
*/
|
|
67
|
+
export declare function isIdleHolder(h: ProcessHolder): boolean;
|
|
68
|
+
/** The holders that make a worktree live: everything but idle shells. */
|
|
69
|
+
export declare function busyHolders(holders: readonly ProcessHolder[]): ProcessHolder[];
|
|
70
|
+
/**
|
|
71
|
+
* Epoch milliseconds of a start time, or NaN when the text is not precise to
|
|
72
|
+
* the second. Accepted: a full ISO-8601 timestamp with a time of day, epoch
|
|
73
|
+
* seconds (9-10 digits), epoch milliseconds (12-13 digits), or the `lstart`
|
|
74
|
+
* form. A date alone, a short digit string or a partial date such as `Oct 25`
|
|
75
|
+
* is NaN, so the owner is treated as alive: the comparison would otherwise
|
|
76
|
+
* call a live owner dead.
|
|
77
|
+
*/
|
|
78
|
+
export declare function startMs(text: string): number;
|
|
79
|
+
/**
|
|
80
|
+
* Parse `lsof -Fpcn` output: `p<pid>`, then `c<command>`, then `n<cwd>` per
|
|
81
|
+
* process. One record per process; a record missing a field is skipped.
|
|
82
|
+
*/
|
|
83
|
+
export declare function parseLsofCwd(output: string): Array<ProcessHolder & {
|
|
84
|
+
cwd: string;
|
|
85
|
+
}>;
|
|
86
|
+
export interface DefaultProbeOptions {
|
|
87
|
+
/** Injected runners for `ps` and `lsof`. Defaults spawn the real binaries. */
|
|
88
|
+
ps?: CommandRunner | undefined;
|
|
89
|
+
lsof?: CommandRunner | undefined;
|
|
90
|
+
/** Cap on each command, in ms. Defaults to 60 s. */
|
|
91
|
+
timeoutMs?: number | undefined;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The default probe: `ps` for liveness, `lsof` for working directories, both
|
|
95
|
+
* through the command seam.
|
|
96
|
+
*
|
|
97
|
+
* `holders` reads the whole table once, on first use, and answers every later
|
|
98
|
+
* call from that snapshot, so one sweep of many worktrees runs `lsof` once;
|
|
99
|
+
* `fresh` reads it again. Make a new probe for a new sweep. Whenever `ps` or
|
|
100
|
+
* `lsof` cannot give a clear answer, `alive` answers true (the owner cannot be
|
|
101
|
+
* ruled out) and `holders` throws.
|
|
102
|
+
*/
|
|
103
|
+
export declare function defaultProcessProbe(opts?: DefaultProbeOptions): ProcessProbe;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process liveness: is the owner of a worktree lock still running, and which
|
|
3
|
+
* processes work inside a directory.
|
|
4
|
+
*
|
|
5
|
+
* These are facts about a worktree, next to "is it dirty" and "is it locked".
|
|
6
|
+
* The engine reads one generic token from a lock reason, `pid <N>`, with an
|
|
7
|
+
* optional `start <time>` after it to guard against pid reuse. It parses no
|
|
8
|
+
* other part of the reason and names no tool.
|
|
9
|
+
*
|
|
10
|
+
* The questions go through a {@link ProcessProbe}, so a test or a host can
|
|
11
|
+
* answer them without a process table. The default probe runs `ps` and `lsof`
|
|
12
|
+
* through the command seam.
|
|
13
|
+
*/
|
|
14
|
+
import { realpathSync } from 'node:fs';
|
|
15
|
+
import { spawnRunner } from '@osdlc/command-seam';
|
|
16
|
+
import { nodeGuard } from '@osdlc/path-guard/node';
|
|
17
|
+
/**
|
|
18
|
+
* The owner claimed by a lock reason, or null when it carries no `pid <N>`
|
|
19
|
+
* token. The token reads `pid <digits>`, optionally followed by
|
|
20
|
+
* `start <text>` running to a closing parenthesis or the end of the reason.
|
|
21
|
+
*/
|
|
22
|
+
export function parseLockOwner(reason) {
|
|
23
|
+
if (reason === null)
|
|
24
|
+
return null;
|
|
25
|
+
const found = /\bpid\s+(\d+)\b(?:\s+start\s+([^)]*))?/.exec(reason);
|
|
26
|
+
if (found === null)
|
|
27
|
+
return null;
|
|
28
|
+
const pid = Number(found[1]);
|
|
29
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
30
|
+
return null;
|
|
31
|
+
const startedAt = found[2]?.trim();
|
|
32
|
+
return startedAt ? { pid, startedAt } : { pid };
|
|
33
|
+
}
|
|
34
|
+
/** Shells that sit idle in a directory and do not make a worktree live. */
|
|
35
|
+
const IDLE_SHELLS = new Set(['sh', 'bash', 'zsh', 'fish']);
|
|
36
|
+
/**
|
|
37
|
+
* True when `command` is the name of a shell (`sh`, `bash`, `zsh`, `fish`); a
|
|
38
|
+
* login shell's leading `-` is ignored. The name alone does not make a shell
|
|
39
|
+
* idle: see {@link busyHolders}. Not for names longer than lsof's 9 characters.
|
|
40
|
+
*/
|
|
41
|
+
export function isIdleShell(command) {
|
|
42
|
+
return IDLE_SHELLS.has(command.replace(/^-/, ''));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Whether a holder is a shell with nothing running under it. A shell whose
|
|
46
|
+
* children are unknown, or that has any, is not idle: it may be running a script.
|
|
47
|
+
*/
|
|
48
|
+
export function isIdleHolder(h) {
|
|
49
|
+
return isIdleShell(h.command) && h.hasChildren === false;
|
|
50
|
+
}
|
|
51
|
+
/** The holders that make a worktree live: everything but idle shells. */
|
|
52
|
+
export function busyHolders(holders) {
|
|
53
|
+
return holders.filter((h) => !isIdleHolder(h));
|
|
54
|
+
}
|
|
55
|
+
/** Allowed difference between a lock's start time and the process's, in ms. */
|
|
56
|
+
const START_TOLERANCE_MS = 2000;
|
|
57
|
+
// A zone is required: without one Date.parse reads local time, and a writer that
|
|
58
|
+
// emitted UTC with no `Z` would shift the start time by hours and make a live owner
|
|
59
|
+
// look like a reused pid.
|
|
60
|
+
const ISO_WITH_TIME = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/;
|
|
61
|
+
/** `ps -o lstart`: `Sat Oct 25 18:22:19 2026`, the day space-padded on Linux. */
|
|
62
|
+
const PS_LSTART = /^[A-Z][a-z]{2}\s+[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/;
|
|
63
|
+
/**
|
|
64
|
+
* Epoch milliseconds of a start time, or NaN when the text is not precise to
|
|
65
|
+
* the second. Accepted: a full ISO-8601 timestamp with a time of day, epoch
|
|
66
|
+
* seconds (9-10 digits), epoch milliseconds (12-13 digits), or the `lstart`
|
|
67
|
+
* form. A date alone, a short digit string or a partial date such as `Oct 25`
|
|
68
|
+
* is NaN, so the owner is treated as alive: the comparison would otherwise
|
|
69
|
+
* call a live owner dead.
|
|
70
|
+
*/
|
|
71
|
+
export function startMs(text) {
|
|
72
|
+
const trimmed = text.trim();
|
|
73
|
+
if (/^\d{9,10}$/.test(trimmed))
|
|
74
|
+
return Number(trimmed) * 1000;
|
|
75
|
+
if (/^\d{12,13}$/.test(trimmed))
|
|
76
|
+
return Number(trimmed);
|
|
77
|
+
if (ISO_WITH_TIME.test(trimmed) || PS_LSTART.test(trimmed))
|
|
78
|
+
return Date.parse(trimmed);
|
|
79
|
+
return Number.NaN;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Parse `lsof -Fpcn` output: `p<pid>`, then `c<command>`, then `n<cwd>` per
|
|
83
|
+
* process. One record per process; a record missing a field is skipped.
|
|
84
|
+
*/
|
|
85
|
+
export function parseLsofCwd(output) {
|
|
86
|
+
const rows = [];
|
|
87
|
+
let pid = 0;
|
|
88
|
+
let command = '';
|
|
89
|
+
for (const line of output.split('\n')) {
|
|
90
|
+
const tag = line[0];
|
|
91
|
+
const value = line.slice(1);
|
|
92
|
+
if (tag === 'p') {
|
|
93
|
+
pid = Number(value);
|
|
94
|
+
command = '';
|
|
95
|
+
}
|
|
96
|
+
else if (tag === 'c') {
|
|
97
|
+
command = value;
|
|
98
|
+
}
|
|
99
|
+
else if (tag === 'n' && pid > 0 && command !== '') {
|
|
100
|
+
rows.push({ pid, command, cwd: value });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return rows;
|
|
104
|
+
}
|
|
105
|
+
/** True when the command ran and reported an exit status. */
|
|
106
|
+
const answered = (r) => r.neverExited !== true;
|
|
107
|
+
/**
|
|
108
|
+
* The default probe: `ps` for liveness, `lsof` for working directories, both
|
|
109
|
+
* through the command seam.
|
|
110
|
+
*
|
|
111
|
+
* `holders` reads the whole table once, on first use, and answers every later
|
|
112
|
+
* call from that snapshot, so one sweep of many worktrees runs `lsof` once;
|
|
113
|
+
* `fresh` reads it again. Make a new probe for a new sweep. Whenever `ps` or
|
|
114
|
+
* `lsof` cannot give a clear answer, `alive` answers true (the owner cannot be
|
|
115
|
+
* ruled out) and `holders` throws.
|
|
116
|
+
*/
|
|
117
|
+
export function defaultProcessProbe(opts = {}) {
|
|
118
|
+
const ps = opts.ps ?? spawnRunner('ps');
|
|
119
|
+
const lsof = opts.lsof ?? spawnRunner('lsof');
|
|
120
|
+
const timeoutMs = opts.timeoutMs ?? 60_000;
|
|
121
|
+
let table = null;
|
|
122
|
+
return {
|
|
123
|
+
alive(pid, startedAt) {
|
|
124
|
+
// `lstart` is the same five-field date on macOS and Linux procps.
|
|
125
|
+
const r = ps.run(['-o', 'lstart=', '-p', String(pid)], { cwd: '/', timeoutMs });
|
|
126
|
+
if (!answered(r))
|
|
127
|
+
return true;
|
|
128
|
+
const started = r.stdout.trim();
|
|
129
|
+
// Only exit 1 with nothing printed is ps saying "no such pid". Any other
|
|
130
|
+
// failure (usage error, permission, a diagnostic) cannot rule the owner out.
|
|
131
|
+
if (r.exitCode === 1 && started === '' && r.stderr.trim() === '')
|
|
132
|
+
return false;
|
|
133
|
+
if (r.exitCode !== 0 || started === '')
|
|
134
|
+
return true;
|
|
135
|
+
if (startedAt === undefined)
|
|
136
|
+
return true;
|
|
137
|
+
const claimed = startMs(startedAt);
|
|
138
|
+
const actual = Date.parse(started);
|
|
139
|
+
if (Number.isNaN(claimed) || Number.isNaN(actual))
|
|
140
|
+
return true;
|
|
141
|
+
return Math.abs(claimed - actual) <= START_TOLERANCE_MS;
|
|
142
|
+
},
|
|
143
|
+
holders(path, holdersOpts) {
|
|
144
|
+
if (table === null || holdersOpts?.fresh === true) {
|
|
145
|
+
// `-a -d cwd`: only the working-directory entry of each process.
|
|
146
|
+
// lsof exits 1 when it could not read some processes yet still lists
|
|
147
|
+
// the rest, so a listing is read whatever the status. No listing at
|
|
148
|
+
// all with a failure status is an error, not an empty table.
|
|
149
|
+
const r = lsof.run(['-n', '-P', '-a', '-d', 'cwd', '-Fpcn'], { cwd: '/', timeoutMs });
|
|
150
|
+
if (!answered(r))
|
|
151
|
+
throw new Error(`lsof did not run: ${r.error ?? r.stderr.trim()}`);
|
|
152
|
+
if ((r.exitCode !== 0 && r.stdout.trim() === '') || r.exitCode > 1) {
|
|
153
|
+
throw new Error(`lsof failed (exit ${r.exitCode}): ${r.stderr.trim() || 'no output'}`);
|
|
154
|
+
}
|
|
155
|
+
const rows = parseLsofCwd(r.stdout).filter((row) => row.pid !== process.pid);
|
|
156
|
+
const parents = rows.some((row) => isIdleShell(row.command))
|
|
157
|
+
? parentPids()
|
|
158
|
+
: new Set();
|
|
159
|
+
table = rows.map((row) => ({ ...row, hasChildren: parents.has(row.pid) }));
|
|
160
|
+
}
|
|
161
|
+
const roots = new Set([path]);
|
|
162
|
+
try {
|
|
163
|
+
roots.add(realpathSync(path));
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// A directory that is gone has no holders.
|
|
167
|
+
}
|
|
168
|
+
return table
|
|
169
|
+
.filter((row) => [...roots].some((root) => nodeGuard.contains(root, row.cwd)))
|
|
170
|
+
.map(({ pid, command, hasChildren }) => ({ pid, command, hasChildren }));
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
/** Pids that are the parent of some process. Throws when `ps` gives no table. */
|
|
174
|
+
function parentPids() {
|
|
175
|
+
const r = ps.run(['-A', '-o', 'pid=,ppid='], { cwd: '/', timeoutMs });
|
|
176
|
+
if (!answered(r))
|
|
177
|
+
throw new Error(`ps did not run: ${r.error ?? r.stderr.trim()}`);
|
|
178
|
+
if (r.exitCode !== 0 || r.stdout.trim() === '') {
|
|
179
|
+
throw new Error(`ps failed (exit ${r.exitCode}): ${r.stderr.trim() || 'no output'}`);
|
|
180
|
+
}
|
|
181
|
+
const parents = new Set();
|
|
182
|
+
for (const line of r.stdout.split('\n')) {
|
|
183
|
+
const m = /^\s*(\d+)\s+(\d+)\s*$/.exec(line);
|
|
184
|
+
if (m !== null)
|
|
185
|
+
parents.add(Number(m[2]));
|
|
186
|
+
}
|
|
187
|
+
return parents;
|
|
188
|
+
}
|
|
189
|
+
}
|
package/dist/prs.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pull requests of a repository, indexed by head branch.
|
|
3
|
+
*
|
|
4
|
+
* One `gh pr list` per repository, not one query per branch: a repository with
|
|
5
|
+
* sixty branches would otherwise pay sixty round trips to answer a question
|
|
6
|
+
* one listing covers.
|
|
7
|
+
*/
|
|
8
|
+
import type { Gh } from '@osdlc/typed-gh';
|
|
9
|
+
import type { PRInfo, RepoInfo } from './types.ts';
|
|
10
|
+
/**
|
|
11
|
+
* Every same-repository pull request, keyed by head branch. Fork PRs are
|
|
12
|
+
* dropped: a fork branch that shares a name proves nothing about ours.
|
|
13
|
+
*
|
|
14
|
+
* A branch can carry several PRs over its life. The one that decides a
|
|
15
|
+
* verdict is the most live: an open PR means keep whatever else happened, and
|
|
16
|
+
* a merged one means the work landed. Ties go to the higher number, so two
|
|
17
|
+
* runs over unchanged state agree.
|
|
18
|
+
*
|
|
19
|
+
* An empty map is the honest answer when `gh` is missing, unauthenticated or
|
|
20
|
+
* failing. Classification degrades to git evidence and the report says so.
|
|
21
|
+
*
|
|
22
|
+
* @param headPrefix Ask `gh` only for PRs whose head starts with this; the map is
|
|
23
|
+
* still keyed by exact head. typed-gh's `head` is exact, so the prefix goes
|
|
24
|
+
* through gh's `head:` search, which matches by prefix, and is checked again here.
|
|
25
|
+
*/
|
|
26
|
+
export declare function fetchPrs(repo: RepoInfo, gh: Gh, headPrefix?: string): Map<string, PRInfo>;
|
package/dist/prs.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pull requests of a repository, indexed by head branch.
|
|
3
|
+
*
|
|
4
|
+
* One `gh pr list` per repository, not one query per branch: a repository with
|
|
5
|
+
* sixty branches would otherwise pay sixty round trips to answer a question
|
|
6
|
+
* one listing covers.
|
|
7
|
+
*/
|
|
8
|
+
/** The fields classification consults. Asking for more costs latency. */
|
|
9
|
+
const FIELDS = [
|
|
10
|
+
'number',
|
|
11
|
+
'state',
|
|
12
|
+
'mergedAt',
|
|
13
|
+
'headRefName',
|
|
14
|
+
'headRefOid',
|
|
15
|
+
'baseRefName',
|
|
16
|
+
'isCrossRepository',
|
|
17
|
+
'title',
|
|
18
|
+
'url',
|
|
19
|
+
];
|
|
20
|
+
const LIMIT = 300;
|
|
21
|
+
/** Open outranks merged outranks closed, and a newer PR outranks an older. */
|
|
22
|
+
function priority(state) {
|
|
23
|
+
return { OPEN: 3, MERGED: 2, CLOSED: 1 }[state] ?? 0;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Every same-repository pull request, keyed by head branch. Fork PRs are
|
|
27
|
+
* dropped: a fork branch that shares a name proves nothing about ours.
|
|
28
|
+
*
|
|
29
|
+
* A branch can carry several PRs over its life. The one that decides a
|
|
30
|
+
* verdict is the most live: an open PR means keep whatever else happened, and
|
|
31
|
+
* a merged one means the work landed. Ties go to the higher number, so two
|
|
32
|
+
* runs over unchanged state agree.
|
|
33
|
+
*
|
|
34
|
+
* An empty map is the honest answer when `gh` is missing, unauthenticated or
|
|
35
|
+
* failing. Classification degrades to git evidence and the report says so.
|
|
36
|
+
*
|
|
37
|
+
* @param headPrefix Ask `gh` only for PRs whose head starts with this; the map is
|
|
38
|
+
* still keyed by exact head. typed-gh's `head` is exact, so the prefix goes
|
|
39
|
+
* through gh's `head:` search, which matches by prefix, and is checked again here.
|
|
40
|
+
*/
|
|
41
|
+
export function fetchPrs(repo, gh, headPrefix) {
|
|
42
|
+
const byHead = new Map();
|
|
43
|
+
if (!(repo.hasGh && repo.ghAuthenticated))
|
|
44
|
+
return byHead;
|
|
45
|
+
const rows = gh.at(repo.root).prList({
|
|
46
|
+
state: 'all',
|
|
47
|
+
limit: LIMIT,
|
|
48
|
+
fields: FIELDS,
|
|
49
|
+
search: headPrefix === undefined ? undefined : `head:${headPrefix}`,
|
|
50
|
+
});
|
|
51
|
+
if (rows === null)
|
|
52
|
+
return byHead;
|
|
53
|
+
for (const row of rows.rows) {
|
|
54
|
+
const head = row.headRefName;
|
|
55
|
+
// A fork's head branch is not this repository's branch, whatever its name.
|
|
56
|
+
if (!head || row.isCrossRepository)
|
|
57
|
+
continue;
|
|
58
|
+
if (headPrefix !== undefined && !head.startsWith(headPrefix))
|
|
59
|
+
continue;
|
|
60
|
+
const info = {
|
|
61
|
+
number: row.number,
|
|
62
|
+
state: row.state,
|
|
63
|
+
mergedAt: row.mergedAt,
|
|
64
|
+
headRef: head,
|
|
65
|
+
headOid: row.headRefOid,
|
|
66
|
+
baseRef: row.baseRefName,
|
|
67
|
+
title: row.title,
|
|
68
|
+
url: row.url,
|
|
69
|
+
};
|
|
70
|
+
const existing = byHead.get(head);
|
|
71
|
+
if (existing === undefined) {
|
|
72
|
+
byHead.set(head, info);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const prio = priority(info.state);
|
|
76
|
+
const existingPrio = priority(existing.state);
|
|
77
|
+
if (prio > existingPrio || (prio === existingPrio && info.number > existing.number)) {
|
|
78
|
+
byHead.set(head, info);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return byHead;
|
|
82
|
+
}
|