repown 0.3.0 → 0.4.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.
@@ -6,9 +6,9 @@
6
6
  export const PICK_QUESTION = 'Which answer do you want to change?';
7
7
  export const BACK_TO_REVIEW = 'Back to the review';
8
8
  export const RUN_THIS_STEP = 'Run this step?';
9
- /** Yes, unless the command changes the whole machine: that needs a deliberate yes, as in the review. */
9
+ /** Yes, unless the command changes the whole machine or rewrites commits: that needs a deliberate yes, as in the review. */
10
10
  export function stepDefault(command) {
11
- return changesMachine(command) ? 'skip' : 'yes';
11
+ return needsDeliberateYes(command) ? 'skip' : 'yes';
12
12
  }
13
13
  export function stepOptions() {
14
14
  return [
@@ -21,8 +21,13 @@ export function stepOptions() {
21
21
  export function stepConfirmLines(brief) {
22
22
  return [...brief.changes, '', brief.why, '> ' + brief.command];
23
23
  }
24
- function changesMachine(command) {
25
- return command.startsWith('repown fix');
24
+ /** `fix` changes the whole machine; `reauthor` rewrites commits. */
25
+ function needsDeliberateYes(command) {
26
+ return command.startsWith('repown fix') || command.startsWith('repown reauthor');
27
+ }
28
+ /** A settled clone's verdict: its settings are right; the notes say what else is not (ADR-026). */
29
+ function settledVerdict(review) {
30
+ return review.blocked ? 'Its settings need no change, but the next push will fail:' : 'Nothing needs to change.';
26
31
  }
27
32
  /**
28
33
  * The body of the review, line by line, wrapped to `width`. `command` styles each
@@ -34,7 +39,7 @@ export function reviewLines(review, width = Infinity, command = (text) => text)
34
39
  // A command's continuation sits deeper, so it can't read as the next command.
35
40
  const code = (text) => wrap(' ' + text, width - 2).map((line, index) => command(index ? ' ' + line : line));
36
41
  if (review.settled)
37
- return [...review.headline.flatMap(words), '', 'Nothing needs to change.', ...notesOf(review).flatMap(words)];
42
+ return [...review.headline.flatMap(words), '', settledVerdict(review), ...notesOf(review).flatMap(words)];
38
43
  const steps = review.steps.flatMap((step, index) => [
39
44
  ...words((index + 1) + '. ' + step.what),
40
45
  ...code(step.command),
@@ -88,7 +93,7 @@ export function reviewOptions(review) {
88
93
  { value: 'decline', label: 'Decline', hint: 'change nothing and exit' },
89
94
  ];
90
95
  }
91
- /** Done, then a way to pick another account or sign in to gh. Change an answer stays once questions were asked. */
96
+ /** Done, then a way to pick another account, sign in to gh or re-author. Change an answer stays once questions were asked. */
92
97
  function settledOptions(review) {
93
98
  const options = [
94
99
  { value: 'done', label: 'Done', hint: 'change nothing' },
@@ -96,15 +101,17 @@ function settledOptions(review) {
96
101
  ];
97
102
  if (review.ghSignIn)
98
103
  options.push({ value: 'gh', label: review.ghSignIn });
104
+ if (review.reauthorOffer)
105
+ options.push({ value: 'reauthor', label: review.reauthorOffer, hint: 'only if you made them; a backup is kept' });
99
106
  if (review.edits !== false)
100
107
  options.push({ value: 'edit', label: 'Change an answer' });
101
108
  return options;
102
109
  }
103
110
  /**
104
- * The choice Enter takes: the first, unless a step changes the whole machine
105
- * (`fix`), which, like its own question, needs a deliberate yes.
111
+ * The choice Enter takes: the first, unless a step changes the whole machine or rewrites commits
112
+ * (`fix`, `reauthor`), which, like its own question, needs a deliberate yes.
106
113
  */
107
114
  export function reviewDefault(review) {
108
- const machineWide = review.steps.some((step) => changesMachine(step.command));
109
- return !review.settled && machineWide ? 'decline' : reviewOptions(review)[0].value;
115
+ const deliberate = review.steps.some((step) => needsDeliberateYes(step.command));
116
+ return !review.settled && deliberate ? 'decline' : reviewOptions(review)[0].value;
110
117
  }
@@ -6,8 +6,8 @@ import { guardState } from "../core/guard/hook.js";
6
6
  const ALLOW_OWNER = 'repown.allowOwner';
7
7
  const AUTO_UPSTREAM = 'push.autoSetupRemote';
8
8
  const LEADING = [NAME_KEY, EMAIL_KEY, USE_CONFIG_ONLY_KEY, ACCOUNT_KEY];
9
- export async function readCloneSnapshot(git, credentialKeys) {
10
- const keys = [...LEADING, ...credentialKeys];
9
+ export async function readCloneSnapshot(git, watched) {
10
+ const keys = [...LEADING, ...watched];
11
11
  const found = await Promise.all(keys.map((key) => git.getConfig(key, 'local')));
12
12
  const [allowOwner, autoUpstream, guard] = await Promise.all([
13
13
  git.getAllConfig(ALLOW_OWNER, 'local'),
@@ -42,10 +42,14 @@ function valueChange(key, before, after) {
42
42
  if (before === after)
43
43
  return null;
44
44
  if (before === null)
45
- return ' ' + key + ': (added) ' + after;
45
+ return ' ' + key + ': (added) ' + shown(after);
46
46
  if (after === null)
47
- return ' ' + key + ': ' + before + ' -> (removed)';
48
- return ' ' + key + ': ' + before + ' -> ' + after;
47
+ return ' ' + key + ': ' + shown(before) + ' -> (removed)';
48
+ return ' ' + key + ': ' + shown(before) + ' -> ' + shown(after);
49
+ }
50
+ /** A URL (`scheme://` or scp-style `user@host:`) can hold a token: the report names it, never shows it. */
51
+ function shown(value) {
52
+ return /^[a-z][\w+.-]*:\/\//i.test(value) || /^[^\s@/]+@[^\s:/]+:/.test(value) ? '(a URL)' : value;
49
53
  }
50
54
  function guardChange(before, after) {
51
55
  if (before === after)
@@ -12,6 +12,7 @@ import { providers } from "../core/hosts/index.js";
12
12
  import { ok, err } from "../core/result.js";
13
13
  import { previewLines } from "../commands/fix.js";
14
14
  import { readUnpushed } from "../core/unpushed.js";
15
+ import { readPushFacts } from "../core/push-state.js";
15
16
  import { SOURCE_GCM, SOURCE_GH, SOURCE_OWNS } from "./setup-flow.js";
16
17
  /**
17
18
  * Candidate logins not already recorded, one entry each. The first spelling
@@ -94,7 +95,7 @@ async function readFacts(git, repo, recorded, options) {
94
95
  }
95
96
  async function loadClone(git, repo, options) {
96
97
  const authPromise = options.auth ? Promise.resolve(options.auth) : inspectAuth(git, repo.originUrl ?? undefined);
97
- const [auth, pinned, allowed, planned, addresses, helpers, ownerIsUser, upstream, unpushed] = await Promise.all([
98
+ const [auth, pinned, allowed, planned, addresses, helpers, ownerIsUser, upstream, [unpushed, push]] = await Promise.all([
98
99
  authPromise,
99
100
  git.getConfig('repown.account', 'local'),
100
101
  git.getAllConfig('repown.allowOwner', 'local'),
@@ -103,10 +104,16 @@ async function loadClone(git, repo, options) {
103
104
  git.getAllConfigRaw('credential.helper'),
104
105
  authPromise.then((auth) => askOwnerIsUser(repo, auth, options)),
105
106
  readUpstream(git),
106
- readUnpushed(git),
107
+ readUnpushedAndPush(git),
107
108
  ]);
108
109
  const { machineName: name, machineEmail: email } = repo.identity;
109
- return { auth, pinned, allowed, planned, addresses, unpushed, helpers, name, email, ownerIsUser, upstream };
110
+ return { auth, pinned, allowed, planned, addresses, unpushed, push, helpers, name, email, ownerIsUser, upstream };
111
+ }
112
+ /** The push facts reuse the unpushed read; `unpushed` stays its own field, as tests set it alone. */
113
+ async function readUnpushedAndPush(git) {
114
+ const unpushed = await readUnpushed(git);
115
+ const { unpushed: _, ...push } = await readPushFacts(git, unpushed);
116
+ return [unpushed, push];
110
117
  }
111
118
  /** Version, effective push.autoSetupRemote, the branch and its tracked ref. One read; nothing is written. */
112
119
  async function readUpstream(git) {
@@ -127,7 +134,7 @@ function trackedOf(head, tracked) {
127
134
  async function finishFacts(git, repo, recorded, loaded) {
128
135
  const ghIsHelper = anyGhHelper(loaded.auth, loaded.planned, loaded.helpers);
129
136
  return {
130
- pinned: loaded.pinned, allowed: loaded.allowed, addresses: loaded.addresses, unpushed: loaded.unpushed,
137
+ pinned: loaded.pinned, allowed: loaded.allowed, addresses: loaded.addresses, unpushed: loaded.unpushed, push: loaded.push,
131
138
  name: loaded.name, email: loaded.email, ownerIsUser: loaded.ownerIsUser, ghIsHelper, stored: loaded.auth.stored,
132
139
  gh: loaded.auth.ghPresent ? loaded.auth.gh : null,
133
140
  pinIntact: await pinIntact(git, loaded.pinned, recorded[loaded.pinned ?? ''], repo),
@@ -151,7 +158,7 @@ function assemble(cwd, recorded, repo, facts) {
151
158
  guard: repo.guard,
152
159
  redirected: repo.hook?.redirected ?? false, hookPath: repo.hook?.path ?? null,
153
160
  fixLines: facts.fixLines,
154
- addresses: facts.addresses, unpushed: facts.unpushed,
161
+ addresses: facts.addresses, unpushed: facts.unpushed, push: facts.push,
155
162
  machineIdentity: { name: facts.name, email: facts.email },
156
163
  upstream: facts.upstream, stored: facts.stored,
157
164
  suggest: suggester(),
@@ -9,7 +9,9 @@
9
9
  import { ghAdvice, upstreamText } from "../commands/status.js";
10
10
  import { providers } from "../core/hosts/index.js";
11
11
  import { shellWord } from "../core/guard/check.js";
12
- import { unpushedLines } from "../core/unpushed.js";
12
+ import { printable } from "../ui/format.js";
13
+ import { foreignAddresses, foreignCount } from "../core/unpushed.js";
14
+ import { blockers } from "../core/blockers.js";
13
15
  import { pinWrites } from "../core/identity.js";
14
16
  import { stepDefault } from "./review-text.js";
15
17
  /** The "a new account" choice. Empty, so it can never be a real account's name. */
@@ -53,9 +55,15 @@ function openingReview(ctx) {
53
55
  function resumeAt(choice, ctx) {
54
56
  if (choice === 'gh')
55
57
  return { answers: ghAnswers(ctx), start: steps(ctx).length };
58
+ if (choice === 'reauthor')
59
+ return { answers: reauthorAnswers(ctx), start: steps(ctx).length };
56
60
  const start = steps(ctx).findIndex((step) => step.id === 'account');
57
61
  return { answers: { mode: 'recommended' }, start: start < 0 ? 0 : start };
58
62
  }
63
+ /** The settled screen's Re-author them: the pinned account's answers, with that one step. */
64
+ function reauthorAnswers(ctx) {
65
+ return recommendedAnswers({ mode: 'recommended', account: ctx.pinned ?? '', reauthor: true }, ctx);
66
+ }
59
67
  function ghAnswers(ctx) {
60
68
  return recommendedAnswers({ mode: 'recommended', account: ctx.pinned ?? '', gh: true }, ctx);
61
69
  }
@@ -128,6 +136,8 @@ function accountSteps(ctx) {
128
136
  }
129
137
  function choiceSteps(ctx) {
130
138
  return [
139
+ repointStep(ctx),
140
+ fetchStep(ctx),
131
141
  ghStep(ctx),
132
142
  { id: 'allowOwner', kind: 'confirm', flag: '--allow-owner', initial: () => true,
133
143
  message: 'This repository belongs to "' + printable(ctx.owner ?? '') + '". Let this clone push to it?',
@@ -144,8 +154,50 @@ function choiceSteps(ctx) {
144
154
  hint: 'undo any time: gh auth setup-git', initial: () => false, when: () => ctx.fixLines !== null,
145
155
  detail: () => 'gh answers git\'s sign-in requests with its active account only, so clones of your other accounts ' +
146
156
  'get password prompts. Yes hands that job back to Git Credential Manager, for every repository on this machine' },
157
+ reauthorStep(ctx),
147
158
  ];
148
159
  }
160
+ /** Never answered by Recommended: only the user knows whether they made those commits. */
161
+ function reauthorStep(ctx) {
162
+ return {
163
+ id: 'reauthor', kind: 'confirm', flag: '--reauthor', initial: () => false,
164
+ message: (answers) => 'Re-author your unpushed commits by ' + printable(othersOf(answers, ctx).join(', ')) +
165
+ ' as ' + printable(accountOf(answers)) + '?',
166
+ hint: 'only if you made them: they get this account\'s name and email. repown fetches first, rewrites only ' +
167
+ 'what no remote has, keeps a backup, and never pushes',
168
+ when: (answers) => reauthorOffered(answers, ctx),
169
+ };
170
+ }
171
+ /**
172
+ * `--repoint`, `--fetch` and `--reauthor` apply only where their step would be asked; elsewhere
173
+ * each is turned off with a note saying why. Read before any question, so a repoint not yet
174
+ * answered counts as the Yes Recommended gives it (a later No drops the fetch from the plan).
175
+ */
176
+ export function keptFlags(given, ctx) {
177
+ const answers = { ...given };
178
+ const notes = [];
179
+ const drop = (key, note) => { answers[key] = false; notes.push('--' + key + ': ' + note); };
180
+ if (answers['repoint'] === true && !ctx.push.repoint)
181
+ drop('repoint', 'this branch does not push to a URL that a remote here names, so there is nothing to repoint');
182
+ if (answers['fetch'] === true && fetchTarget({ ...answers, repoint: answers['repoint'] ?? true }, ctx) === null)
183
+ drop('fetch', fetchDropped(answers, ctx));
184
+ if (answers['reauthor'] === true && !reauthorOffered(answers, ctx))
185
+ drop('reauthor', 'no unpushed commit here is by another address, so there is nothing to re-author');
186
+ return { answers, notes };
187
+ }
188
+ function fetchDropped(answers, ctx) {
189
+ if (answers['repoint'] === false && fetchTarget({ ...answers, repoint: true }, ctx) !== null) {
190
+ return 'this branch pushes to a URL, so fetching ' + printable(ctx.push.repoint.remote) + ' tells nothing about it: add --repoint';
191
+ }
192
+ return 'no commit by another address waits behind a remote this clone has never fetched, so there is nothing to fetch';
193
+ }
194
+ /** Some unpushed commits carry an address other than the chosen account's. */
195
+ export function reauthorOffered(answers, ctx) {
196
+ return othersOf(answers, ctx).length > 0;
197
+ }
198
+ function othersOf(answers, ctx) {
199
+ return foreignAddresses(ctx.unpushed, emailOf(answers, ctx) ?? '');
200
+ }
149
201
  /** Labels for a newcomer; the providers' own labels stay as `repown` prints them elsewhere. */
150
202
  const HOSTS = {
151
203
  github: ['GitHub', 'name, email and the sign-in for pushes'],
@@ -199,6 +251,40 @@ function upstreamStep(ctx) {
199
251
  when: () => offersUpstream(ctx), auto: isRecommended,
200
252
  };
201
253
  }
254
+ function repointStep(ctx) {
255
+ const target = ctx.push.repoint;
256
+ return {
257
+ id: 'repoint', kind: 'confirm', flag: '--repoint', initial: () => true, auto: isRecommended,
258
+ message: 'Push through ' + printable(target?.remote ?? '') + ' instead of the URL set for this branch?',
259
+ hint: 'that URL names the same repository as ' + printable(target?.remote ?? '') + ', but it can carry its own sign-in, so ' +
260
+ 'pushes would not sign in as this account, and it is never fetched. Changes ' + printable(target?.key ?? '') + ', this clone only',
261
+ when: () => target !== null,
262
+ };
263
+ }
264
+ function fetchStep(ctx) {
265
+ return {
266
+ id: 'fetch', kind: 'confirm', flag: '--fetch', initial: () => true, auto: isRecommended,
267
+ message: (answers) => 'Fetch ' + printable(fetchTarget(answers, ctx) ?? '') + ' first?',
268
+ hint: (answers) => 'so repown can tell which of your unpushed commits ' + printable(fetchTarget(answers, ctx) ?? '') +
269
+ ' already has; downloads only, moves none of your branches, and never asks for a password',
270
+ when: (answers) => fetchTarget(answers, ctx) !== null,
271
+ };
272
+ }
273
+ /**
274
+ * The remote to fetch before counting: commits by another address, behind a remote no
275
+ * tracking ref reaches -- the destination itself, or the remote a repoint makes it.
276
+ */
277
+ export function fetchTarget(answers, ctx) {
278
+ if (foreignCount(ctx.unpushed, emailOf(answers, ctx) ?? '') === 0)
279
+ return null;
280
+ const unknown = ctx.unpushed.unknown;
281
+ if (unknown?.kind === 'remote')
282
+ return unknown.name;
283
+ const repoint = ctx.push.repoint;
284
+ if (unknown?.kind !== 'url' || !repoint || repoint.tracked || answers['repoint'] !== true)
285
+ return null;
286
+ return repoint.remote;
287
+ }
202
288
  const SWITCH_MESSAGE = 'Also make this account gh\'s active account?';
203
289
  const SWITCH_HINT = 'gh is GitHub\'s command-line tool: this changes the account gh commands use, in every terminal; git is not affected';
204
290
  function ghStep(ctx) {
@@ -381,6 +467,8 @@ export function planCommands(answers, ctx) {
381
467
  const account = accountOf(answers);
382
468
  const cwd = ctx.cwd ? ['--cwd=' + ctx.cwd] : [];
383
469
  const planned = [
470
+ repointArgv(answers, ctx),
471
+ fetchArgv(answers, ctx),
384
472
  isNew(answers) ? ['accounts', 'add', '--name=' + String(answers['name']), '--email=' + String(answers['email']),
385
473
  '--host=' + hostOf(answers, ctx), '--', account] : null,
386
474
  answers['allowOwner'] === true && ctx.owner ? allowOwnerLine(ctx) : null,
@@ -388,6 +476,7 @@ export function planCommands(answers, ctx) {
388
476
  useArgv(answers, ctx),
389
477
  answers['guard'] === true ? ['guard', 'on', ...cwd] : null,
390
478
  upstreamArgv(answers, ctx),
479
+ answers['reauthor'] === true && reauthorOffered(answers, ctx) ? ['reauthor', '--yes', ...cwd] : null,
391
480
  ];
392
481
  return planned.filter((argv) => argv !== null).map((argv) => ({ argv, what: whatOf(argv, answers, ctx) }));
393
482
  }
@@ -407,8 +496,33 @@ function upstreamArgv(answers, ctx) {
407
496
  return null;
408
497
  return autoUpstreamLine(ctx);
409
498
  }
499
+ function gitIn(ctx) {
500
+ return ['git', ...(ctx.cwd ? ['-C', ctx.cwd] : [])];
501
+ }
410
502
  function autoUpstreamLine(ctx) {
411
- return ['git', ...(ctx.cwd ? ['-C', ctx.cwd] : []), 'config', '--local', 'push.autoSetupRemote', 'true'];
503
+ return [...gitIn(ctx), 'config', '--local', 'push.autoSetupRemote', 'true'];
504
+ }
505
+ function repointArgv(answers, ctx) {
506
+ const target = ctx.push.repoint;
507
+ if (answers['repoint'] !== true || !target)
508
+ return null;
509
+ return [...gitIn(ctx), 'config', '--local', target.key, target.remote];
510
+ }
511
+ function fetchArgv(answers, ctx) {
512
+ const remote = answers['fetch'] === true ? fetchTarget(answers, ctx) : null;
513
+ return remote ? [...gitIn(ctx), 'fetch', remote] : null;
514
+ }
515
+ export function gitStepOf(argv) {
516
+ const sub = argv[1] === '-C' ? argv.slice(3) : argv.slice(1);
517
+ if (sub[0] === 'fetch' && sub.length === 2)
518
+ return 'fetch';
519
+ if (sub[0] !== 'config' || sub[1] !== '--local')
520
+ return null;
521
+ if (sub[2] === '--add' && sub[3] === 'repown.allowOwner' && sub.length === 5)
522
+ return 'allowOwner';
523
+ if (sub[2] === 'push.autoSetupRemote' && sub.length === 4)
524
+ return 'upstream';
525
+ return sub.length === 4 ? 'repoint' : null;
412
526
  }
413
527
  /** What a planned command does, in words for someone who has never used repown. */
414
528
  function whatOf(argv, answers, ctx) {
@@ -421,12 +535,19 @@ function whatOf(argv, answers, ctx) {
421
535
  return 'Stop gh answering git\'s sign-in requests (whole machine)';
422
536
  if (argv[0] === 'guard')
423
537
  return 'Turn on the push guard: each push is checked first';
538
+ if (argv[0] === 'reauthor')
539
+ return 'Re-author your unpushed commits by other addresses as ' + account + ' (a backup is kept; nothing is pushed)';
424
540
  if (answers['gh'] === true)
425
541
  return ghWhat(account, ctx);
426
542
  return 'Pin this clone to ' + account + (ctx.credentialPinned ? ': its commit name, email and push sign-in' : ': its commit name and email');
427
543
  }
428
544
  function gitWhat(argv, ctx) {
429
- if (argv.includes('push.autoSetupRemote'))
545
+ const step = gitStepOf(argv);
546
+ if (step === 'repoint')
547
+ return 'Push through ' + argv.at(-1) + ' instead of the URL in ' + argv.at(-2) + ' (this clone only)';
548
+ if (step === 'fetch')
549
+ return 'Fetch ' + argv.at(-1) + ', so repown can tell which commits it already has';
550
+ if (step === 'upstream')
430
551
  return 'Push branches without -u: the first push sets the upstream (this clone only)';
431
552
  return 'Let this clone push to ' + ctx.owner + '\'s repositories';
432
553
  }
@@ -437,7 +558,7 @@ function ghWhat(account, ctx) {
437
558
  return pin + 'sign ' + account + ' in to gh (opens your browser)';
438
559
  }
439
560
  function allowOwnerLine(ctx) {
440
- return ['git', ...(ctx.cwd ? ['-C', ctx.cwd] : []), 'config', '--local', '--add', 'repown.allowOwner', ctx.owner];
561
+ return [...gitIn(ctx), 'config', '--local', '--add', 'repown.allowOwner', ctx.owner];
441
562
  }
442
563
  /**
443
564
  * The command as you would type it: the account where it reads naturally, options
@@ -455,13 +576,8 @@ export function formatCommand(argv) {
455
576
  const words = dashed ? [...path, ...options, '--', ...positional] : [...path, ...positional, ...options];
456
577
  return printable(['repown', ...words.map(shellWord)].join(' '));
457
578
  }
458
- /**
459
- * Control characters, and the invisible or direction-changing ones, as visible escapes:
460
- * a value read from a remote URL must neither redraw the screen nor read as another name.
461
- */
462
- export function printable(text) {
463
- return text.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, (char) => '\\u' + char.charCodeAt(0).toString(16).padStart(4, '0'));
464
- }
579
+ /** Setup's own importers read it from here; the one definition is in the output helpers. */
580
+ export { printable };
465
581
  /** `--name=value` as `--name value`, unless the value starts with a dash and would read as an option. */
466
582
  function splitOption(token) {
467
583
  const at = token.indexOf('=');
@@ -498,9 +614,12 @@ function pendingReview(answers, ctx, steps, plan) {
498
614
  }
499
615
  function settledReview(answers, ctx, steps, plan) {
500
616
  const offer = ghOffer(accountOf(answers), ctx);
617
+ const reauthor = reauthorOffered(answers, ctx) ? { reauthorOffer: 'Re-author them as ' + printable(accountOf(answers)) } : {};
501
618
  const shown = {
619
+ ...reauthor,
502
620
  title: 'This clone is already set up', headline: settledLines(answers, ctx).map(printable), steps,
503
621
  notes: [...noted(settledNotes(answers, ctx), answers, ctx, plan), ...ghNote(answers, ctx, true)], settled: true,
622
+ blocked: blockersOf(answers, ctx).some((blocker) => blocker.blocks),
504
623
  };
505
624
  return offer ? { ...shown, ghSignIn: offer } : shown;
506
625
  }
@@ -515,11 +634,22 @@ function upstreamOffer(ctx) {
515
634
  return null;
516
635
  return 'optional: push branches without -u: repown setup --auto-upstream';
517
636
  }
637
+ /** What blocks the next push first (ADR-026), then the step's own notes. */
518
638
  function noted(lines, answers, ctx, plan) {
519
639
  const gap = credentialGap(plan, answers, ctx);
520
- const body = [...lines, ...extraNotes(answers, ctx), ...(gap ? [gap] : [])];
640
+ const found = blockersOf(answers, ctx);
641
+ const upstream = found.some((blocker) => blocker.summary.endsWith('has no upstream')) ? null : upstreamNote(ctx);
642
+ const body = [...found.flatMap((blocker) => blocker.lines), ...lines, ...(upstream ? [upstream] : []), ...(gap ? [gap] : [])];
521
643
  return body.map(printable);
522
644
  }
645
+ /** The address depends on the account, so the commits were read once and are compared here. */
646
+ export function blockersOf(answers, ctx) {
647
+ const email = emailOf(answers, ctx) ?? '';
648
+ const unpushed = email || !ctx.unpushed.commits.ok ? ctx.unpushed : { ...ctx.unpushed, branch: null };
649
+ const autoUpstream = answers['upstream'] === true || ctx.upstream.enabled === true;
650
+ const guarded = answers['guard'] === true || ctx.guard !== 'off' || ctx.redirected;
651
+ return blockers({ ...ctx.push, unpushed }, { email, account: accountOf(answers), autoUpstream, guarded });
652
+ }
523
653
  /** use's own line, said here only when this run will not run use. Mirrors use.ts credentialConcern. */
524
654
  function credentialGap(plan, answers, ctx) {
525
655
  if (plan.some((command) => command.argv[0] === 'use') || !ctx.credentialPinned || !ctx.stored?.ok)
@@ -529,17 +659,6 @@ function credentialGap(plan, answers, ctx) {
529
659
  return null;
530
660
  return 'No stored credential for ' + account + ' yet: the first push signs in once (your browser opens).';
531
661
  }
532
- function extraNotes(answers, ctx) {
533
- const upstream = upstreamNote(ctx);
534
- return [...(upstream ? [upstream] : []), ...unpushedNote(answers, ctx)];
535
- }
536
- /** The address depends on the account, so the commits were read once and are compared here. */
537
- function unpushedNote(answers, ctx) {
538
- const email = emailOf(answers, ctx) ?? '';
539
- if (!email && ctx.unpushed.commits.ok)
540
- return [];
541
- return unpushedLines(ctx.unpushed, email);
542
- }
543
662
  /** Old git, or a version that could not be read: say the push the question would have replaced. */
544
663
  function upstreamNote(ctx) {
545
664
  if (ctx.upstream.supported)
@@ -684,6 +803,8 @@ export function changesOf(argv, answers, ctx) {
684
803
  return fixChanges(ctx);
685
804
  if (argv[0] === 'guard')
686
805
  return [guardChange(ctx)];
806
+ if (argv[0] === 'reauthor')
807
+ return [reauthorChange(answers, ctx)];
687
808
  return useChanges(argv, answers, ctx);
688
809
  }
689
810
  /** The confirmation shown before a step in step-by-step mode. */
@@ -703,10 +824,20 @@ function registryChange(answers) {
703
824
  return 'this machine\'s account registry: ' + account + ' = ' + name + ' ' + email;
704
825
  }
705
826
  function gitChange(argv) {
706
- if (argv.includes('push.autoSetupRemote'))
827
+ const step = gitStepOf(argv);
828
+ if (step === 'repoint')
829
+ return argv.at(-2) + ' = ' + argv.at(-1);
830
+ if (step === 'fetch')
831
+ return 'refs/remotes/' + argv.at(-1) + '/*: updated from ' + argv.at(-1) + ' (none of your branches move)';
832
+ if (step === 'upstream')
707
833
  return 'push.autoSetupRemote = true';
708
834
  return 'repown.allowOwner += ' + (argv.at(-1) ?? '');
709
835
  }
836
+ function reauthorChange(answers, ctx) {
837
+ const branch = ctx.unpushed.branch ?? 'this branch';
838
+ return branch + ': unpushed commits by ' + othersOf(answers, ctx).join(', ') + ' get ' + (emailOf(answers, ctx) ?? '') +
839
+ '; the original stays at refs/repown/backup/' + branch + '/<time>';
840
+ }
710
841
  function fixChanges(ctx) {
711
842
  return (ctx.fixLines ?? []).filter((line) => line.trim() !== '');
712
843
  }
@@ -14,13 +14,18 @@ import * as out from "../ui/format.js";
14
14
  import { useColour } from "../ui/format.js";
15
15
  import useCommand, { NEXT_GUARD } from "../commands/use.js";
16
16
  import fixCommand from "../commands/fix.js";
17
+ import reauthorCommand from "../commands/reauthor.js";
17
18
  import guardGroup from "../commands/guard.js";
18
19
  import accountsGroup from "../commands/accounts.js";
19
20
  import { wizard, refusedGiven } from "./engine.js";
20
- import { setupFlow, planCommands, formatCommand, briefOf, missingFlags, printable, dropFixPrefix, NEW_ACCOUNT, accountOf, pinUnchanged, ghNoted } from "./setup-flow.js";
21
+ import { setupFlow, planCommands, formatCommand, gitStepOf, keptFlags, briefOf, missingFlags, printable, dropFixPrefix, NEW_ACCOUNT, accountOf, pinUnchanged, ghNoted } from "./setup-flow.js";
21
22
  import { cloneChangeLines, machineChangeLines, readCloneSnapshot } from "./setup-changes.js";
22
23
  import { readContext, readRegistry } from "./setup-context.js";
23
24
  import { plainPrompter } from "./plain.js";
25
+ import { blockers } from "../core/blockers.js";
26
+ import { readPushFacts } from "../core/push-state.js";
27
+ import { guardState, hookLocation } from "../core/guard/hook.js";
28
+ import { readUnpushed } from "../core/unpushed.js";
24
29
  const CANCELLED = 130;
25
30
  export async function runSetup(args, deps) {
26
31
  const registry = await readRegistry();
@@ -117,8 +122,8 @@ function modeOf(args, answers) {
117
122
  answers['mode'] = 'recommended';
118
123
  return ok(answers);
119
124
  }
120
- const CONFIRM_FLAGS = ['gh', 'guard', 'fix'];
121
- const CONFIRM_DEFAULTS = ['gh', 'allowOwner', 'guard', 'fix', 'upstream'];
125
+ const CONFIRM_FLAGS = ['gh', 'guard', 'fix', 'repoint', 'fetch', 'reauthor'];
126
+ const CONFIRM_DEFAULTS = ['gh', 'allowOwner', 'guard', 'fix', 'upstream', 'repoint', 'fetch', 'reauthor'];
122
127
  /** A passed flag is Yes. With --no-input, a confirm that was not passed is No, not Recommended's Yes. */
123
128
  function applyConfirms(args, answers) {
124
129
  for (const key of CONFIRM_FLAGS)
@@ -143,7 +148,7 @@ function usage(message) {
143
148
  function needsTerminal(given, recorded) {
144
149
  out.fail('setup', 'needs a terminal to ask its questions.');
145
150
  out.detail('without one, give the answers as flags and add --no-input:');
146
- out.detail(' repown setup <account> [--name "..." --email "..."] [--gh] [--allow-owner <owner>] [--guard] [--auto-upstream] [--fix] --no-input');
151
+ out.detail(' repown setup <account> [--name "..." --email "..."] [--gh] [--allow-owner <owner>] [--guard] [--auto-upstream] [--fix] [--repoint] [--fetch] [--reauthor] --no-input');
147
152
  const missing = missingFlags(given, recorded);
148
153
  if (missing.length > 0)
149
154
  out.detail('still needed: ' + missing.join(', '));
@@ -169,7 +174,10 @@ function checkAgainst(given, ctx, allowOwner) {
169
174
  out.detail('--fix: gh is not the credential helper for this clone, so there is nothing to undo');
170
175
  answers['fix'] = false;
171
176
  }
172
- return ok(answers);
177
+ const kept = keptFlags(answers, ctx);
178
+ for (const note of kept.notes)
179
+ out.detail(note);
180
+ return ok(kept.answers);
173
181
  }
174
182
  // ------------------------------------------------------------------- the runs
175
183
  async function runUnattended(answers, ctx, git, readAuth) {
@@ -239,7 +247,8 @@ export async function choosePrompter() {
239
247
  }
240
248
  }
241
249
  function runState(git, readAuth, ctx) {
242
- return { git, readAuth, credentialKeys: ctx.credentialKeys };
250
+ const repointed = ctx.push.repoint ? [ctx.push.repoint.key] : [];
251
+ return { git, readAuth, watchedKeys: [...ctx.credentialKeys, ...repointed] };
243
252
  }
244
253
  function reported(answers, ctx, repeatGh) {
245
254
  return { account: accountOf(answers), pinnedAlready: pinUnchanged(answers, ctx), repeatGh };
@@ -252,7 +261,7 @@ function reported(answers, ctx, repeatGh) {
252
261
  * The clone is read before the first step and again after, including a stop or a failure.
253
262
  */
254
263
  async function execute(plan, state) {
255
- const before = await readCloneSnapshot(state.git, state.credentialKeys);
264
+ const before = await readCloneSnapshot(state.git, state.watchedKeys);
256
265
  const ran = await walk(plan, state.git, state.confirm);
257
266
  await reportRun(before, ran, state);
258
267
  return ran.code ?? 0;
@@ -321,24 +330,43 @@ function halt(remaining, code, why) {
321
330
  /** On stderr, like the step lines: stdout carries only what the commands themselves print. */
322
331
  async function reportRun(before, ran, state) {
323
332
  if (ran.code === null)
324
- announce(ran.done, ran.skipped, state);
333
+ await announce(ran.done, ran.skipped, state);
325
334
  await printClone(before, state);
326
335
  const auth = wantsAuth(ran, state) ? await state.readAuth(state.git) : null;
327
336
  printMachine(ran.done, auth);
328
337
  if (ran.code === null)
329
338
  closeRun(auth, state);
330
339
  }
331
- function announce(done, skipped, report) {
340
+ async function announce(done, skipped, state) {
332
341
  process.stderr.write('\n');
333
342
  const pinned = done.find((planned) => planned.argv[0] === 'use')?.argv.at(-1);
334
- const account = pinned ?? (report.pinnedAlready ? report.account : null);
343
+ const account = pinned ?? (state.pinnedAlready ? state.account : null);
335
344
  if (account)
336
- out.detail('done: this clone is set up for ' + printable(account));
345
+ closing(account, await blockersNow(state.git, account));
337
346
  for (const planned of skipped)
338
347
  out.detail('skipped: ' + printable(planned.what));
339
348
  }
349
+ /**
350
+ * `done` only with nothing left in the way of the next push; otherwise the first, then each one
351
+ * (ADR-026). What blocks nothing (the guard is off) still gets its lines, under `done`.
352
+ */
353
+ function closing(account, found) {
354
+ const blocking = found.filter((blocker) => blocker.blocks);
355
+ const more = blocking.length > 1 ? ' (and ' + (blocking.length - 1) + ' more below)' : '';
356
+ const [first] = blocking;
357
+ out.detail(first ? 'set up for ' + printable(account) + '; the next push will fail: ' + printable(first.summary) + more
358
+ : 'done: this clone is set up for ' + printable(account));
359
+ for (const line of found.flatMap((blocker) => blocker.lines))
360
+ out.detail(' ' + printable(line));
361
+ }
362
+ /** Re-read after the run: a step may have fixed what the review showed, or not. */
363
+ async function blockersNow(git, account) {
364
+ const email = await git.getConfig('user.email', 'local') ?? '';
365
+ const [facts, guard, hook] = await Promise.all([readPushFacts(git, await readUnpushed(git)), guardState(git), hookLocation(git)]);
366
+ return blockers(facts, { email, account, autoUpstream: false, guarded: guard !== 'off' || hook?.redirected === true });
367
+ }
340
368
  async function printClone(before, state) {
341
- const lines = cloneChangeLines(before, await readCloneSnapshot(state.git, state.credentialKeys));
369
+ const lines = cloneChangeLines(before, await readCloneSnapshot(state.git, state.watchedKeys));
342
370
  if (lines.length === 0) {
343
371
  out.detail('nothing changed in this clone');
344
372
  return;
@@ -420,7 +448,12 @@ async function withoutLine(hidden, run) {
420
448
  async function runOne(argv, git) {
421
449
  if (argv[0] === 'git')
422
450
  return gitLine(argv, git);
423
- const [command, rest] = commandFor(argv);
451
+ const found = commandFor(argv);
452
+ if (!found) {
453
+ out.fail('setup', 'could not run ' + formatCommand(argv) + ': not a step setup plans');
454
+ return 2;
455
+ }
456
+ const [command, rest] = found;
424
457
  const parsed = parseArgs(rest, specFor(command));
425
458
  if (!parsed.ok) {
426
459
  out.fail('setup', 'could not run ' + formatCommand(argv) + ': ' + parsed.error);
@@ -428,21 +461,53 @@ async function runOne(argv, git) {
428
461
  }
429
462
  return command.run(parsed.value);
430
463
  }
431
- /** The Command a planned argv names, and the arguments after its name. */
464
+ /** The Command a planned argv names, and the arguments after its name; null for anything else. */
432
465
  function commandFor(argv) {
433
466
  if (argv[0] === 'use')
434
467
  return [useCommand, argv.slice(1)];
435
468
  if (argv[0] === 'fix')
436
469
  return [fixCommand, argv.slice(1)];
437
- if (argv[0] === 'guard')
470
+ if (argv[0] === 'reauthor')
471
+ return [reauthorCommand, argv.slice(1)];
472
+ if (argv[0] === 'guard' && argv[1] === 'on')
438
473
  return [guardGroup.actions['on'], argv.slice(2)];
439
- return [accountsGroup.actions['add'], argv.slice(2)];
440
- }
441
- /** A planned git line. Both are repo-local; neither shells out past the Git wrapper. */
442
- function gitLine(argv, git) {
443
- if (argv.includes('push.autoSetupRemote'))
474
+ if (argv[0] === 'accounts' && argv[1] === 'add')
475
+ return [accountsGroup.actions['add'], argv.slice(2)];
476
+ return null;
477
+ }
478
+ /** A planned git line, each by its own case. None shells out past the Git wrapper. */
479
+ async function gitLine(argv, git) {
480
+ const step = gitStepOf(argv);
481
+ if (step === 'upstream')
444
482
  return setAutoUpstream(git);
445
- return allowOwner(argv.at(-1), git);
483
+ if (step === 'allowOwner')
484
+ return allowOwner(argv.at(-1), git);
485
+ if (step === 'repoint')
486
+ return repoint(argv.at(-2), argv.at(-1), git);
487
+ if (step === 'fetch')
488
+ return fetchFirst(argv.at(-1), git);
489
+ out.fail('setup', 'could not run ' + formatCommand(argv) + ': not a step setup plans');
490
+ return 2;
491
+ }
492
+ /** The key's old value is a URL that can hold a token: it is never printed. */
493
+ async function repoint(key, remote, git) {
494
+ if (!(await git.setConfig(key, remote, 'local'))) {
495
+ out.fail('repoint', 'could not write ' + printable(key));
496
+ return 1;
497
+ }
498
+ out.pass('repoint', printable(key) + ' now names ' + printable(remote) + ': pushes go through it');
499
+ return 0;
500
+ }
501
+ /** Prompts off, like reauthor's. A failure is a warning: the rest of the plan still runs. */
502
+ async function fetchFirst(remote, git) {
503
+ const fetched = await git.fetchQuietly(remote);
504
+ if (fetched.ok) {
505
+ out.pass('fetch', printable(remote) + ' fetched: repown can now tell which commits it already has');
506
+ return 0;
507
+ }
508
+ out.warn('fetch', 'could not fetch ' + printable(remote) + ' (' + printable(fetched.error) + ')');
509
+ out.detail('so repown still can\'t tell which of these commits ' + printable(remote) + ' already has');
510
+ return 0;
446
511
  }
447
512
  /** push.autoSetupRemote, in this clone only, and only when it does not already say true. */
448
513
  async function setAutoUpstream(git) {