repown 0.4.0 → 0.5.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +99 -1
  2. package/README.md +4 -1
  3. package/dist/cli.js +4 -4
  4. package/dist/commands/accounts.js +20 -14
  5. package/dist/commands/doctor.js +7 -5
  6. package/dist/commands/fix.js +5 -5
  7. package/dist/commands/guard.js +7 -5
  8. package/dist/commands/off.js +4 -4
  9. package/dist/commands/reauthor.js +5 -5
  10. package/dist/commands/scan.js +9 -7
  11. package/dist/commands/setup.js +3 -3
  12. package/dist/commands/start.js +6 -6
  13. package/dist/commands/status.js +20 -16
  14. package/dist/commands/use.js +18 -14
  15. package/dist/core/blockers.js +8 -7
  16. package/dist/core/config-snapshot.js +97 -0
  17. package/dist/core/credential/gcm.js +3 -3
  18. package/dist/core/credential/gh.js +14 -6
  19. package/dist/core/credential/repair.js +1 -1
  20. package/dist/core/git.js +27 -4
  21. package/dist/core/guard/check.js +44 -8
  22. package/dist/core/guard/hook.js +1 -1
  23. package/dist/core/hosts/github.js +43 -12
  24. package/dist/core/hosts/index.js +21 -3
  25. package/dist/core/identity.js +1 -1
  26. package/dist/core/inspect.js +19 -8
  27. package/dist/core/push-destination.js +1 -1
  28. package/dist/core/push-state.js +12 -8
  29. package/dist/core/reauthor.js +3 -3
  30. package/dist/core/registry.js +12 -5
  31. package/dist/core/unpushed.js +10 -9
  32. package/dist/program.js +10 -10
  33. package/dist/ui/args.js +3 -3
  34. package/dist/ui/command.js +1 -1
  35. package/dist/ui/dispatch.js +6 -6
  36. package/dist/ui/format.js +31 -0
  37. package/dist/ui/help.js +2 -2
  38. package/dist/ui/prompt.js +1 -1
  39. package/dist/wizard/clack.js +56 -21
  40. package/dist/wizard/engine.js +1 -1
  41. package/dist/wizard/home-context.js +23 -10
  42. package/dist/wizard/home-flow.js +33 -11
  43. package/dist/wizard/home-run.js +92 -44
  44. package/dist/wizard/home-text.js +18 -3
  45. package/dist/wizard/plain.js +2 -2
  46. package/dist/wizard/review-text.js +19 -4
  47. package/dist/wizard/setup-changes.js +2 -2
  48. package/dist/wizard/setup-context.js +22 -18
  49. package/dist/wizard/setup-flow.js +115 -35
  50. package/dist/wizard/setup-run.js +31 -28
  51. package/npm-shrinkwrap.json +378 -17
  52. package/package.json +3 -3
@@ -0,0 +1,97 @@
1
+ // Config reads answered from one `git config [--scope] --list -z` per scope, read on first
2
+ // use, for code that only reads (ADR-029). A plain `--get` or `--get-all` is answered with
3
+ // the output git itself would print for it, so Git's parsing of that output is unchanged.
4
+ // Other config queries (`--type=bool`, `--get-urlmatch`, `--show-origin --get-regexp`) and
5
+ // every non-config call go to git. A config write refuses.
6
+ import { Git } from './git.js';
7
+ import { succeeded } from './exec.js';
8
+ const SCOPE_FLAGS = new Map([['--local', 'local'], ['--global', 'global'], ['--system', 'system']]);
9
+ /** The first argument after `config` and its scope: the query git is asked, never a value. */
10
+ const PASSED_THROUGH = new Set(['--type=bool', '--get-urlmatch', '--show-origin', '--get-regexp', '--list']);
11
+ export class ConfigSnapshot extends Git {
12
+ lists = new Map();
13
+ exec(args, input) {
14
+ if (args[0] !== 'config')
15
+ return this.spawnGit(args, input);
16
+ const read = configRead(args);
17
+ if (read)
18
+ return this.answer(read);
19
+ if (PASSED_THROUGH.has(actionOf(args) ?? ''))
20
+ return this.spawnGit(args, input);
21
+ return Promise.reject(new Error('a config snapshot only reads: git ' + args.join(' ')));
22
+ }
23
+ async answer(read) {
24
+ const listed = await this.listOf(read.scope);
25
+ if (!succeeded(listed))
26
+ return listed;
27
+ const values = valuesOf(listed.stdout, canonicalKey(read.key));
28
+ if (values.length === 0)
29
+ return answered(1, '');
30
+ if (read.all)
31
+ return answered(0, values.map((value) => (value ?? '') + '\n').join(''));
32
+ return answered(0, (values[values.length - 1] ?? '') + '\n');
33
+ }
34
+ /**
35
+ * One list per scope, shared by every read of this snapshot (a failure too). A scope with
36
+ * no file at all is empty: `--list` fails there where `--get` says "not set".
37
+ */
38
+ listOf(scope) {
39
+ const name = scope ?? 'effective';
40
+ if (!this.lists.has(name))
41
+ this.lists.set(name, this.spawnGit(listArgs(scope)).then(missingFileIsEmpty));
42
+ return this.lists.get(name);
43
+ }
44
+ }
45
+ /**
46
+ * A snapshot of a plain `git`, or `git` itself when it already is one. A subclass is refused:
47
+ * the snapshot keeps only the cwd, so whatever the subclass overrides would be dropped.
48
+ */
49
+ export function snapshotOf(git) {
50
+ if (git instanceof ConfigSnapshot)
51
+ return git;
52
+ if (Object.getPrototypeOf(git) !== Git.prototype)
53
+ throw new Error('snapshotOf takes a plain Git, not ' + git.constructor.name);
54
+ return new ConfigSnapshot(git.cwd);
55
+ }
56
+ function listArgs(scope) {
57
+ return scope ? ['config', '--' + scope, '--list', '-z'] : ['config', '--list', '-z'];
58
+ }
59
+ function missingFileIsEmpty(listed) {
60
+ return !succeeded(listed) && /unable to read config file/.test(listed.stderr) ? answered(0, '') : listed;
61
+ }
62
+ /** The query after `config` and an optional scope flag. */
63
+ function actionOf(args) {
64
+ return SCOPE_FLAGS.has(args[1] ?? '') ? args[2] : args[1];
65
+ }
66
+ /** `config [--scope] --get|--get-all <key>`, exactly the shapes Git's plain getters send. */
67
+ function configRead(args) {
68
+ const scoped = SCOPE_FLAGS.get(args[1] ?? '');
69
+ const rest = args.slice(scoped ? 2 : 1);
70
+ if (rest.length !== 2 || (rest[0] !== '--get' && rest[0] !== '--get-all'))
71
+ return null;
72
+ return { scope: scoped, key: rest[1], all: rest[0] === '--get-all' };
73
+ }
74
+ /** Section and variable name are case-insensitive, a subsection is not: `--list` prints them so. */
75
+ function canonicalKey(key) {
76
+ const first = key.indexOf('.');
77
+ const last = key.lastIndexOf('.');
78
+ if (first <= 0 || last === key.length - 1)
79
+ return '\0';
80
+ const section = key.slice(0, first).toLowerCase();
81
+ const name = key.slice(last + 1).toLowerCase();
82
+ return first === last ? section + '.' + name : section + '.' + key.slice(first + 1, last) + '.' + name;
83
+ }
84
+ /** Every value of `key`, in git's order; null for a key written with no `=` (git's implicit true). */
85
+ function valuesOf(listed, key) {
86
+ const values = [];
87
+ for (const entry of listed.split('\0')) {
88
+ const newline = entry.indexOf('\n');
89
+ const name = newline < 0 ? entry : entry.slice(0, newline);
90
+ if (entry !== '' && name === key)
91
+ values.push(newline < 0 ? null : entry.slice(newline + 1));
92
+ }
93
+ return values;
94
+ }
95
+ function answered(code, stdout) {
96
+ return { code, stdout, stderr: '' };
97
+ }
@@ -13,14 +13,14 @@
13
13
  // deliberately rather than rediscovered.
14
14
  import { join, dirname } from 'node:path';
15
15
  import { existsSync } from 'node:fs';
16
- import { run, succeeded, lines, notInstalled } from "../exec.js";
17
- import { ok, err } from "../result.js";
16
+ import { run, succeeded, lines, notInstalled } from '../exec.js';
17
+ import { ok, err } from '../result.js';
18
18
  const NAMES = ['git-credential-manager', 'git-credential-manager-core'];
19
19
  /** Directories that hold GCM but are not necessarily on PATH. */
20
20
  async function searchDirectories() {
21
21
  const directories = [];
22
22
  // Git for Windows bundles GCM as a sibling of git's own exec-path:
23
- // <root>/mingw64/libexec/git-core -> <root>/mingw64/bin
23
+ // <root>/mingw64/libexec/git-core -> <root>/mingw64/bin (ucrt64 from Git 2.56 on)
24
24
  const execPath = await run('git', ['--exec-path']);
25
25
  if (succeeded(execPath)) {
26
26
  const mingw = dirname(dirname(execPath.stdout.trim()));
@@ -20,9 +20,9 @@
20
20
  // "Could not be queried" is a THIRD STATE, distinct both from "gh is not
21
21
  // installed" and from "gh is active as nobody". Collapsing it into either is the
22
22
  // bug this shape exists to prevent.
23
- import { run, inherit, succeeded, notInstalled, output } from "../exec.js";
24
- import { ok, err } from "../result.js";
25
- import { versionAtLeast } from "../version.js";
23
+ import { run, inherit, succeeded, notInstalled, output } from '../exec.js';
24
+ import { ok, err } from '../result.js';
25
+ import { versionAtLeast } from '../version.js';
26
26
  /**
27
27
  * A credential-helper value that `gh auth setup-git` wrote -- `!gh auth
28
28
  * git-credential`, or with gh's path, quoted on Windows -- and nothing more. A
@@ -100,13 +100,21 @@ function toAccount(raw) {
100
100
  }
101
101
  /** Arguments for a github.com profile field. `--hostname` so GH_HOST cannot redirect the call. */
102
102
  export function ghProfileArgs(login, field) {
103
- return ['api', '--hostname', 'github.com', `users/${login}`, '--jq', `.${field}`];
103
+ // One path segment, whatever the login holds (callers also look up only GitHub-shaped logins).
104
+ return ['api', '--hostname', 'github.com', `users/${encodeURIComponent(login)}`, '--jq', `.${field}`];
104
105
  }
105
106
  /** A profile field from github.com, or null. Absence here is unremarkable. */
106
107
  export async function ghProfileField(login, field) {
107
- const result = await run('gh', ghProfileArgs(login, field));
108
+ return (await ghProfileLookup(login, field)).value;
109
+ }
110
+ export async function ghProfileLookup(login, field) {
111
+ return profileLookupFrom(await run('gh', ghProfileArgs(login, field)));
112
+ }
113
+ /** Only github.com's own 404 means missing: offline, refused or no gh is unknown. */
114
+ export function profileLookupFrom(result) {
108
115
  const value = output(result);
109
- return value && value !== 'null' ? value : null;
116
+ const missing = !succeeded(result) && /\(HTTP 404\)/.test(result.stderr);
117
+ return { value: value && value !== 'null' ? value : null, missing };
110
118
  }
111
119
  export async function ghSwitch(login) {
112
120
  const result = await run('gh', ['auth', 'switch', '-u', login]);
@@ -25,7 +25,7 @@
25
25
  // vanished from the report and a partial repair read as a smaller successful one.
26
26
  // The system scope is the realistic case: reading it needs nothing, editing it is
27
27
  // machine-wide and needs an elevated shell.
28
- import { isGh } from "./gh.js";
28
+ import { isGh } from './gh.js';
29
29
  const SCOPES = ['local', 'global', 'system'];
30
30
  const HOSTS = ['https://github.com', 'https://gist.github.com'];
31
31
  /**
package/dist/core/git.js CHANGED
@@ -17,19 +17,24 @@ import { existsSync } from 'node:fs';
17
17
  import { join, resolve } from 'node:path';
18
18
  import { tmpdir } from 'node:os';
19
19
  import { randomUUID } from 'node:crypto';
20
- import { run, succeeded, output, lines } from "./exec.js";
21
- import { ok, err } from "./result.js";
20
+ import { run, succeeded, output, lines } from './exec.js';
21
+ import { ok, err } from './result.js';
22
22
  export class Git {
23
23
  cwd;
24
24
  constructor(cwd = process.cwd()) {
25
25
  this.cwd = cwd;
26
26
  }
27
+ /** Every short git call. A ConfigSnapshot answers plain config reads here instead (ADR-029). */
28
+ exec(args, input) {
29
+ return this.spawnGit(args, input);
30
+ }
27
31
  /**
32
+ * Starts the git child for exec() (execLong starts its own, for fetch and ls-remote).
28
33
  * --no-replace-objects on every call: `git replace` changes what git SHOWS for
29
34
  * an object, never what a push SENDS, so a replaced foreign commit read as the
30
35
  * clean replacement while the original was published.
31
36
  */
32
- exec(args, input) {
37
+ spawnGit(args, input) {
33
38
  const full = ['--no-replace-objects', ...args];
34
39
  return input === undefined
35
40
  ? run('git', full, { cwd: this.cwd })
@@ -70,6 +75,24 @@ export class Git {
70
75
  async remotes() {
71
76
  return lines(await this.exec(['remote']));
72
77
  }
78
+ /**
79
+ * The URL `git push <remote>` uses, as the pre-push hook receives it: pushurl, then
80
+ * pushInsteadOf and insteadOf applied by git itself (the first, when there are several).
81
+ * The raw keys only when git can't say (an old git without `remote get-url`).
82
+ */
83
+ async remotePushUrl(remote) {
84
+ const asked = output(await this.exec(['remote', 'get-url', '--push', '--', remote]));
85
+ if (asked)
86
+ return asked;
87
+ return (await this.getConfig('remote.' + remote + '.pushurl')) ?? this.getConfig('remote.' + remote + '.url');
88
+ }
89
+ /**
90
+ * A bare URL after git's insteadOf rewriting (`ls-remote --get-url` contacts nothing).
91
+ * It reads fetch rules, so a pushInsteadOf on a bare push URL is not applied.
92
+ */
93
+ async rewrittenUrl(url) {
94
+ return output(await this.exec(['ls-remote', '--get-url', '--', url]));
95
+ }
73
96
  /** Remote names, in the order git lists them. A failed read is an error, not "none". */
74
97
  async readRemotes() {
75
98
  const listed = await this.exec(['remote']);
@@ -143,11 +166,11 @@ export class Git {
143
166
  async setConfig(key, value, scope = 'local') {
144
167
  return succeeded(await this.exec(this.scoped(scope, [key, value])));
145
168
  }
146
- /** True when the key is gone afterwards -- including when it was never set. */
147
169
  /** Appends one more value to a multi-valued key. */
148
170
  async addConfig(key, value, scope) {
149
171
  return succeeded(await this.exec(this.scoped(scope, ['--add', key, value])));
150
172
  }
173
+ /** True when the key is gone afterwards -- including when it was never set. */
151
174
  async unsetConfig(key, scope = 'local') {
152
175
  const result = await this.exec(this.scoped(scope, ['--unset-all', key]));
153
176
  return succeeded(result) || result.code === 5; // 5 = the key did not exist
@@ -14,9 +14,9 @@
14
14
  //
15
15
  // which is exactly the set of commits about to be published. The previous design
16
16
  // read that and threw it away.
17
- import { parseGitUrl } from "../url.js";
18
- import { providerFor } from "../hosts/index.js";
19
- import { readIdentity, legacyAccountKey } from "../identity.js";
17
+ import { parseGitUrl } from '../url.js';
18
+ import { providerFor } from '../hosts/index.js';
19
+ import { readIdentity, legacyAccountKey } from '../identity.js';
20
20
  /** The null object id: 40 zeros, or 64 in a SHA-256 repository. */
21
21
  const isZero = (sha) => /^0+$/.test(sha);
22
22
  const MIRROR_KEY = 'repown.mirrorBranch';
@@ -108,7 +108,7 @@ function checkDestination({ url, owner, allowed }, onNote) {
108
108
  'destination: ' + printable(redacted(url.raw)),
109
109
  'allowed here: ' + allowed.join(', '),
110
110
  'if that owner is legitimate -- an organisation you belong to, say:',
111
- ' git config --local --add ' + ALLOW_OWNER_KEY + ' ' + shellWord(printable(owner)),
111
+ ' ' + (allowOwnerCommand(owner) ?? ALLOW_OWNER_BY_HAND),
112
112
  ],
113
113
  }];
114
114
  }
@@ -232,9 +232,12 @@ function unreadableHint(error) {
232
232
  function matches(actual, expected) {
233
233
  return actual.toLowerCase() === expected.toLowerCase();
234
234
  }
235
- /** Text a commit's author chose: control characters could rewrite the terminal around the refusal. */
235
+ /**
236
+ * Text a commit's author or a remote URL chose: control characters could rewrite the
237
+ * terminal around the refusal, and bidi or zero-width ones show one owner as another.
238
+ */
236
239
  function printable(text) {
237
- return text.replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
240
+ return text.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, '?');
238
241
  }
239
242
  /**
240
243
  * A URL as it may be shown: the WHOLE userinfo is replaced. A token is often the
@@ -243,7 +246,40 @@ function printable(text) {
243
246
  function redacted(raw) {
244
247
  return raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i, '$1***@');
245
248
  }
246
- /** An owner comes from the URL, so a suggested command must quote it for the shell. */
249
+ /**
250
+ * A word of a command printed to copy, as sh, bash, dash, zsh, fish, PowerShell and cmd all
251
+ * read it (test/paste.test.ts runs each). Bare when no shell treats any of it specially: a
252
+ * leading `@` is a PowerShell splat, and PowerShell splits a dashed word at `.` or `:`.
253
+ * `--` is quoted, since PowerShell drops a bare one from the `$args` of repown.ps1.
254
+ * Otherwise double quotes, unless they would expand or end early somewhere: `$` and a
255
+ * backtick (POSIX, PowerShell), `%` and `!` (cmd), a curly double quote (PowerShell), a
256
+ * backslash that escapes (`\\`, or one before the closing quote), a control character, or
257
+ * nothing at all (Windows PowerShell drops `""`). Then it is null and the caller prints no
258
+ * command: single quotes are no quotes in cmd, and PowerShell would run the rest of a
259
+ * POSIX `'\''` as code.
260
+ */
247
261
  export function shellWord(value) {
248
- return /^[\w.@-]+$/.test(value) ? value : "'" + value.replace(/'/g, "'\\''") + "'";
262
+ if (value === '--')
263
+ return '"--"';
264
+ if (/^(?:-[\w-]*|[\w./][\w.@+/:-]*)$/.test(value))
265
+ return value;
266
+ if (value === '' || /["$`%!“”„\x00-\x1f\x7f-\x9f]|\\\\|\\$/.test(value))
267
+ return null;
268
+ return '"' + value + '"';
269
+ }
270
+ /** A whole command to copy, or null when one of its words can't be printed safely (shellWord). */
271
+ export function copyableCommand(words) {
272
+ const quoted = words.map(shellWord);
273
+ return quoted.every((word) => word !== null) ? quoted.join(' ') : null;
274
+ }
275
+ /** Said instead of the allow-owner command when that command can't be printed safely. */
276
+ export const ALLOW_OWNER_BY_HAND = 'add that owner to ' + ALLOW_OWNER_KEY + ' with git config yourself (it can\'t be printed safely to paste)';
277
+ /**
278
+ * The command that lets this clone push to `owner`, or null: for an owner git would read
279
+ * as an option, or one that shows as something else (control or bidi characters).
280
+ */
281
+ export function allowOwnerCommand(owner) {
282
+ if (owner.startsWith('-') || printable(owner) !== owner)
283
+ return null;
284
+ return copyableCommand(['git', 'config', '--local', '--add', ALLOW_OWNER_KEY, owner]);
249
285
  }
@@ -19,7 +19,7 @@ import { readFile, writeFile, mkdir, rm, chmod } from 'node:fs/promises';
19
19
  import { existsSync, realpathSync } from 'node:fs';
20
20
  import { join, dirname, resolve } from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
22
- import { ok, err } from "../result.js";
22
+ import { ok, err } from '../result.js';
23
23
  export const MARKER = 'repown-identity-guard';
24
24
  /**
25
25
  * A marker counts only where this tool writes it: line 2 (right after the shebang)
@@ -8,8 +8,9 @@
8
8
  //
9
9
  // Over SSH there is no credential helper at all -- the SSH key decides -- so an
10
10
  // SSH remote pins no credential key rather than one that selects nothing.
11
- import { credentialPrefix } from "../url.js";
12
- import { ghProfileField } from "../credential/gh.js";
11
+ import { credentialPrefix } from '../url.js';
12
+ import { ghProfileField, ghProfileLookup } from '../credential/gh.js';
13
+ import { printable } from '../../ui/format.js';
13
14
  const HOSTS = ['github.com', 'gist.github.com', 'www.github.com', 'ssh.github.com'];
14
15
  export function githubProvider() {
15
16
  return {
@@ -25,28 +26,58 @@ export function githubProvider() {
25
26
  function credentialKeys(url) {
26
27
  return url.scheme === 'https' ? [`credential.${credentialPrefix(url)}.username`] : [];
27
28
  }
28
- async function resolveProfile(account) {
29
- const [name, id] = await Promise.all([
30
- ghProfileField(account, 'name'),
31
- ghProfileField(account, 'id'),
32
- ]);
29
+ /**
30
+ * GitHub's own login shape (an underscore for Enterprise Managed Users). Nothing else is
31
+ * looked up: a typed `../user` would make `users/../user` GitHub's own `/user`, the
32
+ * signed-in account, and suggest its name and address for another login.
33
+ */
34
+ export function githubLogin(login) {
35
+ return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(login);
36
+ }
37
+ function resolveProfile(account) {
38
+ return profileFrom(account, ghProfileField);
39
+ }
40
+ /**
41
+ * The suggestion for a GitHub-shaped login. A name that printable() would change (control,
42
+ * bidi, zero-width characters) is dropped: it would be drawn, and saved if accepted.
43
+ */
44
+ export async function profileFrom(account, read) {
45
+ if (!githubLogin(account))
46
+ return null;
47
+ const [found, id] = await Promise.all([read(account, 'name'), read(account, 'id')]);
48
+ const name = found && printable(found) === found ? found : null;
33
49
  // GitHub's own noreply address: publishable by design, and it still links
34
50
  // the commit to the account. Offered as a default so a private address
35
51
  // need never be published to get working attribution.
36
- const email = id ? `${id}+${account}@users.noreply.github.com` : undefined;
52
+ const email = id && /^\d+$/.test(id) ? `${id}+${account}@users.noreply.github.com` : undefined;
37
53
  if (!name && !email)
38
54
  return null;
39
55
  return { ...(name ? { name } : {}), ...(email ? { email } : {}) };
40
56
  }
57
+ /** The address GitHub gives an account to keep its own private (with or without the id in front). */
58
+ export function isNoreplyAddress(email) {
59
+ return /^(\d+\+)?[^@\s]+@users\.noreply\.github\.com$/i.test(email);
60
+ }
41
61
  /**
42
62
  * The users endpoint answers for an organisation too, with type Organization.
43
63
  * Anything else, including a failed call, is unknown -- not a user.
44
64
  */
45
- async function accountKind(login) {
46
- const type = await ghProfileField(login, 'type');
47
- if (type === 'User')
65
+ function accountKind(login) {
66
+ return kindFrom(login, ghProfileLookup);
67
+ }
68
+ /**
69
+ * What github.com says a login is. One GitHub can't have (a dot, a slash, a leading dash)
70
+ * is missing without asking: the typo still gets its sentence, and nothing reaches the API.
71
+ */
72
+ export async function kindFrom(login, lookup) {
73
+ if (!githubLogin(login))
74
+ return 'missing';
75
+ const found = await lookup(login, 'type');
76
+ if (found.missing)
77
+ return 'missing';
78
+ if (found.value === 'User')
48
79
  return 'user';
49
- if (type === 'Organization')
80
+ if (found.value === 'Organization')
50
81
  return 'organization';
51
82
  return null;
52
83
  }
@@ -1,8 +1,8 @@
1
1
  // Provider resolution. Ordered, with `generic` always last so every URL resolves
2
2
  // to something and no caller has to handle "no provider".
3
- import { githubProvider } from "./github.js";
4
- import { azureDevOpsProvider } from "./azdo.js";
5
- import { genericProvider } from "./generic.js";
3
+ import { githubProvider } from './github.js';
4
+ import { azureDevOpsProvider } from './azdo.js';
5
+ import { genericProvider } from './generic.js';
6
6
  export function providers() {
7
7
  return [githubProvider(), azureDevOpsProvider(), genericProvider()];
8
8
  }
@@ -12,3 +12,21 @@ export function providerFor(url) {
12
12
  return all[all.length - 1];
13
13
  return all.find((provider) => provider.matches(url)) ?? all[all.length - 1];
14
14
  }
15
+ /**
16
+ * What to tell someone about a login the host looked up, or null for a user or an
17
+ * unknown. Only GitHub answers accountKind, so the words name github.com.
18
+ */
19
+ export function loginKindProblem(kind, login) {
20
+ if (kind === 'missing')
21
+ return 'github.com has no account named ' + login + ': check the spelling';
22
+ if (kind === 'organization')
23
+ return login + ' is an organisation on github.com, not an account you sign in as';
24
+ return null;
25
+ }
26
+ /** The host's profile for a login, and a sentence when the host says it is no account or an organisation. */
27
+ export async function lookUpProfile(provider, account) {
28
+ if (!provider?.resolveProfile)
29
+ return { profile: {}, problem: null };
30
+ const [profile, kind] = await Promise.all([provider.resolveProfile(account), provider.accountKind?.(account)]);
31
+ return { profile: profile ?? {}, problem: loginKindProblem(kind, account) };
32
+ }
@@ -12,7 +12,7 @@
12
12
  // for a public repository to leak.
13
13
  //
14
14
  // NO NAMES OR ADDRESSES APPEAR IN THIS FILE.
15
- import { credentialPrefix } from "./url.js";
15
+ import { credentialPrefix } from './url.js';
16
16
  export const NAME_KEY = 'user.name';
17
17
  export const EMAIL_KEY = 'user.email';
18
18
  export const USE_CONFIG_ONLY_KEY = 'user.useConfigOnly';
@@ -6,12 +6,12 @@
6
6
  // (`git --exec-path`, GCM, gh) and is identical for every clone on the machine,
7
7
  // so the commands that need it ask for it separately -- and `repown scan`, which
8
8
  // walks many repositories, never asks for it at all.
9
- import { parseGitUrl } from "./url.js";
10
- import { providerFor } from "./hosts/index.js";
11
- import { readIdentity } from "./identity.js";
12
- import { guardState, hookLocation } from "./guard/hook.js";
13
- import { findGcm, listAccounts, isGcm } from "./credential/gcm.js";
14
- import { ghState, ghInstalled, isGh } from "./credential/gh.js";
9
+ import { parseGitUrl } from './url.js';
10
+ import { providerFor } from './hosts/index.js';
11
+ import { readIdentity } from './identity.js';
12
+ import { guardState, hookLocation } from './guard/hook.js';
13
+ import { findGcm, listAccounts, isGcm } from './credential/gcm.js';
14
+ import { ghState, ghInstalled, isGh } from './credential/gh.js';
15
15
  const DEFAULT_PROBE_URL = 'https://github.com/';
16
16
  export async function inspectRepo(git) {
17
17
  const isRepo = await git.isRepo();
@@ -19,20 +19,31 @@ 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, branch, hook, identity, guard, helper] = await Promise.all([
22
+ const [root, branch, hook, identity, guard, helper, pushed] = await Promise.all([
23
23
  isRepo ? git.root() : Promise.resolve(null),
24
24
  isRepo ? git.currentBranch() : Promise.resolve(null),
25
25
  isRepo ? hookLocation(git) : Promise.resolve(null),
26
26
  readIdentity(git, credentialKeys[0] ?? null),
27
27
  isRepo ? guardState(git) : Promise.resolve('off'),
28
28
  git.getUrlMatch('credential.helper', originUrl ?? DEFAULT_PROBE_URL),
29
+ pushSide(git, originUrl),
29
30
  ]);
30
31
  return {
31
32
  git, isRepo, root, branch, originUrl, url, provider,
32
- owner: url ? provider.ownerOf(url) : null,
33
+ owner: pushed.owner, ownerProvider: pushed.provider,
33
34
  identity, credentialKeys, guard, hook, helper,
34
35
  };
35
36
  }
37
+ /**
38
+ * Who origin's pushes go to, and on which host: the URL git pushes to (pushurl,
39
+ * pushInsteadOf, insteadOf), the one the guard checks, not the configured fetch URL the
40
+ * credentials follow. The owner and its host always come from that same URL.
41
+ */
42
+ async function pushSide(git, originUrl) {
43
+ const pushed = originUrl ? parseGitUrl((await git.remotePushUrl('origin')) ?? originUrl) : null;
44
+ const provider = providerFor(pushed);
45
+ return { owner: pushed ? provider.ownerOf(pushed) : null, provider };
46
+ }
36
47
  export async function inspectAuth(git, probeUrl) {
37
48
  const gcmPath = await findGcm();
38
49
  const [stored, gh, present, helper, ghHelperOrigins] = await Promise.all([
@@ -9,7 +9,7 @@
9
9
  // belongs to whichever remote was fetched last. So the destination is only ever
10
10
  // "known" (it has tracking refs, and pushes where it fetches from) or "unknown",
11
11
  // and a read that fails is unknown.
12
- import { parseGitUrl } from "./url.js";
12
+ import { parseGitUrl } from './url.js';
13
13
  /** Null when the branch pushes nowhere, to `.` (this repository), or where tracking refs reach. */
14
14
  export async function unknownDestination(git, branch) {
15
15
  const listed = await git.readRemotes();
@@ -5,11 +5,11 @@
5
5
  // a clone that could not be read is never reported ready. The push target is resolved
6
6
  // the way a plain `git push` resolves it (push-destination.ts), and a secret in a URL is
7
7
  // only ever reported by the config key that holds it.
8
- import { ok } from "./result.js";
9
- import { pushTarget, unknownDestination } from "./push-destination.js";
10
- import { parseGitUrl } from "./url.js";
11
- import { providerFor } from "./hosts/index.js";
12
- import { hostileSet } from "./guard/check.js";
8
+ import { ok } from './result.js';
9
+ import { pushTarget, unknownDestination } from './push-destination.js';
10
+ import { parseGitUrl } from './url.js';
11
+ import { providerFor } from './hosts/index.js';
12
+ import { hostileSet } from './guard/check.js';
13
13
  const OVERRIDES = ['author.email', 'committer.email'];
14
14
  export async function readPushFacts(git, unpushed, env = process.env) {
15
15
  const head = await git.currentBranch();
@@ -55,7 +55,7 @@ async function repointOf(git, branch) {
55
55
  async function destinationOf(git, target) {
56
56
  if (!target)
57
57
  return null;
58
- const raw = target.isRemote ? await pushUrlOf(git, target.name) : target.name;
58
+ const raw = target.isRemote ? await pushUrlOf(git, target.name) : await bareTargetUrl(git, target.name);
59
59
  const url = raw ? parseGitUrl(raw) : null;
60
60
  const owner = url ? providerFor(url).ownerOf(url) : null;
61
61
  if (!owner)
@@ -63,8 +63,12 @@ async function destinationOf(git, target) {
63
63
  const allowed = (await git.getAllConfig('repown.allowOwner', 'local')).map((value) => value.toLowerCase());
64
64
  return { remote: target.isRemote ? target.name : null, owner, allowed };
65
65
  }
66
- async function pushUrlOf(git, remote) {
67
- return (await git.getConfig('remote.' + remote + '.pushurl')) ?? git.getConfig('remote.' + remote + '.url');
66
+ function pushUrlOf(git, remote) {
67
+ return git.remotePushUrl(remote);
68
+ }
69
+ /** A push straight to a URL, as git rewrites it (insteadOf; see rewrittenUrl). */
70
+ async function bareTargetUrl(git, url) {
71
+ return (await git.rewrittenUrl(url)) ?? url;
68
72
  }
69
73
  /** Only the tracked ref ON the destination: a triangular workflow's upstream does not block its push. */
70
74
  async function divergenceOf(git, target) {
@@ -7,9 +7,9 @@
7
7
  // rebase runs with no hook at all, without autosquash and without moving other branches,
8
8
  // behind a backup ref that is never overwritten, and is checked afterwards: every commit
9
9
  // still there, each by the pin. Nothing here pushes.
10
- import { ok, err } from "./result.js";
11
- import { pushTarget, unknownDestination } from "./push-destination.js";
12
- import { AMEND_COMMAND, isOwn, otherAddresses } from "./unpushed.js";
10
+ import { ok, err } from './result.js';
11
+ import { pushTarget, unknownDestination } from './push-destination.js';
12
+ import { AMEND_COMMAND, isOwn, otherAddresses } from './unpushed.js';
13
13
  const IDENTITY_ENV = ['GIT_AUTHOR_NAME', 'GIT_AUTHOR_EMAIL', 'GIT_COMMITTER_NAME', 'GIT_COMMITTER_EMAIL'];
14
14
  const IDENTITY_CONFIG = ['author.email', 'committer.email', 'author.name', 'committer.name'];
15
15
  /** Null: nothing by another address. An error is a refusal, and nothing was changed. */
@@ -15,7 +15,7 @@
15
15
  import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises';
16
16
  import { homedir } from 'node:os';
17
17
  import { join, dirname } from 'node:path';
18
- import { ok, err } from "./result.js";
18
+ import { ok, err } from './result.js';
19
19
  const EMPTY = { accounts: {}, unreadable: [] };
20
20
  export function configDirectory() {
21
21
  const explicit = process.env['REPOWN_CONFIG_DIR'];
@@ -69,13 +69,20 @@ function readAccounts(value) {
69
69
  }
70
70
  return { accounts, unreadable };
71
71
  }
72
+ /** Why a write would fail or drop entries, or null when it would keep every entry. */
73
+ export function writeProblem(registry) {
74
+ if (!registry.ok)
75
+ return registry.error;
76
+ if (registry.value.unreadable.length === 0)
77
+ return null;
78
+ return registryPath() + ' has entries repown cannot read (' + registry.value.unreadable.join(', ') +
79
+ ') -- saving would drop them; fix or remove them first';
80
+ }
72
81
  /** The registry, but only if a write would keep every entry in it. */
73
82
  async function loadForWrite() {
74
83
  const registry = await loadRegistry();
75
- if (!registry.ok || registry.value.unreadable.length === 0)
76
- return registry;
77
- return err(registryPath() + ' has entries repown cannot read (' + registry.value.unreadable.join(', ') +
78
- ') -- saving would drop them; fix or remove them first');
84
+ const problem = writeProblem(registry);
85
+ return problem === null || !registry.ok ? registry : err(problem);
79
86
  }
80
87
  export async function lookupAccount(account) {
81
88
  const registry = await loadRegistry();
@@ -11,9 +11,9 @@
11
11
  // them (push-destination.ts, ADR-025).
12
12
  // scan's address totals are a different question: every ref, counts only, and
13
13
  // setup loads them only for the guard question.
14
- import { ok } from "./result.js";
15
- import { unknownDestination } from "./push-destination.js";
16
- import { shellWord } from "./guard/check.js";
14
+ import { ok } from './result.js';
15
+ import { unknownDestination } from './push-destination.js';
16
+ import { copyableCommand, shellWord } from './guard/check.js';
17
17
  const ADDRESS_CAP = 3;
18
18
  /** The one re-author command: the advice prints it, and `repown reauthor` runs it. */
19
19
  export const AMEND_COMMAND = 'git commit --amend --no-edit --reset-author --allow-empty';
@@ -93,19 +93,20 @@ function unknownLine(unknown, account) {
93
93
  }
94
94
  function trackingLine(name, account) {
95
95
  const lead = show(name) + ' has no remote-tracking refs, so some of these may already be on it' + GUARD;
96
- if (!copyable(name))
97
- return lead;
98
- return lead + ': git fetch ' + shellWord(show(name)) + ', ' + recount(account);
96
+ const fetch = copyable(name) ? copyableCommand(['git', 'fetch', show(name)]) : null;
97
+ return fetch ? lead + ': ' + fetch + ', ' + recount(account) : lead;
99
98
  }
100
99
  function urlLine(key, remote, account) {
101
100
  const lead = 'this branch pushes to a URL, not a remote' + THERE;
102
101
  if (!remote || !copyable(remote))
103
102
  return lead;
104
- const word = shellWord(show(remote));
105
- return lead + ': git config --local ' + shellWord(show(key)) + ' ' + word + ', git fetch ' + word + ', ' + recount(account);
103
+ const repoint = copyableCommand(['git', 'config', '--local', show(key), show(remote)]);
104
+ const fetch = copyableCommand(['git', 'fetch', show(remote)]);
105
+ return repoint && fetch ? lead + ': ' + repoint + ', ' + fetch + ', ' + recount(account) : lead;
106
106
  }
107
107
  function recount(account) {
108
- return 'then repown use ' + shellWord(show(account)) + ' to count again';
108
+ const word = shellWord(show(account));
109
+ return word ? 'then repown use ' + word + ' to count again' : 'then run repown use again to count again';
109
110
  }
110
111
  /** Quoting keeps a shell from splitting a word, not git from reading `-x` as an option. */
111
112
  function copyable(word) {