repown 0.1.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.
@@ -0,0 +1,145 @@
1
+ // Argument parsing: turning argv into structured, validated Args.
2
+ //
3
+ // Kept out of cli.ts so a command can import it without dragging in
4
+ // the dispatcher -- importing cli.ts used to run `main()` -- and so the parser
5
+ // itself is unit-testable.
6
+ //
7
+ // A command declares its OWN options and how many positionals it takes; this
8
+ // module never guesses. A boolean option never consumes the next token (an
9
+ // earlier bug: `repown use --gh octocat` read "octocat" as --gh's value and left
10
+ // no account), an unknown option is refused rather than silently dropped, and
11
+ // so is an extra positional.
12
+ import { Git } from "../core/git.js";
13
+ import { ok, err } from "../core/result.js";
14
+ import { suggest } from "./suggest.js";
15
+ export const NO_POSITIONALS = { min: 0, max: 0 };
16
+ /** For commands whose payload a script may read. Only `json` is a stable contract (ADR-014). */
17
+ export const FORMAT_OPTION = {
18
+ name: 'format', kind: 'string', default: 'text', choices: ['text', 'json'],
19
+ help: 'text for people, json for scripts',
20
+ };
21
+ export function wantsJson(args) {
22
+ return flagString(args, 'format') === 'json';
23
+ }
24
+ /** Accepted on every command, in addition to whatever it declares itself. */
25
+ export const GLOBAL_OPTIONS = [
26
+ { name: 'cwd', kind: 'string', help: 'run as if started in this directory' },
27
+ ];
28
+ /**
29
+ * `--name value`, `--name=value` and `--flag` are all accepted; everything else
30
+ * is positional. A token that is exactly `--` ends option parsing, so a branch
31
+ * or path beginning with a dash can still be passed. Before it, a `-x` is an
32
+ * unknown option, never a value: `repown use -x` pinned an account named "-x".
33
+ */
34
+ export function parseArgs(tokens, spec) {
35
+ const options = [...GLOBAL_OPTIONS, ...spec.options];
36
+ const positional = [];
37
+ const flags = new Map();
38
+ let optionsEnded = false;
39
+ for (let index = 0; index < tokens.length; index += 1) {
40
+ const token = tokens[index];
41
+ if (optionsEnded || token === '-' || !token.startsWith('-')) {
42
+ positional.push(token);
43
+ continue;
44
+ }
45
+ if (token === '--') {
46
+ optionsEnded = true;
47
+ continue;
48
+ }
49
+ if (!token.startsWith('--'))
50
+ return err(`unknown option ${token}`);
51
+ const consumed = readOption(token, tokens[index + 1], options, flags);
52
+ if (!consumed.ok)
53
+ return err(consumed.error);
54
+ if (consumed.value)
55
+ index += 1;
56
+ }
57
+ const range = checkPositionalCount(positional, spec.positionals);
58
+ if (!range.ok)
59
+ return err(range.error);
60
+ applyDefaults(options, flags);
61
+ return ok({ positional, flags });
62
+ }
63
+ function applyDefaults(options, flags) {
64
+ for (const option of options) {
65
+ if (option.default !== undefined && !flags.has(option.name))
66
+ flags.set(option.name, option.default);
67
+ }
68
+ }
69
+ /** Parses one `--name`/`--name=value` token. Returns whether it also consumed `next`. */
70
+ function readOption(token, next, options, flags) {
71
+ const [name, inline] = splitFlag(token);
72
+ const option = options.find((candidate) => candidate.name === name);
73
+ if (!option)
74
+ return err(unknownOptionMessage(name, options));
75
+ if (option.kind === 'boolean') {
76
+ if (inline !== null)
77
+ return err(`--${name} does not take a value`);
78
+ flags.set(name, true);
79
+ return ok(false);
80
+ }
81
+ const value = inline ?? next;
82
+ if (value === undefined || value.startsWith('--'))
83
+ return err(`--${name} needs a value`);
84
+ if (option.choices && !option.choices.includes(value)) {
85
+ return err(`--${name} must be one of: ${option.choices.join(', ')} (got '${value}')`);
86
+ }
87
+ flags.set(name, value);
88
+ return ok(inline === null);
89
+ }
90
+ function checkPositionalCount(positional, spec) {
91
+ if (positional.length < spec.min) {
92
+ return err(`expects ${describeCount(spec)}${spec.label ? ' ' + spec.label : ''}`);
93
+ }
94
+ if (positional.length > spec.max) {
95
+ const extra = positional.slice(spec.max).map((value) => `'${value}'`).join(', ');
96
+ return err(`unexpected argument${positional.length - spec.max > 1 ? 's' : ''}: ${extra}`);
97
+ }
98
+ return ok(undefined);
99
+ }
100
+ function describeCount(spec) {
101
+ if (spec.min === spec.max)
102
+ return `exactly ${spec.min} argument${spec.min === 1 ? '' : 's'}`;
103
+ return `at least ${spec.min} argument${spec.min === 1 ? '' : 's'}`;
104
+ }
105
+ function unknownOptionMessage(name, options) {
106
+ const hint = suggest(name, options.map((option) => option.name));
107
+ return hint ? `unknown option --${name} (did you mean --${hint}?)` : `unknown option --${name}`;
108
+ }
109
+ function splitFlag(token) {
110
+ const body = token.slice(2);
111
+ const equals = body.indexOf('=');
112
+ return equals === -1 ? [body, null] : [body.slice(0, equals), body.slice(equals + 1)];
113
+ }
114
+ /**
115
+ * True when `--help`/`-h` appears before any `--` end-of-options marker -- and
116
+ * is not the VALUE of a string option. Every installed hook calls
117
+ * `guard check --remote "$1" --url "$2"`, and a remote may be named `-h`: read as
118
+ * help, the check printed usage and exited 0, and git pushed.
119
+ */
120
+ export function hasHelpFlag(tokens, options = []) {
121
+ const takesValue = (token) => {
122
+ const [name, inline] = splitFlag(token);
123
+ return inline === null && [...GLOBAL_OPTIONS, ...options].some((o) => o.name === name && o.kind === 'string');
124
+ };
125
+ for (let index = 0; index < tokens.length; index += 1) {
126
+ const token = tokens[index];
127
+ if (token === '--')
128
+ return false;
129
+ if (token === '--help' || token === '-h')
130
+ return true;
131
+ if (token.startsWith('--') && takesValue(token))
132
+ index += 1;
133
+ }
134
+ return false;
135
+ }
136
+ export function flagString(args, name) {
137
+ const value = args.flags.get(name);
138
+ return typeof value === 'string' ? value : null;
139
+ }
140
+ export function flagBool(args, name) {
141
+ return args.flags.get(name) === true;
142
+ }
143
+ export function gitFor(args) {
144
+ return new Git(flagString(args, 'cwd') ?? process.cwd());
145
+ }
@@ -0,0 +1,25 @@
1
+ // The shape every command and command-group declares itself in.
2
+ //
3
+ // Declaring options and positionals here -- rather than each command reading
4
+ // flags ad hoc -- is what lets one parser (ui/args.ts) validate every command
5
+ // the same way, and one renderer (ui/help.ts) generate help for all of them
6
+ // from the same declarations, so help can never drift from what the parser
7
+ // actually accepts.
8
+ import { NO_POSITIONALS } from "./args.js";
9
+ export function isGroup(entry) {
10
+ return 'actions' in entry;
11
+ }
12
+ export function optionsOf(command) {
13
+ return command.options ?? [];
14
+ }
15
+ export function positionalsOf(command) {
16
+ return command.positionals ?? NO_POSITIONALS;
17
+ }
18
+ /** The parser input for one command: its own declared options and positionals. */
19
+ export function specFor(command) {
20
+ return { options: optionsOf(command), positionals: positionalsOf(command) };
21
+ }
22
+ /** Resolves a hidden alias to its canonical action name; passes any other name through unchanged. */
23
+ export function resolveAlias(group, action) {
24
+ return group.aliases?.[action] ?? action;
25
+ }
@@ -0,0 +1,142 @@
1
+ // Dispatch for a program built from Command/CommandGroup declarations: resolving
2
+ // a command (and, for a group, an action), handling `--help`/`-h`/`help` before a
3
+ // command's own `run()` ever sees the arguments, and reporting a usage error
4
+ // with an exit code of 2.
5
+ //
6
+ // Kept apart from src/cli.ts so a second program (the release tool in scripts/)
7
+ // gets the same grammar without importing cli.ts, which runs repown.
8
+ import { parseArgs, hasHelpFlag } from "./args.js";
9
+ import { isGroup, resolveAlias, specFor } from "./command.js";
10
+ import { renderHelpFor } from "./help.js";
11
+ import { suggest } from "./suggest.js";
12
+ import { ok, err } from "../core/result.js";
13
+ import * as out from "./format.js";
14
+ async function loadAll(program) {
15
+ const names = Object.keys(program.commands);
16
+ const entries = await Promise.all(names.map((name) => program.commands[name]()));
17
+ return new Map(names.map((name, index) => [name, entries[index]]));
18
+ }
19
+ function reportUsageError(tag, message) {
20
+ const [first, ...rest] = message.split('\n');
21
+ out.fail(tag, first ?? message);
22
+ for (const line of rest)
23
+ out.detail(line);
24
+ }
25
+ async function resolveTop(program, argv) {
26
+ const first = argv[0];
27
+ const fallback = program.defaultCommand;
28
+ if (fallback !== undefined && (first === undefined || first.startsWith('-'))) {
29
+ return ok({ name: fallback, entry: await program.commands[fallback](), rest: argv, implicit: true });
30
+ }
31
+ const loader = first === undefined ? undefined : program.commands[first];
32
+ if (!loader)
33
+ return err(unknown('command', first ?? '', Object.keys(program.commands)));
34
+ return ok({ name: first, entry: await loader(), rest: argv.slice(1), implicit: false });
35
+ }
36
+ /** One correction wherever a name is looked up: `<program> x`, `<program> help x`, a group's action. */
37
+ function unknown(kind, name, known) {
38
+ const hint = suggest(name, known);
39
+ const guess = hint ? ` (did you mean '${hint}'?)` : '';
40
+ return 'Unknown ' + kind + ': ' + name + guess + '\nknown: ' + known.join(', ');
41
+ }
42
+ function helpPointer(program, path) {
43
+ return '\nrun `' + [program.name, 'help', ...path].join(' ') + '` for usage';
44
+ }
45
+ function resolveAction(group, rest) {
46
+ const first = rest[0];
47
+ if (first === undefined || first.startsWith('-')) {
48
+ return ok({ command: group.actions[group.defaultAction], action: group.defaultAction, remaining: rest, explicit: false });
49
+ }
50
+ const canonical = resolveAlias(group, first);
51
+ const command = group.actions[canonical];
52
+ if (!command)
53
+ return err(unknown('action', first, Object.keys(group.actions)));
54
+ return ok({ command, action: canonical, remaining: rest.slice(1), explicit: true });
55
+ }
56
+ async function runLeaf(program, leaf) {
57
+ const spec = specFor(leaf.command);
58
+ if (hasHelpFlag(leaf.rest, spec.options)) {
59
+ printHelp(program, leaf.path, leaf.command);
60
+ return 0;
61
+ }
62
+ const parsed = parseArgs(leaf.rest, spec);
63
+ if (!parsed.ok) {
64
+ reportUsageError(leaf.tag, parsed.error + helpPointer(program, leaf.path));
65
+ return 2;
66
+ }
67
+ return leaf.command.run(parsed.value);
68
+ }
69
+ async function dispatch(program, top) {
70
+ const { name, entry, rest } = top;
71
+ if (!isGroup(entry))
72
+ return runLeaf(program, { path: [name], command: entry, rest, tag: top.implicit ? program.name : name });
73
+ const picked = resolveAction(entry, rest);
74
+ if (!picked.ok) {
75
+ reportUsageError(name, picked.error);
76
+ return 2;
77
+ }
78
+ const { command, action, remaining, explicit } = picked.value;
79
+ if (!explicit && hasHelpFlag(remaining)) {
80
+ printHelp(program, [name], entry);
81
+ return 0;
82
+ }
83
+ return runLeaf(program, { path: [name, action], command, rest: remaining, tag: name + ' ' + action });
84
+ }
85
+ function printHelp(program, path, entry) {
86
+ for (const line of renderHelpFor(path, entry, program.name))
87
+ out.line(line);
88
+ }
89
+ async function runHelp(program, path) {
90
+ if (path.length === 0) {
91
+ for (const line of program.topHelp(await loadAll(program)))
92
+ out.line(line);
93
+ return 0;
94
+ }
95
+ const loader = program.commands[path[0]];
96
+ if (!loader) {
97
+ reportUsageError('help', unknown('command', path[0], Object.keys(program.commands)));
98
+ return 2;
99
+ }
100
+ const top = await loader();
101
+ if (!isGroup(top) || path.length === 1) {
102
+ printHelp(program, [path[0]], top);
103
+ return 0;
104
+ }
105
+ const canonical = resolveAlias(top, path[1]);
106
+ const command = top.actions[canonical];
107
+ if (!command) {
108
+ reportUsageError('help', unknown('action', path[1], Object.keys(top.actions)));
109
+ return 2;
110
+ }
111
+ printHelp(program, [path[0], canonical], command);
112
+ return 0;
113
+ }
114
+ export async function runProgram(program, argv) {
115
+ const version = program.version;
116
+ if (version && (argv[0] === '--version' || argv[0] === '-v')) {
117
+ out.line(program.name + ' ' + version());
118
+ return 0;
119
+ }
120
+ if (argv[0] === '--help' || argv[0] === '-h')
121
+ return runHelp(program, []);
122
+ if (argv[0] === 'help')
123
+ return runHelp(program, argv.slice(1));
124
+ if (argv.length === 0 && program.defaultCommand === undefined)
125
+ return runHelp(program, []);
126
+ const top = await resolveTop(program, argv);
127
+ if (!top.ok) {
128
+ reportUsageError(program.name, top.error);
129
+ return 2;
130
+ }
131
+ return dispatch(program, top.value);
132
+ }
133
+ /** The whole life of the process: run, set the exit code, and report a crash as a failure. */
134
+ export function start(program) {
135
+ out.ignoreBrokenPipe();
136
+ runProgram(program, process.argv.slice(2))
137
+ .then((code) => { process.exitCode = code; })
138
+ .catch((error) => {
139
+ out.fail(program.name, error instanceof Error ? error.message : String(error));
140
+ process.exitCode = 1;
141
+ });
142
+ }
@@ -0,0 +1,84 @@
1
+ // Terminal output. Deliberately plain: a fixed-width status word, a short tag
2
+ // saying which check spoke, then the message.
3
+ //
4
+ // OK identity octocat <...> push-as:octocat
5
+ // WARN gh active as someone else, so `gh pr create` would act as them
6
+ // fix: gh auth switch -u octocat
7
+ const COLOURS = {
8
+ green: '\x1b[32m',
9
+ yellow: '\x1b[33m',
10
+ red: '\x1b[31m',
11
+ dim: '\x1b[2m',
12
+ reset: '\x1b[0m',
13
+ };
14
+ /**
15
+ * Colour is a property of the STREAM a line goes to, not of the process: piping
16
+ * stdout into a file while stderr stays a terminal (`repown 2>&1 | less`, or the
17
+ * reverse, `repown 2>err.log`) must not colour the redirected side. `NO_COLOR`
18
+ * only counts when it is non-empty, and `FORCE_COLOR=0`/`false` turns colour
19
+ * off even though the variable is set -- both per the NO_COLOR/FORCE_COLOR
20
+ * conventions these variables are named after. `TERM=dumb` is a terminal that
21
+ * cannot render escape codes, so it gets none unless FORCE_COLOR insists.
22
+ */
23
+ export function useColour(stream) {
24
+ const force = process.env['FORCE_COLOR'];
25
+ if (force !== undefined)
26
+ return force !== '0' && force !== 'false';
27
+ if (process.env['NO_COLOR'])
28
+ return false;
29
+ if (process.env['TERM'] === 'dumb')
30
+ return false;
31
+ return stream.isTTY === true;
32
+ }
33
+ function paint(stream, colour, text) {
34
+ return useColour(stream) ? COLOURS[colour] + text + COLOURS.reset : text;
35
+ }
36
+ function status(level, tag, message) {
37
+ const word = paint(level.stream, level.colour, level.word.padEnd(5));
38
+ level.stream.write(word + ' ' + tag.padEnd(10) + ' ' + message + '\n');
39
+ }
40
+ export function pass(tag, message) {
41
+ status({ stream: process.stdout, word: 'OK', colour: 'green' }, tag, message);
42
+ }
43
+ export function warn(tag, message) {
44
+ status({ stream: process.stderr, word: 'WARN', colour: 'yellow' }, tag, message);
45
+ }
46
+ export function fail(tag, message) {
47
+ status({ stream: process.stderr, word: 'FAIL', colour: 'red' }, tag, message);
48
+ }
49
+ /** A continuation line under a warn or fail, aligned with its message column. */
50
+ export function detail(message) {
51
+ process.stderr.write(' ' + message + '\n');
52
+ }
53
+ export function line(message = '') {
54
+ process.stdout.write(message + '\n');
55
+ }
56
+ /** ` label value` -- the shape every status block uses. */
57
+ export function field(label, value, width = 14) {
58
+ process.stdout.write(' ' + label.padEnd(width) + ' ' + value + '\n');
59
+ }
60
+ /** `--format json`: the whole payload as one JSON document on stdout, never coloured. */
61
+ export function json(value) {
62
+ process.stdout.write(JSON.stringify(value, null, 2) + '\n');
63
+ }
64
+ export function heading(text) {
65
+ process.stdout.write('\n' + paint(process.stdout, 'dim', text) + '\n');
66
+ }
67
+ export function dim(text) {
68
+ return paint(process.stdout, 'dim', text);
69
+ }
70
+ /**
71
+ * A reader closing early (`repown help | head -3`) delivers EPIPE on the next
72
+ * write. That is the reader's choice, not a fault in repown, so the write is
73
+ * dropped rather than left to crash with a stack trace -- and NOTHING ELSE
74
+ * changes. In particular the exit code stands: `git push 2>&1 | true` closes the
75
+ * hook's stderr, and turning that into exit 0 published the commit it refused.
76
+ */
77
+ export function ignoreBrokenPipe() {
78
+ for (const stream of [process.stdout, process.stderr]) {
79
+ stream.on('error', (error) => {
80
+ if (error.code !== 'EPIPE' && error.code !== 'ERR_STREAM_DESTROYED')
81
+ throw error;
82
+ });
83
+ }
84
+ }
@@ -0,0 +1,97 @@
1
+ // Renders help from the same declarations the parser validates against, so
2
+ // help can never promise an option or a positional the parser would refuse.
3
+ //
4
+ // Side-effect free: nothing here writes output, prints go through cli.ts's own
5
+ // `out.line` calls, and nothing here is reachable except by an explicit
6
+ // `--help`/`-h`/`help` request. A command's `run()` never sees a help request --
7
+ // cli.ts intercepts it before parsing the command's own arguments.
8
+ import { GLOBAL_OPTIONS } from "./args.js";
9
+ import { isGroup, optionsOf } from "./command.js";
10
+ export function renderTopHelp(entries) {
11
+ return [
12
+ ...topHeader(entries),
13
+ ...globalOptionsHelp(),
14
+ ...environmentHelp(),
15
+ ' Exit codes: 0 success, 1 failure or refusal, 2 usage error.',
16
+ '',
17
+ ];
18
+ }
19
+ function topHeader(entries) {
20
+ const lines = ['', ' repown <command> [options]', ''];
21
+ for (const [name, entry] of entries)
22
+ lines.push(' ' + name.padEnd(10) + entry.summary);
23
+ lines.push('', ' Run `repown` with no command for the state of this repository.');
24
+ lines.push(' Run `repown help <command>` for its options.', '');
25
+ return lines;
26
+ }
27
+ function globalOptionsHelp() {
28
+ const lines = [' Global options:'];
29
+ for (const option of GLOBAL_OPTIONS)
30
+ lines.push(' ' + optionHelp(option));
31
+ lines.push(' ' + '--help, -h'.padEnd(20) + 'show help for the command', '');
32
+ lines.push(' `repown --version` (or -v) prints the installed version.', '');
33
+ return lines;
34
+ }
35
+ function environmentHelp() {
36
+ return [
37
+ ' Environment:',
38
+ ' ' + 'REPOWN_CONFIG_DIR'.padEnd(20) + 'where the per-machine account registry lives',
39
+ ' ' + 'NO_COLOR'.padEnd(20) + 'disable colored output when set to a non-empty value',
40
+ ' ' + 'FORCE_COLOR'.padEnd(20) + 'colored output even when not a terminal; 0 or false turns it off (wins over NO_COLOR)',
41
+ ' ' + 'TERM'.padEnd(20) + 'set to dumb, disables colored output (FORCE_COLOR still wins)',
42
+ '',
43
+ ];
44
+ }
45
+ export function renderCommandHelp(path, command, program = 'repown') {
46
+ const lines = ['', ' ' + usageFor(program, path, command), '', ' ' + command.summary, ''];
47
+ if (optionsOf(command).length > 0)
48
+ lines.push(...optionsHelp(command), '');
49
+ lines.push(' Global options:', ...GLOBAL_OPTIONS.map((option) => ' ' + optionHelp(option)), '');
50
+ if (command.examples && command.examples.length > 0)
51
+ lines.push(...examplesHelp(command.examples), '');
52
+ return lines;
53
+ }
54
+ export function renderGroupHelp(path, group, program = 'repown') {
55
+ const lines = ['', ' ' + program + ' ' + path.join(' ') + ' <action>', '', ' Actions:'];
56
+ for (const [name, action] of Object.entries(group.actions)) {
57
+ const marker = name === group.defaultAction ? ' (default)' : '';
58
+ lines.push(' ' + name.padEnd(10) + action.summary + marker);
59
+ }
60
+ lines.push('', ' Run `' + program + ' help ' + path.join(' ') + ' <action>` for its options.', '');
61
+ return lines;
62
+ }
63
+ export function renderHelpFor(path, entry, program = 'repown') {
64
+ return isGroup(entry) ? renderGroupHelp(path, entry, program) : renderCommandHelp(path, entry, program);
65
+ }
66
+ function usageFor(program, path, command) {
67
+ const positionals = positionalUsage(command);
68
+ const options = optionsOf(command).map(optionUsageToken).join(' ');
69
+ return [program, ...path, positionals, options].filter((part) => part.length > 0).join(' ');
70
+ }
71
+ function positionalUsage(command) {
72
+ const spec = command.positionals;
73
+ if (!spec || spec.max === 0)
74
+ return '';
75
+ const label = spec.label ?? '<arg>';
76
+ const shown = spec.max === Infinity ? label + '...' : label;
77
+ return spec.min === 0 ? '[' + shown + ']' : shown;
78
+ }
79
+ function optionUsageToken(option) {
80
+ const value = option.kind === 'boolean' ? '' : ' ' + (option.choices?.join('|') ?? '<value>');
81
+ return '[--' + option.name + value + ']';
82
+ }
83
+ function optionsHelp(command) {
84
+ const lines = [' Options:'];
85
+ for (const option of optionsOf(command))
86
+ lines.push(' ' + optionHelp(option));
87
+ return lines;
88
+ }
89
+ function examplesHelp(examples) {
90
+ return [' Examples:', ...examples.map((example) => ' ' + example)];
91
+ }
92
+ function optionHelp(option) {
93
+ const value = option.kind === 'boolean' ? '' : ' <value>';
94
+ const choices = option.choices ? ' (' + option.choices.join('|') + ')' : '';
95
+ const fallback = option.default !== undefined && option.default !== '' ? ' [default: ' + option.default + ']' : '';
96
+ return ('--' + option.name + value).padEnd(20) + option.help + choices + fallback;
97
+ }
@@ -0,0 +1,43 @@
1
+ // Asking the user for a value, with a default they can accept by pressing enter.
2
+ //
3
+ // Refuses rather than hangs when there is no terminal. A hook, a CI job or a
4
+ // piped invocation has nobody to answer, and a prompt there is an unkillable
5
+ // wait that looks like a crash -- so the absence of a TTY is reported as what it
6
+ // is, with the flag that would have avoided the question.
7
+ //
8
+ // The prompt itself writes to STDERR, matching every other piece of output that
9
+ // is not the payload (WARN and FAIL go there too): stdout stays reserved for
10
+ // whatever a command actually produces, so `repown accounts add x | tee log` does
11
+ // not interleave a prompt into the log.
12
+ import { createInterface } from 'node:readline/promises';
13
+ import { ok, err } from "../core/result.js";
14
+ export function interactive() {
15
+ return process.stdin.isTTY === true && process.stderr.isTTY === true;
16
+ }
17
+ export async function ask(label, suggestion) {
18
+ if (!interactive()) {
19
+ return err('this needs an interactive terminal to ask for the ' + label);
20
+ }
21
+ const shown = suggestion ? label + ' [' + suggestion + ']' : label;
22
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
23
+ try {
24
+ const answer = (await rl.question(' ' + shown.padEnd(30) + ' ')).trim();
25
+ const value = answer.length > 0 ? answer : (suggestion ?? '');
26
+ return value.length > 0 ? ok(value) : err('a value is required for ' + label);
27
+ }
28
+ finally {
29
+ rl.close();
30
+ }
31
+ }
32
+ export async function confirm(question) {
33
+ if (!interactive())
34
+ return false;
35
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
36
+ try {
37
+ const answer = (await rl.question(' ' + question + ' [y/N] ')).trim().toLowerCase();
38
+ return answer === 'y' || answer === 'yes';
39
+ }
40
+ finally {
41
+ rl.close();
42
+ }
43
+ }
@@ -0,0 +1,33 @@
1
+ // "Did you mean X?" for a mistyped command, action or option.
2
+ //
3
+ // Only ever offers a hint when exactly one candidate is close enough to be
4
+ // worth guessing -- a tie, or nothing within the threshold, gets no hint
5
+ // rather than a wrong one.
6
+ export function suggest(input, candidates) {
7
+ const ranked = candidates
8
+ .map((candidate) => ({ candidate, distance: levenshtein(input, candidate) }))
9
+ .filter((entry) => entry.distance > 0 && entry.distance <= threshold(input))
10
+ .sort((a, b) => a.distance - b.distance);
11
+ if (ranked.length === 0)
12
+ return null;
13
+ if (ranked.length > 1 && ranked[1].distance === ranked[0].distance)
14
+ return null;
15
+ return ranked[0].candidate;
16
+ }
17
+ function threshold(input) {
18
+ return input.length <= 4 ? 1 : 2;
19
+ }
20
+ function levenshtein(a, b) {
21
+ const dist = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
22
+ for (let i = 0; i <= a.length; i += 1)
23
+ dist[i][0] = i;
24
+ for (let j = 0; j <= b.length; j += 1)
25
+ dist[0][j] = j;
26
+ for (let i = 1; i <= a.length; i += 1) {
27
+ for (let j = 1; j <= b.length; j += 1) {
28
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
29
+ dist[i][j] = Math.min(dist[i - 1][j] + 1, dist[i][j - 1] + 1, dist[i - 1][j - 1] + cost);
30
+ }
31
+ }
32
+ return dist[a.length][b.length];
33
+ }
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "repown",
3
+ "version": "0.1.0",
4
+ "description": "Use several git accounts on one machine: each repo owns its identity, so you move between repos with no switch command and never push the wrong one.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/makubexD/repown.git"
8
+ },
9
+ "homepage": "https://github.com/makubexD/repown#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/makubexD/repown/issues"
12
+ },
13
+ "type": "module",
14
+ "bin": {
15
+ "repown": "dist/cli.js"
16
+ },
17
+ "main": "dist/cli.js",
18
+ "engines": {
19
+ "node": ">=20"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "!dist/**/*.map",
24
+ "CHANGELOG.md"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsc && tsc -p tsconfig.test.json",
28
+ "watch": "tsc --watch",
29
+ "test": "node --test \"test/*.test.ts\"",
30
+ "test:quiet": "node --test --test-reporter=dot \"test/*.test.ts\"",
31
+ "prepare": "npm run build",
32
+ "changelog": "node scripts/release.ts changelog draft",
33
+ "release:check": "node scripts/release.ts check repo",
34
+ "pack:check": "npm pack --dry-run --json --ignore-scripts | node scripts/release.ts check package -",
35
+ "release:patch": "npm version patch",
36
+ "release:minor": "npm version minor",
37
+ "release:major": "npm version major",
38
+ "release:beta": "npm version prerelease --preid=beta",
39
+ "preversion": "npm run release:check && npm run test:quiet && npm run build && npm run pack:check",
40
+ "version": "node scripts/release.ts changelog release && git add CHANGELOG.md",
41
+ "postversion": "node -e \"console.error('next: git push --follow-tags')\"",
42
+ "prepublishOnly": "node scripts/release.ts check tag"
43
+ },
44
+ "keywords": [
45
+ "git",
46
+ "identity",
47
+ "credential",
48
+ "pre-push",
49
+ "multi-account"
50
+ ],
51
+ "license": "MIT",
52
+ "publishConfig": {
53
+ "access": "public"
54
+ },
55
+ "devDependencies": {
56
+ "@types/node": "^22.10.0",
57
+ "typescript": "^5.7.0"
58
+ }
59
+ }