repown 0.5.1 → 0.5.2

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.
@@ -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.
@@ -101,11 +106,19 @@ export class Git {
101
106
  return ok(lines(listed));
102
107
  }
103
108
  /** 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 + '/']);
109
+ /**
110
+ * Whether any ref lies under `prefixes` but not under `excluded` (namespaces nested inside
111
+ * them that belong to someone else). No prefix is no ref. Listing stops at one when
112
+ * nothing is excluded.
113
+ */
114
+ async hasRefsUnder(prefixes, excluded = []) {
115
+ if (prefixes.length === 0)
116
+ return ok(false);
117
+ const count = excluded.length === 0 ? ['--count=1'] : [];
118
+ const listed = await this.exec(['for-each-ref', ...count, '--format=%(refname)', ...prefixes]);
106
119
  if (!succeeded(listed))
107
120
  return err(listed.stderr.trim() || 'git for-each-ref failed');
108
- return ok(lines(listed).length > 0);
121
+ return ok(lines(listed).some((ref) => !excluded.some((prefix) => ref.startsWith(prefix))));
109
122
  }
110
123
  /**
111
124
  * The directory every worktree shares -- where hooks and config actually live.
@@ -195,12 +208,14 @@ export class Git {
195
208
  // ---- history ------------------------------------------------------------
196
209
  /**
197
210
  * 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`.
211
+ * separate arguments so a caller can use `<sha> --not --remotes=origin`. `excluded`
212
+ * commits (and what they reach) are left out, through stdin (see excludedInput).
199
213
  */
200
- async identitiesIn(range) {
214
+ async identitiesIn(range, excluded = []) {
215
+ const [stdin, input] = excludedInput(excluded);
201
216
  const [log, count] = await Promise.all([
202
- this.exec(['log', '--no-show-signature', `--format=${IDENTITY_FORMAT}`, ...range]),
203
- this.exec(['rev-list', '--count', ...range]),
217
+ this.exec(['log', '--no-show-signature', `--format=${IDENTITY_FORMAT}`, ...range, ...stdin], input),
218
+ this.exec(['rev-list', '--count', ...range, ...stdin], input),
204
219
  ]);
205
220
  // An empty list would read as "no foreign commits": a failure must stay one.
206
221
  if (!succeeded(log))
@@ -246,14 +261,36 @@ export class Git {
246
261
  }
247
262
  /** Fetch with every prompt off: a sign-in that would ask fails instead. The reason is cleaned for display. */
248
263
  async fetchQuietly(remote) {
249
- const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', remote], await this.quietEnvHere(), NETWORK_MS);
264
+ const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', '--', remote], await this.quietEnvHere(), NETWORK_MS);
250
265
  return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
251
266
  }
252
267
  /** How many branches the remote lists (network, prompts off). */
253
268
  async remoteHeadCount(remote) {
254
- const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', remote], await this.quietEnvHere(), NETWORK_MS);
269
+ const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', '--', remote], await this.quietEnvHere(), NETWORK_MS);
255
270
  return succeeded(listed) ? ok(lines(listed).length) : err(networkReason(listed));
256
271
  }
272
+ /**
273
+ * The commits the remote's branches and tags point at (network, prompts off), as the
274
+ * remote lists them: a tag's peeled `^{}` line when there is one, else the tag itself.
275
+ */
276
+ async remoteTips(remote) {
277
+ const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', '--tags', '--', remote], await this.quietEnvHere(), NETWORK_MS);
278
+ return succeeded(listed) ? ok(parseTips(lines(listed))) : err(networkReason(listed));
279
+ }
280
+ /**
281
+ * Each object as the commit it peels to here, or null when this clone has no such commit.
282
+ * Lazy fetching is off: a partial clone must not reach the network to answer.
283
+ */
284
+ async localCommits(objects) {
285
+ if (objects.length === 0)
286
+ return ok([]);
287
+ const env = { ...process.env, GIT_NO_LAZY_FETCH: '1' };
288
+ const input = objects.map((sha) => sha + '^{commit}').join('\n') + '\n';
289
+ const checked = await run('git', ['--no-replace-objects', 'cat-file', '--batch-check=%(objectname) %(objecttype)'], { cwd: this.cwd, input, env });
290
+ if (!succeeded(checked))
291
+ return err(checked.stderr.trim() || 'git cat-file failed');
292
+ return ok(lines(checked).map((line) => line.endsWith(' commit') ? line.split(' ')[0] : null));
293
+ }
257
294
  /** Prompts off. ssh gets BatchMode only where neither the shell nor this clone names an ssh command. */
258
295
  async quietEnvHere() {
259
296
  return quietEnv(process.env, await this.getConfig('core.sshCommand') !== null);
@@ -285,20 +322,40 @@ export class Git {
285
322
  async parentOf(sha) {
286
323
  return output(await this.exec(['rev-parse', '--verify', '--quiet', sha + '^']));
287
324
  }
288
- async countIn(range) {
289
- const counted = await this.exec(['rev-list', '--count', ...range]);
325
+ async countIn(range, excluded = []) {
326
+ const [stdin, input] = excludedInput(excluded);
327
+ const counted = await this.exec(['rev-list', '--count', ...range, ...stdin], input);
290
328
  const count = Number(counted.stdout.trim());
291
329
  return succeeded(counted) && Number.isInteger(count) ? ok(count) : err(counted.stderr.trim() || 'git rev-list failed');
292
330
  }
293
- /** Tracked changes, or entries hidden with skip-worktree / assume-unchanged, that a rebase could clobber. */
331
+ /**
332
+ * Tracked changes, or entries hidden with skip-worktree / assume-unchanged, that a rebase could
333
+ * clobber, anywhere in the work tree. In a sparse checkout a skip-worktree entry whose file is
334
+ * not on disk is what sparse-checkout left out, and a rebase keeps it out.
335
+ */
294
336
  async hasTrackedChanges() {
295
- const [status, files] = await Promise.all([
296
- this.exec(['status', '--porcelain', '--untracked-files=no']), this.exec(['ls-files', '-v']),
337
+ const [status, files, sparse] = await Promise.all([
338
+ this.exec(['status', '--porcelain', '--untracked-files=no']), this.exec(['ls-files', '-v', '-z', '--', ':/']),
339
+ this.getBoolConfig('core.sparseCheckout'),
297
340
  ]);
298
341
  if (!succeeded(status) || !succeeded(files))
299
342
  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);
343
+ const hidden = files.stdout.split('\0').filter((entry) => /^([a-z]|S) /.test(entry));
344
+ const kept = sparse === true ? hidden.filter((entry) => !this.leftOut(entry)) : hidden;
345
+ return ok(status.stdout.trim().length > 0 || kept.length > 0);
346
+ }
347
+ /** An `ls-files -v` entry marked skip-worktree only (`S`) whose file is not there. */
348
+ leftOut(entry) {
349
+ if (!entry.startsWith('S '))
350
+ return false;
351
+ try {
352
+ lstatSync(resolve(this.cwd, entry.slice(2)));
353
+ return false;
354
+ }
355
+ catch (error) {
356
+ const code = error.code;
357
+ return code === 'ENOENT' || code === 'ENOTDIR';
358
+ }
302
359
  }
303
360
  /** The operation a half-finished rebase, merge, cherry-pick, revert or bisect left, or null. */
304
361
  async operationInProgress() {
@@ -417,3 +474,29 @@ function parseIdentities(stdout) {
417
474
  }
418
475
  return ok(commits);
419
476
  }
477
+ /** `ls-remote` lines: `<object><TAB><ref>`, any hash length; a tag's peeled line wins over the tag. */
478
+ function parseTips(listed) {
479
+ const heads = [];
480
+ const tags = new Map();
481
+ for (const line of listed) {
482
+ const [object, ref] = line.split(/\s+/);
483
+ if (!object || !ref)
484
+ continue;
485
+ if (ref.startsWith('refs/heads/'))
486
+ heads.push(object);
487
+ else if (ref.endsWith('^{}'))
488
+ tags.set(ref.slice(0, -3), object);
489
+ else if (!tags.has(ref))
490
+ tags.set(ref, object);
491
+ }
492
+ return { heads, tags: [...tags.values()] };
493
+ }
494
+ /**
495
+ * `--stdin` with one `^<sha>` per line: git reads each line with its own flags, so the
496
+ * caret, not a `--not` on the command line, excludes it; and no command line is too long.
497
+ */
498
+ function excludedInput(excluded) {
499
+ if (excluded.length === 0)
500
+ return [[], undefined];
501
+ return [['--stdin'], excluded.map((sha) => '^' + sha).join('\n') + '\n'];
502
+ }
@@ -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();
@@ -8,10 +8,17 @@
8
8
  // unfetched one, and FETCH_HEAD is no answer: a FAILED fetch writes it too, and it
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
- // and a read that fails is unknown.
11
+ // and a read that fails is unknown. A remote that fetches only some branches (a
12
+ // --single-branch clone, a negative refspec) is unknown for a branch it leaves out:
13
+ // pushing that branch updates no tracking ref (refspec.ts).
12
14
  import { parseGitUrl } from './url.js';
15
+ import { ok } from './result.js';
16
+ import { trackingPrefixes, trackingRefOf } from './refspec.js';
17
+ import { readerOf } from './config-snapshot.js';
13
18
  /** Null when the branch pushes nowhere, to `.` (this repository), or where tracking refs reach. */
14
- export async function unknownDestination(git, branch) {
19
+ export async function unknownDestination(given, branch) {
20
+ // Read-only: one config list answers every key read below (ADR-029).
21
+ const git = readerOf(given);
15
22
  const listed = await git.readRemotes();
16
23
  if (!listed.ok)
17
24
  return { kind: 'unread' };
@@ -21,13 +28,14 @@ export async function unknownDestination(git, branch) {
21
28
  if (!name || name === '.')
22
29
  return null;
23
30
  if (listed.value.includes(name))
24
- return remoteState(git, name);
31
+ return remoteState(git, { name, branch, remotes: listed.value });
25
32
  if (!set || !looksLikeUrl(name))
26
33
  return { kind: 'unnamed', name };
27
34
  return { kind: 'url', key: set.key, remote: await remoteWithUrl(git, listed.value, name) };
28
35
  }
29
36
  /** Null when there is no destination, it is `.`, or the remotes could not be listed. */
30
- export async function pushTarget(git, branch) {
37
+ export async function pushTarget(given, branch) {
38
+ const git = readerOf(given);
31
39
  const listed = await git.readRemotes();
32
40
  if (!listed.ok)
33
41
  return null;
@@ -47,21 +55,53 @@ async function configuredTarget(git, branch) {
47
55
  }
48
56
  return null;
49
57
  }
50
- async function remoteState(git, name) {
51
- if (!await isTracked(git, name))
58
+ async function remoteState(git, remote) {
59
+ const { name } = remote;
60
+ const tracked = await trackingRefsOf(git, name, remote.remotes);
61
+ if (!tracked.ok || !tracked.value)
52
62
  return { kind: 'remote', name };
53
- return await pushesElsewhere(git, name) ? { kind: 'pushurl', name } : null;
63
+ if (await pushesElsewhere(git, name))
64
+ return { kind: 'pushurl', name };
65
+ const branch = await destinationBranch(git, remote);
66
+ const specs = await git.getAllConfig('remote.' + name + '.fetch');
67
+ return trackingRefOf(specs, 'refs/heads/' + branch) ? null : { kind: 'untracked', name, branch };
54
68
  }
55
- async function isTracked(git, remote) {
56
- const found = await git.hasTrackingRefs(remote);
57
- return found.ok && found.value;
69
+ /** Whether the remote has any tracking ref where its own refspecs write them. */
70
+ export async function hasTrackingRefs(given, remote) {
71
+ const git = readerOf(given);
72
+ const listed = await git.readRemotes();
73
+ if (!listed.ok)
74
+ return listed;
75
+ return trackingRefsOf(git, remote, listed.value);
76
+ }
77
+ /** Another remote's namespace nested inside this one's (`origin/x` in `origin`'s) is not this one's. */
78
+ async function trackingRefsOf(git, remote, remotes) {
79
+ const prefixes = trackingPrefixes(await git.getAllConfig('remote.' + remote + '.fetch'));
80
+ if (prefixes.length === 0)
81
+ return ok(false);
82
+ const others = await Promise.all(remotes.filter((other) => other !== remote).map((other) => git.getAllConfig('remote.' + other + '.fetch')));
83
+ const nested = others.flatMap(trackingPrefixes).filter((other) => prefixes.some((own) => other.length > own.length && other.startsWith(own)));
84
+ return git.hasRefsUnder(prefixes, nested);
85
+ }
86
+ /** The branch a plain push updates: the upstream's under push.default=upstream, else its own name. */
87
+ async function destinationBranch(git, remote) {
88
+ if (await git.getConfig('push.default') !== 'upstream')
89
+ return remote.branch;
90
+ if (await git.getConfig('branch.' + remote.branch + '.remote') !== remote.name)
91
+ return remote.branch;
92
+ const merge = await git.getConfig('branch.' + remote.branch + '.merge');
93
+ return merge ? merge.replace(/^refs\/heads\//, '') : remote.branch;
58
94
  }
59
- /** Tracking refs come from the fetch URL; a different pushurl is somewhere never fetched. */
95
+ /**
96
+ * Tracking refs come from the first fetch URL; any push URL elsewhere (a pushurl, a second
97
+ * url, a pushInsteadOf rewrite) is somewhere never fetched. A failed read is elsewhere.
98
+ */
60
99
  async function pushesElsewhere(git, remote) {
61
- const push = await git.getConfig('remote.' + remote + '.pushurl');
62
- if (!push)
63
- return false;
64
- return urlKey(push) !== urlKey(await git.getConfig('remote.' + remote + '.url') ?? '');
100
+ const [push, fetch] = await Promise.all([git.remoteUrls(remote, true), git.remoteUrls(remote, false)]);
101
+ if (!push.ok || !fetch.ok)
102
+ return true;
103
+ const fetched = urlKey(fetch.value[0] ?? '');
104
+ return push.value.some((url) => urlKey(url) !== fetched);
65
105
  }
66
106
  /** A URL or a path, as git would read it where a remote name was expected. */
67
107
  function looksLikeUrl(value) {
@@ -6,7 +6,7 @@
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
8
  import { ok } from './result.js';
9
- import { pushTarget, unknownDestination } from './push-destination.js';
9
+ import { hasTrackingRefs, pushTarget, unknownDestination } from './push-destination.js';
10
10
  import { parseGitUrl } from './url.js';
11
11
  import { providerFor } from './hosts/index.js';
12
12
  import { hostileSet } from './guard/check.js';
@@ -49,7 +49,7 @@ async function repointOf(git, branch) {
49
49
  const unknown = branch ? await unknownDestination(git, branch) : null;
50
50
  if (unknown?.kind !== 'url' || !unknown.remote)
51
51
  return null;
52
- const tracked = await git.hasTrackingRefs(unknown.remote);
52
+ const tracked = await hasTrackingRefs(git, unknown.remote);
53
53
  return { key: unknown.key, remote: unknown.remote, tracked: tracked.ok && tracked.value };
54
54
  }
55
55
  async function destinationOf(git, target) {