repown 0.5.1 → 0.5.3

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.
@@ -6,7 +6,8 @@
6
6
  // never an absence (a skipped check must not look passed). What only the guard would
7
7
  // refuse is still said with the guard off, as a warning that blocks nothing.
8
8
  import { unpushedLines, foreignCount } from './unpushed.js';
9
- import { ALLOW_OWNER_BY_HAND, allowOwnerCommand, copyableCommand } from './guard/check.js';
9
+ import { ALLOW_OWNER_BY_HAND, allowOwnerCommand } from './guard/check.js';
10
+ import { copyableCommand, positional } from './shell.js';
10
11
  import { printable } from '../ui/format.js';
11
12
  const TOKENS = ['GH_TOKEN', 'GITHUB_TOKEN'];
12
13
  export function blockers(facts, choice) {
@@ -18,6 +19,8 @@ export function blockers(facts, choice) {
18
19
  ...facts.env.map((name) => envBlocker(name, choice)),
19
20
  ...facts.configOverrides.map((key) => configBlocker(key, choice.email)),
20
21
  ...ownerBlocker(facts.destination, branch, choice),
22
+ ...laterUrlsBlocker(facts.laterUrls, facts.destination, choice),
23
+ ...rewriteBlocker(facts.rewritable, branch),
21
24
  ...divergenceBlocker(facts.divergence, branch),
22
25
  ...upstreamBlocker(facts, branch, choice.autoUpstream),
23
26
  ...(facts.detached ? [detachedBlocker()] : []),
@@ -40,14 +43,16 @@ function unpushedBlocker(fact, choice) {
40
43
  }
41
44
  /** Where a remote names the same repository, the fix is setup's repoint. */
42
45
  function signinBlocker(facts, branch, account) {
43
- const key = facts.signinKey;
44
- if (!key)
46
+ const signin = facts.signin;
47
+ if (!signin)
45
48
  return [];
46
- const fix = facts.repoint?.key === key ? ': point it back at ' + facts.repoint.remote + ' with repown setup --repoint' : '';
49
+ // A rewrite rule's key holds the token in its name: only the remote is ever printed for it.
50
+ const holder = 'key' in signin ? signin.key : 'named' in signin ? signin.named : printable(signin.remote) + "'s push URL, as git resolves it,";
51
+ const fix = 'key' in signin && facts.repoint?.key === signin.key ? ': point it back at ' + facts.repoint.remote + ' with repown setup --repoint' : '';
47
52
  return [{
48
53
  kind: 'signin',
49
54
  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],
55
+ lines: [holder + ' carries its own sign-in, so pushes from ' + branch + ' use it, not ' + account + fix],
51
56
  blocks: true,
52
57
  }];
53
58
  }
@@ -92,21 +97,60 @@ function envBlocker(name, choice) {
92
97
  };
93
98
  }
94
99
  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))
100
+ if (!destination || allows(destination.owner, destination.allowed, choice.account))
99
101
  return [];
100
102
  const where = destination.remote ?? 'its URL';
101
103
  const guard = choice.guarded ? 'the guard will refuse it' : 'the guard is off, so it pushes there anyway';
102
104
  return [{
103
105
  kind: 'owner',
106
+ owner: destination.owner,
104
107
  summary: 'the push goes to "' + printable(destination.owner) + '"',
105
108
  lines: [branch + ' pushes to ' + where + ', owned by "' + printable(destination.owner) + '", not ' + choice.account +
106
109
  ': ' + guard + '. If you belong there: ' + (allowOwnerCommand(destination.owner) ?? ALLOW_OWNER_BY_HAND)],
107
110
  blocks: choice.guarded,
108
111
  }];
109
112
  }
113
+ /**
114
+ * A later push URL the guard refuses while the first takes the push: the push half-lands.
115
+ * Judged as ownerBlocker judges the first URL, which speaks alone when it is refused itself.
116
+ */
117
+ function laterUrlsBlocker(later, first, choice) {
118
+ if (!later || (first && !allows(first.owner, first.allowed, choice.account)))
119
+ return [];
120
+ const refused = onceEach(later.owners.filter(({ owner }) => !allows(owner, later.allowed, choice.account)));
121
+ if (refused.length === 0)
122
+ return [];
123
+ const names = refused.map(({ owner, host }) => '"' + printable(owner) + '" (' + host + ')').join(', ');
124
+ const urls = refused.length === 1 ? 'that URL' : 'those URLs';
125
+ const guard = choice.guarded ? 'the guard will refuse ' + urls + ' while the first takes the push' : 'the guard is off, so the push goes there too';
126
+ const fix = refused.map(({ owner }) => allowOwnerCommand(owner) ?? ALLOW_OWNER_BY_HAND).join(' and ');
127
+ const remote = printable(later.remote);
128
+ return [{
129
+ kind: 'pushurls',
130
+ summary: remote + ' also pushes to "' + printable(refused[0].owner) + '"',
131
+ lines: [remote + ' also pushes to ' + names + ', not ' + choice.account + ': ' + guard + '. If you belong there: ' + fix],
132
+ blocks: choice.guarded,
133
+ }];
134
+ }
135
+ /** One per owner, compared as the guard compares them (case-insensitively), first spelling kept. */
136
+ function onceEach(owners) {
137
+ return owners.filter(({ owner }, index) => owners.findIndex((other) => other.owner.toLowerCase() === owner.toLowerCase()) === index);
138
+ }
139
+ /** Said, never blocking: the guard still checks the URL git hands it. */
140
+ function rewriteBlocker(rewritable, branch) {
141
+ if (!rewritable)
142
+ return [];
143
+ return [{
144
+ kind: 'rewrite',
145
+ summary: "repown can't tell where the push goes",
146
+ lines: [rewritable.key + ' names a URL that a pushInsteadOf rule may rewrite, so repown ' +
147
+ "can't tell where a push from " + branch + ' lands: the guard checks it when you push'],
148
+ blocks: false,
149
+ }];
150
+ }
151
+ function allows(owner, allowed, account) {
152
+ return owner.toLowerCase() === account.toLowerCase() || allowed.includes(owner.toLowerCase());
153
+ }
110
154
  function divergenceBlocker(divergence, branch) {
111
155
  if (!divergence.ok) {
112
156
  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 }];
@@ -125,7 +169,7 @@ function divergenceBlocker(divergence, branch) {
125
169
  function upstreamBlocker(facts, branch, autoUpstream) {
126
170
  if (facts.upstream !== 'missing' || autoUpstream)
127
171
  return [];
128
- const push = copyableCommand(['git', 'push', '-u', facts.destination?.remote ?? 'origin', branch]) ?? 'git push -u with the remote and this branch';
172
+ const push = copyableCommand(['git', 'push', '-u', ...positional(facts.destination?.remote ?? 'origin'), branch]) ?? 'git push -u with the remote and this branch';
129
173
  return [{ kind: 'upstream', summary: branch + ' has no upstream', lines: [branch + ' has no upstream: the first push needs ' + push], blocks: true }];
130
174
  }
131
175
  function detachedBlocker() {
@@ -42,6 +42,13 @@ export class ConfigSnapshot extends Git {
42
42
  return this.lists.get(name);
43
43
  }
44
44
  }
45
+ /**
46
+ * For read-only code handed any Git: a snapshot of a plain one (or the snapshot itself), and a
47
+ * subclass as it is, since a snapshot would drop what it overrides.
48
+ */
49
+ export function readerOf(git) {
50
+ return git instanceof ConfigSnapshot || Object.getPrototypeOf(git) === Git.prototype ? snapshotOf(git) : git;
51
+ }
45
52
  /**
46
53
  * A snapshot of a plain `git`, or `git` itself when it already is one. A subclass is refused:
47
54
  * the snapshot keeps only the cwd, so whatever the subclass overrides would be dropped.
@@ -20,7 +20,7 @@
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';
23
+ import { run, inherit, succeeded, notInstalled } from '../exec.js';
24
24
  import { ok, err } from '../result.js';
25
25
  import { versionAtLeast } from '../version.js';
26
26
  /**
@@ -98,23 +98,34 @@ function toAccount(raw) {
98
98
  return [];
99
99
  return [{ login: entry.login, active: entry.active === true }];
100
100
  }
101
- /** Arguments for a github.com profile field. `--hostname` so GH_HOST cannot redirect the call. */
102
- export function ghProfileArgs(login, field) {
101
+ /** Arguments for a github.com profile, every field at once. `--hostname` so GH_HOST cannot redirect the call. */
102
+ export function ghUserArgs(login) {
103
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
+ return ['api', '--hostname', 'github.com', `users/${encodeURIComponent(login)}`];
105
105
  }
106
- /** A profile field from github.com, or null. Absence here is unremarkable. */
107
- export async function ghProfileField(login, field) {
108
- return (await ghProfileLookup(login, field)).value;
106
+ export async function ghUser(login) {
107
+ return userLookupFrom(await run('gh', ghUserArgs(login)));
109
108
  }
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) {
115
- const value = output(result);
109
+ /** Only github.com's own 404 means missing: offline, refused, no gh or an unreadable reply is unknown. */
110
+ export function userLookupFrom(result) {
116
111
  const missing = !succeeded(result) && /\(HTTP 404\)/.test(result.stderr);
117
- return { value: value && value !== 'null' ? value : null, missing };
112
+ return { fields: succeeded(result) ? objectIn(result.stdout) : null, missing };
113
+ }
114
+ /** One field as text: a non-empty string as it is, a number in decimal, anything else null. */
115
+ export function fieldOf(user, field) {
116
+ const value = user.fields?.[field];
117
+ const text = typeof value === 'string' && value ? value : typeof value === 'number' ? String(value) : null;
118
+ return { value: text, missing: user.missing };
119
+ }
120
+ /** The JSON object gh printed, or null: a reply that is not one is an unknown, like a failed call. */
121
+ function objectIn(text) {
122
+ try {
123
+ const parsed = JSON.parse(text);
124
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
125
+ }
126
+ catch {
127
+ return null;
128
+ }
118
129
  }
119
130
  export async function ghSwitch(login) {
120
131
  const result = await run('gh', ['auth', 'switch', '-u', login]);
package/dist/core/exec.js CHANGED
@@ -25,6 +25,7 @@
25
25
  // `shell: false` throughout: no argument ever reaches a shell parser, so a
26
26
  // branch name or URL containing shell metacharacters cannot be interpreted.
27
27
  import { spawn } from 'node:child_process';
28
+ import { join } from 'node:path';
28
29
  const DEFAULT_TIMEOUT_MS = 30_000;
29
30
  /** How many `inherit` children are running. `handingOver` is the read-only view. */
30
31
  let inherited = 0;
@@ -47,18 +48,68 @@ export function run(file, args, options = {}) {
47
48
  windowsHide: true,
48
49
  });
49
50
  const output = collect(child);
50
- let timedOut = false;
51
- const timer = setTimeout(() => { timedOut = true; child.kill(); }, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
52
- const settle = (result) => {
53
- clearTimeout(timer);
54
- resolve({ ...output(), ...result, ...(timedOut ? { timedOut } : {}) });
55
- };
51
+ const clock = { timedOut: false, timers: [] };
52
+ const settle = once((result) => {
53
+ for (const timer of clock.timers)
54
+ clearTimeout(timer);
55
+ resolve({ ...output(), ...result, ...(clock.timedOut ? { timedOut: true } : {}) });
56
+ });
57
+ clock.timers.push(setTimeout(() => expire(child, clock, settle), options.timeoutMs ?? DEFAULT_TIMEOUT_MS));
56
58
  child.on('error', (error) => settle({ code: -1, spawnError: error }));
57
59
  child.on('close', (code) => settle({ code: code ?? -1 }));
60
+ // Exited, but something it started may still hold the pipes ('close' waits for every holder).
61
+ child.on('exit', () => clock.timers.push(setTimeout(() => abandon(child, clock, settle), GRACE_MS)));
58
62
  child.stdin.on('error', () => { });
59
63
  child.stdin.end(options.input ?? '');
60
64
  });
61
65
  }
66
+ /** How long an exited or stopped child's pipes may stay open before repown stops waiting for them. */
67
+ const GRACE_MS = 3_000;
68
+ /** At the timeout: stop the child and what it started, then stop waiting after a grace. */
69
+ function expire(child, clock, settle) {
70
+ clock.timedOut = true;
71
+ stopTree(child);
72
+ clock.timers.push(setTimeout(() => abandon(child, clock, settle), GRACE_MS));
73
+ }
74
+ /** Stop waiting for the pipes. A timed-out run never reads as succeeded, whatever the child exited with. */
75
+ function abandon(child, clock, settle) {
76
+ child.stdout.destroy();
77
+ child.stderr.destroy();
78
+ child.unref();
79
+ settle({ code: clock.timedOut ? -1 : child.exitCode ?? -1 });
80
+ }
81
+ /**
82
+ * SIGTERM to the child on POSIX. On Windows the git on PATH is often a wrapper (cmd\git.exe)
83
+ * whose real git outlives TerminateProcess, so the whole tree is ended with taskkill /T /F
84
+ * while the child still runs (Node holds its handle, so the PID is still ours); the child
85
+ * itself is killed after, so the tree is still there to walk. A forced end runs no cleanup:
86
+ * a lock git held stays, as the timeout message's callers say.
87
+ */
88
+ function stopTree(child) {
89
+ const running = child.exitCode === null && child.signalCode === null;
90
+ if (process.platform !== 'win32' || child.pid === undefined || !running) {
91
+ child.kill();
92
+ return;
93
+ }
94
+ const root = process.env['SystemRoot'] ?? process.env['windir'] ?? 'C:\\Windows';
95
+ const killer = spawn(join(root, 'System32', 'taskkill.exe'), ['/PID', String(child.pid), '/T', '/F'], {
96
+ shell: false, windowsHide: true, stdio: 'ignore',
97
+ });
98
+ killer.unref();
99
+ const after = once(() => { child.kill(); });
100
+ killer.on('error', after);
101
+ killer.on('close', after);
102
+ }
103
+ /** A function that runs only the first time it is called. */
104
+ function once(act) {
105
+ let done = false;
106
+ return (...args) => {
107
+ if (done)
108
+ return;
109
+ done = true;
110
+ act(...args);
111
+ };
112
+ }
62
113
  /**
63
114
  * The terminal belongs to the child. Only `gh auth login` uses this, and only
64
115
  * from a terminal: repown cannot see what the child prints.
package/dist/core/git.js CHANGED
@@ -13,7 +13,7 @@
13
13
  // `git config --get` EXITS 1 WHEN A KEY IS NOT SET. That is an answer, not a
14
14
  // failure, and it is why nothing here treats a non-zero code as an error by
15
15
  // itself. See the note in exec.ts.
16
- import { existsSync } from 'node:fs';
16
+ import { existsSync, lstatSync } 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';
@@ -86,6 +86,11 @@ export class Git {
86
86
  return asked;
87
87
  return (await this.getConfig('remote.' + remote + '.pushurl')) ?? this.getConfig('remote.' + remote + '.url');
88
88
  }
89
+ /** Every URL git pushes (`push`) or fetches with, after insteadOf/pushInsteadOf; offline. */
90
+ async remoteUrls(remote, push) {
91
+ const asked = await this.exec(['remote', 'get-url', ...(push ? ['--push'] : []), '--all', '--', remote]);
92
+ return succeeded(asked) ? ok(lines(asked)) : err(asked.stderr.trim() || 'git remote get-url failed');
93
+ }
89
94
  /**
90
95
  * A bare URL after git's insteadOf rewriting (`ls-remote --get-url` contacts nothing).
91
96
  * It reads fetch rules, so a pushInsteadOf on a bare push URL is not applied.
@@ -93,6 +98,21 @@ export class Git {
93
98
  async rewrittenUrl(url) {
94
99
  return output(await this.exec(['ls-remote', '--get-url', '--', url]));
95
100
  }
101
+ /**
102
+ * The values of every key matching `pattern`, null for a key set with no value. A failed
103
+ * read keeps no git message: one can quote a key that holds a token (`url.<base>.*`).
104
+ */
105
+ async configValues(pattern) {
106
+ const asked = await this.exec(['config', '--get-regexp', '-z', pattern]);
107
+ if (asked.code === 1 && !asked.stdout)
108
+ return ok([]);
109
+ if (!succeeded(asked))
110
+ return err('git config could not be read');
111
+ return ok(asked.stdout.split('\0').filter(Boolean).map((entry) => {
112
+ const newline = entry.indexOf('\n');
113
+ return newline < 0 ? null : entry.slice(newline + 1);
114
+ }));
115
+ }
96
116
  /** Remote names, in the order git lists them. A failed read is an error, not "none". */
97
117
  async readRemotes() {
98
118
  const listed = await this.exec(['remote']);
@@ -101,11 +121,19 @@ export class Git {
101
121
  return ok(lines(listed));
102
122
  }
103
123
  /** Whether any ref exists under `refs/remotes/<remote>/`. A failed read is an error, not "none". */
104
- async hasTrackingRefs(remote) {
105
- const listed = await this.exec(['for-each-ref', '--count=1', '--format=%(refname)', 'refs/remotes/' + remote + '/']);
124
+ /**
125
+ * Whether any ref lies under `prefixes` but not under `excluded` (namespaces nested inside
126
+ * them that belong to someone else). No prefix is no ref. Listing stops at one when
127
+ * nothing is excluded.
128
+ */
129
+ async hasRefsUnder(prefixes, excluded = []) {
130
+ if (prefixes.length === 0)
131
+ return ok(false);
132
+ const count = excluded.length === 0 ? ['--count=1'] : [];
133
+ const listed = await this.exec(['for-each-ref', ...count, '--format=%(refname)', ...prefixes]);
106
134
  if (!succeeded(listed))
107
135
  return err(listed.stderr.trim() || 'git for-each-ref failed');
108
- return ok(lines(listed).length > 0);
136
+ return ok(lines(listed).some((ref) => !excluded.some((prefix) => ref.startsWith(prefix))));
109
137
  }
110
138
  /**
111
139
  * The directory every worktree shares -- where hooks and config actually live.
@@ -195,12 +223,14 @@ export class Git {
195
223
  // ---- history ------------------------------------------------------------
196
224
  /**
197
225
  * Author and committer of every commit in `range`, which is passed to git as
198
- * separate arguments so a caller can use `<sha> --not --remotes=origin`.
226
+ * separate arguments so a caller can use `<sha> --not --remotes=origin`. `excluded`
227
+ * commits (and what they reach) are left out, through stdin (see excludedInput).
199
228
  */
200
- async identitiesIn(range) {
229
+ async identitiesIn(range, excluded = []) {
230
+ const [stdin, input] = excludedInput(excluded);
201
231
  const [log, count] = await Promise.all([
202
- this.exec(['log', '--no-show-signature', `--format=${IDENTITY_FORMAT}`, ...range]),
203
- this.exec(['rev-list', '--count', ...range]),
232
+ this.exec(['log', '--no-show-signature', `--format=${IDENTITY_FORMAT}`, ...range, ...stdin], input),
233
+ this.exec(['rev-list', '--count', ...range, ...stdin], input),
204
234
  ]);
205
235
  // An empty list would read as "no foreign commits": a failure must stay one.
206
236
  if (!succeeded(log))
@@ -246,14 +276,36 @@ export class Git {
246
276
  }
247
277
  /** Fetch with every prompt off: a sign-in that would ask fails instead. The reason is cleaned for display. */
248
278
  async fetchQuietly(remote) {
249
- const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', remote], await this.quietEnvHere(), NETWORK_MS);
279
+ const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', '--', remote], await this.quietEnvHere(), NETWORK_MS);
250
280
  return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
251
281
  }
252
282
  /** How many branches the remote lists (network, prompts off). */
253
283
  async remoteHeadCount(remote) {
254
- const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', remote], await this.quietEnvHere(), NETWORK_MS);
284
+ const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', '--', remote], await this.quietEnvHere(), NETWORK_MS);
255
285
  return succeeded(listed) ? ok(lines(listed).length) : err(networkReason(listed));
256
286
  }
287
+ /**
288
+ * The commits the remote's branches and tags point at (network, prompts off), as the
289
+ * remote lists them: a tag's peeled `^{}` line when there is one, else the tag itself.
290
+ */
291
+ async remoteTips(remote) {
292
+ const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', '--tags', '--', remote], await this.quietEnvHere(), NETWORK_MS);
293
+ return succeeded(listed) ? ok(parseTips(lines(listed))) : err(networkReason(listed));
294
+ }
295
+ /**
296
+ * Each object as the commit it peels to here, or null when this clone has no such commit.
297
+ * Lazy fetching is off: a partial clone must not reach the network to answer.
298
+ */
299
+ async localCommits(objects) {
300
+ if (objects.length === 0)
301
+ return ok([]);
302
+ const env = { ...process.env, GIT_NO_LAZY_FETCH: '1' };
303
+ const input = objects.map((sha) => sha + '^{commit}').join('\n') + '\n';
304
+ const checked = await run('git', ['--no-replace-objects', 'cat-file', '--batch-check=%(objectname) %(objecttype)'], { cwd: this.cwd, input, env });
305
+ if (!succeeded(checked))
306
+ return err(checked.stderr.trim() || 'git cat-file failed');
307
+ return ok(lines(checked).map((line) => line.endsWith(' commit') ? line.split(' ')[0] : null));
308
+ }
257
309
  /** Prompts off. ssh gets BatchMode only where neither the shell nor this clone names an ssh command. */
258
310
  async quietEnvHere() {
259
311
  return quietEnv(process.env, await this.getConfig('core.sshCommand') !== null);
@@ -285,20 +337,40 @@ export class Git {
285
337
  async parentOf(sha) {
286
338
  return output(await this.exec(['rev-parse', '--verify', '--quiet', sha + '^']));
287
339
  }
288
- async countIn(range) {
289
- const counted = await this.exec(['rev-list', '--count', ...range]);
340
+ async countIn(range, excluded = []) {
341
+ const [stdin, input] = excludedInput(excluded);
342
+ const counted = await this.exec(['rev-list', '--count', ...range, ...stdin], input);
290
343
  const count = Number(counted.stdout.trim());
291
344
  return succeeded(counted) && Number.isInteger(count) ? ok(count) : err(counted.stderr.trim() || 'git rev-list failed');
292
345
  }
293
- /** Tracked changes, or entries hidden with skip-worktree / assume-unchanged, that a rebase could clobber. */
346
+ /**
347
+ * Tracked changes, or entries hidden with skip-worktree / assume-unchanged, that a rebase could
348
+ * clobber, anywhere in the work tree. In a sparse checkout a skip-worktree entry whose file is
349
+ * not on disk is what sparse-checkout left out, and a rebase keeps it out.
350
+ */
294
351
  async hasTrackedChanges() {
295
- const [status, files] = await Promise.all([
296
- this.exec(['status', '--porcelain', '--untracked-files=no']), this.exec(['ls-files', '-v']),
352
+ const [status, files, sparse] = await Promise.all([
353
+ this.exec(['status', '--porcelain', '--untracked-files=no']), this.exec(['ls-files', '-v', '-z', '--', ':/']),
354
+ this.getBoolConfig('core.sparseCheckout'),
297
355
  ]);
298
356
  if (!succeeded(status) || !succeeded(files))
299
357
  return err('git status failed');
300
- const hidden = lines(files).some((line) => /^([a-z]|S) /.test(line));
301
- return ok(status.stdout.trim().length > 0 || hidden);
358
+ const hidden = files.stdout.split('\0').filter((entry) => /^([a-z]|S) /.test(entry));
359
+ const kept = sparse === true ? hidden.filter((entry) => !this.leftOut(entry)) : hidden;
360
+ return ok(status.stdout.trim().length > 0 || kept.length > 0);
361
+ }
362
+ /** An `ls-files -v` entry marked skip-worktree only (`S`) whose file is not there. */
363
+ leftOut(entry) {
364
+ if (!entry.startsWith('S '))
365
+ return false;
366
+ try {
367
+ lstatSync(resolve(this.cwd, entry.slice(2)));
368
+ return false;
369
+ }
370
+ catch (error) {
371
+ const code = error.code;
372
+ return code === 'ENOENT' || code === 'ENOTDIR';
373
+ }
302
374
  }
303
375
  /** The operation a half-finished rebase, merge, cherry-pick, revert or bisect left, or null. */
304
376
  async operationInProgress() {
@@ -417,3 +489,29 @@ function parseIdentities(stdout) {
417
489
  }
418
490
  return ok(commits);
419
491
  }
492
+ /** `ls-remote` lines: `<object><TAB><ref>`, any hash length; a tag's peeled line wins over the tag. */
493
+ function parseTips(listed) {
494
+ const heads = [];
495
+ const tags = new Map();
496
+ for (const line of listed) {
497
+ const [object, ref] = line.split(/\s+/);
498
+ if (!object || !ref)
499
+ continue;
500
+ if (ref.startsWith('refs/heads/'))
501
+ heads.push(object);
502
+ else if (ref.endsWith('^{}'))
503
+ tags.set(ref.slice(0, -3), object);
504
+ else if (!tags.has(ref))
505
+ tags.set(ref, object);
506
+ }
507
+ return { heads, tags: [...tags.values()] };
508
+ }
509
+ /**
510
+ * `--stdin` with one `^<sha>` per line: git reads each line with its own flags, so the
511
+ * caret, not a `--not` on the command line, excludes it; and no command line is too long.
512
+ */
513
+ function excludedInput(excluded) {
514
+ if (excluded.length === 0)
515
+ return [[], undefined];
516
+ return [['--stdin'], excluded.map((sha) => '^' + sha).join('\n') + '\n'];
517
+ }
@@ -17,6 +17,7 @@
17
17
  import { parseGitUrl } from '../url.js';
18
18
  import { providerFor } from '../hosts/index.js';
19
19
  import { readIdentity, legacyAccountKey } from '../identity.js';
20
+ import { copyableCommand } from '../shell.js';
20
21
  /** The null object id: 40 zeros, or 64 in a SHA-256 repository. */
21
22
  const isZero = (sha) => /^0+$/.test(sha);
22
23
  const MIRROR_KEY = 'repown.mirrorBranch';
@@ -246,32 +247,6 @@ function printable(text) {
246
247
  function redacted(raw) {
247
248
  return raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i, '$1***@');
248
249
  }
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
- */
261
- export function shellWord(value) {
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
250
  /** Said instead of the allow-owner command when that command can't be printed safely. */
276
251
  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
252
  /**
@@ -9,7 +9,7 @@
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
11
  import { credentialPrefix } from '../url.js';
12
- import { ghProfileField, ghProfileLookup } from '../credential/gh.js';
12
+ import { fieldOf, ghUser } from '../credential/gh.js';
13
13
  import { printable } from '../../ui/format.js';
14
14
  const HOSTS = ['github.com', 'gist.github.com', 'www.github.com', 'ssh.github.com'];
15
15
  export function githubProvider() {
@@ -21,6 +21,7 @@ export function githubProvider() {
21
21
  credentialKeys,
22
22
  resolveProfile,
23
23
  accountKind,
24
+ lookUp,
24
25
  };
25
26
  }
26
27
  function credentialKeys(url) {
@@ -35,7 +36,24 @@ export function githubLogin(login) {
35
36
  return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(login);
36
37
  }
37
38
  function resolveProfile(account) {
38
- return profileFrom(account, ghProfileField);
39
+ return profileFrom(account, reader(once(account)));
40
+ }
41
+ /** The profile and what kind of account it is, from one `gh api` call. */
42
+ async function lookUp(login) {
43
+ const user = once(login);
44
+ const [profile, kind] = await Promise.all([profileFrom(login, reader(user)), kindFrom(login, looker(user))]);
45
+ return { profile, kind };
46
+ }
47
+ /** One `gh api users/<login>` however many fields are read, and none if no field is. */
48
+ function once(login) {
49
+ let asked;
50
+ return () => (asked ??= ghUser(login));
51
+ }
52
+ function reader(user) {
53
+ return async (_login, field) => fieldOf(await user(), field).value;
54
+ }
55
+ function looker(user) {
56
+ return async (_login, field) => fieldOf(await user(), field);
39
57
  }
40
58
  /**
41
59
  * The suggestion for a GitHub-shaped login. A name that printable() would change (control,
@@ -63,7 +81,7 @@ export function isNoreplyAddress(email) {
63
81
  * Anything else, including a failed call, is unknown -- not a user.
64
82
  */
65
83
  function accountKind(login) {
66
- return kindFrom(login, ghProfileLookup);
84
+ return kindFrom(login, looker(once(login)));
67
85
  }
68
86
  /**
69
87
  * What github.com says a login is. One GitHub can't have (a dot, a slash, a leading dash)
@@ -27,6 +27,8 @@ export function loginKindProblem(kind, login) {
27
27
  export async function lookUpProfile(provider, account) {
28
28
  if (!provider?.resolveProfile)
29
29
  return { profile: {}, problem: null };
30
- const [profile, kind] = await Promise.all([provider.resolveProfile(account), provider.accountKind?.(account)]);
30
+ const { profile, kind } = provider.lookUp
31
+ ? await provider.lookUp(account)
32
+ : { profile: await provider.resolveProfile(account), kind: await provider.accountKind?.(account) };
31
33
  return { profile: profile ?? {}, problem: loginKindProblem(kind, account) };
32
34
  }
@@ -17,32 +17,59 @@ export async function inspectRepo(git) {
17
17
  const isRepo = await git.isRepo();
18
18
  const originUrl = isRepo ? await git.getConfig('remote.origin.url') : null;
19
19
  const url = originUrl ? parseGitUrl(originUrl) : null;
20
- const provider = providerFor(url);
21
- const credentialKeys = url ? provider.credentialKeys(url) : [];
22
- const [root, branch, hook, identity, guard, helper, pushed] = await Promise.all([
20
+ const sides = await originSides(git, originUrl);
21
+ const [root, branch, hook, identity, guard, helper] = await Promise.all([
23
22
  isRepo ? git.root() : Promise.resolve(null),
24
23
  isRepo ? git.currentBranch() : Promise.resolve(null),
25
24
  isRepo ? hookLocation(git) : Promise.resolve(null),
26
- readIdentity(git, credentialKeys[0] ?? null),
25
+ readIdentity(git, sides.credential.keys[0] ?? null),
27
26
  isRepo ? guardState(git) : Promise.resolve('off'),
28
- git.getUrlMatch('credential.helper', originUrl ?? DEFAULT_PROBE_URL),
29
- pushSide(git, originUrl),
27
+ git.getUrlMatch('credential.helper', sides.credential.url ?? DEFAULT_PROBE_URL),
30
28
  ]);
31
29
  return {
32
- git, isRepo, root, branch, originUrl, url, provider,
33
- owner: pushed.owner, ownerProvider: pushed.provider,
34
- identity, credentialKeys, guard, hook, helper,
30
+ git, isRepo, root, branch, originUrl, url, provider: providerFor(url),
31
+ owner: sides.owner, ownerProvider: sides.ownerProvider,
32
+ identity, credentialKeys: sides.credential.keys, credentialUrl: sides.credential.url,
33
+ credentialHost: sides.credential.host, guard, hook, helper,
35
34
  };
36
35
  }
36
+ /** Origin's URLs as git uses them, read once for both the push owner and the credential side. */
37
+ async function originSides(git, originUrl) {
38
+ if (!originUrl)
39
+ return { owner: null, ownerProvider: providerFor(null), credential: { keys: [], url: null, host: providerFor(null) } };
40
+ const [fetched, pushed] = await Promise.all([git.remoteUrls('origin', false), git.remoteUrls('origin', true)]);
41
+ const owner = await pushSide(git, originUrl, pushed);
42
+ return { owner: owner.owner, ownerProvider: owner.provider, credential: credentialSide(originUrl, [fetched, pushed]) };
43
+ }
37
44
  /**
38
45
  * 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.
46
+ * pushInsteadOf, insteadOf), the one the guard checks (the first, when there are several).
47
+ * The owner and its host always come from that same URL.
48
+ */
49
+ async function pushSide(git, originUrl, pushed) {
50
+ const url = parseGitUrl((pushed.ok ? pushed.value[0] : await git.remotePushUrl('origin')) ?? originUrl);
51
+ const provider = providerFor(url);
52
+ return { owner: url ? provider.ownerOf(url) : null, provider };
53
+ }
54
+ /**
55
+ * Every credential request git makes for origin goes to one of these URLs, after insteadOf
56
+ * and pushInsteadOf; each gets its own host's keys. When git can't list them nothing is
57
+ * claimed, and the configured URL is the one described.
41
58
  */
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 };
59
+ function credentialSide(originUrl, listed) {
60
+ const urls = listed.every((urls) => urls.ok) ? listed.flatMap((urls) => (urls.ok ? urls.value : [])) : [];
61
+ const keyed = urls.map((raw) => ({ raw, keys: keysOf(raw) }));
62
+ const url = keyed.find((entry) => entry.keys.length > 0)?.raw ?? urls[0] ?? originUrl;
63
+ return { keys: [...new Set(keyed.flatMap((entry) => entry.keys))], url, host: providerFor(parseGitUrl(url)) };
64
+ }
65
+ /** Whether repown pins a credential for this clone: only where it measured one (ADR-009). */
66
+ export function pinsCredential(repo) {
67
+ return repo.credentialKeys.length > 0;
68
+ }
69
+ /** The credential keys repown pins for one URL; empty where it can't pin (ADR-009). */
70
+ export function keysOf(raw) {
71
+ const url = parseGitUrl(raw);
72
+ return url ? providerFor(url).credentialKeys(url) : [];
46
73
  }
47
74
  export async function inspectAuth(git, probeUrl) {
48
75
  const gcmPath = await findGcm();