repown 0.5.0 → 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.
@@ -17,7 +17,7 @@
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';
20
+ import { inspectRepo, inspectAuth, pinsCredential } from '../core/inspect.js';
21
21
  import { pinIdentity } from '../core/identity.js';
22
22
  import { lookupAccount, saveAccount } from '../core/registry.js';
23
23
  import { ghSwitch, ghLogin, readGhLoginVersion, } from '../core/credential/gh.js';
@@ -50,7 +50,7 @@ export default {
50
50
  return 1;
51
51
  if (!reportPinned(await pinIdentity(git, { ...values, account }, repo.credentialKeys)))
52
52
  return 1;
53
- out.pass('identity', values.name + ' <' + values.email + '> push-as:' + account);
53
+ out.pass('identity', out.printable(values.name + ' <' + values.email + '>' + (pinsCredential(repo) ? ' push-as:' + account : '')));
54
54
  if (flagBool(args, 'gh'))
55
55
  await applyGh(account, repo);
56
56
  await reportConcerns(account, repo, values.email);
@@ -100,16 +100,20 @@ async function askAndRecord(account, repo, known) {
100
100
  out.line();
101
101
  out.line(' No record of "' + account + '" yet. Asking once, then never again.');
102
102
  const entry = await askProfile({
103
- name: known.name ?? suggested.name ?? account, email: known.email ?? suggested.email,
103
+ name: offered(known.name) ?? suggested.name ?? offered(account) ?? '', email: offered(known.email) ?? suggested.email,
104
104
  }, repo.provider.id);
105
105
  if (!entry)
106
106
  return null;
107
107
  const saved = await saveAccount(account, entry);
108
108
  if (!saved.ok)
109
- out.warn('accounts', 'pinned, but not recorded: ' + saved.error);
109
+ out.warn('accounts', 'pinned, but not recorded: ' + out.printable(saved.error));
110
110
  out.line();
111
111
  return entry;
112
112
  }
113
+ /** A default worth offering: one printable() would change would be drawn raw, and saved if accepted. */
114
+ function offered(value) {
115
+ return value && out.printable(value) === value ? value : undefined;
116
+ }
113
117
  async function askProfile(defaults, host) {
114
118
  const name = await ask('Commit name', defaults.name);
115
119
  if (!name.ok) {
@@ -158,7 +162,7 @@ function storesIn(gcm, helper) {
158
162
  return ASK + 'press Enter (Yes): it also stores this sign-in in ' + where + ', so the first push won\'t ask again.';
159
163
  }
160
164
  async function applyGh(account, repo) {
161
- const auth = await inspectAuth(repo.git, repo.originUrl ?? undefined);
165
+ const auth = await inspectAuth(repo.git, repo.credentialUrl ?? undefined);
162
166
  const action = ghAction(account, auth, interactive());
163
167
  if (action === 'advise')
164
168
  return notSignedIn(account);
@@ -206,7 +210,7 @@ function loginFailed(failure) {
206
210
  out.detail('fix: gh auth login');
207
211
  }
208
212
  async function reportLogin(account, repo, before) {
209
- const after = await inspectAuth(repo.git, repo.originUrl ?? undefined);
213
+ const after = await inspectAuth(repo.git, repo.credentialUrl ?? undefined);
210
214
  reportActive(account, after);
211
215
  if (!before.ghIsHelper && after.ghIsHelper)
212
216
  helperTakenOver();
@@ -249,8 +253,8 @@ async function switchCli(account) {
249
253
  /** Everything that is now true but not yet right. Warnings, never refusals. */
250
254
  async function reportConcerns(account, repo, email) {
251
255
  await reportUnpushed(repo, email, account);
252
- if (repo.credentialKeys.length === 0 && repo.url) {
253
- out.warn('host', repo.provider.label + ' credentials are not pinned by repown.');
256
+ if (!pinsCredential(repo) && repo.url) {
257
+ out.warn('host', 'credentials on ' + repo.credentialHost.label + ' are not pinned by repown.');
254
258
  out.detail('commits are pinned and the guard still runs; only credential');
255
259
  out.detail('selection is left to whatever already serves this host.');
256
260
  }
@@ -279,8 +283,11 @@ async function ownerConcern(account, repo) {
279
283
  out.detail('normal for an organisation repository. To stop the guard refusing it:');
280
284
  out.detail(' ' + (allowOwnerCommand(repo.owner) ?? ALLOW_OWNER_BY_HAND));
281
285
  }
286
+ /** Only where use pinned a credential: elsewhere pushes use the host's own sign-in, as setup's credentialGap says. */
282
287
  async function credentialConcern(account, repo) {
283
- const auth = await inspectAuth(repo.git, repo.originUrl ?? undefined);
288
+ if (!pinsCredential(repo))
289
+ return;
290
+ const auth = await inspectAuth(repo.git, repo.credentialUrl ?? undefined);
284
291
  if (auth.ghIsHelper) {
285
292
  out.warn('helper', 'gh is still the git credential helper, so this pin is not honoured.');
286
293
  out.detail('fix: repown fix');
@@ -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) {
@@ -101,6 +102,7 @@ function ownerBlocker(destination, branch, choice) {
101
102
  const guard = choice.guarded ? 'the guard will refuse it' : 'the guard is off, so it pushes there anyway';
102
103
  return [{
103
104
  kind: 'owner',
105
+ owner: destination.owner,
104
106
  summary: 'the push goes to "' + printable(destination.owner) + '"',
105
107
  lines: [branch + ' pushes to ' + where + ', owned by "' + printable(destination.owner) + '", not ' + choice.account +
106
108
  ': ' + guard + '. If you belong there: ' + (allowOwnerCommand(destination.owner) ?? ALLOW_OWNER_BY_HAND)],
@@ -125,7 +127,7 @@ function divergenceBlocker(divergence, branch) {
125
127
  function upstreamBlocker(facts, branch, autoUpstream) {
126
128
  if (facts.upstream !== 'missing' || autoUpstream)
127
129
  return [];
128
- const push = copyableCommand(['git', 'push', '-u', facts.destination?.remote ?? 'origin', branch]) ?? 'git push -u with the remote and this branch';
130
+ const push = copyableCommand(['git', 'push', '-u', ...positional(facts.destination?.remote ?? 'origin'), branch]) ?? 'git push -u with the remote and this branch';
129
131
  return [{ kind: 'upstream', summary: branch + ' has no upstream', lines: [branch + ' has no upstream: the first push needs ' + push], blocks: true }];
130
132
  }
131
133
  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 @@ const NAMES = ['git-credential-manager', 'git-credential-manager-core'];
20
20
  async function searchDirectories() {
21
21
  const directories = [];
22
22
  // Git for Windows bundles GCM as a sibling of git's own exec-path:
23
- // <root>/mingw64/libexec/git-core -> <root>/mingw64/bin
23
+ // <root>/mingw64/libexec/git-core -> <root>/mingw64/bin (ucrt64 from Git 2.56 on)
24
24
  const execPath = await run('git', ['--exec-path']);
25
25
  if (succeeded(execPath)) {
26
26
  const mingw = dirname(dirname(execPath.stdout.trim()));
@@ -20,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,22 +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) {
103
- return ['api', '--hostname', 'github.com', `users/${login}`, '--jq', `.${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
+ // One path segment, whatever the login holds (callers also look up only GitHub-shaped logins).
104
+ return ['api', '--hostname', 'github.com', `users/${encodeURIComponent(login)}`];
104
105
  }
105
- /** A profile field from github.com, or null. Absence here is unremarkable. */
106
- export async function ghProfileField(login, field) {
107
- return (await ghProfileLookup(login, field)).value;
106
+ export async function ghUser(login) {
107
+ return userLookupFrom(await run('gh', ghUserArgs(login)));
108
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) {
114
- 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) {
115
111
  const missing = !succeeded(result) && /\(HTTP 404\)/.test(result.stderr);
116
- 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
+ }
117
129
  }
118
130
  export async function ghSwitch(login) {
119
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';
@@ -75,6 +75,29 @@ export class Git {
75
75
  async remotes() {
76
76
  return lines(await this.exec(['remote']));
77
77
  }
78
+ /**
79
+ * The URL `git push <remote>` uses, as the pre-push hook receives it: pushurl, then
80
+ * pushInsteadOf and insteadOf applied by git itself (the first, when there are several).
81
+ * The raw keys only when git can't say (an old git without `remote get-url`).
82
+ */
83
+ async remotePushUrl(remote) {
84
+ const asked = output(await this.exec(['remote', 'get-url', '--push', '--', remote]));
85
+ if (asked)
86
+ return asked;
87
+ return (await this.getConfig('remote.' + remote + '.pushurl')) ?? this.getConfig('remote.' + remote + '.url');
88
+ }
89
+ /** 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
+ }
94
+ /**
95
+ * A bare URL after git's insteadOf rewriting (`ls-remote --get-url` contacts nothing).
96
+ * It reads fetch rules, so a pushInsteadOf on a bare push URL is not applied.
97
+ */
98
+ async rewrittenUrl(url) {
99
+ return output(await this.exec(['ls-remote', '--get-url', '--', url]));
100
+ }
78
101
  /** Remote names, in the order git lists them. A failed read is an error, not "none". */
79
102
  async readRemotes() {
80
103
  const listed = await this.exec(['remote']);
@@ -83,11 +106,19 @@ export class Git {
83
106
  return ok(lines(listed));
84
107
  }
85
108
  /** Whether any ref exists under `refs/remotes/<remote>/`. A failed read is an error, not "none". */
86
- async hasTrackingRefs(remote) {
87
- 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]);
88
119
  if (!succeeded(listed))
89
120
  return err(listed.stderr.trim() || 'git for-each-ref failed');
90
- return ok(lines(listed).length > 0);
121
+ return ok(lines(listed).some((ref) => !excluded.some((prefix) => ref.startsWith(prefix))));
91
122
  }
92
123
  /**
93
124
  * The directory every worktree shares -- where hooks and config actually live.
@@ -177,12 +208,14 @@ export class Git {
177
208
  // ---- history ------------------------------------------------------------
178
209
  /**
179
210
  * Author and committer of every commit in `range`, which is passed to git as
180
- * 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).
181
213
  */
182
- async identitiesIn(range) {
214
+ async identitiesIn(range, excluded = []) {
215
+ const [stdin, input] = excludedInput(excluded);
183
216
  const [log, count] = await Promise.all([
184
- this.exec(['log', '--no-show-signature', `--format=${IDENTITY_FORMAT}`, ...range]),
185
- 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),
186
219
  ]);
187
220
  // An empty list would read as "no foreign commits": a failure must stay one.
188
221
  if (!succeeded(log))
@@ -228,14 +261,36 @@ export class Git {
228
261
  }
229
262
  /** Fetch with every prompt off: a sign-in that would ask fails instead. The reason is cleaned for display. */
230
263
  async fetchQuietly(remote) {
231
- 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);
232
265
  return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
233
266
  }
234
267
  /** How many branches the remote lists (network, prompts off). */
235
268
  async remoteHeadCount(remote) {
236
- 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);
237
270
  return succeeded(listed) ? ok(lines(listed).length) : err(networkReason(listed));
238
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
+ }
239
294
  /** Prompts off. ssh gets BatchMode only where neither the shell nor this clone names an ssh command. */
240
295
  async quietEnvHere() {
241
296
  return quietEnv(process.env, await this.getConfig('core.sshCommand') !== null);
@@ -267,20 +322,40 @@ export class Git {
267
322
  async parentOf(sha) {
268
323
  return output(await this.exec(['rev-parse', '--verify', '--quiet', sha + '^']));
269
324
  }
270
- async countIn(range) {
271
- 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);
272
328
  const count = Number(counted.stdout.trim());
273
329
  return succeeded(counted) && Number.isInteger(count) ? ok(count) : err(counted.stderr.trim() || 'git rev-list failed');
274
330
  }
275
- /** 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
+ */
276
336
  async hasTrackedChanges() {
277
- const [status, files] = await Promise.all([
278
- 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'),
279
340
  ]);
280
341
  if (!succeeded(status) || !succeeded(files))
281
342
  return err('git status failed');
282
- const hidden = lines(files).some((line) => /^([a-z]|S) /.test(line));
283
- 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
+ }
284
359
  }
285
360
  /** The operation a half-finished rebase, merge, cherry-pick, revert or bisect left, or null. */
286
361
  async operationInProgress() {
@@ -399,3 +474,29 @@ function parseIdentities(stdout) {
399
474
  }
400
475
  return ok(commits);
401
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,8 @@
9
9
  // Over SSH there is no credential helper at all -- the SSH key decides -- so an
10
10
  // SSH remote pins no credential key rather than one that selects nothing.
11
11
  import { credentialPrefix } from '../url.js';
12
- import { ghProfileField, ghProfileLookup } from '../credential/gh.js';
12
+ import { fieldOf, ghUser } from '../credential/gh.js';
13
+ import { printable } from '../../ui/format.js';
13
14
  const HOSTS = ['github.com', 'gist.github.com', 'www.github.com', 'ssh.github.com'];
14
15
  export function githubProvider() {
15
16
  return {
@@ -20,20 +21,53 @@ export function githubProvider() {
20
21
  credentialKeys,
21
22
  resolveProfile,
22
23
  accountKind,
24
+ lookUp,
23
25
  };
24
26
  }
25
27
  function credentialKeys(url) {
26
28
  return url.scheme === 'https' ? [`credential.${credentialPrefix(url)}.username`] : [];
27
29
  }
28
- async function resolveProfile(account) {
29
- const [name, id] = await Promise.all([
30
- ghProfileField(account, 'name'),
31
- ghProfileField(account, 'id'),
32
- ]);
30
+ /**
31
+ * GitHub's own login shape (an underscore for Enterprise Managed Users). Nothing else is
32
+ * looked up: a typed `../user` would make `users/../user` GitHub's own `/user`, the
33
+ * signed-in account, and suggest its name and address for another login.
34
+ */
35
+ export function githubLogin(login) {
36
+ return /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(login);
37
+ }
38
+ function resolveProfile(account) {
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);
57
+ }
58
+ /**
59
+ * The suggestion for a GitHub-shaped login. A name that printable() would change (control,
60
+ * bidi, zero-width characters) is dropped: it would be drawn, and saved if accepted.
61
+ */
62
+ export async function profileFrom(account, read) {
63
+ if (!githubLogin(account))
64
+ return null;
65
+ const [found, id] = await Promise.all([read(account, 'name'), read(account, 'id')]);
66
+ const name = found && printable(found) === found ? found : null;
33
67
  // GitHub's own noreply address: publishable by design, and it still links
34
68
  // the commit to the account. Offered as a default so a private address
35
69
  // need never be published to get working attribution.
36
- const email = id ? `${id}+${account}@users.noreply.github.com` : undefined;
70
+ const email = id && /^\d+$/.test(id) ? `${id}+${account}@users.noreply.github.com` : undefined;
37
71
  if (!name && !email)
38
72
  return null;
39
73
  return { ...(name ? { name } : {}), ...(email ? { email } : {}) };
@@ -46,8 +80,17 @@ export function isNoreplyAddress(email) {
46
80
  * The users endpoint answers for an organisation too, with type Organization.
47
81
  * Anything else, including a failed call, is unknown -- not a user.
48
82
  */
49
- async function accountKind(login) {
50
- const found = await ghProfileLookup(login, 'type');
83
+ function accountKind(login) {
84
+ return kindFrom(login, looker(once(login)));
85
+ }
86
+ /**
87
+ * What github.com says a login is. One GitHub can't have (a dot, a slash, a leading dash)
88
+ * is missing without asking: the typo still gets its sentence, and nothing reaches the API.
89
+ */
90
+ export async function kindFrom(login, lookup) {
91
+ if (!githubLogin(login))
92
+ return 'missing';
93
+ const found = await lookup(login, 'type');
51
94
  if (found.missing)
52
95
  return 'missing';
53
96
  if (found.value === 'User')
@@ -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
  }