repown 0.2.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.
@@ -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) {
@@ -329,11 +415,16 @@ function required(value) {
329
415
  }
330
416
  /** A login as hosts spell them: it also becomes part of a profile lookup's URL. */
331
417
  const LOGIN = /^[\w.@-]+$/;
332
- function newAccountProblem(value, ctx) {
418
+ /** Empty, or not spelled as a login. The start screen asks for a login by this rule too. */
419
+ export function loginProblem(value) {
333
420
  if (!value.trim())
334
421
  return 'a value is required';
335
- if (!LOGIN.test(value))
336
- return 'use letters, digits and . _ @ - only';
422
+ return LOGIN.test(value) ? null : 'use letters, digits and . _ @ - only';
423
+ }
424
+ function newAccountProblem(value, ctx) {
425
+ const problem = loginProblem(value);
426
+ if (problem)
427
+ return problem;
337
428
  const clash = Object.keys(ctx.recorded).find((account) => lower(account) === lower(value));
338
429
  return clash ? '"' + clash + '" is already recorded on this machine: use it by that name' : null;
339
430
  }
@@ -376,6 +467,8 @@ export function planCommands(answers, ctx) {
376
467
  const account = accountOf(answers);
377
468
  const cwd = ctx.cwd ? ['--cwd=' + ctx.cwd] : [];
378
469
  const planned = [
470
+ repointArgv(answers, ctx),
471
+ fetchArgv(answers, ctx),
379
472
  isNew(answers) ? ['accounts', 'add', '--name=' + String(answers['name']), '--email=' + String(answers['email']),
380
473
  '--host=' + hostOf(answers, ctx), '--', account] : null,
381
474
  answers['allowOwner'] === true && ctx.owner ? allowOwnerLine(ctx) : null,
@@ -383,6 +476,7 @@ export function planCommands(answers, ctx) {
383
476
  useArgv(answers, ctx),
384
477
  answers['guard'] === true ? ['guard', 'on', ...cwd] : null,
385
478
  upstreamArgv(answers, ctx),
479
+ answers['reauthor'] === true && reauthorOffered(answers, ctx) ? ['reauthor', '--yes', ...cwd] : null,
386
480
  ];
387
481
  return planned.filter((argv) => argv !== null).map((argv) => ({ argv, what: whatOf(argv, answers, ctx) }));
388
482
  }
@@ -402,8 +496,33 @@ function upstreamArgv(answers, ctx) {
402
496
  return null;
403
497
  return autoUpstreamLine(ctx);
404
498
  }
499
+ function gitIn(ctx) {
500
+ return ['git', ...(ctx.cwd ? ['-C', ctx.cwd] : [])];
501
+ }
405
502
  function autoUpstreamLine(ctx) {
406
- 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;
407
526
  }
408
527
  /** What a planned command does, in words for someone who has never used repown. */
409
528
  function whatOf(argv, answers, ctx) {
@@ -416,12 +535,19 @@ function whatOf(argv, answers, ctx) {
416
535
  return 'Stop gh answering git\'s sign-in requests (whole machine)';
417
536
  if (argv[0] === 'guard')
418
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)';
419
540
  if (answers['gh'] === true)
420
541
  return ghWhat(account, ctx);
421
542
  return 'Pin this clone to ' + account + (ctx.credentialPinned ? ': its commit name, email and push sign-in' : ': its commit name and email');
422
543
  }
423
544
  function gitWhat(argv, ctx) {
424
- 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')
425
551
  return 'Push branches without -u: the first push sets the upstream (this clone only)';
426
552
  return 'Let this clone push to ' + ctx.owner + '\'s repositories';
427
553
  }
@@ -432,7 +558,7 @@ function ghWhat(account, ctx) {
432
558
  return pin + 'sign ' + account + ' in to gh (opens your browser)';
433
559
  }
434
560
  function allowOwnerLine(ctx) {
435
- 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];
436
562
  }
437
563
  /**
438
564
  * The command as you would type it: the account where it reads naturally, options
@@ -450,13 +576,8 @@ export function formatCommand(argv) {
450
576
  const words = dashed ? [...path, ...options, '--', ...positional] : [...path, ...positional, ...options];
451
577
  return printable(['repown', ...words.map(shellWord)].join(' '));
452
578
  }
453
- /**
454
- * Control characters, and the invisible or direction-changing ones, as visible escapes:
455
- * a value read from a remote URL must neither redraw the screen nor read as another name.
456
- */
457
- export function printable(text) {
458
- return text.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, (char) => '\\u' + char.charCodeAt(0).toString(16).padStart(4, '0'));
459
- }
579
+ /** Setup's own importers read it from here; the one definition is in the output helpers. */
580
+ export { printable };
460
581
  /** `--name=value` as `--name value`, unless the value starts with a dash and would read as an option. */
461
582
  function splitOption(token) {
462
583
  const at = token.indexOf('=');
@@ -493,9 +614,12 @@ function pendingReview(answers, ctx, steps, plan) {
493
614
  }
494
615
  function settledReview(answers, ctx, steps, plan) {
495
616
  const offer = ghOffer(accountOf(answers), ctx);
617
+ const reauthor = reauthorOffered(answers, ctx) ? { reauthorOffer: 'Re-author them as ' + printable(accountOf(answers)) } : {};
496
618
  const shown = {
619
+ ...reauthor,
497
620
  title: 'This clone is already set up', headline: settledLines(answers, ctx).map(printable), steps,
498
621
  notes: [...noted(settledNotes(answers, ctx), answers, ctx, plan), ...ghNote(answers, ctx, true)], settled: true,
622
+ blocked: blockersOf(answers, ctx).some((blocker) => blocker.blocks),
499
623
  };
500
624
  return offer ? { ...shown, ghSignIn: offer } : shown;
501
625
  }
@@ -510,11 +634,22 @@ function upstreamOffer(ctx) {
510
634
  return null;
511
635
  return 'optional: push branches without -u: repown setup --auto-upstream';
512
636
  }
637
+ /** What blocks the next push first (ADR-026), then the step's own notes. */
513
638
  function noted(lines, answers, ctx, plan) {
514
639
  const gap = credentialGap(plan, answers, ctx);
515
- 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] : [])];
516
643
  return body.map(printable);
517
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
+ }
518
653
  /** use's own line, said here only when this run will not run use. Mirrors use.ts credentialConcern. */
519
654
  function credentialGap(plan, answers, ctx) {
520
655
  if (plan.some((command) => command.argv[0] === 'use') || !ctx.credentialPinned || !ctx.stored?.ok)
@@ -524,17 +659,6 @@ function credentialGap(plan, answers, ctx) {
524
659
  return null;
525
660
  return 'No stored credential for ' + account + ' yet: the first push signs in once (your browser opens).';
526
661
  }
527
- function extraNotes(answers, ctx) {
528
- const upstream = upstreamNote(ctx);
529
- return [...(upstream ? [upstream] : []), ...unpushedNote(answers, ctx)];
530
- }
531
- /** The address depends on the account, so the commits were read once and are compared here. */
532
- function unpushedNote(answers, ctx) {
533
- const email = emailOf(answers, ctx) ?? '';
534
- if (!email && ctx.unpushed.commits.ok)
535
- return [];
536
- return unpushedLines(ctx.unpushed, email);
537
- }
538
662
  /** Old git, or a version that could not be read: say the push the question would have replaced. */
539
663
  function upstreamNote(ctx) {
540
664
  if (ctx.upstream.supported)
@@ -679,6 +803,8 @@ export function changesOf(argv, answers, ctx) {
679
803
  return fixChanges(ctx);
680
804
  if (argv[0] === 'guard')
681
805
  return [guardChange(ctx)];
806
+ if (argv[0] === 'reauthor')
807
+ return [reauthorChange(answers, ctx)];
682
808
  return useChanges(argv, answers, ctx);
683
809
  }
684
810
  /** The confirmation shown before a step in step-by-step mode. */
@@ -698,10 +824,20 @@ function registryChange(answers) {
698
824
  return 'this machine\'s account registry: ' + account + ' = ' + name + ' ' + email;
699
825
  }
700
826
  function gitChange(argv) {
701
- 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')
702
833
  return 'push.autoSetupRemote = true';
703
834
  return 'repown.allowOwner += ' + (argv.at(-1) ?? '');
704
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
+ }
705
841
  function fixChanges(ctx) {
706
842
  return (ctx.fixLines ?? []).filter((line) => line.trim() !== '');
707
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();
@@ -35,24 +40,28 @@ export async function runSetup(args, deps) {
35
40
  if (!deps.interactive && !unattended)
36
41
  return needsTerminal(given.value, registry.value.accounts);
37
42
  const git = gitFor(args);
38
- if (!(await git.isRepo())) {
39
- out.fail('setup', 'Not a git repository: ' + git.cwd);
40
- out.detail('run it inside a clone: cd path/to/repo, then repown setup');
41
- return 1;
42
- }
43
+ if (!(await git.isRepo()))
44
+ return notARepo(git);
43
45
  const prompter = unattended ? null : deps.prompter ?? await choosePrompter();
44
46
  try {
45
47
  return await continueSetup({
46
48
  args, git, given: given.value, prompter, accountKind: deps.accountKind, readAuth: deps.auth ?? inspectAuth,
47
49
  ...(deps.preview ? { preview: deps.preview } : {}),
50
+ ...(deps.lead === undefined ? {} : { lead: deps.lead }),
48
51
  });
49
52
  }
50
53
  finally {
51
54
  prompter?.close();
52
55
  }
53
56
  }
54
- async function continueSetup({ args, git, given, prompter, accountKind, readAuth, preview }) {
57
+ function notARepo(git) {
58
+ out.fail('setup', 'Not a git repository: ' + git.cwd);
59
+ out.detail('run it inside a clone: cd path/to/repo, then repown setup');
60
+ return 1;
61
+ }
62
+ async function continueSetup({ args, git, given, prompter, accountKind, readAuth, preview, lead }) {
55
63
  prompter?.intro?.('repown setup');
64
+ drawLead(prompter, lead);
56
65
  prompter?.busy?.('Reading this clone and this machine');
57
66
  const ctx = await readContext(git, flagString(args, 'cwd'), contextOptions(prompter, accountKind, preview));
58
67
  if (!ctx.ok) {
@@ -66,6 +75,15 @@ async function continueSetup({ args, git, given, prompter, accountKind, readAuth
66
75
  return runUnattended(answers.value, ctx.value, git, readAuth);
67
76
  return runGuided(answers.value, ctx.value, { git, prompter, readAuth });
68
77
  }
78
+ /** The bare-repown sentence, inside the frame when the prompter can draw it. */
79
+ function drawLead(prompter, lead) {
80
+ if (lead === undefined)
81
+ return;
82
+ if (prompter?.show)
83
+ prompter.show([lead]);
84
+ else
85
+ out.note(lead);
86
+ }
69
87
  function contextOptions(prompter, accountKind, preview) {
70
88
  const classifyOwner = prompter !== null;
71
89
  const auth = preview ? { auth: preview } : {};
@@ -104,8 +122,8 @@ function modeOf(args, answers) {
104
122
  answers['mode'] = 'recommended';
105
123
  return ok(answers);
106
124
  }
107
- const CONFIRM_FLAGS = ['gh', 'guard', 'fix'];
108
- 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'];
109
127
  /** A passed flag is Yes. With --no-input, a confirm that was not passed is No, not Recommended's Yes. */
110
128
  function applyConfirms(args, answers) {
111
129
  for (const key of CONFIRM_FLAGS)
@@ -130,7 +148,7 @@ function usage(message) {
130
148
  function needsTerminal(given, recorded) {
131
149
  out.fail('setup', 'needs a terminal to ask its questions.');
132
150
  out.detail('without one, give the answers as flags and add --no-input:');
133
- 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');
134
152
  const missing = missingFlags(given, recorded);
135
153
  if (missing.length > 0)
136
154
  out.detail('still needed: ' + missing.join(', '));
@@ -156,7 +174,10 @@ function checkAgainst(given, ctx, allowOwner) {
156
174
  out.detail('--fix: gh is not the credential helper for this clone, so there is nothing to undo');
157
175
  answers['fix'] = false;
158
176
  }
159
- 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);
160
181
  }
161
182
  // ------------------------------------------------------------------- the runs
162
183
  async function runUnattended(answers, ctx, git, readAuth) {
@@ -211,8 +232,9 @@ function stoppedBefore(status, prompter) {
211
232
  * @clack/prompts when colour is on for stderr and the terminal can draw it; the plain
212
233
  * prompter otherwise, and whenever the optional dependency is absent or fails to load
213
234
  * (an older Node skips installing it, ADR-016) -- said once, then carried on.
235
+ * Setup and the start screen both ask through this, so clack loads in only one place.
214
236
  */
215
- async function choosePrompter() {
237
+ export async function choosePrompter() {
216
238
  const streams = { input: process.stdin, output: process.stderr };
217
239
  if (!useColour(process.stderr) || process.env['TERM'] === 'dumb')
218
240
  return plainPrompter(streams);
@@ -225,7 +247,8 @@ async function choosePrompter() {
225
247
  }
226
248
  }
227
249
  function runState(git, readAuth, ctx) {
228
- return { git, readAuth, credentialKeys: ctx.credentialKeys };
250
+ const repointed = ctx.push.repoint ? [ctx.push.repoint.key] : [];
251
+ return { git, readAuth, watchedKeys: [...ctx.credentialKeys, ...repointed] };
229
252
  }
230
253
  function reported(answers, ctx, repeatGh) {
231
254
  return { account: accountOf(answers), pinnedAlready: pinUnchanged(answers, ctx), repeatGh };
@@ -238,7 +261,7 @@ function reported(answers, ctx, repeatGh) {
238
261
  * The clone is read before the first step and again after, including a stop or a failure.
239
262
  */
240
263
  async function execute(plan, state) {
241
- const before = await readCloneSnapshot(state.git, state.credentialKeys);
264
+ const before = await readCloneSnapshot(state.git, state.watchedKeys);
242
265
  const ran = await walk(plan, state.git, state.confirm);
243
266
  await reportRun(before, ran, state);
244
267
  return ran.code ?? 0;
@@ -307,24 +330,43 @@ function halt(remaining, code, why) {
307
330
  /** On stderr, like the step lines: stdout carries only what the commands themselves print. */
308
331
  async function reportRun(before, ran, state) {
309
332
  if (ran.code === null)
310
- announce(ran.done, ran.skipped, state);
333
+ await announce(ran.done, ran.skipped, state);
311
334
  await printClone(before, state);
312
335
  const auth = wantsAuth(ran, state) ? await state.readAuth(state.git) : null;
313
336
  printMachine(ran.done, auth);
314
337
  if (ran.code === null)
315
338
  closeRun(auth, state);
316
339
  }
317
- function announce(done, skipped, report) {
340
+ async function announce(done, skipped, state) {
318
341
  process.stderr.write('\n');
319
342
  const pinned = done.find((planned) => planned.argv[0] === 'use')?.argv.at(-1);
320
- const account = pinned ?? (report.pinnedAlready ? report.account : null);
343
+ const account = pinned ?? (state.pinnedAlready ? state.account : null);
321
344
  if (account)
322
- out.detail('done: this clone is set up for ' + printable(account));
345
+ closing(account, await blockersNow(state.git, account));
323
346
  for (const planned of skipped)
324
347
  out.detail('skipped: ' + printable(planned.what));
325
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
+ }
326
368
  async function printClone(before, state) {
327
- const lines = cloneChangeLines(before, await readCloneSnapshot(state.git, state.credentialKeys));
369
+ const lines = cloneChangeLines(before, await readCloneSnapshot(state.git, state.watchedKeys));
328
370
  if (lines.length === 0) {
329
371
  out.detail('nothing changed in this clone');
330
372
  return;
@@ -406,7 +448,12 @@ async function withoutLine(hidden, run) {
406
448
  async function runOne(argv, git) {
407
449
  if (argv[0] === 'git')
408
450
  return gitLine(argv, git);
409
- 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;
410
457
  const parsed = parseArgs(rest, specFor(command));
411
458
  if (!parsed.ok) {
412
459
  out.fail('setup', 'could not run ' + formatCommand(argv) + ': ' + parsed.error);
@@ -414,21 +461,53 @@ async function runOne(argv, git) {
414
461
  }
415
462
  return command.run(parsed.value);
416
463
  }
417
- /** 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. */
418
465
  function commandFor(argv) {
419
466
  if (argv[0] === 'use')
420
467
  return [useCommand, argv.slice(1)];
421
468
  if (argv[0] === 'fix')
422
469
  return [fixCommand, argv.slice(1)];
423
- if (argv[0] === 'guard')
470
+ if (argv[0] === 'reauthor')
471
+ return [reauthorCommand, argv.slice(1)];
472
+ if (argv[0] === 'guard' && argv[1] === 'on')
424
473
  return [guardGroup.actions['on'], argv.slice(2)];
425
- return [accountsGroup.actions['add'], argv.slice(2)];
426
- }
427
- /** A planned git line. Both are repo-local; neither shells out past the Git wrapper. */
428
- function gitLine(argv, git) {
429
- 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')
430
482
  return setAutoUpstream(git);
431
- 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;
432
511
  }
433
512
  /** push.autoSetupRemote, in this clone only, and only when it does not already say true. */
434
513
  async function setAutoUpstream(git) {
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "repown",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "repown",
9
- "version": "0.2.0",
9
+ "version": "0.4.0",
10
10
  "license": "MIT",
11
11
  "bin": {
12
12
  "repown": "dist/cli.js"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repown",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Use several git accounts on one machine: each repo owns its identity, so you move between repos with no switch command and never push the wrong one.",
5
5
  "repository": {
6
6
  "type": "git",