repown 0.1.1 → 0.2.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.
@@ -5,6 +5,10 @@
5
5
  // reporting -- a pull request opened from the wrong account on a public repo is
6
6
  // as permanent as a commit.
7
7
  //
8
+ // `ghLogin` does not ask. It hands the terminal to `gh auth login` and never
9
+ // reads what gh prints. Below gh 2.40.0 that login is refused: it would
10
+ // replace the host's account.
11
+ //
8
12
  // NOT `gh api user`. That spent an API round trip to learn one login and, the
9
13
  // reason it had to go, returned nothing on failure. Callers guarded their
10
14
  // warnings on the value being truthy, so an offline machine or an expired token
@@ -16,8 +20,9 @@
16
20
  // "Could not be queried" is a THIRD STATE, distinct both from "gh is not
17
21
  // installed" and from "gh is active as nobody". Collapsing it into either is the
18
22
  // bug this shape exists to prevent.
19
- import { run, succeeded, notInstalled, output } from "../exec.js";
23
+ import { run, inherit, succeeded, notInstalled, output } from "../exec.js";
20
24
  import { ok, err } from "../result.js";
25
+ import { versionAtLeast } from "../version.js";
21
26
  /**
22
27
  * A credential-helper value that `gh auth setup-git` wrote -- `!gh auth
23
28
  * git-credential`, or with gh's path, quoted on Windows -- and nothing more. A
@@ -31,7 +36,10 @@ export async function ghInstalled() {
31
36
  return !notInstalled(await run('gh', ['--version']));
32
37
  }
33
38
  export async function ghState(host = 'github.com') {
34
- const result = await run('gh', ['auth', 'status', '--json', 'hosts']);
39
+ return ghStateFrom(await run('gh', ['auth', 'status', '--json', 'hosts']), host);
40
+ }
41
+ /** A finished `gh auth status --json hosts`. Exit 0 with no host entry is nobody signed in. */
42
+ export function ghStateFrom(result, host = 'github.com') {
35
43
  if (notInstalled(result))
36
44
  return err('gh is not installed');
37
45
  if (!succeeded(result))
@@ -41,17 +49,45 @@ export async function ghState(host = 'github.com') {
41
49
  return err('gh auth status returned nothing usable');
42
50
  return ok(parsed);
43
51
  }
52
+ /**
53
+ * gh 2.88.1 exits 0 and prints `{"hosts":{}}` when it is signed in to nobody.
54
+ * A missing host key, or an empty list, is that same answer.
55
+ */
44
56
  function parseHosts(raw, host) {
45
- let hosts;
57
+ const hosts = hostsObject(raw);
58
+ if (hosts === null)
59
+ return null;
60
+ if (!Object.hasOwn(hosts, host))
61
+ return { accounts: [], active: null };
62
+ const entries = hosts[host];
63
+ if (!Array.isArray(entries))
64
+ return null;
65
+ return accountsFrom(entries);
66
+ }
67
+ function hostsObject(raw) {
68
+ const parsed = jsonObject(raw);
69
+ if (parsed === null)
70
+ return null;
71
+ const hosts = parsed['hosts'];
72
+ return isRecord(hosts) ? hosts : null;
73
+ }
74
+ function jsonObject(raw) {
46
75
  try {
47
- hosts = JSON.parse(raw).hosts ?? {};
76
+ const parsed = JSON.parse(plainJson(raw));
77
+ return isRecord(parsed) ? parsed : null;
48
78
  }
49
79
  catch {
50
80
  return null;
51
81
  }
52
- const entries = hosts[host];
53
- if (!Array.isArray(entries))
54
- return null;
82
+ }
83
+ /** gh paints `--json` when colour is forced, even on a pipe. The object is unchanged. */
84
+ function plainJson(raw) {
85
+ return raw.replace(/\x1b\[[0-9;]*m/g, '');
86
+ }
87
+ function isRecord(value) {
88
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
89
+ }
90
+ function accountsFrom(entries) {
55
91
  const accounts = entries.flatMap(toAccount);
56
92
  const active = accounts.find((account) => account.active)?.login ?? null;
57
93
  return { accounts, active };
@@ -62,9 +98,13 @@ function toAccount(raw) {
62
98
  return [];
63
99
  return [{ login: entry.login, active: entry.active === true }];
64
100
  }
65
- /** A profile field from the public API, or null. Absence here is unremarkable. */
101
+ /** Arguments for a github.com profile field. `--hostname` so GH_HOST cannot redirect the call. */
102
+ export function ghProfileArgs(login, field) {
103
+ return ['api', '--hostname', 'github.com', `users/${login}`, '--jq', `.${field}`];
104
+ }
105
+ /** A profile field from github.com, or null. Absence here is unremarkable. */
66
106
  export async function ghProfileField(login, field) {
67
- const result = await run('gh', ['api', `users/${login}`, '--jq', `.${field}`]);
107
+ const result = await run('gh', ghProfileArgs(login, field));
68
108
  const value = output(result);
69
109
  return value && value !== 'null' ? value : null;
70
110
  }
@@ -76,3 +116,50 @@ export async function ghSwitch(login) {
76
116
  return err(result.stderr.trim() || `gh auth switch exited ${result.code}`);
77
117
  return ok(undefined);
78
118
  }
119
+ const LOGIN_MIN = [2, 40, 0];
120
+ export function ghLoginVersion(text) {
121
+ const found = /gh version (\d+)\.(\d+)\.(\d+)/.exec(text);
122
+ if (!found)
123
+ return 'unknown';
124
+ return versionAtLeast(found, LOGIN_MIN) ? 'ready' : 'old';
125
+ }
126
+ export async function readGhLoginVersion() {
127
+ const result = await run('gh', ['--version']);
128
+ return succeeded(result) ? ghLoginVersion(result.stdout) : 'unknown';
129
+ }
130
+ /**
131
+ * Browser login for one host. The child inherits the terminal (`inherit`), with
132
+ * `GH_TOKEN` and `GITHUB_TOKEN` removed so gh will store the new sign-in.
133
+ */
134
+ export async function ghLogin(host, runner = inherit) {
135
+ const result = await runner('gh', loginArgs(host), { env: withoutGhTokens(process.env) });
136
+ return loginResult(result);
137
+ }
138
+ function loginArgs(host) {
139
+ return ['auth', 'login', '--hostname', host, '--web', '--git-protocol', 'https'];
140
+ }
141
+ function loginResult(result) {
142
+ if (notInstalled(result))
143
+ return err({ kind: 'failed', reason: 'gh is not installed' });
144
+ if (result.spawnError)
145
+ return err({ kind: 'failed', reason: result.spawnError.message });
146
+ if (result.code === 0)
147
+ return ok(undefined);
148
+ if (result.code === 2)
149
+ return err({ kind: 'cancelled' });
150
+ return err({ kind: 'failed', reason: 'gh auth login exited ' + result.code });
151
+ }
152
+ /** Windows matches env names case-insensitively; either spelling blocks login. */
153
+ function withoutGhTokens(env) {
154
+ const child = {};
155
+ for (const [key, value] of Object.entries(env)) {
156
+ if (value === undefined || isGhToken(key))
157
+ continue;
158
+ child[key] = value;
159
+ }
160
+ return child;
161
+ }
162
+ function isGhToken(key) {
163
+ const name = key.toUpperCase();
164
+ return name === 'GH_TOKEN' || name === 'GITHUB_TOKEN';
165
+ }
package/dist/core/exec.js CHANGED
@@ -2,16 +2,23 @@
2
2
  //
3
3
  // TWO INVARIANTS, BOTH LOAD-BEARING.
4
4
  //
5
- // 1. NOTHING HERE WRITES TO A CONSOLE, EVER. Credential helpers and git can
6
- // print live secrets on stdout. Whatever a child prints is RETURNED to the
7
- // caller, never shown, so this layer is never the thing that leaks it.
8
- // There is no debug flag and no logging hook by design -- the absence is
5
+ // 1. THIS FILE WRITES NOTHING. `run` returns whatever the child prints and
6
+ // never shows it. Credential helpers and git can print live secrets, and
7
+ // there is no debug flag and no logging hook by design -- the absence is
9
8
  // the control. test/exec.test.ts asserts it.
10
9
  //
10
+ // `inherit` hands the terminal to the child (`stdio: 'inherit'`). repown
11
+ // never sees that output -- the result's stdout and stderr stay empty --
12
+ // so a credential cannot pass through repown. It is used only for
13
+ // `gh auth login`, and only from a terminal. The child prints to the
14
+ // terminal itself; this function still writes nothing.
15
+ // The parent ignores SIGINT while the child runs, so Ctrl-C reaches the child.
16
+ //
11
17
  // 2. A NON-ZERO EXIT IS NOT AN ERROR. git answers questions with exit codes:
12
18
  // `git config --get missing.key` exits 1, and that is the answer "not set",
13
- // not a failure. So this resolves rather than rejects, and callers read
14
- // `code` themselves. (PowerShell 7.4 turning native exit codes into
19
+ // not a failure. So both runners resolve rather than reject, and callers
20
+ // read `code` themselves. A spawn error such as ENOENT resolves too, as
21
+ // `notInstalled`. (PowerShell 7.4 turning native exit codes into
15
22
  // terminating errors is what forced `Use-NativeExitCodes` in the version
16
23
  // this replaces; Node has no such behaviour, but the discipline is the same.)
17
24
  //
@@ -19,6 +26,12 @@
19
26
  // branch name or URL containing shell metacharacters cannot be interpreted.
20
27
  import { spawn } from 'node:child_process';
21
28
  const DEFAULT_TIMEOUT_MS = 30_000;
29
+ /** How many `inherit` children are running. `handingOver` is the read-only view. */
30
+ let inherited = 0;
31
+ /** True while an inherited child is running. Ctrl-C then belongs to that child. */
32
+ export function handingOver() {
33
+ return inherited > 0;
34
+ }
22
35
  /**
23
36
  * The timeout is our own timer, NOT spawn's `timeout` option. Node clears that
24
37
  * one only on 'exit', which a spawn that fails (ENOENT) never emits -- so every
@@ -46,6 +59,42 @@ export function run(file, args, options = {}) {
46
59
  child.stdin.end(options.input ?? '');
47
60
  });
48
61
  }
62
+ /**
63
+ * The terminal belongs to the child. Only `gh auth login` uses this, and only
64
+ * from a terminal: repown cannot see what the child prints.
65
+ */
66
+ export function inherit(file, args, options = {}) {
67
+ return new Promise((resolve) => {
68
+ inherited += 1;
69
+ const ignore = () => { };
70
+ process.on('SIGINT', ignore);
71
+ const child = spawn(file, [...args], {
72
+ env: options.env ?? process.env,
73
+ shell: false,
74
+ stdio: 'inherit',
75
+ // gh must stay attached to the console so it receives Ctrl-C.
76
+ windowsHide: false,
77
+ });
78
+ settleInherit(child, ignore, resolve);
79
+ });
80
+ }
81
+ /** Drops the parent's SIGINT listener when the child closes or fails to spawn. */
82
+ function settleInherit(child, ignore, resolve) {
83
+ let settled = false;
84
+ const done = (result) => {
85
+ if (settled)
86
+ return;
87
+ settled = true;
88
+ inherited -= 1;
89
+ process.off('SIGINT', ignore);
90
+ resolve(result);
91
+ };
92
+ child.on('error', (error) => done(spawnFailure(error)));
93
+ child.on('close', (code) => done({ code: code ?? -1, stdout: '', stderr: '' }));
94
+ }
95
+ function spawnFailure(error) {
96
+ return { code: -1, stdout: '', stderr: '', spawnError: error };
97
+ }
49
98
  /** Accumulates the child's stdout and stderr; call the result for what has arrived so far. */
50
99
  function collect(child) {
51
100
  let stdout = '';
package/dist/core/git.js CHANGED
@@ -35,10 +35,37 @@ export class Git {
35
35
  async isRepo() {
36
36
  return succeeded(await this.exec(['rev-parse', '--git-dir']));
37
37
  }
38
+ /** No work tree to pin a commit identity in. A failed rev-parse is not bare. */
39
+ async isBare() {
40
+ return output(await this.exec(['rev-parse', '--is-bare-repository'])) === 'true';
41
+ }
38
42
  /** The working tree root. Asked of git so a linked worktree resolves to itself. */
39
43
  async root() {
40
44
  return output(await this.exec(['rev-parse', '--show-toplevel']));
41
45
  }
46
+ /**
47
+ * `symbolic-ref` answers with the branch name even when that branch has no
48
+ * commits yet. Detached HEAD is not a symbolic ref, so the short hash names it.
49
+ */
50
+ async currentBranch() {
51
+ const name = output(await this.exec(['symbolic-ref', '--short', '-q', 'HEAD']));
52
+ if (name)
53
+ return { kind: 'branch', name };
54
+ const hash = output(await this.exec(['rev-parse', '--short', 'HEAD']));
55
+ return hash ? { kind: 'detached', hash } : null;
56
+ }
57
+ /** `git --version`, or null when git cannot be run. Unreadable is not a version. */
58
+ async version() {
59
+ return output(await this.exec(['--version']));
60
+ }
61
+ /** The tracked ref as git reports it (`origin/main`), or null when none is set. */
62
+ async upstreamRef() {
63
+ return output(await this.exec(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']));
64
+ }
65
+ /** Remote names, in the order git lists them. */
66
+ async remotes() {
67
+ return lines(await this.exec(['remote']));
68
+ }
42
69
  /**
43
70
  * The directory every worktree shares -- where hooks and config actually live.
44
71
  * In a linked worktree `.git` is a FILE, so joining '.git' to the root gives a
@@ -65,6 +92,11 @@ export class Git {
65
92
  async getConfig(key, scope) {
66
93
  return output(await this.exec(this.scoped(scope, ['--get', key])));
67
94
  }
95
+ /** Effective boolean, or null when unset or not a bool. Omit `scope` for any-scope. */
96
+ async getBoolConfig(key, scope) {
97
+ const value = output(await this.exec(this.scoped(scope, ['--type=bool', '--get', key])));
98
+ return value === 'true' ? true : value === 'false' ? false : null;
99
+ }
68
100
  async getAllConfig(key, scope) {
69
101
  return lines(await this.exec(this.scoped(scope, ['--get-all', key])));
70
102
  }
@@ -82,7 +114,8 @@ export class Git {
82
114
  const result = await this.exec(this.scoped(scope, ['--get-all', key]));
83
115
  if (!succeeded(result))
84
116
  return [];
85
- const split = result.stdout.split(/\r?\n/);
117
+ // git ends every value with LF on every platform, so a CR is part of a value: kept.
118
+ const split = result.stdout.split('\n');
86
119
  // git terminates the last value with a newline, so a trailing empty element
87
120
  // is an artefact of splitting -- unlike any earlier one, which is a value.
88
121
  if (split[split.length - 1] === '')
@@ -165,6 +198,15 @@ export class Git {
165
198
  }
166
199
  return err('tag chain longer than ' + MAX_TAG_CHAIN + ' starting at ' + sha);
167
200
  }
201
+ /** Full hash of the oldest commit in `range`, or null when none or git cannot list them. */
202
+ async oldestIn(range) {
203
+ const listed = lines(await this.exec(['rev-list', '--reverse', ...range]));
204
+ return listed[0] ?? null;
205
+ }
206
+ /** Short hash of the parent. Null when the commit is a root or cannot be read. */
207
+ async parentShort(sha) {
208
+ return output(await this.exec(['rev-parse', '--verify', '--short', sha + '^']));
209
+ }
168
210
  /** Whether this clone has the commit at all -- a remote tip it never fetched is absent. */
169
211
  async hasCommit(sha) {
170
212
  return succeeded(await this.exec(['cat-file', '-e', sha + '^{commit}']));
@@ -48,7 +48,7 @@ export async function check(input) {
48
48
  if (!identity.email) {
49
49
  return [{
50
50
  reason: 'This clone sets no identity of its own, so the guard cannot tell ' +
51
- 'your commits from anyone else’s.',
51
+ 'your commits from anyone else\'s.',
52
52
  detail: ['fix: repown use <account>'],
53
53
  }];
54
54
  }
@@ -36,6 +36,14 @@ export function entryPoint() {
36
36
  const here = fileURLToPath(import.meta.url);
37
37
  return join(dirname(here), '..', '..', 'cli' + here.slice(here.lastIndexOf('.')));
38
38
  }
39
+ /**
40
+ * True when `entry` sits in a folder of npm's `_npx` cache, where `npx repown` runs a
41
+ * package that isn't installed. A hook pointing there loses its entry point when that
42
+ * folder is deleted. Only npm's layout was measured; other runners aren't recognised.
43
+ */
44
+ export function fromNpxCache(entry) {
45
+ return entry.split(/[\\/]/).slice(0, -1).includes('_npx');
46
+ }
39
47
  /** git may answer relative to the directory it ran in; both are made absolute against it. */
40
48
  async function hookDirs(git) {
41
49
  const [common, hooks] = await Promise.all([git.commonDir(), git.hooksDir()]);
@@ -150,10 +158,11 @@ export async function installGuard(git) {
150
158
  if (await stateOf(path) === 'foreign') {
151
159
  return err('a pre-push hook this tool did not write already exists at ' + path + ' -- leaving it alone');
152
160
  }
161
+ const entry = entryPoint();
153
162
  await mkdir(dirname(path), { recursive: true });
154
- await writeFile(path, hookBody(entryPoint(), process.execPath), 'utf8');
163
+ await writeFile(path, hookBody(entry, process.execPath), 'utf8');
155
164
  await chmod(path, 0o755).catch(() => { });
156
- return ok({ path });
165
+ return ok({ path, entry });
157
166
  }
158
167
  /**
159
168
  * Deletes only a hook repown can prove it wrote, and only from this clone's own
@@ -17,19 +17,36 @@ export function githubProvider() {
17
17
  label: 'GitHub',
18
18
  matches: (url) => HOSTS.includes(url.host),
19
19
  ownerOf: (url) => url.segments[0] ?? null,
20
- credentialKeys: (url) => url.scheme === 'https' ? [`credential.${credentialPrefix(url)}.username`] : [],
21
- resolveProfile: async (account) => {
22
- const [name, id] = await Promise.all([
23
- ghProfileField(account, 'name'),
24
- ghProfileField(account, 'id'),
25
- ]);
26
- // GitHub's own noreply address: publishable by design, and it still links
27
- // the commit to the account. Offered as a default so a private address
28
- // need never be published to get working attribution.
29
- const email = id ? `${id}+${account}@users.noreply.github.com` : undefined;
30
- if (!name && !email)
31
- return null;
32
- return { ...(name ? { name } : {}), ...(email ? { email } : {}) };
33
- },
20
+ credentialKeys,
21
+ resolveProfile,
22
+ accountKind,
34
23
  };
35
24
  }
25
+ function credentialKeys(url) {
26
+ return url.scheme === 'https' ? [`credential.${credentialPrefix(url)}.username`] : [];
27
+ }
28
+ async function resolveProfile(account) {
29
+ const [name, id] = await Promise.all([
30
+ ghProfileField(account, 'name'),
31
+ ghProfileField(account, 'id'),
32
+ ]);
33
+ // GitHub's own noreply address: publishable by design, and it still links
34
+ // the commit to the account. Offered as a default so a private address
35
+ // need never be published to get working attribution.
36
+ const email = id ? `${id}+${account}@users.noreply.github.com` : undefined;
37
+ if (!name && !email)
38
+ return null;
39
+ return { ...(name ? { name } : {}), ...(email ? { email } : {}) };
40
+ }
41
+ /**
42
+ * The users endpoint answers for an organisation too, with type Organization.
43
+ * Anything else, including a failed call, is unknown -- not a user.
44
+ */
45
+ async function accountKind(login) {
46
+ const type = await ghProfileField(login, 'type');
47
+ if (type === 'User')
48
+ return 'user';
49
+ if (type === 'Organization')
50
+ return 'organization';
51
+ return null;
52
+ }
@@ -45,13 +45,26 @@ export async function readIdentity(git, credentialKey) {
45
45
  git.getConfig(NAME_KEY),
46
46
  git.getConfig(EMAIL_KEY),
47
47
  ]);
48
+ const machine = name || email
49
+ ? await machineIdentity(git)
50
+ : { name: inheritedName, email: inheritedEmail };
48
51
  const account = credentialKey ? await git.getConfig(credentialKey, 'local') : null;
49
52
  const inheritedAccount = credentialKey ? await git.getConfig(credentialKey) : null;
50
53
  return {
51
54
  name, email, account, owner, useConfigOnly,
52
55
  inheritedName, inheritedEmail, inheritedAccount,
56
+ machineName: machine.name, machineEmail: machine.email,
53
57
  };
54
58
  }
59
+ /** The identity outside this clone, for a clone that sets its own: global, then system. */
60
+ async function machineIdentity(git) {
61
+ const [name, email] = await Promise.all([configOrSystem(git, NAME_KEY), configOrSystem(git, EMAIL_KEY)]);
62
+ return { name, email };
63
+ }
64
+ async function configOrSystem(git, key) {
65
+ const global = await git.getConfig(key, 'global');
66
+ return global ?? await git.getConfig(key, 'system');
67
+ }
55
68
  /**
56
69
  * Writes the identity to `scope`, plus user.useConfigOnly so git refuses to
57
70
  * invent an identity from the hostname rather than silently using one. That does
@@ -59,14 +72,27 @@ export async function readIdentity(git, credentialKey) {
59
72
  * commit-range check in the guard is for, not a substitute for it.
60
73
  */
61
74
  export async function pinIdentity(git, values, credentialKeys, scope = 'local') {
62
- const writes = [
75
+ return writeAll(pinWrites(values, credentialKeys), (key, value) => git.setConfig(key, value, scope));
76
+ }
77
+ /** Every key `pinIdentity` writes, with the value it writes. */
78
+ export function pinWrites(values, credentialKeys) {
79
+ return [
63
80
  [NAME_KEY, values.name],
64
81
  [EMAIL_KEY, values.email],
65
82
  [USE_CONFIG_ONLY_KEY, 'true'],
66
83
  [ACCOUNT_KEY, values.account],
67
84
  ...credentialKeys.map((key) => [key, values.account]),
68
85
  ];
69
- return writeAll(writes, (key, value) => git.setConfig(key, value, scope));
86
+ }
87
+ /**
88
+ * True only when pinning again would write nothing new: every key holds exactly one
89
+ * value, character for character. Read raw, because a trimmed read hides the stray
90
+ * blank or padded value that makes git and the guard disagree.
91
+ */
92
+ export async function pinHolds(git, values, credentialKeys) {
93
+ const writes = pinWrites(values, credentialKeys);
94
+ const found = await Promise.all(writes.map(([key]) => git.getAllConfigRaw(key, 'local')));
95
+ return writes.every(([, value], index) => found[index].length === 1 && found[index][0] === value);
70
96
  }
71
97
  export async function clearIdentity(git, credentialKeys, scope = 'local') {
72
98
  const keys = [NAME_KEY, EMAIL_KEY, USE_CONFIG_ONLY_KEY, ACCOUNT_KEY, ...credentialKeys];
@@ -19,15 +19,16 @@ export async function inspectRepo(git) {
19
19
  const url = originUrl ? parseGitUrl(originUrl) : null;
20
20
  const provider = providerFor(url);
21
21
  const credentialKeys = url ? provider.credentialKeys(url) : [];
22
- const [root, hook, identity, guard, helper] = await Promise.all([
22
+ const [root, branch, hook, identity, guard, helper] = await Promise.all([
23
23
  isRepo ? git.root() : Promise.resolve(null),
24
+ isRepo ? git.currentBranch() : Promise.resolve(null),
24
25
  isRepo ? hookLocation(git) : Promise.resolve(null),
25
26
  readIdentity(git, credentialKeys[0] ?? null),
26
27
  isRepo ? guardState(git) : Promise.resolve('off'),
27
28
  git.getUrlMatch('credential.helper', originUrl ?? DEFAULT_PROBE_URL),
28
29
  ]);
29
30
  return {
30
- git, isRepo, root, originUrl, url, provider,
31
+ git, isRepo, root, branch, originUrl, url, provider,
31
32
  owner: url ? provider.ownerOf(url) : null,
32
33
  identity, credentialKeys, guard, hook, helper,
33
34
  };
@@ -0,0 +1,110 @@
1
+ // Commits on the current branch that no remote-tracking ref has.
2
+ //
3
+ // Pinning does not rewrite them (ADR-013). The guard refuses them at push
4
+ // (ADR-002, ADR-011), so `use` and setup's review say so first, with a copyable
5
+ // `git rebase` onto the parent of the oldest of those commits (`--root` when it
6
+ // has none). The identities come from `git log` through Git.identitiesIn
7
+ // (`--no-show-signature`). The base is `rev-list` and `rev-parse` on Git.
8
+ // scan's address totals are a different question: every ref, counts only, and
9
+ // setup loads them only for the guard question.
10
+ import { ok } from "./result.js";
11
+ const ADDRESS_CAP = 3;
12
+ const AMEND = '--exec "git commit --amend --no-edit --reset-author --allow-empty"';
13
+ export async function readUnpushed(git) {
14
+ const head = await git.currentBranch();
15
+ if (head?.kind !== 'branch')
16
+ return quiet(null);
17
+ const commits = await commitsOf(git);
18
+ if (!commits.ok || commits.value.length === 0)
19
+ return { branch: head.name, commits, rebaseBase: null };
20
+ return { branch: head.name, commits, rebaseBase: await rebaseBase(git) };
21
+ }
22
+ function quiet(branch) {
23
+ return { branch, commits: ok([]), rebaseBase: null };
24
+ }
25
+ /** Parent of the oldest unpushed commit, or `--root` when that commit has none. */
26
+ async function rebaseBase(git) {
27
+ const oldest = await git.oldestIn(['HEAD', '--not', '--remotes']);
28
+ if (!oldest)
29
+ return null;
30
+ return (await git.parentShort(oldest)) ?? '--root';
31
+ }
32
+ /** No commit yet is an empty list. A log git could not print stays an error. */
33
+ async function commitsOf(git) {
34
+ if (!await git.hasCommit('HEAD'))
35
+ return ok([]);
36
+ const found = await git.identitiesIn(['HEAD', '--not', '--remotes']);
37
+ if (!found.ok)
38
+ return found;
39
+ return ok(found.value.map(brief));
40
+ }
41
+ function brief(commit) {
42
+ return { authorEmail: commit.authorEmail, committerEmail: commit.committerEmail };
43
+ }
44
+ /** Lines to show. Empty when there is nothing to say. The first is the fact; any other is how to fix it. */
45
+ export function unpushedLines(fact, email) {
46
+ if (fact.branch === null)
47
+ return [];
48
+ if (!fact.commits.ok)
49
+ return [unread(fact.branch, fact.commits.error)];
50
+ return foreignLines(fact.branch, fact.commits.value, email, fact.rebaseBase);
51
+ }
52
+ function foreignLines(branch, commits, email, base) {
53
+ const found = collect(commits, fold(email));
54
+ if (found.count === 0)
55
+ return [];
56
+ return [sentence(branch, found), ...reauthorLine(found.count, base)];
57
+ }
58
+ function reauthorLine(count, base) {
59
+ if (!base)
60
+ return [];
61
+ const them = count === 1 ? 'it' : 'them';
62
+ return ['re-author ' + them + ': git rebase ' + base + ' ' + AMEND + ', or pin that address'];
63
+ }
64
+ function collect(commits, wanted) {
65
+ const foreign = commits.filter((commit) => !own(commit, wanted));
66
+ return { count: foreign.length, addresses: distinct(foreign, wanted) };
67
+ }
68
+ function own(commit, wanted) {
69
+ return fold(commit.authorEmail) === wanted && fold(commit.committerEmail) === wanted;
70
+ }
71
+ function distinct(commits, wanted) {
72
+ const seen = new Map();
73
+ for (const address of commits.flatMap(both))
74
+ remember(seen, address, wanted);
75
+ return [...seen.values()];
76
+ }
77
+ function both(commit) {
78
+ return [commit.authorEmail, commit.committerEmail];
79
+ }
80
+ function remember(seen, address, wanted) {
81
+ const key = fold(address);
82
+ if (key === wanted || seen.has(key))
83
+ return;
84
+ seen.set(key, address);
85
+ }
86
+ function fold(address) {
87
+ return address.toLowerCase();
88
+ }
89
+ function sentence(branch, found) {
90
+ const noun = found.count === 1 ? '1 commit' : found.count + ' commits';
91
+ const verb = found.count === 1 ? 'is' : 'are';
92
+ const them = found.count === 1 ? 'it' : 'them';
93
+ return noun + ' on ' + show(branch) + ' not on any remote ' + verb + ' by ' +
94
+ list(found.addresses) + '; the guard will refuse ' + them;
95
+ }
96
+ function list(addresses) {
97
+ const shown = addresses.slice(0, ADDRESS_CAP).map(show);
98
+ const rest = addresses.length - shown.length;
99
+ const tail = rest > 0 ? ' and ' + rest + ' more' : '';
100
+ return shown.join(', ') + tail;
101
+ }
102
+ function unread(branch, error) {
103
+ return 'commits on ' + show(branch) + ' not on any remote could not be read (' +
104
+ show(error) + '), so repown can\'t say whether the guard will refuse them';
105
+ }
106
+ /** Control characters could redraw the terminal around a line taken from a commit. */
107
+ function show(text) {
108
+ const cleaned = text.replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
109
+ return cleaned.length > 0 ? cleaned : '(none)';
110
+ }
@@ -0,0 +1,17 @@
1
+ // Comparing a tool's reported major.minor.patch. gh's login gate and setup's
2
+ // push.autoSetupRemote gate share this, so the two comparisons cannot drift.
3
+ /** True when the captured major.minor.patch is at least `min`. A non-number fails. */
4
+ export function versionAtLeast(found, min) {
5
+ for (let i = 0; i < min.length; i++) {
6
+ const got = Number(found[i + 1]);
7
+ if (got !== min[i])
8
+ return got > min[i];
9
+ }
10
+ return true;
11
+ }
12
+ /** Git gained `push.autoSetupRemote` in 2.37.0. Unreadable text is not that. */
13
+ const AUTO_UPSTREAM_MIN = [2, 37, 0];
14
+ export function gitSupportsAutoUpstream(text) {
15
+ const found = /git version (\d+)\.(\d+)\.(\d+)/.exec(text);
16
+ return found !== null && versionAtLeast(found, AUTO_UPSTREAM_MIN);
17
+ }
@@ -121,15 +121,25 @@ export async function runProgram(program, argv) {
121
121
  return runHelp(program, []);
122
122
  if (argv[0] === 'help')
123
123
  return runHelp(program, argv.slice(1));
124
- if (argv.length === 0 && program.defaultCommand === undefined)
124
+ const words = await bareArgv(program, argv);
125
+ if (words === 'help')
125
126
  return runHelp(program, []);
126
- const top = await resolveTop(program, argv);
127
+ if (words.length === 0 && program.defaultCommand === undefined)
128
+ return runHelp(program, []);
129
+ const top = await resolveTop(program, words);
127
130
  if (!top.ok) {
128
131
  reportUsageError(program.name, top.error + helpPointer(program, []));
129
132
  return 2;
130
133
  }
131
134
  return dispatch(program, top.value);
132
135
  }
136
+ /** Empty argv with a chooser becomes that command, or `'help'` for the top help. */
137
+ async function bareArgv(program, argv) {
138
+ if (argv.length > 0 || program.chooseDefault === undefined)
139
+ return argv;
140
+ const chosen = await program.chooseDefault();
141
+ return chosen === 'help' ? 'help' : [chosen];
142
+ }
133
143
  /** The whole life of the process: run, set the exit code, and report a crash as a failure. */
134
144
  export function start(program) {
135
145
  out.ignoreBrokenPipe();