ticket-runner 0.6.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/LICENSE +21 -0
- package/README.ko.md +97 -0
- package/README.md +98 -0
- package/bin/ticket-runner.js +6 -0
- package/docs/templates/operator-skill.md +87 -0
- package/package.json +42 -0
- package/src/acceptance-criteria.ts +44 -0
- package/src/adapters/claude-agent-runner.ts +389 -0
- package/src/adapters/exec.ts +169 -0
- package/src/adapters/gh-tracker.ts +955 -0
- package/src/adapters/git-workspace.ts +951 -0
- package/src/adapters/repo-root.ts +20 -0
- package/src/adapters/version.ts +118 -0
- package/src/base-branch.ts +21 -0
- package/src/branch.ts +33 -0
- package/src/cli.ts +135 -0
- package/src/command-line.ts +190 -0
- package/src/config.ts +277 -0
- package/src/conventions.ts +118 -0
- package/src/criteria.ts +106 -0
- package/src/frontier.ts +36 -0
- package/src/guards.ts +143 -0
- package/src/handoff.ts +82 -0
- package/src/host.ts +116 -0
- package/src/init.ts +405 -0
- package/src/labels.ts +42 -0
- package/src/landing.ts +75 -0
- package/src/lifecycle.ts +34 -0
- package/src/lock.ts +215 -0
- package/src/note-schema.ts +58 -0
- package/src/notes.ts +433 -0
- package/src/operator-skill.ts +24 -0
- package/src/orchestrator.ts +1816 -0
- package/src/ports/agent-runner.ts +105 -0
- package/src/ports/tracker.ts +334 -0
- package/src/ports/workspace.ts +422 -0
- package/src/progress.ts +231 -0
- package/src/prompts.ts +288 -0
- package/src/readiness.ts +256 -0
- package/src/remove.ts +732 -0
- package/src/resume.ts +145 -0
- package/src/run-log.ts +85 -0
- package/src/run.ts +331 -0
- package/src/self-hosting.ts +33 -0
- package/src/stage-guard.ts +32 -0
- package/src/staleness.ts +101 -0
- package/src/start.ts +284 -0
- package/src/startup.ts +34 -0
- package/src/stop.ts +178 -0
- package/src/stranded.ts +136 -0
- package/src/templates.ts +596 -0
- package/src/title.ts +97 -0
- package/src/verdict.ts +88 -0
- package/src/version-number.ts +67 -0
- package/src/version-pr.ts +103 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { dirname } from "node:path";
|
|
2
|
+
import { execOrThrow } from "./exec.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The main checkout, even when the command was started from inside one of the
|
|
6
|
+
* pipeline's own worktrees.
|
|
7
|
+
*
|
|
8
|
+
* `--show-toplevel` would answer with the worktree. The Run lock, `.worktrees/`
|
|
9
|
+
* and the run logs all have to land in one place per repo rather than one place
|
|
10
|
+
* per worktree, or two Runs started from different directories of the same
|
|
11
|
+
* clone would never see each other.
|
|
12
|
+
*/
|
|
13
|
+
export async function findRepoRoot(cwd?: string): Promise<string> {
|
|
14
|
+
const { stdout } = await execOrThrow(
|
|
15
|
+
"git",
|
|
16
|
+
["rev-parse", "--path-format=absolute", "--git-common-dir"],
|
|
17
|
+
cwd === undefined ? {} : { cwd },
|
|
18
|
+
);
|
|
19
|
+
return dirname(stdout.trim());
|
|
20
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { exec } from "./exec.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Which Version this copy of the pipeline is (ADR-0007).
|
|
8
|
+
*
|
|
9
|
+
* Computed once, in the CLI, and handed to the Run and to `init` the way the
|
|
10
|
+
* run id is. Nothing downstream asks again: every line one Run stamps — its
|
|
11
|
+
* summary, each Progress comment, each State file, the file beside its
|
|
12
|
+
* transcripts — has to say the same thing, and the only way to promise that is
|
|
13
|
+
* to read it once.
|
|
14
|
+
*
|
|
15
|
+
* No port describes this, and none should: a port is how a Run reaches a
|
|
16
|
+
* Target, and this reads the pipeline's own package and the git directory it
|
|
17
|
+
* was started from. That is what {@link import("./repo-root.js").findRepoRoot}
|
|
18
|
+
* already is, and it lives here for the same reason — the modules that spawn a
|
|
19
|
+
* process are the adapters, whoever they are asking about.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** The package root: the directory this package's `package.json` sits in. */
|
|
23
|
+
export const PACKAGE_ROOT = fileURLToPath(new URL("../..", import.meta.url));
|
|
24
|
+
|
|
25
|
+
/** What a copy with no number to read calls itself, rather than guessing one. */
|
|
26
|
+
const UNKNOWN = "unknown";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The Version, as everything this Run writes will report it.
|
|
30
|
+
*
|
|
31
|
+
* An installed copy is its number and nothing else, because a machine installs
|
|
32
|
+
* a tag: two machines that say `0.4.0` run the same code. A development
|
|
33
|
+
* checkout runs whatever commit it has, so it adds that commit in semver's
|
|
34
|
+
* build-metadata position and a `dirty` mark when the tree has uncommitted
|
|
35
|
+
* changes — `0.4.0`, `0.4.0+331d79c`, `0.4.0+331d79c.dirty`.
|
|
36
|
+
*/
|
|
37
|
+
export async function pipelineVersion(packageRoot: string = PACKAGE_ROOT): Promise<string> {
|
|
38
|
+
const number = packageNumber(packageRoot);
|
|
39
|
+
const commit = await checkoutCommit(packageRoot);
|
|
40
|
+
return commit === undefined ? number : `${number}+${commit}`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The pipeline's own repository as `owner/name`, from the `repository` field of
|
|
45
|
+
* its package, and undefined where the package names none or names one this
|
|
46
|
+
* cannot read.
|
|
47
|
+
*
|
|
48
|
+
* The one thing a Run has to know to ask whether a newer Version is out. It is
|
|
49
|
+
* read from the package rather than written down here for the same reason the
|
|
50
|
+
* number is: an installed copy and a checkout answer the same way, and a fork
|
|
51
|
+
* asks about itself (ADR-0007).
|
|
52
|
+
*/
|
|
53
|
+
export function pipelineRepository(packageRoot: string = PACKAGE_ROOT): string | undefined {
|
|
54
|
+
const field = packageField(packageRoot, "repository");
|
|
55
|
+
const url =
|
|
56
|
+
typeof field === "string"
|
|
57
|
+
? field
|
|
58
|
+
: field !== null && typeof field === "object" && "url" in field
|
|
59
|
+
? field.url
|
|
60
|
+
: undefined;
|
|
61
|
+
if (typeof url !== "string") return undefined;
|
|
62
|
+
|
|
63
|
+
// Every spelling npm takes for a GitHub repository: `owner/name`,
|
|
64
|
+
// `github:owner/name`, and the git URL `npm init` writes.
|
|
65
|
+
const match = /(?:github\.com[/:]|^(?:github:)?)([\w.-]+\/[\w.-]+?)(?:\.git)?$/.exec(url);
|
|
66
|
+
return match?.[1];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The number in `package.json`, which is the whole of an installed Version. */
|
|
70
|
+
function packageNumber(packageRoot: string): string {
|
|
71
|
+
const version = packageField(packageRoot, "version");
|
|
72
|
+
return typeof version === "string" && version !== "" ? version : UNKNOWN;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One field of the package, and undefined where the package cannot be read at all. */
|
|
76
|
+
function packageField(packageRoot: string, field: string): unknown {
|
|
77
|
+
let parsed: unknown;
|
|
78
|
+
try {
|
|
79
|
+
parsed = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
|
|
80
|
+
} catch {
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
return parsed !== null && typeof parsed === "object" && field in parsed
|
|
84
|
+
? (parsed as Record<string, unknown>)[field]
|
|
85
|
+
: undefined;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The commit a development checkout runs, with a `dirty` mark where the tree
|
|
90
|
+
* has uncommitted changes. Undefined for an installed copy, and for a checkout
|
|
91
|
+
* git could not be asked about.
|
|
92
|
+
*
|
|
93
|
+
* Nothing is reported on a guess: a checkout whose status could not be read
|
|
94
|
+
* gets no commit at all, because a transcript naming a commit the code did not
|
|
95
|
+
* match is worse than one naming none.
|
|
96
|
+
*/
|
|
97
|
+
async function checkoutCommit(packageRoot: string): Promise<string | undefined> {
|
|
98
|
+
// A package root that is a git repository is a development checkout, which a
|
|
99
|
+
// global install never is. `.git` is a directory in a clone and a file in a
|
|
100
|
+
// worktree, and its presence is the whole question.
|
|
101
|
+
if (!existsSync(join(packageRoot, ".git"))) return undefined;
|
|
102
|
+
|
|
103
|
+
const commit = await git(packageRoot, ["rev-parse", "--short", "HEAD"]);
|
|
104
|
+
if (commit === undefined || commit === "") return undefined;
|
|
105
|
+
const status = await git(packageRoot, ["status", "--porcelain"]);
|
|
106
|
+
if (status === undefined) return undefined;
|
|
107
|
+
return status === "" ? commit : `${commit}.dirty`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** What git said, or undefined where it failed or could not be run at all. */
|
|
111
|
+
async function git(cwd: string, args: string[]): Promise<string | undefined> {
|
|
112
|
+
try {
|
|
113
|
+
const { exitCode, stdout } = await exec("git", args, { cwd });
|
|
114
|
+
return exitCode === 0 ? stdout.trim() : undefined;
|
|
115
|
+
} catch {
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Config } from "./config.js";
|
|
2
|
+
import type { Tracker } from "./ports/tracker.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The branch a Run works against: the one it branches Tickets from, rebases
|
|
6
|
+
* them onto, targets their pull requests at, and pulls the main checkout to
|
|
7
|
+
* once they merge.
|
|
8
|
+
*
|
|
9
|
+
* The Target's default branch on GitHub, so a repository on `master` needs no
|
|
10
|
+
* config file at all; a `baseBranch` in the config file wins, for the repo
|
|
11
|
+
* whose merges go somewhere other than where GitHub points `HEAD`.
|
|
12
|
+
*
|
|
13
|
+
* Asked once at the start of a Run and carried from there: it is a remote
|
|
14
|
+
* round-trip, and every Ticket of a Run merges into the same branch.
|
|
15
|
+
*/
|
|
16
|
+
export async function resolveBaseBranch(
|
|
17
|
+
tracker: Tracker,
|
|
18
|
+
config: Pick<Config, "baseBranch">,
|
|
19
|
+
): Promise<string> {
|
|
20
|
+
return config.baseBranch ?? (await tracker.defaultBranch());
|
|
21
|
+
}
|
package/src/branch.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
|
|
3
|
+
const MAX_SLUG_LENGTH = 40;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The Ticket title as a branch-safe slug: lowercase kebab-case, cut to
|
|
7
|
+
* {@link MAX_SLUG_LENGTH} at a word boundary so the name stays readable.
|
|
8
|
+
*/
|
|
9
|
+
export function slug(title: string): string {
|
|
10
|
+
const kebab = title
|
|
11
|
+
.toLowerCase()
|
|
12
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
13
|
+
.replace(/^-+|-+$/g, "");
|
|
14
|
+
if (kebab === "") return "ticket";
|
|
15
|
+
if (kebab.length <= MAX_SLUG_LENGTH) return kebab;
|
|
16
|
+
|
|
17
|
+
const cut = kebab.slice(0, MAX_SLUG_LENGTH);
|
|
18
|
+
const lastDash = cut.lastIndexOf("-");
|
|
19
|
+
return (lastDash > 0 ? cut.slice(0, lastDash) : cut).replace(/-+$/, "");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Where every branch a Run creates lives, and nothing else branches. */
|
|
23
|
+
export const AGENT_BRANCH_PREFIX = "agent/";
|
|
24
|
+
|
|
25
|
+
/** `agent/<n>-<slug>`, the name reserved for pipeline Runs. */
|
|
26
|
+
export function branchName(ticket: number, title: string): string {
|
|
27
|
+
return `${AGENT_BRANCH_PREFIX}${ticket}-${slug(title)}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The gitignored worktree a Ticket is implemented in. */
|
|
31
|
+
export function worktreePath(repoRoot: string, ticket: number): string {
|
|
32
|
+
return join(repoRoot, ".worktrees", `ticket-${ticket}`);
|
|
33
|
+
}
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createInterface } from "node:readline/promises";
|
|
2
|
+
import { ClaudeAgentRunner } from "./adapters/claude-agent-runner.js";
|
|
3
|
+
import { GhTracker } from "./adapters/gh-tracker.js";
|
|
4
|
+
import { GitWorkspace } from "./adapters/git-workspace.js";
|
|
5
|
+
import { findRepoRoot } from "./adapters/repo-root.js";
|
|
6
|
+
import { pipelineRepository, pipelineVersion } from "./adapters/version.js";
|
|
7
|
+
import { USAGE, readCommandLine } from "./command-line.js";
|
|
8
|
+
import { ConfigError, loadConfig } from "./config.js";
|
|
9
|
+
import { initTarget } from "./init.js";
|
|
10
|
+
import { removeTarget } from "./remove.js";
|
|
11
|
+
import { newRunId } from "./run-log.js";
|
|
12
|
+
import { nestedRunRefusal } from "./stage-guard.js";
|
|
13
|
+
import { startRun } from "./start.js";
|
|
14
|
+
import { requestStop } from "./stop.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Exit codes: 1 at least one hand-off, 2 nothing was taken at all — the Run
|
|
18
|
+
* never started, or it was given Ticket numbers and took none of them — and 0
|
|
19
|
+
* otherwise. `init` reads them as its own: 0 every reported item passed, 1 one of
|
|
20
|
+
* them is the human's to put right, 2 a Stage's shell was refused. `stop` reads
|
|
21
|
+
* 0 as a Stop sent and 2 as no Run there was anything to ask. `remove` reads 0
|
|
22
|
+
* as everything gone or nothing to remove, 1 as a removal that failed, and 2 as
|
|
23
|
+
* refused before anything changed.
|
|
24
|
+
*/
|
|
25
|
+
async function main(argv: string[]): Promise<number> {
|
|
26
|
+
// First, before the repo, the config, `gh` or even `--help`: a Stage's shell
|
|
27
|
+
// may not start a Run of the pipeline it is working on.
|
|
28
|
+
const nested = nestedRunRefusal(process.env);
|
|
29
|
+
if (nested !== undefined) {
|
|
30
|
+
console.error(nested);
|
|
31
|
+
return 2;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const commandLine = readCommandLine(argv);
|
|
35
|
+
if (commandLine.kind === "refused") {
|
|
36
|
+
console.error(commandLine.message);
|
|
37
|
+
return 2;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Resolved once, here, and handed to everything that stamps it the way the
|
|
41
|
+
// run id is: a Run whose summary, comments, State files and transcripts all
|
|
42
|
+
// read it separately could report four different things (ADR-0007).
|
|
43
|
+
const version = await pipelineVersion();
|
|
44
|
+
// The repository a newer Version would be published on, read from the same
|
|
45
|
+
// package the number came from, so a fork asks about itself (ADR-0007).
|
|
46
|
+
const repository = pipelineRepository();
|
|
47
|
+
if (commandLine.kind === "version") {
|
|
48
|
+
console.log(version);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (commandLine.kind === "usage") {
|
|
53
|
+
console.log(USAGE);
|
|
54
|
+
return commandLine.exitCode;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Before the config and the Target's readiness, which a Stop needs none of:
|
|
58
|
+
// a Run is already running, so whatever they would have refused it over was
|
|
59
|
+
// answered when it started.
|
|
60
|
+
if (commandLine.kind === "stop") {
|
|
61
|
+
const root = await findRepoRoot();
|
|
62
|
+
return await requestStop({ workspace: new GitWorkspace(root) });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (commandLine.kind === "init") {
|
|
66
|
+
const root = await findRepoRoot();
|
|
67
|
+
// No Run lock, because no Ticket is claimed, and no startup refusal: the
|
|
68
|
+
// missing Checks it would refuse over are one of the things `init` reports.
|
|
69
|
+
return initTarget({
|
|
70
|
+
repoRoot: root,
|
|
71
|
+
version,
|
|
72
|
+
repository,
|
|
73
|
+
config: loadConfig(root, version),
|
|
74
|
+
tracker: new GhTracker({ cwd: root }),
|
|
75
|
+
runner: new ClaudeAgentRunner(),
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (commandLine.kind === "remove") {
|
|
80
|
+
const root = await findRepoRoot();
|
|
81
|
+
return removeTarget({
|
|
82
|
+
repoRoot: root,
|
|
83
|
+
version,
|
|
84
|
+
repository,
|
|
85
|
+
config: loadConfig(root, version),
|
|
86
|
+
tracker: new GhTracker({ cwd: root }),
|
|
87
|
+
workspace: new GitWorkspace(root),
|
|
88
|
+
yes: commandLine.yes,
|
|
89
|
+
// Asked of stdin, which is where the answer would come from.
|
|
90
|
+
interactive: process.stdin.isTTY === true,
|
|
91
|
+
ask,
|
|
92
|
+
runId: newRunId(),
|
|
93
|
+
command: ["ticket-runner", ...argv].join(" "),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const repoRoot = await findRepoRoot();
|
|
98
|
+
const config = loadConfig(repoRoot, version);
|
|
99
|
+
return startRun({
|
|
100
|
+
work: commandLine.work,
|
|
101
|
+
repoRoot,
|
|
102
|
+
config,
|
|
103
|
+
// The one setting an adapter holds rather than being handed per call: the
|
|
104
|
+
// CI wait's grace is the tracker's own, so the Target's minutes reach it here.
|
|
105
|
+
tracker: new GhTracker({
|
|
106
|
+
cwd: repoRoot,
|
|
107
|
+
checksGraceMs: config.ciGraceMinutes * 60_000,
|
|
108
|
+
}),
|
|
109
|
+
runner: new ClaudeAgentRunner(),
|
|
110
|
+
workspace: new GitWorkspace(repoRoot),
|
|
111
|
+
runId: newRunId(),
|
|
112
|
+
version,
|
|
113
|
+
repository,
|
|
114
|
+
// Every argument, `--lanes` included, so whoever meets the lock sees how
|
|
115
|
+
// the Run was started.
|
|
116
|
+
command: ["ticket-runner", ...argv].join(" "),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Put a question to the human at the terminal, and give back what they typed. */
|
|
121
|
+
async function ask(question: string): Promise<string> {
|
|
122
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout });
|
|
123
|
+
try {
|
|
124
|
+
return await terminal.question(question);
|
|
125
|
+
} finally {
|
|
126
|
+
terminal.close();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
132
|
+
} catch (error) {
|
|
133
|
+
console.error(error instanceof ConfigError ? error.message : error);
|
|
134
|
+
process.exitCode = 2;
|
|
135
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { parseArgs } from "node:util";
|
|
2
|
+
import type { Work } from "./start.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* What the arguments ask for, read before anything is looked at: no repository,
|
|
6
|
+
* no config, no `gh`.
|
|
7
|
+
*
|
|
8
|
+
* Kept out of the CLI so it can be tested — the CLI runs the moment it is
|
|
9
|
+
* imported, so nothing it says can be asked of it — and so the CLI is left with
|
|
10
|
+
* what it does about the answer.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const USAGE = `ticket-runner — humans plan, the pipeline executes.
|
|
14
|
+
|
|
15
|
+
It works in the GitHub repository you start it in, on the open issues
|
|
16
|
+
labelled \`ready-for-agent\`. For each one it has a Claude Code session
|
|
17
|
+
implement the issue, runs the repository's tests itself, has a second
|
|
18
|
+
session grade the work against the issue's acceptance criteria, opens a
|
|
19
|
+
pull request, and squash-merges it once CI is green. An issue it cannot
|
|
20
|
+
finish is left to a human, with a draft pull request and a comment.
|
|
21
|
+
|
|
22
|
+
The repository has to be set up for this first: \`init\` puts in place what
|
|
23
|
+
it can and reports the rest, which is yours to put right.
|
|
24
|
+
|
|
25
|
+
Usage:
|
|
26
|
+
ticket-runner init Set this repository up for the pipeline.
|
|
27
|
+
ticket-runner run [<n>...] Work through every issue that is ready, or
|
|
28
|
+
only the issues numbered <n>. The numbers say
|
|
29
|
+
which issues to take, not the order to take
|
|
30
|
+
them in: they are taken lowest number first.
|
|
31
|
+
ticket-runner stop Tell the run in progress to take no more.
|
|
32
|
+
ticket-runner remove Take the pipeline out of this repository.
|
|
33
|
+
|
|
34
|
+
Options:
|
|
35
|
+
--lanes <n> With \`run\`: work on up to <n> issues at once,
|
|
36
|
+
whatever \`lanes\` in ticket-runner.json says.
|
|
37
|
+
-y, --yes With \`remove\`: go ahead without asking.
|
|
38
|
+
-h, --help Show this message.
|
|
39
|
+
-v, --version Show which version this pipeline is.`;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* What the command line comes to.
|
|
43
|
+
*
|
|
44
|
+
* `usage` goes to stdout, with the exit code it earned: 0 when it was asked
|
|
45
|
+
* for, 2 when there was nothing else to say. `refused` goes to stderr and exits
|
|
46
|
+
* 2, like every other invocation that never started.
|
|
47
|
+
*/
|
|
48
|
+
export type CommandLine =
|
|
49
|
+
| { kind: "usage"; exitCode: 0 | 2 }
|
|
50
|
+
| { kind: "version" }
|
|
51
|
+
| { kind: "refused"; message: string }
|
|
52
|
+
| { kind: "init" }
|
|
53
|
+
| { kind: "stop" }
|
|
54
|
+
| { kind: "remove"; yes: boolean }
|
|
55
|
+
| { kind: "work"; work: Work };
|
|
56
|
+
|
|
57
|
+
/** Read the arguments after the command's own name. */
|
|
58
|
+
export function readCommandLine(argv: string[]): CommandLine {
|
|
59
|
+
const parsed = parseCommandLine(argv);
|
|
60
|
+
if (typeof parsed === "string") return refused(parsed);
|
|
61
|
+
const { positionals, values } = parsed;
|
|
62
|
+
|
|
63
|
+
if (values.version) return { kind: "version" };
|
|
64
|
+
if (values.help || positionals.length === 0) {
|
|
65
|
+
return { kind: "usage", exitCode: values.help ? 0 : 2 };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const [command, ...rest] = positionals;
|
|
69
|
+
if (!isCommand(command)) return refused(`Unknown command \`${command}\`.`);
|
|
70
|
+
|
|
71
|
+
// Refused rather than ignored everywhere but `run`: `init`, `stop` and
|
|
72
|
+
// `remove` start nothing, so a count given to any of them is a mistake the
|
|
73
|
+
// human should hear about.
|
|
74
|
+
if (values.lanes !== undefined && command !== "run") {
|
|
75
|
+
return refused("`--lanes` is for `run` only, which has a Frontier to share out.");
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// The same for `--yes` everywhere but `remove`, the one command that asks
|
|
79
|
+
// before it acts: given to any other, it answers a question nobody asks.
|
|
80
|
+
if (values.yes === true && command !== "remove") {
|
|
81
|
+
return refused("`--yes` is for `remove` only, the one command that asks before it acts.");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (command === "init" || command === "stop") return { kind: command };
|
|
85
|
+
if (command === "remove") return { kind: "remove", yes: values.yes === true };
|
|
86
|
+
|
|
87
|
+
const tickets = ticketNumbers(rest);
|
|
88
|
+
if (typeof tickets === "string") {
|
|
89
|
+
return refused(
|
|
90
|
+
`\`run\` takes Ticket numbers, each a whole number of one or more, not \`${tickets}\`.`,
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const lanes = values.lanes === undefined ? undefined : wholeNumber(values.lanes);
|
|
95
|
+
if (values.lanes !== undefined && lanes === undefined) {
|
|
96
|
+
return refused(`\`--lanes\` needs a whole number of one or more, not \`${values.lanes}\`.`);
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
kind: "work",
|
|
100
|
+
work: {
|
|
101
|
+
command: "run",
|
|
102
|
+
...(lanes === undefined ? {} : { lanes }),
|
|
103
|
+
...(tickets.length === 0 ? {} : { tickets }),
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The commands this CLI takes, in the order the usage lists them. */
|
|
109
|
+
const COMMANDS = ["init", "run", "stop", "remove"] as const;
|
|
110
|
+
|
|
111
|
+
function isCommand(given: string | undefined): given is (typeof COMMANDS)[number] {
|
|
112
|
+
return (COMMANDS as readonly (string | undefined)[]).includes(given);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The Tickets the numbers after `run` name, ascending and each once, or the
|
|
117
|
+
* first argument that is not one.
|
|
118
|
+
*
|
|
119
|
+
* Ascending because a Run takes the Frontier lowest number first and a
|
|
120
|
+
* narrowed Run is no different: the numbers say which Tickets, and blockers say
|
|
121
|
+
* which goes before which. `#12` is read as `12`, since that is how a human
|
|
122
|
+
* copies a Ticket's number off GitHub.
|
|
123
|
+
*/
|
|
124
|
+
function ticketNumbers(given: string[]): number[] | string {
|
|
125
|
+
const tickets = new Set<number>();
|
|
126
|
+
for (const argument of given) {
|
|
127
|
+
const ticket = wholeNumber(argument.startsWith("#") ? argument.slice(1) : argument);
|
|
128
|
+
if (ticket === undefined) return argument;
|
|
129
|
+
tickets.add(ticket);
|
|
130
|
+
}
|
|
131
|
+
return [...tickets].sort((first, second) => first - second);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* `given` as a whole number of one or more, or nothing where it is not one:
|
|
136
|
+
* what a Lane count and a Ticket number both have to be.
|
|
137
|
+
*/
|
|
138
|
+
function wholeNumber(given: string): number | undefined {
|
|
139
|
+
if (!/^\d+$/.test(given)) return undefined;
|
|
140
|
+
const number = Number(given);
|
|
141
|
+
return Number.isSafeInteger(number) && number > 0 ? number : undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function refused(complaint: string): CommandLine {
|
|
145
|
+
return { kind: "refused", message: `${complaint}\n\n${USAGE}` };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** What `parseArgs` makes of the arguments: the options, and the rest. */
|
|
149
|
+
interface ParsedArgs {
|
|
150
|
+
positionals: string[];
|
|
151
|
+
values: { help?: boolean; version?: boolean; lanes?: string; yes?: boolean };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The arguments, or Node's complaint about them when they name an option this
|
|
156
|
+
* CLI does not take.
|
|
157
|
+
*
|
|
158
|
+
* `parseArgs` throws over one, and an uncaught throw reaches a terminal as a
|
|
159
|
+
* stack trace through `node:internal` that says nothing the usage does not say
|
|
160
|
+
* better. An unknown option is the mistake an unknown command is, made one
|
|
161
|
+
* character earlier, so it is answered the same way and costs the same exit
|
|
162
|
+
* code.
|
|
163
|
+
*/
|
|
164
|
+
function parseCommandLine(argv: string[]): ParsedArgs | string {
|
|
165
|
+
try {
|
|
166
|
+
return parseArgs({
|
|
167
|
+
args: argv,
|
|
168
|
+
options: {
|
|
169
|
+
help: { type: "boolean", short: "h" },
|
|
170
|
+
version: { type: "boolean", short: "v" },
|
|
171
|
+
lanes: { type: "string" },
|
|
172
|
+
yes: { type: "boolean", short: "y" },
|
|
173
|
+
},
|
|
174
|
+
allowPositionals: true,
|
|
175
|
+
});
|
|
176
|
+
} catch (error) {
|
|
177
|
+
return argumentComplaint(error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Node's own sentence about the argument, and only the first: it follows the
|
|
183
|
+
* complaint with advice about passing a positional that starts with a `-`,
|
|
184
|
+
* which no command of this CLI takes.
|
|
185
|
+
*/
|
|
186
|
+
function argumentComplaint(error: unknown): string {
|
|
187
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
188
|
+
const [sentence = message] = message.split(". ");
|
|
189
|
+
return sentence.endsWith(".") ? sentence : `${sentence}.`;
|
|
190
|
+
}
|