repown 0.3.0 → 0.5.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/README.md +11 -3
  3. package/dist/cli.js +4 -4
  4. package/dist/commands/accounts.js +19 -13
  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 +64 -0
  10. package/dist/commands/scan.js +7 -6
  11. package/dist/commands/setup.js +7 -4
  12. package/dist/commands/start.js +6 -6
  13. package/dist/commands/status.js +66 -22
  14. package/dist/commands/use.js +14 -14
  15. package/dist/core/blockers.js +133 -0
  16. package/dist/core/config-snapshot.js +97 -0
  17. package/dist/core/credential/gcm.js +2 -2
  18. package/dist/core/credential/gh.js +12 -5
  19. package/dist/core/credential/repair.js +1 -1
  20. package/dist/core/git.js +145 -12
  21. package/dist/core/guard/check.js +48 -8
  22. package/dist/core/guard/hook.js +1 -1
  23. package/dist/core/hosts/github.js +11 -5
  24. package/dist/core/hosts/index.js +21 -3
  25. package/dist/core/identity.js +1 -1
  26. package/dist/core/inspect.js +6 -6
  27. package/dist/core/push-destination.js +82 -0
  28. package/dist/core/push-state.js +109 -0
  29. package/dist/core/reauthor.js +145 -0
  30. package/dist/core/registry.js +1 -1
  31. package/dist/core/unpushed.js +112 -43
  32. package/dist/program.js +10 -9
  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 +39 -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 +7 -4
  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 +85 -44
  44. package/dist/wizard/home-text.js +14 -3
  45. package/dist/wizard/plain.js +2 -2
  46. package/dist/wizard/review-text.js +36 -14
  47. package/dist/wizard/setup-changes.js +11 -7
  48. package/dist/wizard/setup-context.js +31 -20
  49. package/dist/wizard/setup-flow.js +265 -56
  50. package/dist/wizard/setup-run.js +108 -40
  51. package/npm-shrinkwrap.json +378 -17
  52. package/package.json +3 -3
@@ -11,19 +11,27 @@
11
11
  // All three are printed, because the one that is invisible is the one that
12
12
  // catches people out. gh's active account is a note: it never affects the push.
13
13
  // A gh that could not be queried stays a warning, because that answer is unknown.
14
- // This reports; it changes nothing.
15
- import { inspectRepo, inspectAuth, activeAccountLabel } from "../core/inspect.js";
16
- import { isPinned } from "../core/identity.js";
17
- import { loadRegistry } from "../core/registry.js";
18
- import { allowedOwners, shellWord } from "../core/guard/check.js";
14
+ // What would stop the next push (blockers.ts, the list setup reads too) comes first among
15
+ // the warnings, and `ready:` is said only without it (ADR-026). It is still a warning:
16
+ // the exit code is unchanged (ADR-020). This reports; it changes nothing.
17
+ import { inspectRepo, inspectAuth, activeAccountLabel } from '../core/inspect.js';
18
+ import { isPinned } from '../core/identity.js';
19
+ import { loadRegistry } from '../core/registry.js';
20
+ import { snapshotOf } from '../core/config-snapshot.js';
21
+ import { ALLOW_OWNER_BY_HAND, allowOwnerCommand, allowedOwners, copyableCommand } from '../core/guard/check.js';
19
22
  import { existsSync } from 'node:fs';
20
23
  import { join } from 'node:path';
21
- import { gitFor } from "../ui/args.js";
22
- import * as out from "../ui/format.js";
24
+ import { gitFor } from '../ui/args.js';
25
+ import * as out from '../ui/format.js';
26
+ import { printable } from '../ui/format.js';
27
+ import { blockers } from '../core/blockers.js';
28
+ import { readPushFacts } from '../core/push-state.js';
29
+ import { readUnpushed } from '../core/unpushed.js';
23
30
  export default {
24
31
  summary: 'this clone\'s and this machine\'s settings, and what to fix (bare `repown` when output isn\'t a terminal)',
25
32
  async run(args) {
26
- const git = gitFor(args);
33
+ // Read-only: every config read of this run comes from one list per scope (ADR-029).
34
+ const git = snapshotOf(gitFor(args));
27
35
  const repo = await inspectRepo(git);
28
36
  if (!repo.isRepo) {
29
37
  out.fail('repown', 'Not a git repository: ' + git.cwd);
@@ -34,10 +42,12 @@ export default {
34
42
  const registry = await loadRegistry();
35
43
  await summary(repo, auth, registry);
36
44
  const problems = collectProblems(repo, auth);
37
- const warnings = await reportWarnings(repo, auth, registry);
45
+ const account = accountShown(repo, registry);
46
+ const found = problems.length === 0 ? await pushBlockers(repo, account) : [];
47
+ const warnings = await reportWarnings(repo, auth, registry, found);
38
48
  const code = verdict(repo, auth, problems);
39
49
  const ghNote = printGhNote(pinnedAccount(repo), auth);
40
- closeStatus({ repo, problems, warnings, account: accountShown(repo, registry), ghNote });
50
+ closeStatus({ repo, problems, warnings, blockers: found, account, ghNote });
41
51
  return code;
42
52
  },
43
53
  };
@@ -169,12 +179,39 @@ function matchesRecord(repo, entry) {
169
179
  const id = repo.identity;
170
180
  return id.name === entry.name && id.email?.toLowerCase() === entry.email.toLowerCase();
171
181
  }
182
+ /** Read only when status finds no problem: otherwise the problem comes first. */
183
+ async function pushBlockers(repo, account) {
184
+ const facts = await readPushFacts(repo.git, await readUnpushed(repo.git));
185
+ const guarded = repo.guard !== 'off' || repo.hook?.redirected === true;
186
+ // The upstream field already says how to push a branch without one: not a warning here.
187
+ return blockers(facts, { email: repo.identity.email ?? '', account, autoUpstream: true, guarded });
188
+ }
189
+ /** First among the warnings. An owner the origin warning names is not said twice. */
190
+ function printBlockers(found, ownerWarned) {
191
+ for (const blocker of found) {
192
+ if (blocker.kind === 'owner' && ownerWarned)
193
+ continue;
194
+ const [first = '', ...rest] = blocker.lines;
195
+ out.warn('push', printable(first));
196
+ for (const line of rest)
197
+ out.detail(printable(line));
198
+ }
199
+ }
172
200
  function closeStatus(end) {
173
- const line = end.problems.length === 0
174
- ? readyLine(end.repo, end.account, end.warnings, end.ghNote)
175
- : tally(end.problems.length, end.warnings.length) + setupHint(end.repo);
176
201
  out.note('');
177
- out.note(line);
202
+ out.note(closingLine(end));
203
+ }
204
+ function closingLine(end) {
205
+ if (end.problems.length > 0)
206
+ return tally(end.problems.length, end.warnings.length) + setupHint(end.repo);
207
+ const blocking = end.blockers.filter((blocker) => blocker.blocks);
208
+ const [first] = blocking;
209
+ // What blocks nothing (the guard is off) is still a warning, and counted as one.
210
+ const quiet = end.blockers.filter((blocker) => !blocker.blocks).map(() => 'push');
211
+ if (!first)
212
+ return readyLine(end.repo, end.account, [...quiet, ...end.warnings], end.ghNote);
213
+ const more = blocking.length > 1 ? ' (and ' + (blocking.length - 1) + ' more above)' : '';
214
+ return 'the next push will fail: ' + printable(first.summary) + more;
178
215
  }
179
216
  const GH_OPTIONAL = ' · gh: optional (see the note above)';
180
217
  function readyLine(repo, account, warnings, ghNote) {
@@ -223,10 +260,12 @@ export function identityProblems(repo) {
223
260
  fix: SETUP_FIX,
224
261
  }];
225
262
  }
226
- async function reportWarnings(repo, auth, registry) {
263
+ async function reportWarnings(repo, auth, registry, found) {
227
264
  const tags = ['origin', 'account', 'guard', 'submodule', 'helper', 'gh'];
265
+ const foreignOwner = await originForeign(repo);
266
+ printBlockers(found, foreignOwner);
228
267
  const fired = [
229
- await ownerWarning(repo),
268
+ foreignOwner && ownerWarning(repo),
230
269
  accountWarning(repo, registry),
231
270
  guardWarning(repo),
232
271
  submoduleWarning(repo),
@@ -285,13 +324,16 @@ function submoduleWarning(repo) {
285
324
  * An organisation is never an account name, so a bare owner-vs-account
286
325
  * comparison warns on every org repository -- which is most of them at work.
287
326
  */
288
- async function ownerWarning(repo) {
327
+ async function originForeign(repo) {
289
328
  const allowed = await allowedOwners(repo.git, repo.identity.owner ?? repo.identity.account);
290
- if (!repo.owner || allowed.length === 0 || allowed.includes(repo.owner.toLowerCase()))
329
+ return !!repo.owner && allowed.length > 0 && !allowed.includes(repo.owner.toLowerCase());
330
+ }
331
+ function ownerWarning(repo) {
332
+ if (!repo.owner)
291
333
  return false;
292
- out.warn('origin', 'origin belongs to "' + repo.owner + '", which is not an owner this clone pushes to.');
334
+ out.warn('origin', 'origin belongs to "' + out.printable(repo.owner) + '", which is not an owner this clone pushes to.');
293
335
  out.detail('if that is an organisation you belong to:');
294
- out.detail(' git config --local --add repown.allowOwner ' + shellWord(repo.owner));
336
+ out.detail(' ' + (allowOwnerCommand(repo.owner) ?? ALLOW_OWNER_BY_HAND));
295
337
  return true;
296
338
  }
297
339
  function registryUnread() {
@@ -318,9 +360,11 @@ const GH_UNVERIFIED = 'could not be queried, so who `gh pr create` would act as
318
360
  /** `gh auth switch` only works for a login gh already lists, and only in gh's spelling. */
319
361
  function ghFix(account, auth) {
320
362
  const login = ghReportedLogin(account, auth);
363
+ const shown = out.printable(account);
364
+ const fix = login !== null ? copyableCommand(['gh', 'auth', 'switch', '-u', login]) : copyableCommand(['repown', 'use', account, '--gh']);
321
365
  if (login !== null)
322
- return 'fix: gh auth switch -u ' + login;
323
- return 'fix: repown use ' + account + ' --gh (signs ' + account + ' in to gh)';
366
+ return 'fix: ' + (fix ?? 'gh auth switch to ' + out.printable(login));
367
+ return 'fix: ' + (fix ?? 'repown use with --gh') + ' (signs ' + shown + ' in to gh)';
324
368
  }
325
369
  function ghReportedLogin(account, auth) {
326
370
  if (!auth.gh.ok)
@@ -17,15 +17,15 @@
17
17
  // GitHub CLI on the same account: `gh auth switch` when gh already lists it,
18
18
  // and, in a terminal, `gh auth login` when it does not. After `repown fix`
19
19
  // neither changes which account git pushes as.
20
- import { inspectRepo, inspectAuth } from "../core/inspect.js";
21
- import { pinIdentity } from "../core/identity.js";
22
- import { lookupAccount, saveAccount } from "../core/registry.js";
23
- import { ghSwitch, ghLogin, readGhLoginVersion, } from "../core/credential/gh.js";
24
- import { allowedOwners, shellWord } from "../core/guard/check.js";
25
- import { readUnpushed, unpushedLines } from "../core/unpushed.js";
26
- import { ask, interactive } from "../ui/prompt.js";
27
- import { flagString, flagBool, gitFor } from "../ui/args.js";
28
- import * as out from "../ui/format.js";
20
+ import { inspectRepo, inspectAuth } from '../core/inspect.js';
21
+ import { pinIdentity } from '../core/identity.js';
22
+ import { lookupAccount, saveAccount } from '../core/registry.js';
23
+ import { ghSwitch, ghLogin, readGhLoginVersion, } from '../core/credential/gh.js';
24
+ import { ALLOW_OWNER_BY_HAND, allowOwnerCommand, allowedOwners } from '../core/guard/check.js';
25
+ import { readUnpushed, unpushedLines } from '../core/unpushed.js';
26
+ import { ask, interactive } from '../ui/prompt.js';
27
+ import { flagString, flagBool, gitFor } from '../ui/args.js';
28
+ import * as out from '../ui/format.js';
29
29
  /** The last hint while the guard is off; `repown setup` leaves it out when its next step turns the guard on. */
30
30
  export const NEXT_GUARD = ' Next: repown guard on (check every push before it leaves)';
31
31
  export default {
@@ -248,7 +248,7 @@ async function switchCli(account) {
248
248
  }
249
249
  /** Everything that is now true but not yet right. Warnings, never refusals. */
250
250
  async function reportConcerns(account, repo, email) {
251
- await reportUnpushed(repo, email);
251
+ await reportUnpushed(repo, email, account);
252
252
  if (repo.credentialKeys.length === 0 && repo.url) {
253
253
  out.warn('host', repo.provider.label + ' credentials are not pinned by repown.');
254
254
  out.detail('commits are pinned and the guard still runs; only credential');
@@ -262,8 +262,8 @@ async function reportConcerns(account, repo, email) {
262
262
  }
263
263
  }
264
264
  /** A warning only. Rewriting the commits stays the owner's call (ADR-013). */
265
- async function reportUnpushed(repo, email) {
266
- const [first, ...rest] = unpushedLines(await readUnpushed(repo.git), email);
265
+ async function reportUnpushed(repo, email, account) {
266
+ const [first, ...rest] = unpushedLines(await readUnpushed(repo.git), email, account);
267
267
  if (!first)
268
268
  return;
269
269
  out.warn('commits', first);
@@ -275,9 +275,9 @@ async function ownerConcern(account, repo) {
275
275
  return;
276
276
  if ((await allowedOwners(repo.git, account)).includes(repo.owner.toLowerCase()))
277
277
  return;
278
- out.warn('origin', 'origin belongs to "' + repo.owner + '", not "' + account + '".');
278
+ out.warn('origin', 'origin belongs to "' + out.printable(repo.owner) + '", not "' + out.printable(account) + '".');
279
279
  out.detail('normal for an organisation repository. To stop the guard refusing it:');
280
- out.detail(' git config --local --add repown.allowOwner ' + shellWord(repo.owner));
280
+ out.detail(' ' + (allowOwnerCommand(repo.owner) ?? ALLOW_OWNER_BY_HAND));
281
281
  }
282
282
  async function credentialConcern(account, repo) {
283
283
  const auth = await inspectAuth(repo.git, repo.originUrl ?? undefined);
@@ -0,0 +1,133 @@
1
+ // What will make the next commit, pull or push fail in this clone, from facts read once.
2
+ //
3
+ // Pure: setup's review and settled screen, its closing line and `repown status` all
4
+ // read the same list, so none of them can say "done" or "ready" over a push the guard
5
+ // (or git) is about to refuse. A fact that could not be read is a blocker of its own,
6
+ // never an absence (a skipped check must not look passed). What only the guard would
7
+ // refuse is still said with the guard off, as a warning that blocks nothing.
8
+ import { unpushedLines, foreignCount } from './unpushed.js';
9
+ import { ALLOW_OWNER_BY_HAND, allowOwnerCommand, copyableCommand } from './guard/check.js';
10
+ import { printable } from '../ui/format.js';
11
+ const TOKENS = ['GH_TOKEN', 'GITHUB_TOKEN'];
12
+ export function blockers(facts, choice) {
13
+ const branch = facts.unpushed.branch ?? 'HEAD';
14
+ return [
15
+ ...unpushedBlocker(facts.unpushed, choice),
16
+ ...elsewhereBlocker(facts.elsewhere, facts.destination, branch, choice),
17
+ ...signinBlocker(facts, branch, choice.account),
18
+ ...facts.env.map((name) => envBlocker(name, choice)),
19
+ ...facts.configOverrides.map((key) => configBlocker(key, choice.email)),
20
+ ...ownerBlocker(facts.destination, branch, choice),
21
+ ...divergenceBlocker(facts.divergence, branch),
22
+ ...upstreamBlocker(facts, branch, choice.autoUpstream),
23
+ ...(facts.detached ? [detachedBlocker()] : []),
24
+ ];
25
+ }
26
+ /** What the guard does with them: refuses, or, while it is off, lets them through. */
27
+ function guardWord(guarded, many) {
28
+ if (guarded)
29
+ return 'the guard will refuse ' + (many ? 'them' : 'it');
30
+ return 'the guard is off, so ' + (many ? 'they push as they are' : 'it pushes as it is');
31
+ }
32
+ function unpushedBlocker(fact, choice) {
33
+ const lines = unpushedLines(fact, choice.email, choice.account, choice.guarded);
34
+ if (lines.length === 0)
35
+ return [];
36
+ if (!fact.commits.ok)
37
+ return [{ kind: 'unpushed', summary: 'unpushed commits could not be read', lines, blocks: choice.guarded }];
38
+ const count = foreignCount(fact, choice.email);
39
+ return [{ kind: 'unpushed', summary: count + (count === 1 ? ' commit' : ' commits') + ' by another address', lines, blocks: choice.guarded }];
40
+ }
41
+ /** Where a remote names the same repository, the fix is setup's repoint. */
42
+ function signinBlocker(facts, branch, account) {
43
+ const key = facts.signinKey;
44
+ if (!key)
45
+ return [];
46
+ const fix = facts.repoint?.key === key ? ': point it back at ' + facts.repoint.remote + ' with repown setup --repoint' : '';
47
+ return [{
48
+ kind: 'signin',
49
+ summary: 'the branch pushes with its own sign-in',
50
+ lines: [key + ' carries its own sign-in, so pushes from ' + branch + ' use it, not ' + account + fix],
51
+ blocks: true,
52
+ }];
53
+ }
54
+ /** Counted with the guard's own exclusion, so a fork's upstream commits are not missed. */
55
+ function elsewhereBlocker(elsewhere, destination, branch, choice) {
56
+ if (!elsewhere.ok) {
57
+ return [{ kind: 'elsewhere', summary: 'commits on other remotes could not be read', lines: ['commits on other remotes could not be read (' + elsewhere.error + ')'], blocks: choice.guarded }];
58
+ }
59
+ const count = foreignCount({ branch, commits: elsewhere, unknown: null }, choice.email);
60
+ if (count === 0)
61
+ return [];
62
+ const where = destination?.remote ?? 'the destination';
63
+ const noun = count === 1 ? '1 commit' : count + ' commits';
64
+ return [{
65
+ kind: 'elsewhere',
66
+ summary: noun + ' from another remote',
67
+ lines: [noun + ' on ' + branch + ' by another address ' + (count === 1 ? 'is' : 'are') + ' on another remote but not on ' + where +
68
+ ': ' + guardWord(choice.guarded, count > 1) + ' (a fork mirroring upstream? see repown.mirrorBranch)'],
69
+ blocks: choice.guarded,
70
+ }];
71
+ }
72
+ function configBlocker(key, email) {
73
+ return {
74
+ kind: 'config',
75
+ summary: key + ' is set',
76
+ lines: [key + " is set in git config: commits made here won't use " + email + ' (unset it: git config --unset ' + key + ')'],
77
+ blocks: true,
78
+ };
79
+ }
80
+ /** An identity variable still changes every commit; a token only matters to the guard. */
81
+ function envBlocker(name, choice) {
82
+ const token = TOKENS.includes(name);
83
+ const identity = token ? '' : ": commits made here won't use " + choice.email;
84
+ const guard = choice.guarded ? 'the guard refuses every push while it is set'
85
+ : token ? 'the guard is off, so it stops nothing now, but with the guard on every push is refused' : '';
86
+ const joiner = !guard ? '' : identity ? ', and ' : ': ';
87
+ return {
88
+ kind: 'env',
89
+ summary: name + ' is set',
90
+ lines: [name + ' is set in this shell' + identity + joiner + guard + ' (unset it)'],
91
+ blocks: choice.guarded || !token,
92
+ };
93
+ }
94
+ function ownerBlocker(destination, branch, choice) {
95
+ if (!destination)
96
+ return [];
97
+ const owner = destination.owner.toLowerCase();
98
+ if (owner === choice.account.toLowerCase() || destination.allowed.includes(owner))
99
+ return [];
100
+ const where = destination.remote ?? 'its URL';
101
+ const guard = choice.guarded ? 'the guard will refuse it' : 'the guard is off, so it pushes there anyway';
102
+ return [{
103
+ kind: 'owner',
104
+ summary: 'the push goes to "' + printable(destination.owner) + '"',
105
+ lines: [branch + ' pushes to ' + where + ', owned by "' + printable(destination.owner) + '", not ' + choice.account +
106
+ ': ' + guard + '. If you belong there: ' + (allowOwnerCommand(destination.owner) ?? ALLOW_OWNER_BY_HAND)],
107
+ blocks: choice.guarded,
108
+ }];
109
+ }
110
+ function divergenceBlocker(divergence, branch) {
111
+ if (!divergence.ok) {
112
+ return [{ kind: 'divergence', summary: branch + ' could not be compared with its upstream', lines: [branch + ' could not be compared with its upstream (' + divergence.error + ')'], blocks: true }];
113
+ }
114
+ const found = divergence.value;
115
+ if (!found || found.behind === 0 || found.ahead === 0)
116
+ return [];
117
+ return [{
118
+ kind: 'divergence',
119
+ summary: branch + ' has diverged from ' + found.tracked,
120
+ lines: [branch + ' is ' + found.behind + ' behind and ' + found.ahead + ' ahead of ' + found.tracked +
121
+ ': push and pull fail until you git pull --rebase'],
122
+ blocks: true,
123
+ }];
124
+ }
125
+ function upstreamBlocker(facts, branch, autoUpstream) {
126
+ if (facts.upstream !== 'missing' || autoUpstream)
127
+ return [];
128
+ const push = copyableCommand(['git', 'push', '-u', facts.destination?.remote ?? 'origin', branch]) ?? 'git push -u with the remote and this branch';
129
+ return [{ kind: 'upstream', summary: branch + ' has no upstream', lines: [branch + ' has no upstream: the first push needs ' + push], blocks: true }];
130
+ }
131
+ function detachedBlocker() {
132
+ return { kind: 'detached', summary: 'HEAD is detached', lines: ['HEAD is detached: git pull and a plain git push fail here; git switch to a branch first'], blocks: true };
133
+ }
@@ -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,8 +13,8 @@
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() {
@@ -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
@@ -104,9 +104,16 @@ export function ghProfileArgs(login, field) {
104
104
  }
105
105
  /** A profile field from github.com, or null. Absence here is unremarkable. */
106
106
  export async function ghProfileField(login, field) {
107
- const result = await run('gh', ghProfileArgs(login, field));
107
+ return (await ghProfileLookup(login, field)).value;
108
+ }
109
+ export async function ghProfileLookup(login, field) {
110
+ return profileLookupFrom(await run('gh', ghProfileArgs(login, field)));
111
+ }
112
+ /** Only github.com's own 404 means missing: offline, refused or no gh is unknown. */
113
+ export function profileLookupFrom(result) {
108
114
  const value = output(result);
109
- return value && value !== 'null' ? value : null;
115
+ const missing = !succeeded(result) && /\(HTTP 404\)/.test(result.stderr);
116
+ return { value: value && value !== 'null' ? value : null, missing };
110
117
  }
111
118
  export async function ghSwitch(login) {
112
119
  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
  /**