@williamthorsen/toolbelt.git 0.0.0 → 0.3.1

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 ADDED
@@ -0,0 +1,52 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ ## 0.3.1 — 2026-09-06
6
+
7
+ ### Bug fixes
8
+
9
+ - Point every package bin at a committed wrapper (#296)
10
+
11
+ - Points the `tb-git`, `tb-jira`, and `tb-secret` commands at committed wrappers under each package's `bin/`, so the target exists when the package manager links the command rather than only after a build.
12
+
13
+ - Fix piped-stdin reads and unhandled EPIPE in the CLIs (#301)
14
+
15
+ - Fixes an issue where `tb-secret set` and `tb-jira auth set` failed with `EAGAIN: resource temporarily unavailable` when the producer of a piped credential delayed its first byte, as `tb-secret get`, `op read`, and `gh auth token` all do.
16
+ - Stops `tb-secret`, `tb-jira`, and `tb-git` from crashing with an unhandled `EPIPE` when the reader on their stdout or stderr exits first, so that `tb-secret get | head -1` ends quietly, as a program that ignores `SIGPIPE` does.
17
+
18
+ ### Documentation
19
+
20
+ - Repair reduced object relatives in the READMEs and AGENTS.md (#263)
21
+
22
+ Repairs the reduced object relative in `AGENTS.md`, the root `README.md`, and the package READMEs.
23
+
24
+ - Repair the repository's prose and record every rejection's ground (#290)
25
+
26
+ Applies one repo-wide `revise-prose` sweep across the repository's READMEs, `AGENTS.md`, source comments, doc descriptions, and test names.
27
+
28
+ ## 0.3.0 — 2026-08-30
29
+
30
+ ### Features
31
+
32
+ - Add a tb-git CLI for branch-number and ticket-ref (#250)
33
+
34
+ Adds a `tb-git` command to `@williamthorsen/toolbelt.git`, enabling the use of `deriveBranchNumber` and `findBranchTicketRef` on the command line. `tb-git branch-number` prints the number derived from a branch name; `tb-git ticket-ref` prints the ID of the ticket encoded by the name, or the whole ref when the `--json` option is used. Both take an optional branch name and otherwise use the checked-out branch.
35
+
36
+ ## 0.2.0 — 2026-08-28
37
+
38
+ ### Features
39
+
40
+ - Add findBranchTicketRef and deriveBranchNumber to toolbelt.git (#239)
41
+
42
+ Adds `findBranchTicketRef` and `deriveBranchNumber` to `@williamthorsen/toolbelt.git` at the candidate tier.
43
+
44
+ `findBranchTicketRef` extracts the ticket ID encoded in a branch name. `deriveBranchNumber` relies on it to give every branch a stable number: the ticket's if the branch name includes one, and otherwise a `hashString` digest of the name. The number is bounded by the caller-specified range.
45
+
46
+ ### Internal
47
+
48
+ - Scaffold toolbelt.git for git utilities (#235)
49
+
50
+ Adds `packages/git`, an empty `@williamthorsen/toolbelt.git` at version `0.1.0` with its four maturity tiers in place.
51
+
52
+ <!-- Generated by release-kit. Do not edit this file. Use .meta/changelog-overrides.json to override entries. -->
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 William Thorsen
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
6
+
7
+ The software is provided "as is" and the author disclaims all warranties with regard to this software including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, direct, indirect, or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software.
package/README.md CHANGED
@@ -1 +1,170 @@
1
- Placeholder for `@williamthorsen/toolbelt.git` — awaiting first release.
1
+ # @williamthorsen/toolbelt.git
2
+
3
+ Utilities for working with git.
4
+
5
+ <!-- section:release-notes -->
6
+ ## Release notes — v0.3.1 (2026-09-06)
7
+
8
+ ### Bug fixes
9
+
10
+ - Point every package bin at a committed wrapper (#296)
11
+
12
+ - Points the `tb-git`, `tb-jira`, and `tb-secret` commands at committed wrappers under each package's `bin/`, so the target exists when the package manager links the command rather than only after a build.
13
+
14
+ - Fix piped-stdin reads and unhandled EPIPE in the CLIs (#301)
15
+
16
+ - Fixes an issue where `tb-secret set` and `tb-jira auth set` failed with `EAGAIN: resource temporarily unavailable` when the producer of a piped credential delayed its first byte, as `tb-secret get`, `op read`, and `gh auth token` all do.
17
+ - Stops `tb-secret`, `tb-jira`, and `tb-git` from crashing with an unhandled `EPIPE` when the reader on their stdout or stderr exits first, so that `tb-secret get | head -1` ends quietly, as a program that ignores `SIGPIPE` does.
18
+ <!-- /section:release-notes -->
19
+
20
+ ## Installation
21
+
22
+ ```sh
23
+ pnpm add @williamthorsen/toolbelt.git
24
+ ```
25
+
26
+ Requires Node.js 24 or later.
27
+
28
+ ## CLI
29
+
30
+ The package ships a `tb-git` command exposing the same functions to a shell caller.
31
+
32
+ ```sh
33
+ pnpm add --global @williamthorsen/toolbelt.git # puts tb-git on PATH
34
+ npx @williamthorsen/toolbelt.git branch-number # or run it without installing
35
+ ```
36
+
37
+ The short `npx` form works because the package declares exactly one bin, which npm falls back to whatever its name. Were a second bin added, the invocation would become `npx --package @williamthorsen/toolbelt.git tb-git ...`.
38
+
39
+ `tb-git --help`, each subcommand's `--help`, and `tb-git --version` report the surface and the installed version.
40
+
41
+ ### `tb-git branch-number [<branch>] [options]`
42
+
43
+ Prints [`deriveBranchNumber`](#derivebranchnumber)'s result.
44
+
45
+ | Option | Effect |
46
+ | ------------ | ----------------------------------------------- |
47
+ | `--key K` | The project's ticket key, matched in any casing |
48
+ | `--max N` | Upper bound, inclusive (default 4294967295) |
49
+ | `--min N` | Lower bound, inclusive (default 0) |
50
+ | `--offset N` | Rotate the result within the bounds |
51
+
52
+ ```sh
53
+ tb-git branch-number 232_add-widget --min 3000 --max 3999
54
+ # 3232
55
+ ```
56
+
57
+ A negative offset takes the `=` form, `--offset=-3`: A bare `-3` reads as an option rather than as the value.
58
+
59
+ ### `tb-git ticket-ref [<branch>] [options]`
60
+
61
+ Prints [`findBranchTicketRef`](#findbranchticketref)'s `id`.
62
+
63
+ | Option | Effect |
64
+ | --------- | ----------------------------------------------- |
65
+ | `--json` | Print the whole ref on one line as JSON |
66
+ | `--key K` | The project's ticket key, matched in any casing |
67
+
68
+ ```sh
69
+ tb-git ticket-ref wt/MAC-22.1-add-widget
70
+ # MAC-22
71
+
72
+ tb-git ticket-ref wt/MAC-22.1-add-widget --json
73
+ # {"id":"MAC-22","key":"MAC","number":22,"revisit":1}
74
+ ```
75
+
76
+ ### The branch argument
77
+
78
+ With no `<branch>`, both subcommands resolve the checked-out branch with `git branch --show-current`, which reports a worktree's own branch. A directory that is not a repository, an absent git, and a detached HEAD each fail rather than falling back to a derived value. An empty argument is an error too, so `tb-git ticket-ref "$BRANCH"` with `BRANCH` unset fails instead of quietly using the current branch.
79
+
80
+ ### Exit codes
81
+
82
+ | Code | Meaning |
83
+ | ---- | ----------------------------------------------------------------------- |
84
+ | `0` | A result was printed |
85
+ | `1` | `ticket-ref` found no ticket in the branch name; both streams are empty |
86
+ | `2` | Usage or validation error, with the message on stderr |
87
+
88
+ A bound, offset, or key rejected by the library exits `2` carrying the message that it raises. So does an empty option value, so `--min "$PORT_MIN"` with `PORT_MIN` unset fails instead of bounding at `0`.
89
+
90
+ ```sh
91
+ if ref=$(tb-git ticket-ref); then
92
+ echo "on ticket $ref"
93
+ fi
94
+ ```
95
+
96
+ ## `findBranchTicketRef`
97
+
98
+ ```ts
99
+ findBranchTicketRef(branch: string, options?: { key?: string }): BranchTicketRef | undefined;
100
+
101
+ interface BranchTicketRef {
102
+ readonly id: string;
103
+ readonly key?: string | undefined;
104
+ readonly number: number;
105
+ readonly revisit?: number | undefined;
106
+ }
107
+ ```
108
+
109
+ Finds the ticket encoded by a branch name, or `undefined` when it encodes none.
110
+
111
+ ```ts
112
+ import { findBranchTicketRef } from '@williamthorsen/toolbelt.git/candidate';
113
+
114
+ findBranchTicketRef('wt/MAC-22.1-add-widget');
115
+ // { id: 'MAC-22', key: 'MAC', number: 22, revisit: 1 }
116
+
117
+ findBranchTicketRef('232_add-widget');
118
+ // { id: '232', number: 232 }
119
+ ```
120
+
121
+ A ref must begin a segment. `/` and `_` both delimit one, so an author prefix and a worktree-safe spelling parse alike, and the leftmost segment carrying a ref wins. Anchoring to a segment is what keeps a kebab-case description from reading as a ticket: `feat/add-widget-2` encodes none, because `widget` follows a hyphen rather than a separator.
122
+
123
+ Two forms are recognized, each taking an optional `.N` revisit suffix. A **keyed** ref is a Jira-style key and number, the key matching Jira's own rule of a letter followed by letters and digits. A **bare-numeric** ref is the number alone. `id` and `key` are emitted uppercased, since a branch name may be lowercase but the ticket that it names is `MAC-22`.
124
+
125
+ By default a key must be uppercase, which is what Jira permits and the only property separating a real key from an ordinary word: without it, `feat-2` would read as ticket `FEAT-2`. Declaring the project's own key through `key` is both more permissive and more precise, since it then matches in any casing and is the only key that matches at all.
126
+
127
+ ```ts
128
+ findBranchTicketRef('mac-22/add-widget');
129
+ // undefined -- a lowercase key with none declared
130
+
131
+ findBranchTicketRef('mac-22/add-widget', { key: 'mac' });
132
+ // { id: 'MAC-22', key: 'MAC', number: 22 }
133
+
134
+ findBranchTicketRef('feat-2', { key: 'mac' });
135
+ // undefined -- `feat` is not the declared key
136
+ ```
137
+
138
+ The bare-numeric form stays active whether or not a key is declared. A `RangeError` names the fault when `key` is not a well-formed key, which would otherwise match nothing at all.
139
+
140
+ A trailing `-N` is not read as a sub-ID, being indistinguishable from a description: `232-3-column-layout` carries no revisit. Neither suffix affects `number`.
141
+
142
+ ## `deriveBranchNumber`
143
+
144
+ ```ts
145
+ deriveBranchNumber(branch: string, options?: { key?: string; max?: number; min?: number; offset?: number }): number;
146
+ ```
147
+
148
+ Derives a number from a branch name, for a port offset, a bucket, or any slot that must stay stable across checkouts of the same branch.
149
+
150
+ ```ts
151
+ import { deriveBranchNumber } from '@williamthorsen/toolbelt.git/candidate';
152
+
153
+ deriveBranchNumber('232_add-widget');
154
+ // 232
155
+
156
+ deriveBranchNumber('main');
157
+ // 663286764
158
+ ```
159
+
160
+ The number is the ticket's when the branch names one, and a [`hashString`](https://github.com/williamthorsen/toolbelt/tree/main/packages/strings#hashstring) digest of the whole name when it does not, so every branch yields something. `min`, `max`, and `offset` are `hashString`'s, and apply to both paths alike: The two land in one range, and `offset` stays a pure rotation.
161
+
162
+ ```ts
163
+ deriveBranchNumber('232_add-widget', { min: 3000, max: 3999 });
164
+ // 3232
165
+
166
+ deriveBranchNumber('refactor/tidy-imports', { min: 3000, max: 3999 });
167
+ // 3508
168
+ ```
169
+
170
+ A number that overruns the range wraps into it, so `deriveBranchNumber('1232', { max: 999 })` is `232`. `key` is passed through to `findBranchTicketRef`, and a bad `key`, bound, or offset raises the same `RangeError` whether or not the branch names a ticket.
package/bin/tb-git.js ADDED
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Imports only node builtins: a top-level import resolves before the gate below runs, so an unresolvable
4
+ // dependency would replace this file's build-first message with ERR_MODULE_NOT_FOUND.
5
+ import { existsSync } from 'node:fs';
6
+
7
+ // Thin wrapper so pnpm can link the bin at install time, before `dist/` exists. The real entry point loads
8
+ // at runtime from the build output.
9
+ const entryPoint = new URL('../dist/esm/bin/tb-git.js', import.meta.url);
10
+
11
+ // Gate on the entry file itself: Node raises ERR_MODULE_NOT_FOUND for any unresolved module in the graph,
12
+ // so keying the build-first message off the error code would also fire when the build is present and one
13
+ // of its imports is missing.
14
+ if (!existsSync(entryPoint)) {
15
+ process.stderr.write(
16
+ 'tb-git: build output not found. In a source checkout, run `nmr build`; otherwise reinstall the package.\n',
17
+ );
18
+ process.exit(1);
19
+ }
20
+
21
+ try {
22
+ await import(entryPoint.href);
23
+ } catch (error) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ process.stderr.write(`tb-git: failed to load: ${message}\n`);
26
+ process.exit(1);
27
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import { type BranchTicketRefOptions } from './findBranchTicketRef.js';
2
+ /**
3
+ * Derives a number from a branch name: the number of the ticket encoded by the name, or a hash of the name
4
+ * when it encodes none, so a branch always yields a stable number. `min` and `max` bound the result
5
+ * inclusively, and `offset` rotates it, wrapping at the bounds. Throws a RangeError on a malformed `key`,
6
+ * or on a bound or offset rejected by hashString.
7
+ *
8
+ * @category Git
9
+ * @experimental
10
+ * @stage candidate
11
+ */
12
+ export declare function deriveBranchNumber(branch: string, options?: DeriveBranchNumberOptions): number;
13
+ export interface DeriveBranchNumberOptions extends BranchTicketRefOptions {
14
+ readonly max?: number | undefined;
15
+ readonly min?: number | undefined;
16
+ readonly offset?: number | undefined;
17
+ }
@@ -0,0 +1,14 @@
1
+ import { hashString } from '@williamthorsen/toolbelt.strings/candidate';
2
+ import { findBranchTicketRef } from "./findBranchTicketRef.js";
3
+ const MAX_UINT32 = 0xffff_ffff;
4
+ export function deriveBranchNumber(branch, options = {}) {
5
+ const digest = hashString(branch, options);
6
+ const ref = findBranchTicketRef(branch, options);
7
+ return ref === undefined ? digest : wrapIntoRange(ref.number, options);
8
+ }
9
+ function wrapIntoRange(value, options) {
10
+ const { max = MAX_UINT32, min = 0, offset = 0 } = options;
11
+ const size = max - min + 1;
12
+ const shift = ((offset % size) + size) % size;
13
+ return min + ((value + shift) % size);
14
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Finds the ticket ref encoded by a branch name, or `undefined` when it encodes none. A ref must begin a
3
+ * `/`- or `_`-delimited segment, and the leftmost segment containing one wins. A key must be uppercase,
4
+ * unless `key` names the project's own key, which then matches in any casing and is the only key that
5
+ * does; a bare-numeric ref is found either way. Throws a RangeError if `key` is not a well-formed key.
6
+ *
7
+ * @category Git
8
+ * @experimental
9
+ * @stage candidate
10
+ */
11
+ export declare function findBranchTicketRef(branch: string, options?: BranchTicketRefOptions): BranchTicketRef | undefined;
12
+ export interface BranchTicketRef {
13
+ /** The canonical ID: an uppercased key and number (`MAC-22`), or the number alone for a bare-numeric ref. */
14
+ readonly id: string;
15
+ /** The uppercased project key, absent for a bare-numeric ref. */
16
+ readonly key?: string | undefined;
17
+ readonly number: number;
18
+ /** The revisit ordinal, present when the ref has a `.N` suffix. */
19
+ readonly revisit?: number | undefined;
20
+ }
21
+ export interface BranchTicketRefOptions {
22
+ /** The project's own key, which then matches in any casing and displaces the uppercase-key rule. */
23
+ readonly key?: string | undefined;
24
+ }
@@ -0,0 +1,39 @@
1
+ const SEGMENT_SEPARATOR = /[/_]/;
2
+ const REF_PATTERN = /^(?:(?<key>[A-Za-z][A-Za-z0-9]+)-)?(?<number>[0-9]+)(?:\.(?<revisit>[0-9]+))?/;
3
+ const KEY_PATTERN = /^[A-Za-z][A-Za-z0-9]+$/;
4
+ export function findBranchTicketRef(branch, options = {}) {
5
+ const { key: declaredKey } = options;
6
+ if (declaredKey !== undefined && !KEY_PATTERN.test(declaredKey)) {
7
+ const received = `Received ${JSON.stringify(declaredKey)}.`;
8
+ throw new RangeError(`Invalid key: A key must be a letter followed by letters or digits. ${received}`);
9
+ }
10
+ for (const segment of branch.split(SEGMENT_SEPARATOR)) {
11
+ const groups = REF_PATTERN.exec(segment)?.groups;
12
+ if (groups === undefined) {
13
+ continue;
14
+ }
15
+ const { key, number, revisit } = groups;
16
+ if (number !== undefined && isAcceptableKey(key, declaredKey)) {
17
+ return composeRef(key, number, revisit);
18
+ }
19
+ }
20
+ return undefined;
21
+ }
22
+ function composeRef(key, number, revisit) {
23
+ const canonicalKey = key?.toUpperCase();
24
+ return {
25
+ id: canonicalKey === undefined ? number : `${canonicalKey}-${number}`,
26
+ ...(canonicalKey !== undefined && { key: canonicalKey }),
27
+ number: Number(number),
28
+ ...(revisit !== undefined && { revisit: Number(revisit) }),
29
+ };
30
+ }
31
+ function isAcceptableKey(key, declaredKey) {
32
+ if (key === undefined) {
33
+ return true;
34
+ }
35
+ if (declaredKey !== undefined) {
36
+ return key.toLowerCase() === declaredKey.toLowerCase();
37
+ }
38
+ return key === key.toUpperCase();
39
+ }
@@ -0,0 +1,2 @@
1
+ export { deriveBranchNumber, type DeriveBranchNumberOptions } from './deriveBranchNumber.js';
2
+ export { type BranchTicketRef, type BranchTicketRefOptions, findBranchTicketRef } from './findBranchTicketRef.js';
@@ -0,0 +1,2 @@
1
+ export { deriveBranchNumber } from "./deriveBranchNumber.js";
2
+ export { findBranchTicketRef } from "./findBranchTicketRef.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Finds the manifest of the package owning a directory, ascending to the first `package.json` declaring a
3
+ * `name`. One declaring none is a marker manifest, such as the `{"type": "commonjs"}` file left in `dist/`
4
+ * by a dual-format build, and the ascent passes over it, so the answer is the owning package rather than
5
+ * the nearest manifest. Throws where no ancestor declares a name.
6
+ *
7
+ * @internal
8
+ */
9
+ export declare function findOwningManifest(startDir: string): OwningManifest;
10
+ export interface OwningManifest {
11
+ readonly manifest: {
12
+ readonly version?: unknown;
13
+ };
14
+ readonly manifestPath: string;
15
+ }
@@ -0,0 +1,24 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ export function findOwningManifest(startDir) {
4
+ let dir = startDir;
5
+ for (;;) {
6
+ const manifestPath = path.join(dir, 'package.json');
7
+ if (fs.existsSync(manifestPath)) {
8
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
9
+ if (isNamedManifest(manifest))
10
+ return { manifest, manifestPath };
11
+ }
12
+ const parent = path.dirname(dir);
13
+ if (parent === dir)
14
+ throw new Error(`No package manifest declaring a name at or above ${startDir}.`);
15
+ dir = parent;
16
+ }
17
+ }
18
+ function isNamedManifest(value) {
19
+ return (typeof value === 'object' &&
20
+ value !== null &&
21
+ !Array.isArray(value) &&
22
+ 'name' in value &&
23
+ typeof value.name === 'string');
24
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Resolves the branch checked out in the current directory. Throws when git is absent, the directory is
3
+ * not a repository, or HEAD names no branch, since each leaves the caller without the name that it asked
4
+ * to derive from.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function resolveCheckedOutBranch(): string;
@@ -0,0 +1,17 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ const FAILURE_PREFIX = 'Could not resolve the checked-out branch with `git branch --show-current`:';
3
+ const FAILURE_SUFFIX = 'Pass a branch name explicitly.';
4
+ export function resolveCheckedOutBranch() {
5
+ const { error, status, stderr, stdout } = spawnSync('git', ['branch', '--show-current'], { encoding: 'utf8' });
6
+ if (error !== undefined)
7
+ throw failToResolve(error.message);
8
+ if (status !== 0)
9
+ throw failToResolve(stderr.trim());
10
+ const branch = stdout.trim();
11
+ if (branch === '')
12
+ throw failToResolve('HEAD names no branch.');
13
+ return branch;
14
+ }
15
+ function failToResolve(cause) {
16
+ return new Error(`${FAILURE_PREFIX} ${cause}\n${FAILURE_SUFFIX}`);
17
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Reads the version declared by the package owning a directory, defaulting to this module's own, which is
3
+ * this package whether it runs from source under the test runner or from the build output once installed.
4
+ * Throws where the owning manifest declares no string version.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare function resolveSelfVersion(fromDir?: string): string;
@@ -0,0 +1,8 @@
1
+ import { findOwningManifest } from "./findOwningManifest.js";
2
+ export function resolveSelfVersion(fromDir = import.meta.dirname) {
3
+ const { manifest, manifestPath } = findOwningManifest(fromDir);
4
+ if (typeof manifest.version !== 'string') {
5
+ throw new TypeError(`No version declared in the package manifest at ${manifestPath}.`);
6
+ }
7
+ return manifest.version;
8
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runs the `tb-git` command line, returning what to write and exit with rather than doing either, so the
3
+ * whole surface is exercisable without a process. Every failure is reported through the result: Nothing throws.
4
+ *
5
+ * @internal
6
+ */
7
+ export declare function runTbGit(args: string[], effects: TbGitEffects): TbGitResult;
8
+ /** The effects deferred to the entry point, which keeps the runner free of I/O. */
9
+ export interface TbGitEffects {
10
+ readonly resolveBranch: () => string;
11
+ readonly resolveVersion: () => string;
12
+ }
13
+ /** What the caller should write to each stream and exit with. */
14
+ export interface TbGitResult {
15
+ readonly exitCode: number;
16
+ readonly stderr: string;
17
+ readonly stdout: string;
18
+ }
@@ -0,0 +1,135 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { deriveBranchNumber } from "../3-candidate/deriveBranchNumber.js";
3
+ import { findBranchTicketRef } from "../3-candidate/findBranchTicketRef.js";
4
+ const EXIT_OK = 0;
5
+ const EXIT_NO_RESULT = 1;
6
+ const EXIT_USAGE = 2;
7
+ const SUBCOMMANDS = new Set(['branch-number', 'ticket-ref']);
8
+ const HELP_OPTION = { help: { type: 'boolean', short: 'h' } };
9
+ const ROOT_HELP = `Usage: tb-git <subcommand> [<branch>] [options]
10
+
11
+ Utilities for working with git branch names.
12
+
13
+ Subcommands:
14
+ branch-number Print a stable number derived from a branch name
15
+ ticket-ref Print the ID of the ticket encoded by a branch name
16
+
17
+ Options:
18
+ -h, --help Print this help; each subcommand takes its own --help
19
+ --version Print the installed version
20
+
21
+ With no <branch>, the checked-out branch is used.
22
+
23
+ Exit codes:
24
+ 0 A result was printed
25
+ 1 ticket-ref found no ticket in the branch name
26
+ 2 Usage or validation error`;
27
+ const BRANCH_NUMBER_HELP = `Usage: tb-git branch-number [<branch>] [options]
28
+
29
+ Print the number of the ticket encoded by the branch name, or a hash of the name when it encodes none.
30
+
31
+ Options:
32
+ -h, --help Print this help
33
+ --key K The project's ticket key, matched in any casing
34
+ --max N Upper bound, inclusive (default 4294967295)
35
+ --min N Lower bound, inclusive (default 0)
36
+ --offset N Rotate the result within the bounds; write a negative one as --offset=-3
37
+
38
+ With no <branch>, the checked-out branch is used.`;
39
+ const TICKET_REF_HELP = `Usage: tb-git ticket-ref [<branch>] [options]
40
+
41
+ Print the ID of the ticket encoded by the branch name, exiting 1 when it encodes none.
42
+
43
+ Options:
44
+ -h, --help Print this help
45
+ --json Print the whole ref on one line as JSON
46
+ --key K The project's ticket key, matched in any casing
47
+
48
+ With no <branch>, the checked-out branch is used.`;
49
+ export function runTbGit(args, effects) {
50
+ try {
51
+ return dispatch(args, effects);
52
+ }
53
+ catch (error) {
54
+ return fail(describeError(error), args[0]);
55
+ }
56
+ }
57
+ function describeError(error) {
58
+ return error instanceof Error ? error.message : String(error);
59
+ }
60
+ function dispatch(args, effects) {
61
+ const [command, ...rest] = args;
62
+ if (command === 'branch-number')
63
+ return runBranchNumber(rest, effects);
64
+ if (command === 'ticket-ref')
65
+ return runTicketRef(rest, effects);
66
+ if (command === '--help' || command === '-h')
67
+ return succeed(ROOT_HELP);
68
+ if (command === '--version')
69
+ return succeed(effects.resolveVersion());
70
+ if (command === undefined)
71
+ return fail('A subcommand is required.', command);
72
+ return fail(`Unknown ${command.startsWith('-') ? 'option' : 'subcommand'}: ${command}`, command);
73
+ }
74
+ function fail(message, command) {
75
+ const scope = command !== undefined && SUBCOMMANDS.has(command) ? `tb-git ${command}` : 'tb-git';
76
+ return { exitCode: EXIT_USAGE, stderr: `${message}\nTry \`${scope} --help\`.\n`, stdout: '' };
77
+ }
78
+ function runBranchNumber(args, effects) {
79
+ const { positionals, values } = parseArgs({
80
+ allowPositionals: true,
81
+ args,
82
+ options: {
83
+ ...HELP_OPTION,
84
+ key: { type: 'string' },
85
+ max: { type: 'string' },
86
+ min: { type: 'string' },
87
+ offset: { type: 'string' },
88
+ },
89
+ strict: true,
90
+ });
91
+ if (values.help)
92
+ return succeed(BRANCH_NUMBER_HELP);
93
+ const number = deriveBranchNumber(selectBranch(positionals, effects), {
94
+ key: values.key,
95
+ max: toNumber('max', values.max),
96
+ min: toNumber('min', values.min),
97
+ offset: toNumber('offset', values.offset),
98
+ });
99
+ return succeed(String(number));
100
+ }
101
+ function runTicketRef(args, effects) {
102
+ const { positionals, values } = parseArgs({
103
+ allowPositionals: true,
104
+ args,
105
+ options: { ...HELP_OPTION, json: { type: 'boolean' }, key: { type: 'string' } },
106
+ strict: true,
107
+ });
108
+ if (values.help)
109
+ return succeed(TICKET_REF_HELP);
110
+ const ref = findBranchTicketRef(selectBranch(positionals, effects), { key: values.key });
111
+ if (ref === undefined)
112
+ return { exitCode: EXIT_NO_RESULT, stderr: '', stdout: '' };
113
+ return succeed(values.json === true ? JSON.stringify(ref) : ref.id);
114
+ }
115
+ function selectBranch(positionals, effects) {
116
+ if (positionals.length > 1) {
117
+ throw new Error(`Expected at most one branch name. Received ${positionals.length}.`);
118
+ }
119
+ const [branch] = positionals;
120
+ if (branch === undefined)
121
+ return effects.resolveBranch();
122
+ if (branch === '')
123
+ throw new Error('The branch name is empty. Omit it to use the checked-out branch.');
124
+ return branch;
125
+ }
126
+ function succeed(output) {
127
+ return { exitCode: EXIT_OK, stderr: '', stdout: `${output}\n` };
128
+ }
129
+ function toNumber(flag, value) {
130
+ if (value === undefined)
131
+ return undefined;
132
+ if (value.trim() === '')
133
+ throw new Error(`The value of --${flag} is empty.`);
134
+ return Number(value);
135
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ import { resolveCheckedOutBranch } from "./resolveCheckedOutBranch.js";
2
+ import { resolveSelfVersion } from "./resolveSelfVersion.js";
3
+ import { runTbGit } from "./runTbGit.js";
4
+ for (const stream of [process.stdout, process.stderr]) {
5
+ stream.on('error', (error) => {
6
+ if (error.code !== 'EPIPE')
7
+ throw error;
8
+ });
9
+ }
10
+ const { exitCode, stderr, stdout } = runTbGit(process.argv.slice(2), {
11
+ resolveBranch: resolveCheckedOutBranch,
12
+ resolveVersion: resolveSelfVersion,
13
+ });
14
+ if (stdout !== '')
15
+ process.stdout.write(stdout);
16
+ if (stderr !== '')
17
+ process.stderr.write(stderr);
18
+ process.exitCode = exitCode;
package/package.json CHANGED
@@ -1,4 +1,61 @@
1
1
  {
2
2
  "name": "@williamthorsen/toolbelt.git",
3
- "version": "0.0.0"
4
- }
3
+ "version": "0.3.1",
4
+ "description": "Utilities for working with git",
5
+ "keywords": [
6
+ "esm",
7
+ "git",
8
+ "toolbelt",
9
+ "typescript",
10
+ "utilities"
11
+ ],
12
+ "homepage": "https://github.com/williamthorsen/toolbelt/tree/main/packages/git#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/williamthorsen/toolbelt/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/williamthorsen/toolbelt.git",
19
+ "directory": "packages/git"
20
+ },
21
+ "license": "ISC",
22
+ "author": "William Thorsen <william@thorsen.dev> (https://github.com/williamthorsen)",
23
+ "sideEffects": false,
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "import": "./dist/esm/4-release/index.js"
28
+ },
29
+ "./candidate": {
30
+ "import": "./dist/esm/3-candidate/index.js"
31
+ },
32
+ "./draft": {
33
+ "import": "./dist/esm/2-draft/index.js"
34
+ },
35
+ "./proposed": {
36
+ "import": "./dist/esm/1-proposed/index.js"
37
+ }
38
+ },
39
+ "bin": {
40
+ "tb-git": "./bin/tb-git.js"
41
+ },
42
+ "files": [
43
+ "bin/*",
44
+ "CHANGELOG.md",
45
+ "dist/*"
46
+ ],
47
+ "dependencies": {
48
+ "@williamthorsen/toolbelt.strings": "7.2.0"
49
+ },
50
+ "devDependencies": {
51
+ "@williamthorsen/toolbelt.filesystem": "0.8.3"
52
+ },
53
+ "engines": {
54
+ "node": ">=24.0.0"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public",
58
+ "registry": "https://registry.npmjs.org"
59
+ },
60
+ "scripts": {}
61
+ }