repown 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/README.md +11 -3
  3. package/dist/cli.js +4 -4
  4. package/dist/commands/accounts.js +19 -13
  5. package/dist/commands/doctor.js +7 -5
  6. package/dist/commands/fix.js +5 -5
  7. package/dist/commands/guard.js +7 -5
  8. package/dist/commands/off.js +4 -4
  9. package/dist/commands/reauthor.js +64 -0
  10. package/dist/commands/scan.js +7 -6
  11. package/dist/commands/setup.js +7 -4
  12. package/dist/commands/start.js +6 -6
  13. package/dist/commands/status.js +66 -22
  14. package/dist/commands/use.js +14 -14
  15. package/dist/core/blockers.js +133 -0
  16. package/dist/core/config-snapshot.js +97 -0
  17. package/dist/core/credential/gcm.js +2 -2
  18. package/dist/core/credential/gh.js +12 -5
  19. package/dist/core/credential/repair.js +1 -1
  20. package/dist/core/git.js +145 -12
  21. package/dist/core/guard/check.js +48 -8
  22. package/dist/core/guard/hook.js +1 -1
  23. package/dist/core/hosts/github.js +11 -5
  24. package/dist/core/hosts/index.js +21 -3
  25. package/dist/core/identity.js +1 -1
  26. package/dist/core/inspect.js +6 -6
  27. package/dist/core/push-destination.js +82 -0
  28. package/dist/core/push-state.js +109 -0
  29. package/dist/core/reauthor.js +145 -0
  30. package/dist/core/registry.js +1 -1
  31. package/dist/core/unpushed.js +112 -43
  32. package/dist/program.js +10 -9
  33. package/dist/ui/args.js +3 -3
  34. package/dist/ui/command.js +1 -1
  35. package/dist/ui/dispatch.js +6 -6
  36. package/dist/ui/format.js +39 -0
  37. package/dist/ui/help.js +2 -2
  38. package/dist/ui/prompt.js +1 -1
  39. package/dist/wizard/clack.js +56 -21
  40. package/dist/wizard/engine.js +7 -4
  41. package/dist/wizard/home-context.js +23 -10
  42. package/dist/wizard/home-flow.js +33 -11
  43. package/dist/wizard/home-run.js +85 -44
  44. package/dist/wizard/home-text.js +14 -3
  45. package/dist/wizard/plain.js +2 -2
  46. package/dist/wizard/review-text.js +36 -14
  47. package/dist/wizard/setup-changes.js +11 -7
  48. package/dist/wizard/setup-context.js +31 -20
  49. package/dist/wizard/setup-flow.js +265 -56
  50. package/dist/wizard/setup-run.js +108 -40
  51. package/npm-shrinkwrap.json +378 -17
  52. package/package.json +3 -3
package/dist/core/git.js CHANGED
@@ -13,19 +13,28 @@
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 { run, succeeded, output, lines } from "./exec.js";
17
- import { ok, err } from "./result.js";
16
+ import { existsSync } from 'node:fs';
17
+ import { join, resolve } from 'node:path';
18
+ import { tmpdir } from 'node:os';
19
+ import { randomUUID } from 'node:crypto';
20
+ import { run, succeeded, output, lines } from './exec.js';
21
+ import { ok, err } from './result.js';
18
22
  export class Git {
19
23
  cwd;
20
24
  constructor(cwd = process.cwd()) {
21
25
  this.cwd = cwd;
22
26
  }
27
+ /** Every short git call. A ConfigSnapshot answers plain config reads here instead (ADR-029). */
28
+ exec(args, input) {
29
+ return this.spawnGit(args, input);
30
+ }
23
31
  /**
32
+ * Starts the git child for exec() (execLong starts its own, for fetch and ls-remote).
24
33
  * --no-replace-objects on every call: `git replace` changes what git SHOWS for
25
34
  * an object, never what a push SENDS, so a replaced foreign commit read as the
26
35
  * clean replacement while the original was published.
27
36
  */
28
- exec(args, input) {
37
+ spawnGit(args, input) {
29
38
  const full = ['--no-replace-objects', ...args];
30
39
  return input === undefined
31
40
  ? run('git', full, { cwd: this.cwd })
@@ -66,6 +75,20 @@ export class Git {
66
75
  async remotes() {
67
76
  return lines(await this.exec(['remote']));
68
77
  }
78
+ /** Remote names, in the order git lists them. A failed read is an error, not "none". */
79
+ async readRemotes() {
80
+ const listed = await this.exec(['remote']);
81
+ if (!succeeded(listed))
82
+ return err(listed.stderr.trim() || 'git remote failed');
83
+ return ok(lines(listed));
84
+ }
85
+ /** 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 + '/']);
88
+ if (!succeeded(listed))
89
+ return err(listed.stderr.trim() || 'git for-each-ref failed');
90
+ return ok(lines(listed).length > 0);
91
+ }
69
92
  /**
70
93
  * The directory every worktree shares -- where hooks and config actually live.
71
94
  * In a linked worktree `.git` is a FILE, so joining '.git' to the root gives a
@@ -125,11 +148,11 @@ export class Git {
125
148
  async setConfig(key, value, scope = 'local') {
126
149
  return succeeded(await this.exec(this.scoped(scope, [key, value])));
127
150
  }
128
- /** True when the key is gone afterwards -- including when it was never set. */
129
151
  /** Appends one more value to a multi-valued key. */
130
152
  async addConfig(key, value, scope) {
131
153
  return succeeded(await this.exec(this.scoped(scope, ['--add', key, value])));
132
154
  }
155
+ /** True when the key is gone afterwards -- including when it was never set. */
133
156
  async unsetConfig(key, scope = 'local') {
134
157
  const result = await this.exec(this.scoped(scope, ['--unset-all', key]));
135
158
  return succeeded(result) || result.code === 5; // 5 = the key did not exist
@@ -198,14 +221,91 @@ export class Git {
198
221
  }
199
222
  return err('tag chain longer than ' + MAX_TAG_CHAIN + ' starting at ' + sha);
200
223
  }
201
- /** Full hash of the oldest commit in `range`, or null when none or git cannot list them. */
202
- async oldestIn(range) {
203
- const listed = lines(await this.exec(['rev-list', '--reverse', ...range]));
204
- return listed[0] ?? null;
224
+ // ---- rewriting (repown reauthor only) -------------------------------------
225
+ /** A long or networked call: its own environment and timeout. Still only exec.ts spawns. */
226
+ execLong(args, env, timeoutMs) {
227
+ return run('git', ['--no-replace-objects', ...args], { cwd: this.cwd, env, timeoutMs });
228
+ }
229
+ /** Fetch with every prompt off: a sign-in that would ask fails instead. The reason is cleaned for display. */
230
+ async fetchQuietly(remote) {
231
+ const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', remote], await this.quietEnvHere(), NETWORK_MS);
232
+ return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
233
+ }
234
+ /** How many branches the remote lists (network, prompts off). */
235
+ async remoteHeadCount(remote) {
236
+ const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', remote], await this.quietEnvHere(), NETWORK_MS);
237
+ return succeeded(listed) ? ok(lines(listed).length) : err(networkReason(listed));
238
+ }
239
+ /** Prompts off. ssh gets BatchMode only where neither the shell nor this clone names an ssh command. */
240
+ async quietEnvHere() {
241
+ return quietEnv(process.env, await this.getConfig('core.sshCommand') !== null);
242
+ }
243
+ /**
244
+ * `git rebase <base> --exec <cmd>`, without moving other branches' refs, without folding
245
+ * commits (autosquash), and with no hook at all: hooksPath names a directory that does not
246
+ * exist, and `-c` reaches the --exec child too, so its `git commit` runs none either.
247
+ */
248
+ async rebaseExec(base, exec) {
249
+ const noHooks = join(tmpdir(), 'repown-no-hooks-' + randomUUID());
250
+ const off = ['-c', 'rebase.updateRefs=false', '-c', 'rebase.autoSquash=false', '-c', 'core.hooksPath=' + noHooks];
251
+ const args = [...off, 'rebase', '--quiet', base, '--exec', exec];
252
+ const rebased = await this.execLong(args, process.env, REBASE_MS);
253
+ return succeeded(rebased) ? ok(undefined) : err(rebased.timedOut ? 'timed out' : networkReason(rebased));
254
+ }
255
+ async abortRebase() {
256
+ return succeeded(await this.exec(['rebase', '--abort']));
257
+ }
258
+ /** Creates `ref` at `sha`; refuses when it exists already, so nothing is overwritten. */
259
+ async createRef(ref, sha) {
260
+ return succeeded(await this.exec(['update-ref', ref, sha, '']));
205
261
  }
206
- /** Short hash of the parent. Null when the commit is a root or cannot be read. */
207
- async parentShort(sha) {
208
- return output(await this.exec(['rev-parse', '--verify', '--short', sha + '^']));
262
+ /** Full hash of `rev`, or null when it does not resolve. */
263
+ async revParse(rev) {
264
+ return output(await this.exec(['rev-parse', '--verify', '--quiet', rev + '^{commit}']));
265
+ }
266
+ /** Full hash of the first parent; null for a root commit. */
267
+ async parentOf(sha) {
268
+ return output(await this.exec(['rev-parse', '--verify', '--quiet', sha + '^']));
269
+ }
270
+ async countIn(range) {
271
+ const counted = await this.exec(['rev-list', '--count', ...range]);
272
+ const count = Number(counted.stdout.trim());
273
+ return succeeded(counted) && Number.isInteger(count) ? ok(count) : err(counted.stderr.trim() || 'git rev-list failed');
274
+ }
275
+ /** Tracked changes, or entries hidden with skip-worktree / assume-unchanged, that a rebase could clobber. */
276
+ async hasTrackedChanges() {
277
+ const [status, files] = await Promise.all([
278
+ this.exec(['status', '--porcelain', '--untracked-files=no']), this.exec(['ls-files', '-v']),
279
+ ]);
280
+ if (!succeeded(status) || !succeeded(files))
281
+ 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);
284
+ }
285
+ /** The operation a half-finished rebase, merge, cherry-pick, revert or bisect left, or null. */
286
+ async operationInProgress() {
287
+ for (const [path, name] of IN_PROGRESS) {
288
+ const where = output(await this.exec(['rev-parse', '--git-path', path]));
289
+ if (where && existsSync(resolve(this.cwd, where)))
290
+ return name;
291
+ }
292
+ return null;
293
+ }
294
+ /** `git rev-list --left-right --count A...B`: commits only on the left, and only on the right. */
295
+ async leftRightCount(range) {
296
+ const counted = await this.exec(['rev-list', '--left-right', '--count', range]);
297
+ const [left, right] = (succeeded(counted) ? counted.stdout.trim() : '').split(/\s+/).map(Number);
298
+ if (!succeeded(counted) || !Number.isInteger(left) || !Number.isInteger(right)) {
299
+ return err(counted.stderr.trim() || 'git rev-list could not count ' + range);
300
+ }
301
+ return ok({ left: left, right: right });
302
+ }
303
+ /** Each commit in `range` (full hash) and its first parent's short hash, null for a root. */
304
+ async firstParentsIn(range) {
305
+ const listed = await this.exec(['log', '--no-show-signature', '--format=%H %p', ...range]);
306
+ if (!succeeded(listed))
307
+ return err(listed.stderr.trim() || 'git log failed');
308
+ return ok(new Map(lines(listed).map(parentPair)));
209
309
  }
210
310
  /** Whether this clone has the commit at all -- a remote tip it never fetched is absent. */
211
311
  async hasCommit(sha) {
@@ -220,7 +320,9 @@ export class Git {
220
320
  * clone. Excluding the mirror branch leaves the commits written HERE.
221
321
  */
222
322
  async emailCounts(exclude) {
223
- const range = exclude ? ['--all', '--not', exclude] : ['--all'];
323
+ // repown reauthor's backups keep the old commits alive; they are not this clone's history.
324
+ const all = ['--exclude=refs/repown/*', '--all'];
325
+ const range = exclude ? [...all, '--not', exclude] : all;
224
326
  // --no-show-signature: a scanned repository's own log.showSignature + gpg.program
225
327
  // would otherwise run a program of its choosing.
226
328
  const result = await this.exec(['log', '--no-show-signature', ...range, '--format=%ae%n%ce']);
@@ -250,6 +352,37 @@ function parseOriginLine(line) {
250
352
  * so nothing an author writes can shift them; the subject cannot reach past its
251
353
  * own terminator either. Records are a fixed IDENTITY_FIELDS long.
252
354
  */
355
+ const NETWORK_MS = 120_000;
356
+ const REBASE_MS = 600_000;
357
+ /** Empty askPass: git asks no helper for a password (GIT_TERMINAL_PROMPT covers the terminal). */
358
+ const QUIET = ['-c', 'core.askPass=', '-c', 'credential.interactive=false'];
359
+ const IN_PROGRESS = [
360
+ ['rebase-merge', 'rebase'], ['rebase-apply', 'rebase'], ['MERGE_HEAD', 'merge'],
361
+ ['CHERRY_PICK_HEAD', 'cherry-pick'], ['REVERT_HEAD', 'revert'], ['BISECT_LOG', 'bisect'],
362
+ ];
363
+ /**
364
+ * The whole environment, with every way git could prompt turned off. ssh is made
365
+ * non-interactive only where nothing names an ssh command already: GIT_SSH_COMMAND outranks
366
+ * core.sshCommand and GIT_SSH, so setting it would replace a per-account key (`ssh -i ...`).
367
+ */
368
+ export function quietEnv(env, sshConfigured) {
369
+ const { GIT_ASKPASS: _git, SSH_ASKPASS: _ssh, ...rest } = env;
370
+ const ownSsh = sshConfigured || !!env['GIT_SSH_COMMAND'] || !!env['GIT_SSH'];
371
+ const batch = ownSsh ? {} : { GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' };
372
+ return { ...rest, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', ...batch };
373
+ }
374
+ /** git's last error line, with a URL's credentials and query masked and control characters removed. */
375
+ export function networkReason(result) {
376
+ if (result.timedOut)
377
+ return 'timed out';
378
+ const last = result.stderr.trim().split('\n').filter(Boolean).at(-1) ?? 'git failed';
379
+ return last.replace(/(\w+:\/\/)\S*@/g, '$1***@').replace(/(\w+:\/\/[^\s?]*)\?[^\s'"]*/g, '$1?***').replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
380
+ }
381
+ /** `<sha> <parent> [<parent>...]`; a root has none. */
382
+ function parentPair(line) {
383
+ const [sha = '', first = ''] = line.trim().split(' ');
384
+ return [sha, first || null];
385
+ }
253
386
  const IDENTITY_FORMAT = '%H%x00%ae%x00%ce%x00%an%x00%cn%x00%s%x00';
254
387
  const IDENTITY_FIELDS = 6;
255
388
  const MAX_TAG_CHAIN = 16;
@@ -14,9 +14,9 @@
14
14
  //
15
15
  // which is exactly the set of commits about to be published. The previous design
16
16
  // read that and threw it away.
17
- import { parseGitUrl } from "../url.js";
18
- import { providerFor } from "../hosts/index.js";
19
- import { readIdentity, legacyAccountKey } from "../identity.js";
17
+ import { parseGitUrl } from '../url.js';
18
+ import { providerFor } from '../hosts/index.js';
19
+ import { readIdentity, legacyAccountKey } from '../identity.js';
20
20
  /** The null object id: 40 zeros, or 64 in a SHA-256 repository. */
21
21
  const isZero = (sha) => /^0+$/.test(sha);
22
22
  const MIRROR_KEY = 'repown.mirrorBranch';
@@ -58,6 +58,10 @@ export async function check(input) {
58
58
  const destination = checkDestination({ url, owner, allowed }, input.onNote);
59
59
  return [...destination, ...await checkCommits(input, identity.email)];
60
60
  }
61
+ /** The names of the variables above that are set (non-empty) in `env`, in that order. */
62
+ export function hostileSet(env) {
63
+ return HOSTILE.filter(([name]) => !!env[name]).map(([name]) => name);
64
+ }
61
65
  function checkEnvironment() {
62
66
  return HOSTILE.flatMap(([name, why]) => {
63
67
  if (!process.env[name])
@@ -104,7 +108,7 @@ function checkDestination({ url, owner, allowed }, onNote) {
104
108
  'destination: ' + printable(redacted(url.raw)),
105
109
  'allowed here: ' + allowed.join(', '),
106
110
  'if that owner is legitimate -- an organisation you belong to, say:',
107
- ' git config --local --add ' + ALLOW_OWNER_KEY + ' ' + shellWord(printable(owner)),
111
+ ' ' + (allowOwnerCommand(owner) ?? ALLOW_OWNER_BY_HAND),
108
112
  ],
109
113
  }];
110
114
  }
@@ -228,9 +232,12 @@ function unreadableHint(error) {
228
232
  function matches(actual, expected) {
229
233
  return actual.toLowerCase() === expected.toLowerCase();
230
234
  }
231
- /** Text a commit's author chose: control characters could rewrite the terminal around the refusal. */
235
+ /**
236
+ * Text a commit's author or a remote URL chose: control characters could rewrite the
237
+ * terminal around the refusal, and bidi or zero-width ones show one owner as another.
238
+ */
232
239
  function printable(text) {
233
- return text.replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
240
+ return text.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, '?');
234
241
  }
235
242
  /**
236
243
  * A URL as it may be shown: the WHOLE userinfo is replaced. A token is often the
@@ -239,7 +246,40 @@ function printable(text) {
239
246
  function redacted(raw) {
240
247
  return raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i, '$1***@');
241
248
  }
242
- /** An owner comes from the URL, so a suggested command must quote it for the shell. */
249
+ /**
250
+ * A word of a command printed to copy, as sh, bash, dash, zsh, fish, PowerShell and cmd all
251
+ * read it (test/paste.test.ts runs each). Bare when no shell treats any of it specially: a
252
+ * leading `@` is a PowerShell splat, and PowerShell splits a dashed word at `.` or `:`.
253
+ * `--` is quoted, since PowerShell drops a bare one from the `$args` of repown.ps1.
254
+ * Otherwise double quotes, unless they would expand or end early somewhere: `$` and a
255
+ * backtick (POSIX, PowerShell), `%` and `!` (cmd), a curly double quote (PowerShell), a
256
+ * backslash that escapes (`\\`, or one before the closing quote), a control character, or
257
+ * nothing at all (Windows PowerShell drops `""`). Then it is null and the caller prints no
258
+ * command: single quotes are no quotes in cmd, and PowerShell would run the rest of a
259
+ * POSIX `'\''` as code.
260
+ */
243
261
  export function shellWord(value) {
244
- return /^[\w.@-]+$/.test(value) ? value : "'" + value.replace(/'/g, "'\\''") + "'";
262
+ if (value === '--')
263
+ return '"--"';
264
+ if (/^(?:-[\w-]*|[\w./][\w.@+/:-]*)$/.test(value))
265
+ return value;
266
+ if (value === '' || /["$`%!“”„\x00-\x1f\x7f-\x9f]|\\\\|\\$/.test(value))
267
+ return null;
268
+ return '"' + value + '"';
269
+ }
270
+ /** A whole command to copy, or null when one of its words can't be printed safely (shellWord). */
271
+ export function copyableCommand(words) {
272
+ const quoted = words.map(shellWord);
273
+ return quoted.every((word) => word !== null) ? quoted.join(' ') : null;
274
+ }
275
+ /** Said instead of the allow-owner command when that command can't be printed safely. */
276
+ export const ALLOW_OWNER_BY_HAND = 'add that owner to ' + ALLOW_OWNER_KEY + ' with git config yourself (it can\'t be printed safely to paste)';
277
+ /**
278
+ * The command that lets this clone push to `owner`, or null: for an owner git would read
279
+ * as an option, or one that shows as something else (control or bidi characters).
280
+ */
281
+ export function allowOwnerCommand(owner) {
282
+ if (owner.startsWith('-') || printable(owner) !== owner)
283
+ return null;
284
+ return copyableCommand(['git', 'config', '--local', '--add', ALLOW_OWNER_KEY, owner]);
245
285
  }
@@ -19,7 +19,7 @@ import { readFile, writeFile, mkdir, rm, chmod } from 'node:fs/promises';
19
19
  import { existsSync, realpathSync } from 'node:fs';
20
20
  import { join, dirname, resolve } from 'node:path';
21
21
  import { fileURLToPath } from 'node:url';
22
- import { ok, err } from "../result.js";
22
+ import { ok, err } from '../result.js';
23
23
  export const MARKER = 'repown-identity-guard';
24
24
  /**
25
25
  * A marker counts only where this tool writes it: line 2 (right after the shebang)
@@ -8,8 +8,8 @@
8
8
  //
9
9
  // Over SSH there is no credential helper at all -- the SSH key decides -- so an
10
10
  // SSH remote pins no credential key rather than one that selects nothing.
11
- import { credentialPrefix } from "../url.js";
12
- import { ghProfileField } from "../credential/gh.js";
11
+ import { credentialPrefix } from '../url.js';
12
+ import { ghProfileField, ghProfileLookup } from '../credential/gh.js';
13
13
  const HOSTS = ['github.com', 'gist.github.com', 'www.github.com', 'ssh.github.com'];
14
14
  export function githubProvider() {
15
15
  return {
@@ -38,15 +38,21 @@ async function resolveProfile(account) {
38
38
  return null;
39
39
  return { ...(name ? { name } : {}), ...(email ? { email } : {}) };
40
40
  }
41
+ /** The address GitHub gives an account to keep its own private (with or without the id in front). */
42
+ export function isNoreplyAddress(email) {
43
+ return /^(\d+\+)?[^@\s]+@users\.noreply\.github\.com$/i.test(email);
44
+ }
41
45
  /**
42
46
  * The users endpoint answers for an organisation too, with type Organization.
43
47
  * Anything else, including a failed call, is unknown -- not a user.
44
48
  */
45
49
  async function accountKind(login) {
46
- const type = await ghProfileField(login, 'type');
47
- if (type === 'User')
50
+ const found = await ghProfileLookup(login, 'type');
51
+ if (found.missing)
52
+ return 'missing';
53
+ if (found.value === 'User')
48
54
  return 'user';
49
- if (type === 'Organization')
55
+ if (found.value === 'Organization')
50
56
  return 'organization';
51
57
  return null;
52
58
  }
@@ -1,8 +1,8 @@
1
1
  // Provider resolution. Ordered, with `generic` always last so every URL resolves
2
2
  // to something and no caller has to handle "no provider".
3
- import { githubProvider } from "./github.js";
4
- import { azureDevOpsProvider } from "./azdo.js";
5
- import { genericProvider } from "./generic.js";
3
+ import { githubProvider } from './github.js';
4
+ import { azureDevOpsProvider } from './azdo.js';
5
+ import { genericProvider } from './generic.js';
6
6
  export function providers() {
7
7
  return [githubProvider(), azureDevOpsProvider(), genericProvider()];
8
8
  }
@@ -12,3 +12,21 @@ export function providerFor(url) {
12
12
  return all[all.length - 1];
13
13
  return all.find((provider) => provider.matches(url)) ?? all[all.length - 1];
14
14
  }
15
+ /**
16
+ * What to tell someone about a login the host looked up, or null for a user or an
17
+ * unknown. Only GitHub answers accountKind, so the words name github.com.
18
+ */
19
+ export function loginKindProblem(kind, login) {
20
+ if (kind === 'missing')
21
+ return 'github.com has no account named ' + login + ': check the spelling';
22
+ if (kind === 'organization')
23
+ return login + ' is an organisation on github.com, not an account you sign in as';
24
+ return null;
25
+ }
26
+ /** The host's profile for a login, and a sentence when the host says it is no account or an organisation. */
27
+ export async function lookUpProfile(provider, account) {
28
+ if (!provider?.resolveProfile)
29
+ return { profile: {}, problem: null };
30
+ const [profile, kind] = await Promise.all([provider.resolveProfile(account), provider.accountKind?.(account)]);
31
+ return { profile: profile ?? {}, problem: loginKindProblem(kind, account) };
32
+ }
@@ -12,7 +12,7 @@
12
12
  // for a public repository to leak.
13
13
  //
14
14
  // NO NAMES OR ADDRESSES APPEAR IN THIS FILE.
15
- import { credentialPrefix } from "./url.js";
15
+ import { credentialPrefix } from './url.js';
16
16
  export const NAME_KEY = 'user.name';
17
17
  export const EMAIL_KEY = 'user.email';
18
18
  export const USE_CONFIG_ONLY_KEY = 'user.useConfigOnly';
@@ -6,12 +6,12 @@
6
6
  // (`git --exec-path`, GCM, gh) and is identical for every clone on the machine,
7
7
  // so the commands that need it ask for it separately -- and `repown scan`, which
8
8
  // walks many repositories, never asks for it at all.
9
- import { parseGitUrl } from "./url.js";
10
- import { providerFor } from "./hosts/index.js";
11
- import { readIdentity } from "./identity.js";
12
- import { guardState, hookLocation } from "./guard/hook.js";
13
- import { findGcm, listAccounts, isGcm } from "./credential/gcm.js";
14
- import { ghState, ghInstalled, isGh } from "./credential/gh.js";
9
+ import { parseGitUrl } from './url.js';
10
+ import { providerFor } from './hosts/index.js';
11
+ import { readIdentity } from './identity.js';
12
+ import { guardState, hookLocation } from './guard/hook.js';
13
+ import { findGcm, listAccounts, isGcm } from './credential/gcm.js';
14
+ import { ghState, ghInstalled, isGh } from './credential/gh.js';
15
15
  const DEFAULT_PROBE_URL = 'https://github.com/';
16
16
  export async function inspectRepo(git) {
17
17
  const isRepo = await git.isRepo();
@@ -0,0 +1,82 @@
1
+ // Where `git push` with no arguments sends a branch, and whether this clone can
2
+ // tell what is already there (ADR-025).
3
+ //
4
+ // `HEAD --not --remotes` only knows remote-tracking refs. A destination with none
5
+ // (a remote never fetched, an empty one, or a URL, which never gets any) may
6
+ // already hold commits that range calls unpushed, so a rebase from its base would
7
+ // rewrite published history. Nothing offline tells an empty remote from an
8
+ // unfetched one, and FETCH_HEAD is no answer: a FAILED fetch writes it too, and it
9
+ // belongs to whichever remote was fetched last. So the destination is only ever
10
+ // "known" (it has tracking refs, and pushes where it fetches from) or "unknown",
11
+ // and a read that fails is unknown.
12
+ import { parseGitUrl } from './url.js';
13
+ /** Null when the branch pushes nowhere, to `.` (this repository), or where tracking refs reach. */
14
+ export async function unknownDestination(git, branch) {
15
+ const listed = await git.readRemotes();
16
+ if (!listed.ok)
17
+ return { kind: 'unread' };
18
+ const set = await configuredTarget(git, branch);
19
+ // No "only remote" fallback: git push has none, it fails "No configured push destination".
20
+ const name = set?.value ?? (listed.value.includes('origin') ? 'origin' : null);
21
+ if (!name || name === '.')
22
+ return null;
23
+ if (listed.value.includes(name))
24
+ return remoteState(git, name);
25
+ if (!set || !looksLikeUrl(name))
26
+ return { kind: 'unnamed', name };
27
+ return { kind: 'url', key: set.key, remote: await remoteWithUrl(git, listed.value, name) };
28
+ }
29
+ /** Null when there is no destination, it is `.`, or the remotes could not be listed. */
30
+ export async function pushTarget(git, branch) {
31
+ const listed = await git.readRemotes();
32
+ if (!listed.ok)
33
+ return null;
34
+ const set = await configuredTarget(git, branch);
35
+ const name = set?.value ?? (listed.value.includes('origin') ? 'origin' : null);
36
+ if (!name || name === '.')
37
+ return null;
38
+ return { name, isRemote: listed.value.includes(name), key: set?.key ?? null };
39
+ }
40
+ /** git's own order for a push with no arguments. */
41
+ async function configuredTarget(git, branch) {
42
+ const keys = ['branch.' + branch + '.pushRemote', 'remote.pushDefault', 'branch.' + branch + '.remote'];
43
+ for (const key of keys) {
44
+ const value = await git.getConfig(key);
45
+ if (value)
46
+ return { key, value };
47
+ }
48
+ return null;
49
+ }
50
+ async function remoteState(git, name) {
51
+ if (!await isTracked(git, name))
52
+ return { kind: 'remote', name };
53
+ return await pushesElsewhere(git, name) ? { kind: 'pushurl', name } : null;
54
+ }
55
+ async function isTracked(git, remote) {
56
+ const found = await git.hasTrackingRefs(remote);
57
+ return found.ok && found.value;
58
+ }
59
+ /** Tracking refs come from the fetch URL; a different pushurl is somewhere never fetched. */
60
+ 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') ?? '');
65
+ }
66
+ /** A URL or a path, as git would read it where a remote name was expected. */
67
+ function looksLikeUrl(value) {
68
+ return parseGitUrl(value) !== null || /[\\/:]/.test(value);
69
+ }
70
+ /** The configured remote at the same host and path, credentials aside. */
71
+ async function remoteWithUrl(git, remotes, url) {
72
+ const wanted = urlKey(url);
73
+ for (const name of remotes) {
74
+ if (urlKey(await git.getConfig('remote.' + name + '.url') ?? '') === wanted)
75
+ return name;
76
+ }
77
+ return null;
78
+ }
79
+ function urlKey(raw) {
80
+ const url = parseGitUrl(raw);
81
+ return url ? url.host.toLowerCase() + '/' + url.path : raw.trim();
82
+ }
@@ -0,0 +1,109 @@
1
+ // The facts about this clone that decide whether its next commit, pull or push works:
2
+ // read once, offline, for setup and status to turn into blockers (src/core/blockers.ts).
3
+ //
4
+ // Every read that fails is kept as a failure (a Result), never as "nothing found", so
5
+ // a clone that could not be read is never reported ready. The push target is resolved
6
+ // the way a plain `git push` resolves it (push-destination.ts), and a secret in a URL is
7
+ // only ever reported by the config key that holds it.
8
+ import { ok } from './result.js';
9
+ import { pushTarget, unknownDestination } from './push-destination.js';
10
+ import { parseGitUrl } from './url.js';
11
+ import { providerFor } from './hosts/index.js';
12
+ import { hostileSet } from './guard/check.js';
13
+ const OVERRIDES = ['author.email', 'committer.email'];
14
+ export async function readPushFacts(git, unpushed, env = process.env) {
15
+ const head = await git.currentBranch();
16
+ const branch = head?.kind === 'branch' ? head.name : null;
17
+ const target = branch ? await pushTarget(git, branch) : null;
18
+ const [configOverrides, signinKey, repoint, destination, divergence, elsewhere, upstream] = await Promise.all([
19
+ overridesIn(git), signinOf(git, target), repointOf(git, branch), destinationOf(git, target),
20
+ divergenceOf(git, target), elsewhereOf(git, target), upstreamOf(git, branch, target),
21
+ ]);
22
+ return {
23
+ unpushed, env: hostileSet(env), configOverrides, elsewhere, signinKey, repoint, destination, divergence,
24
+ detached: head?.kind === 'detached', upstream,
25
+ };
26
+ }
27
+ async function overridesIn(git) {
28
+ const values = await Promise.all(OVERRIDES.map((key) => git.getConfig(key)));
29
+ return OVERRIDES.filter((_, index) => values[index]);
30
+ }
31
+ /** A password or a token in the userinfo. A bare username (GCM's own advice) is not a secret. */
32
+ function carriesSecret(raw) {
33
+ const user = raw ? parseGitUrl(raw)?.user : null;
34
+ return !!user && (user.includes(':') || /^(gh[pousr]_|github_pat_)/i.test(user));
35
+ }
36
+ async function signinOf(git, target) {
37
+ if (target && !target.isRemote && carriesSecret(target.name))
38
+ return target.key;
39
+ if (target?.isRemote) {
40
+ // A push uses pushurl when there is one, so a token in the fetch url does not sign it in.
41
+ const key = await git.getConfig('remote.' + target.name + '.pushurl') !== null ? 'remote.' + target.name + '.pushurl' : 'remote.' + target.name + '.url';
42
+ if (carriesSecret(await git.getConfig(key)))
43
+ return key;
44
+ }
45
+ const headers = await git.configOrigins('^http\\.(.*\\.)?extraheader$');
46
+ return headers[0]?.key ?? null;
47
+ }
48
+ async function repointOf(git, branch) {
49
+ const unknown = branch ? await unknownDestination(git, branch) : null;
50
+ if (unknown?.kind !== 'url' || !unknown.remote)
51
+ return null;
52
+ const tracked = await git.hasTrackingRefs(unknown.remote);
53
+ return { key: unknown.key, remote: unknown.remote, tracked: tracked.ok && tracked.value };
54
+ }
55
+ async function destinationOf(git, target) {
56
+ if (!target)
57
+ return null;
58
+ const raw = target.isRemote ? await pushUrlOf(git, target.name) : target.name;
59
+ const url = raw ? parseGitUrl(raw) : null;
60
+ const owner = url ? providerFor(url).ownerOf(url) : null;
61
+ if (!owner)
62
+ return null;
63
+ const allowed = (await git.getAllConfig('repown.allowOwner', 'local')).map((value) => value.toLowerCase());
64
+ return { remote: target.isRemote ? target.name : null, owner, allowed };
65
+ }
66
+ async function pushUrlOf(git, remote) {
67
+ return (await git.getConfig('remote.' + remote + '.pushurl')) ?? git.getConfig('remote.' + remote + '.url');
68
+ }
69
+ /** Only the tracked ref ON the destination: a triangular workflow's upstream does not block its push. */
70
+ async function divergenceOf(git, target) {
71
+ if (!target?.isRemote)
72
+ return ok(null);
73
+ const tracked = await git.upstreamRef();
74
+ if (!tracked || !tracked.startsWith(target.name + '/'))
75
+ return ok(null);
76
+ const counts = await git.leftRightCount(tracked + '...HEAD');
77
+ if (!counts.ok)
78
+ return counts;
79
+ return ok({ tracked, behind: counts.value.left, ahead: counts.value.right });
80
+ }
81
+ /** The guard excludes only the destination's refs; `--remotes` excludes every remote's. */
82
+ async function elsewhereOf(git, target) {
83
+ if (!target?.isRemote || !await git.hasCommit('HEAD'))
84
+ return ok([]);
85
+ const [guarded, anywhere] = await Promise.all([
86
+ git.identitiesIn(['HEAD', '--not', '--remotes=' + target.name]),
87
+ git.identitiesIn(['HEAD', '--not', '--remotes']),
88
+ ]);
89
+ if (!guarded.ok)
90
+ return guarded;
91
+ if (!anywhere.ok)
92
+ return anywhere;
93
+ const unpushed = new Set(anywhere.value.map((commit) => commit.sha));
94
+ return ok(guarded.value.filter((commit) => !unpushed.has(commit.sha))
95
+ .map((commit) => ({ authorEmail: commit.authorEmail, committerEmail: commit.committerEmail, parent: null })));
96
+ }
97
+ /** `missing` only where git would refuse a plain push: default push.default, no pushRemote, no autoSetupRemote. */
98
+ async function upstreamOf(git, branch, target) {
99
+ if (!branch || !target?.isRemote)
100
+ return null;
101
+ if (await git.upstreamRef())
102
+ return 'set';
103
+ if (target.key && target.key !== 'branch.' + branch + '.remote')
104
+ return null;
105
+ const [mode, auto] = await Promise.all([git.getConfig('push.default'), git.getBoolConfig('push.autoSetupRemote')]);
106
+ if (auto === true || (mode && !['simple', 'upstream', 'tracking'].includes(mode.toLowerCase())))
107
+ return null;
108
+ return 'missing';
109
+ }