repown 0.1.1 → 0.2.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.
@@ -0,0 +1,728 @@
1
+ // What `repown setup` asks, and what the answers turn into. Every answer becomes a
2
+ // flag or argument of a command that already exists -- `accounts add`, `use`,
3
+ // `guard on`, `fix` -- or a repo-local git line (an organisation's allowOwner, or
4
+ // push.autoSetupRemote), so the review can show exactly what will run, and a
5
+ // script can run the same thing.
6
+ //
7
+ // Pure: no I/O. What the clone and the machine look like arrives as a SetupContext
8
+ // (src/wizard/setup-context.ts), read before the first question.
9
+ import { ghAdvice, upstreamText } from "../commands/status.js";
10
+ import { providers } from "../core/hosts/index.js";
11
+ import { shellWord } from "../core/guard/check.js";
12
+ import { unpushedLines } from "../core/unpushed.js";
13
+ import { pinWrites } from "../core/identity.js";
14
+ import { stepDefault } from "./review-text.js";
15
+ /** The "a new account" choice. Empty, so it can never be a real account's name. */
16
+ export const NEW_ACCOUNT = '';
17
+ /** A detected choice's value. The login grammar refuses '+', so a recorded account cannot collide. */
18
+ export const DETECTED_PREFIX = '+';
19
+ const lower = (value) => value.toLowerCase();
20
+ /** The account the answers are about: a recorded one, a detected login, or the new one typed in. */
21
+ export function accountOf(answers) {
22
+ const picked = answers['account'];
23
+ if (picked === undefined || picked === NEW_ACCOUNT)
24
+ return String(answers['newAccount'] ?? '');
25
+ return stripDetected(String(picked));
26
+ }
27
+ /** A recorded account is not new. A detected login still has to be recorded. */
28
+ export function isNew(answers) {
29
+ const picked = answers['account'];
30
+ if (picked === undefined || picked === NEW_ACCOUNT)
31
+ return true;
32
+ return String(picked).startsWith(DETECTED_PREFIX);
33
+ }
34
+ function stripDetected(value) {
35
+ return value.startsWith(DETECTED_PREFIX) ? value.slice(DETECTED_PREFIX.length) : value;
36
+ }
37
+ /** The login is typed only for "a new account". A detected login is already chosen. */
38
+ function asksForLogin(answers) {
39
+ return (answers['account'] ?? NEW_ACCOUNT) === NEW_ACCOUNT;
40
+ }
41
+ export function setupFlow(ctx) {
42
+ return {
43
+ steps: steps(ctx), review: (answers) => review(answers, ctx), fill: (answers) => recommendedAnswers(answers, ctx),
44
+ opening: () => openingReview(ctx), resume: (choice) => resumeAt(choice, ctx),
45
+ };
46
+ }
47
+ function openingReview(ctx) {
48
+ if (!ctx.pinned || !ctx.pinIntact)
49
+ return null;
50
+ const shown = review(recommendedAnswers({ mode: 'recommended', account: ctx.pinned }, ctx), ctx);
51
+ return shown.settled ? { ...shown, edits: false } : null;
52
+ }
53
+ function resumeAt(choice, ctx) {
54
+ if (choice === 'gh')
55
+ return { answers: ghAnswers(ctx), start: steps(ctx).length };
56
+ const start = steps(ctx).findIndex((step) => step.id === 'account');
57
+ return { answers: { mode: 'recommended' }, start: start < 0 ? 0 : start };
58
+ }
59
+ function ghAnswers(ctx) {
60
+ return recommendedAnswers({ mode: 'recommended', account: ctx.pinned ?? '', gh: true }, ctx);
61
+ }
62
+ /** Yes for confirms Recommended skips. An answer already given, including from Change an answer, stays. */
63
+ export function recommendedAnswers(answers, ctx) {
64
+ if (!isRecommended(answers))
65
+ return answers;
66
+ const filled = { ...answers };
67
+ for (const step of steps(ctx))
68
+ fillRecommended(step, filled, ctx);
69
+ return filled;
70
+ }
71
+ function fillRecommended(step, filled, ctx) {
72
+ if (filled[step.id] !== undefined || step.skip?.(filled, ctx))
73
+ return;
74
+ if (!step.auto?.(filled, ctx))
75
+ return;
76
+ if (step.when && !step.when(filled, ctx))
77
+ return;
78
+ filled[step.id] = true;
79
+ }
80
+ function isRecommended(answers) {
81
+ return answers['mode'] === 'recommended';
82
+ }
83
+ function steps(ctx) {
84
+ return [
85
+ modeStep(),
86
+ ...accountSteps(ctx),
87
+ { id: 'host', kind: 'select', flag: '--host', message: 'Where is this account hosted?',
88
+ hint: 'on GitHub, repown also makes pushes sign in as this account', when: (answers) => isNew(answers),
89
+ choices: () => hostChoices(), initial: () => ctx.host },
90
+ { id: 'name', kind: 'text', flag: '--name', message: 'Your name, as your commits show it',
91
+ hint: 'e.g. Octo Cat; anyone who can see the repository sees it', when: (answers) => isNew(answers), validate: required,
92
+ initial: async (answers) => (await ctx.suggest(accountOf(answers), hostOf(answers, ctx))).name ?? accountOf(answers),
93
+ detail: (answers) => nameDetail(answers, ctx) },
94
+ { id: 'email', kind: 'text', flag: '--email', message: 'Your email, as your commits show it',
95
+ hint: 'anyone who can see the repository can read it once you push', when: (answers) => isNew(answers), validate: required,
96
+ initial: async (answers) => (await ctx.suggest(accountOf(answers), hostOf(answers, ctx))).email,
97
+ detail: (answers) => emailDetail(answers, ctx) },
98
+ ...choiceSteps(ctx),
99
+ ];
100
+ }
101
+ function modeStep() {
102
+ return {
103
+ id: 'mode', kind: 'select', flag: '--step-by-step',
104
+ message: 'How should setup work?',
105
+ hint: 'Recommended fills in the answers that only change this clone; Step by step asks each one',
106
+ choices: () => modeChoices(), initial: () => 'recommended',
107
+ };
108
+ }
109
+ function modeChoices() {
110
+ return [
111
+ { value: 'recommended', label: 'Recommended',
112
+ hint: 'asks only what it must, fills in the rest, and shows every step before running' },
113
+ { value: 'step', label: 'Step by step',
114
+ hint: 'asks every question, and explains each change before making it' },
115
+ ];
116
+ }
117
+ function accountSteps(ctx) {
118
+ return [
119
+ { id: 'account', kind: 'select', flag: '<account>', message: 'Which account should this clone belong to?',
120
+ hint: 'commits made here carry its name and email; on GitHub, pushes from here also sign in as it',
121
+ when: () => Object.keys(ctx.recorded).length > 0 || ctx.detected.length > 0,
122
+ choices: () => accountChoices(ctx), initial: () => defaultAccount(ctx),
123
+ detail: () => (ctx.pinned ? 'right now this clone is pinned to ' + ctx.pinned : 'right now this clone isn\'t pinned to any account') },
124
+ { id: 'newAccount', kind: 'text', flag: '<account>', message: 'The account\'s user name (login)',
125
+ hint: 'the name you sign in with, e.g. octocat; not your email address', when: (answers) => asksForLogin(answers),
126
+ validate: (value) => newAccountProblem(String(value), ctx), initial: () => ownerInitial(ctx) },
127
+ ];
128
+ }
129
+ function choiceSteps(ctx) {
130
+ return [
131
+ ghStep(ctx),
132
+ { id: 'allowOwner', kind: 'confirm', flag: '--allow-owner', initial: () => true,
133
+ message: 'This repository belongs to "' + printable(ctx.owner ?? '') + '". Let this clone push to it?',
134
+ hint: 'Yes if you\'re a member of that organisation or a collaborator on it; with No, ' +
135
+ 'the push guard refuses pushes there. Saved in this clone only',
136
+ when: (answers) => ownerForeign(accountOf(answers), ctx) },
137
+ { id: 'guard', kind: 'confirm', flag: '--guard', message: 'Turn on the push guard?',
138
+ hint: 'before each push, it checks that every commit is yours and goes to the right place, and stops the push if not; ' +
139
+ 'turn it off any time: repown guard off',
140
+ initial: () => true, when: () => ctx.guard === 'off' && !ctx.redirected, auto: isRecommended,
141
+ detail: (answers) => historyNote(answers, ctx) },
142
+ upstreamStep(ctx),
143
+ { id: 'fix', kind: 'confirm', flag: '--fix', message: 'Stop gh answering git\'s sign-in requests? (whole machine)',
144
+ hint: 'undo any time: gh auth setup-git', initial: () => false, when: () => ctx.fixLines !== null,
145
+ detail: () => 'gh answers git\'s sign-in requests with its active account only, so clones of your other accounts ' +
146
+ 'get password prompts. Yes hands that job back to Git Credential Manager, for every repository on this machine' },
147
+ ];
148
+ }
149
+ /** Labels for a newcomer; the providers' own labels stay as `repown` prints them elsewhere. */
150
+ const HOSTS = {
151
+ github: ['GitHub', 'name, email and the sign-in for pushes'],
152
+ azdo: ['Azure DevOps', 'name and email; you sign in as usual'],
153
+ generic: ['another host (GitLab, Bitbucket, self-hosted)', 'name and email; you sign in as usual'],
154
+ };
155
+ function hostChoices() {
156
+ return providers().map((provider) => {
157
+ const [label, hint] = HOSTS[provider.id] ?? [provider.label, ''];
158
+ return { value: provider.id, label, ...(hint ? { hint } : {}) };
159
+ });
160
+ }
161
+ /** Where a GitHub account's private address comes from, for someone who has never looked. */
162
+ function noreplyExample(answers, ctx) {
163
+ if (hostOf(answers, ctx) !== 'github')
164
+ return undefined;
165
+ return 'tip: to keep your own address private, use the one GitHub gives you, shown at ' +
166
+ 'github.com/settings/emails, like 1234+' + printable(accountOf(answers)) + '@users.noreply.github.com';
167
+ }
168
+ /** The machine's name, beside a new account. Never that account's initial value. */
169
+ function nameDetail(answers, ctx) {
170
+ const name = ctx.machineIdentity.name;
171
+ if (!isNew(answers) || !name)
172
+ return undefined;
173
+ return 'not this machine\'s default name (' + printable(name) + '), unless this account uses it';
174
+ }
175
+ /** Noreply tip first, then the machine address. Two sentences; both prompters wrap one detail. */
176
+ function emailDetail(answers, ctx) {
177
+ const tip = noreplyExample(answers, ctx);
178
+ const line = addressDetail(answers, ctx);
179
+ if (tip && line)
180
+ return tip + '; ' + line;
181
+ return tip ?? line;
182
+ }
183
+ function addressDetail(answers, ctx) {
184
+ const email = ctx.machineIdentity.email;
185
+ if (!isNew(answers) || !email)
186
+ return undefined;
187
+ return 'not this machine\'s default address (' + printable(email) + '), unless this account uses it';
188
+ }
189
+ const UPSTREAM_HINT = 'sets push.autoSetupRemote in this clone only, so the first push of a branch without an upstream ' +
190
+ 'creates it on origin; the guard still checks it';
191
+ /** Asked only when git has the key and the effective value is not already true. */
192
+ function offersUpstream(ctx) {
193
+ return ctx.upstream.supported && ctx.upstream.enabled !== true;
194
+ }
195
+ function upstreamStep(ctx) {
196
+ return {
197
+ id: 'upstream', kind: 'confirm', flag: '--auto-upstream', initial: () => true,
198
+ message: 'Push branches without -u?', hint: UPSTREAM_HINT,
199
+ when: () => offersUpstream(ctx), auto: isRecommended,
200
+ };
201
+ }
202
+ const SWITCH_MESSAGE = 'Also make this account gh\'s active account?';
203
+ 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
+ function ghStep(ctx) {
205
+ return {
206
+ id: 'gh', kind: 'confirm', flag: '--gh', initial: () => false,
207
+ message: (answers) => ghMessage(accountOf(answers), ctx),
208
+ hint: (answers) => ghHint(accountOf(answers), ctx),
209
+ detail: () => ghDetail(ctx),
210
+ when: (answers) => ghAsked(accountOf(answers), ctx),
211
+ auto: (answers) => ghAuto(answers, ctx),
212
+ skip: (answers) => ghSkipped(answers, ctx),
213
+ };
214
+ }
215
+ function ghAuto(answers, ctx) {
216
+ return isRecommended(answers) && inGh(accountOf(answers), ctx) && !sameAccount(answers, ctx);
217
+ }
218
+ /** Recommended leaves gh at No when this clone is already pinned to the chosen account. */
219
+ function ghSkipped(answers, ctx) {
220
+ return isRecommended(answers) && sameAccount(answers, ctx);
221
+ }
222
+ function sameAccount(answers, ctx) {
223
+ return ctx.pinned !== null && !isNew(answers) && accountOf(answers) === ctx.pinned;
224
+ }
225
+ function ghMessage(account, ctx) {
226
+ if (inGh(account, ctx))
227
+ return SWITCH_MESSAGE;
228
+ return 'Sign in to gh as ' + printable(account) + ' too?';
229
+ }
230
+ function ghHint(account, ctx) {
231
+ if (inGh(account, ctx))
232
+ return SWITCH_HINT;
233
+ return 'gh is GitHub\'s command-line tool (gh pr create); git pushes don\'t need it. ' +
234
+ 'Yes opens your browser to sign in, and gh then acts as ' + printable(account) + ' in every terminal';
235
+ }
236
+ function ghDetail(ctx) {
237
+ if (noGhAccounts(ctx))
238
+ return 'gh isn\'t signed in to any account';
239
+ return 'gh\'s active account is ' + ghActive(ctx);
240
+ }
241
+ function noGhAccounts(ctx) {
242
+ return ctx.gh?.ok === true && ctx.gh.value.accounts.length === 0;
243
+ }
244
+ function ghAsked(account, ctx) {
245
+ if (ctx.host !== 'github' || !ctx.gh?.ok)
246
+ return false;
247
+ if (!inGh(account, ctx))
248
+ return true;
249
+ return lower(ctx.gh.value.active ?? '') !== lower(account);
250
+ }
251
+ function inGh(account, ctx) {
252
+ if (!ctx.gh?.ok)
253
+ return false;
254
+ return ctx.gh.value.accounts.some((entry) => lower(entry.login) === lower(account));
255
+ }
256
+ function ghActive(ctx) {
257
+ return ctx.gh?.ok ? printable(ctx.gh.value.active ?? 'none') : 'unknown';
258
+ }
259
+ /** Where a detected login was seen. Detection records these; the account hint prints them. */
260
+ export const SOURCE_OWNS = 'owns this repository';
261
+ export const SOURCE_GH = 'signed in to gh';
262
+ export const SOURCE_GCM = 'stored in Git Credential Manager';
263
+ const OWNER_UNKNOWN = SOURCE_OWNS + '; may be an organisation';
264
+ function accountChoices(ctx) {
265
+ const recorded = Object.entries(ctx.recorded).map(([account, entry]) => ({ value: account, label: account, hint: entry.name + ' <' + entry.email + '>' }));
266
+ const detected = ctx.detected.map((account) => detectedChoice(account, ctx));
267
+ return [...recorded, ...detected, { value: NEW_ACCOUNT, label: 'a new account', hint: 'record another account on this machine' }];
268
+ }
269
+ function detectedChoice(account, ctx) {
270
+ return {
271
+ value: DETECTED_PREFIX + account.login,
272
+ label: printable(account.login),
273
+ hint: printable(detectedHint(account, ctx)),
274
+ };
275
+ }
276
+ function detectedHint(account, ctx) {
277
+ return account.from.map((source) => sourceText(source, account, ctx)).join('; ');
278
+ }
279
+ function sourceText(source, account, ctx) {
280
+ if (source !== SOURCE_OWNS || ctx.ownerIsUser !== null)
281
+ return source;
282
+ return sameLogin(account.login, ctx.owner) ? OWNER_UNKNOWN : source;
283
+ }
284
+ function defaultAccount(ctx) {
285
+ return pinnedAccount(ctx) ?? recordedOwner(ctx) ?? detectedOwnerValue(ctx) ?? firstRecorded(ctx) ?? NEW_ACCOUNT;
286
+ }
287
+ /** Registry spelling of the pin. Case differs after a login is recorded again; the pin still wins. */
288
+ function pinnedAccount(ctx) {
289
+ return registrySpelling(ctx.recorded, ctx.pinned);
290
+ }
291
+ /** Registry spelling of the owner. A known organisation is listed with the recorded accounts and is not the default. */
292
+ function recordedOwner(ctx) {
293
+ if (ctx.ownerIsUser === false)
294
+ return undefined;
295
+ return registrySpelling(ctx.recorded, ctx.owner);
296
+ }
297
+ function registrySpelling(recorded, login) {
298
+ if (login === null)
299
+ return undefined;
300
+ return Object.keys(recorded).find((account) => sameLogin(account, login));
301
+ }
302
+ /** The first recorded account, other than an owner known to be an organisation. */
303
+ function firstRecorded(ctx) {
304
+ return Object.keys(ctx.recorded).find((account) => !knownOrganisation(ctx, account));
305
+ }
306
+ function knownOrganisation(ctx, account) {
307
+ return ctx.ownerIsUser === false && sameLogin(account, ctx.owner);
308
+ }
309
+ /** The detected spelling, which is the choice the list can highlight. */
310
+ function detectedOwnerValue(ctx) {
311
+ if (ctx.ownerIsUser !== true)
312
+ return undefined;
313
+ const found = ctx.detected.find((account) => sameLogin(account.login, ctx.owner));
314
+ return found === undefined ? undefined : DETECTED_PREFIX + found.login;
315
+ }
316
+ /** Origin's owner, only as a typed login, and only when it is a user not recorded yet. */
317
+ function ownerInitial(ctx) {
318
+ const owner = ctx.owner;
319
+ if (ctx.ownerIsUser !== true || owner === null)
320
+ return undefined;
321
+ const recorded = Object.keys(ctx.recorded).some((account) => sameLogin(account, owner));
322
+ return recorded ? undefined : owner;
323
+ }
324
+ function sameLogin(login, other) {
325
+ return other !== null && lower(other) === lower(login);
326
+ }
327
+ function required(value) {
328
+ return String(value).trim() ? null : 'a value is required';
329
+ }
330
+ /** A login as hosts spell them: it also becomes part of a profile lookup's URL. */
331
+ const LOGIN = /^[\w.@-]+$/;
332
+ function newAccountProblem(value, ctx) {
333
+ if (!value.trim())
334
+ return 'a value is required';
335
+ if (!LOGIN.test(value))
336
+ return 'use letters, digits and . _ @ - only';
337
+ const clash = Object.keys(ctx.recorded).find((account) => lower(account) === lower(value));
338
+ return clash ? '"' + clash + '" is already recorded on this machine: use it by that name' : null;
339
+ }
340
+ function hostOf(answers, ctx) {
341
+ return typeof answers['host'] === 'string' ? answers['host'] : ctx.host;
342
+ }
343
+ function ownerForeign(account, ctx) {
344
+ if (!ctx.owner || lower(ctx.owner) === lower(account))
345
+ return false;
346
+ return !ctx.allowed.includes(lower(ctx.owner));
347
+ }
348
+ /** The addresses in history besides this account's, said as a count -- or that it couldn't be read. */
349
+ function historyNote(answers, ctx) {
350
+ if (!ctx.addresses.ok) {
351
+ return 'this repository\'s commits could not be read (' + printable(ctx.addresses.error) + '), so repown can\'t say who else committed here';
352
+ }
353
+ if (ctx.addresses.value.size === 0)
354
+ return 'this repository has no commits yet';
355
+ const own = lower(emailOf(answers, ctx) ?? '');
356
+ const others = [...ctx.addresses.value.keys()].filter((address) => lower(address) !== own).length;
357
+ if (others === 0)
358
+ return 'only your email address is in this repository\'s commits';
359
+ return (others === 1 ? '1 other person\'s email address is' : others + ' other people\'s email addresses are') +
360
+ ' in this repository\'s commits: the guard suits you if you push only your own commits; ' +
361
+ 'choose No if you push commits others made here';
362
+ }
363
+ function emailOf(answers, ctx) {
364
+ if (isNew(answers))
365
+ return typeof answers['email'] === 'string' ? answers['email'] : undefined;
366
+ return ctx.recorded[accountOf(answers)]?.email;
367
+ }
368
+ function nameOf(answers, ctx) {
369
+ if (isNew(answers))
370
+ return typeof answers['name'] === 'string' ? answers['name'] : undefined;
371
+ return ctx.recorded[accountOf(answers)]?.name;
372
+ }
373
+ // ------------------------------------------------------------------ the plan
374
+ /** The commands the answers stand for, in the order they run. */
375
+ export function planCommands(answers, ctx) {
376
+ const account = accountOf(answers);
377
+ const cwd = ctx.cwd ? ['--cwd=' + ctx.cwd] : [];
378
+ const planned = [
379
+ isNew(answers) ? ['accounts', 'add', '--name=' + String(answers['name']), '--email=' + String(answers['email']),
380
+ '--host=' + hostOf(answers, ctx), '--', account] : null,
381
+ answers['allowOwner'] === true && ctx.owner ? allowOwnerLine(ctx) : null,
382
+ answers['fix'] === true ? ['fix', '--yes', ...cwd] : null,
383
+ useArgv(answers, ctx),
384
+ answers['guard'] === true ? ['guard', 'on', ...cwd] : null,
385
+ upstreamArgv(answers, ctx),
386
+ ];
387
+ return planned.filter((argv) => argv !== null).map((argv) => ({ argv, what: whatOf(argv, answers, ctx) }));
388
+ }
389
+ /** A pin that would write nothing is left out. `use --gh` still runs: that step changes gh. */
390
+ export function pinUnchanged(answers, ctx) {
391
+ return sameAccount(answers, ctx) && ctx.pinIntact && answers['gh'] !== true;
392
+ }
393
+ function useArgv(answers, ctx) {
394
+ if (pinUnchanged(answers, ctx))
395
+ return null;
396
+ const cwd = ctx.cwd ? ['--cwd=' + ctx.cwd] : [];
397
+ const gh = answers['gh'] === true ? ['--gh'] : [];
398
+ return ['use', ...gh, ...cwd, '--', accountOf(answers)];
399
+ }
400
+ function upstreamArgv(answers, ctx) {
401
+ if (answers['upstream'] !== true || !offersUpstream(ctx))
402
+ return null;
403
+ return autoUpstreamLine(ctx);
404
+ }
405
+ function autoUpstreamLine(ctx) {
406
+ return ['git', ...(ctx.cwd ? ['-C', ctx.cwd] : []), 'config', '--local', 'push.autoSetupRemote', 'true'];
407
+ }
408
+ /** What a planned command does, in words for someone who has never used repown. */
409
+ function whatOf(argv, answers, ctx) {
410
+ const account = accountOf(answers);
411
+ if (argv[0] === 'accounts')
412
+ return 'Record the account ' + account + ' on this machine: ' + String(answers['email']);
413
+ if (argv[0] === 'git')
414
+ return gitWhat(argv, ctx);
415
+ if (argv[0] === 'fix')
416
+ return 'Stop gh answering git\'s sign-in requests (whole machine)';
417
+ if (argv[0] === 'guard')
418
+ return 'Turn on the push guard: each push is checked first';
419
+ if (answers['gh'] === true)
420
+ return ghWhat(account, ctx);
421
+ return 'Pin this clone to ' + account + (ctx.credentialPinned ? ': its commit name, email and push sign-in' : ': its commit name and email');
422
+ }
423
+ function gitWhat(argv, ctx) {
424
+ if (argv.includes('push.autoSetupRemote'))
425
+ return 'Push branches without -u: the first push sets the upstream (this clone only)';
426
+ return 'Let this clone push to ' + ctx.owner + '\'s repositories';
427
+ }
428
+ function ghWhat(account, ctx) {
429
+ const pin = 'Pin this clone to ' + account + ', and ';
430
+ if (inGh(account, ctx))
431
+ return pin + 'make it gh\'s active account';
432
+ return pin + 'sign ' + account + ' in to gh (opens your browser)';
433
+ }
434
+ function allowOwnerLine(ctx) {
435
+ return ['git', ...(ctx.cwd ? ['-C', ctx.cwd] : []), 'config', '--local', '--add', 'repown.allowOwner', ctx.owner];
436
+ }
437
+ /**
438
+ * The command as you would type it: the account where it reads naturally, options
439
+ * as `--name value`, and `--host github` left out because it's the default.
440
+ */
441
+ export function formatCommand(argv) {
442
+ if (argv[0] === 'git')
443
+ return printable(argv.map(shellWord).join(' '));
444
+ const end = argv.indexOf('--');
445
+ const head = end < 0 ? argv : argv.slice(0, end);
446
+ const positional = end < 0 ? [] : argv.slice(end + 1);
447
+ const path = head.filter((token) => !token.startsWith('-'));
448
+ const options = head.filter((token) => token.startsWith('-') && token !== '--host=github').flatMap(splitOption);
449
+ const dashed = positional.some((value) => value.startsWith('-'));
450
+ const words = dashed ? [...path, ...options, '--', ...positional] : [...path, ...positional, ...options];
451
+ return printable(['repown', ...words.map(shellWord)].join(' '));
452
+ }
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
+ }
460
+ /** `--name=value` as `--name value`, unless the value starts with a dash and would read as an option. */
461
+ function splitOption(token) {
462
+ const at = token.indexOf('=');
463
+ return at < 0 || token[at + 1] === '-' ? [token] : [token.slice(0, at), token.slice(at + 1)];
464
+ }
465
+ /** What `--no-input` still needs, as the flags that would supply it. */
466
+ export function missingFlags(given, recorded) {
467
+ if (given['account'] === undefined)
468
+ return ['<account>'];
469
+ if (!isNew(given))
470
+ return [];
471
+ if (accountOf(given) && Object.hasOwn(recorded, accountOf(given)))
472
+ return [];
473
+ const login = accountOf(given) ? [] : ['<account>'];
474
+ return [...login, ...['name', 'email'].filter((key) => given[key] === undefined).map((key) => '--' + key)];
475
+ }
476
+ // ---------------------------------------------------------------- the review
477
+ function review(answers, ctx) {
478
+ const plan = planCommands(answers, ctx);
479
+ const steps = stepsOf(plan, ctx);
480
+ return settled(answers, ctx, plan) ? settledReview(answers, ctx, steps, plan) : pendingReview(answers, ctx, steps, plan);
481
+ }
482
+ function stepsOf(plan, ctx) {
483
+ return plan.map((command) => ({
484
+ what: printable(command.what), command: formatCommand(command.argv),
485
+ detail: command.argv[0] === 'fix' ? (ctx.fixLines ?? []).map(printable) : [],
486
+ }));
487
+ }
488
+ function pendingReview(answers, ctx, steps, plan) {
489
+ return {
490
+ title: 'Review: nothing has changed yet', headline: [printable(headline(answers, ctx))], steps,
491
+ notes: [...noted(notes(answers, ctx), answers, ctx, plan), ...ghNote(answers, ctx, false)], settled: false,
492
+ };
493
+ }
494
+ function settledReview(answers, ctx, steps, plan) {
495
+ const offer = ghOffer(accountOf(answers), ctx);
496
+ const shown = {
497
+ title: 'This clone is already set up', headline: settledLines(answers, ctx).map(printable), steps,
498
+ notes: [...noted(settledNotes(answers, ctx), answers, ctx, plan), ...ghNote(answers, ctx, true)], settled: true,
499
+ };
500
+ return offer ? { ...shown, ghSignIn: offer } : shown;
501
+ }
502
+ function settledNotes(answers, ctx) {
503
+ const lines = ['Checked: the settings git uses here are ' + printable(accountOf(answers)) + '\'s, as recorded.',
504
+ 'See it any time: repown status (this clone), repown doctor (this machine)'];
505
+ const offer = upstreamOffer(ctx);
506
+ return offer ? [...lines, offer] : lines;
507
+ }
508
+ function upstreamOffer(ctx) {
509
+ if (!offersUpstream(ctx))
510
+ return null;
511
+ return 'optional: push branches without -u: repown setup --auto-upstream';
512
+ }
513
+ function noted(lines, answers, ctx, plan) {
514
+ const gap = credentialGap(plan, answers, ctx);
515
+ const body = [...lines, ...extraNotes(answers, ctx), ...(gap ? [gap] : [])];
516
+ return body.map(printable);
517
+ }
518
+ /** use's own line, said here only when this run will not run use. Mirrors use.ts credentialConcern. */
519
+ function credentialGap(plan, answers, ctx) {
520
+ if (plan.some((command) => command.argv[0] === 'use') || !ctx.credentialPinned || !ctx.stored?.ok)
521
+ return null;
522
+ const account = accountOf(answers);
523
+ if (ctx.stored.value.includes(account))
524
+ return null;
525
+ return 'No stored credential for ' + account + ' yet: the first push signs in once (your browser opens).';
526
+ }
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
+ /** Old git, or a version that could not be read: say the push the question would have replaced. */
539
+ function upstreamNote(ctx) {
540
+ if (ctx.upstream.supported)
541
+ return null;
542
+ const branch = ctx.upstream.branch ?? '<branch>';
543
+ return 'the first push of a branch without an upstream needs: git push -u origin ' + branch;
544
+ }
545
+ /** gh still acts as someone else, and this run will not change that. */
546
+ function ghNote(answers, ctx, onSettled) {
547
+ const line = ghLeft(answers, ctx, onSettled);
548
+ return line ? [printable(line)] : [];
549
+ }
550
+ /** True when the review already says how to point gh at this account, so the run does not say it again. */
551
+ export function ghNoted(answers, ctx) {
552
+ return ghLeft(answers, ctx, false) !== null;
553
+ }
554
+ /** Drop the leading "fix: " on ghAdvice's remedy, so a sentence can name it itself. */
555
+ export function dropFixPrefix(detail) {
556
+ return detail.replace(/^fix: /, '');
557
+ }
558
+ function ghLeft(answers, ctx, onSettled) {
559
+ const gh = ctx.gh;
560
+ if (answers['gh'] === true || !gh?.ok || !gh.value.active)
561
+ return null;
562
+ const advice = ghAdvice(accountOf(answers), { ghPresent: true, gh });
563
+ if (!advice)
564
+ return null;
565
+ return ghSentence(gh.value.active, ghEnding(accountOf(answers), ctx, advice.detail, onSettled));
566
+ }
567
+ function ghSentence(active, ending) {
568
+ return 'gh still acts as ' + active + ', so gh pr create here would act as that account (git pushes are unaffected). ' + ending;
569
+ }
570
+ /** The settled screen points at its menu. Every other review names the command. */
571
+ function ghEnding(account, ctx, detail, onSettled) {
572
+ const offer = onSettled ? ghOffer(account, ctx) : null;
573
+ if (offer !== null)
574
+ return 'If you use gh here, choose "' + offer + '" below.';
575
+ return 'If you use gh here: ' + ghRemedy(detail) + '.';
576
+ }
577
+ function ghRemedy(detail) {
578
+ return dropFixPrefix(detail).replace(/ {2,}/g, ' ');
579
+ }
580
+ /**
581
+ * Nothing to do: the plan is empty because the pin would change nothing, with no
582
+ * organisation the guard would refuse and gh nowhere in the helper list. Saying No
583
+ * to push.autoSetupRemote still counts; the settled screen names the flag. Recommended
584
+ * answers Yes, so that step is in the plan and the clone is not settled.
585
+ */
586
+ function settled(answers, ctx, plan) {
587
+ if (plan.length > 0 || !pinUnchanged(answers, ctx))
588
+ return false;
589
+ return !ctx.ghIsHelper && !ownerForeign(accountOf(answers), ctx);
590
+ }
591
+ function headline(answers, ctx) {
592
+ const account = accountOf(answers);
593
+ if (ctx.credentialPinned)
594
+ return 'This clone will commit and push as ' + account + '.';
595
+ return 'This clone will commit as ' + account + '. Its pushes sign in with whatever you use for this host: ' +
596
+ 'repown pins the sign-in on GitHub only.';
597
+ }
598
+ function settledLines(answers, ctx) {
599
+ const account = accountOf(answers);
600
+ const entry = ctx.recorded[account];
601
+ return [
602
+ 'commits as ' + (entry ? entry.name + ' <' + entry.email + '>' : account),
603
+ 'pushes as ' + (ctx.credentialPinned ? account : 'your own sign-in for this host (repown pins it on GitHub only)'),
604
+ 'guard ' + guardState(ctx),
605
+ ...upstreamSettled(ctx),
606
+ ];
607
+ }
608
+ function upstreamSettled(ctx) {
609
+ const text = upstreamText(ctx.upstream.tracked, ctx.upstream.enabled);
610
+ return text === null ? [] : ['upstream ' + text];
611
+ }
612
+ function ghOffer(account, ctx) {
613
+ if (!otherGh(account, ctx))
614
+ return null;
615
+ return inGh(account, ctx) ? 'Make ' + account + " gh's active account" : 'Sign in to gh as ' + account;
616
+ }
617
+ function otherGh(account, ctx) {
618
+ if (ctx.host !== 'github' || !ctx.gh?.ok || !ctx.gh.value.active)
619
+ return false;
620
+ return lower(ctx.gh.value.active) !== lower(account);
621
+ }
622
+ function guardState(ctx) {
623
+ if (ctx.redirected)
624
+ return 'not repown\'s: core.hooksPath sends hooks elsewhere';
625
+ if (ctx.guard === 'foreign')
626
+ return 'not repown\'s: another tool owns the pre-push hook';
627
+ return ctx.guard === 'on' ? 'on: every push is checked before it leaves' : 'off: turn it on with repown guard on';
628
+ }
629
+ function notes(answers, ctx) {
630
+ const account = accountOf(answers);
631
+ const lines = [];
632
+ const pin = pinNote(account, ctx);
633
+ if (pin)
634
+ lines.push(pin);
635
+ const guard = guardNote(answers, ctx);
636
+ if (guard)
637
+ lines.push(guard);
638
+ const guarded = answers['guard'] === true || ctx.guard === 'on';
639
+ if (guarded && ownerForeign(account, ctx) && answers['allowOwner'] !== true) {
640
+ lines.push('Warning: the push guard will refuse pushes to "' + ctx.owner + '". To allow them later: ' +
641
+ 'git config --local --add repown.allowOwner ' + shellWord(ctx.owner));
642
+ }
643
+ if (ctx.ghIsHelper && answers['fix'] !== true && ctx.credentialPinned) {
644
+ lines.push('Note: gh is still git\'s credential helper, so pushes sign in as gh\'s active account, not ' + account + '.');
645
+ }
646
+ return lines;
647
+ }
648
+ /** What pinning changes for a clone pinned already: another account, or settings that drifted. */
649
+ function pinNote(account, ctx) {
650
+ if (!ctx.pinned)
651
+ return null;
652
+ if (lower(ctx.pinned) !== lower(account)) {
653
+ return 'This clone moves from ' + ctx.pinned + ' to ' + account + ': its next commits and pushes use ' + account +
654
+ '. Commits already made keep their author.';
655
+ }
656
+ return ctx.pinIntact ? null : 'This clone\'s settings differ from what is recorded for ' + account + ': pinning again restores them.';
657
+ }
658
+ /** What happens to the guard, when no step says it already. */
659
+ function guardNote(answers, ctx) {
660
+ if (ctx.redirected)
661
+ return 'The push guard stays off: core.hooksPath sends this clone\'s hooks elsewhere (see: repown guard status).';
662
+ if (ctx.guard === 'foreign') {
663
+ return 'The push guard stays off: another tool (husky, for example) owns this clone\'s pre-push hook. ' +
664
+ 'To keep the check, call repown guard check from that hook (HOW-IT-WORKS card 10).';
665
+ }
666
+ if (ctx.guard === 'on')
667
+ return 'The push guard is already on in this clone.';
668
+ return answers['guard'] === true ? null
669
+ : 'The push guard stays off: pushes are not checked (turn it on later: repown guard on).';
670
+ }
671
+ // ------------------------------------------------- what one step would change
672
+ /** The config lines, or the gh action, a planned command writes. Pure. */
673
+ export function changesOf(argv, answers, ctx) {
674
+ if (argv[0] === 'accounts')
675
+ return [registryChange(answers)];
676
+ if (argv[0] === 'git')
677
+ return [gitChange(argv)];
678
+ if (argv[0] === 'fix')
679
+ return fixChanges(ctx);
680
+ if (argv[0] === 'guard')
681
+ return [guardChange(ctx)];
682
+ return useChanges(argv, answers, ctx);
683
+ }
684
+ /** The confirmation shown before a step in step-by-step mode. */
685
+ export function briefOf(planned, answers, ctx) {
686
+ const command = formatCommand(planned.argv);
687
+ return {
688
+ changes: changesOf(planned.argv, answers, ctx).map(printable),
689
+ why: printable(planned.what),
690
+ command,
691
+ initial: stepDefault(command),
692
+ };
693
+ }
694
+ function registryChange(answers) {
695
+ const account = accountOf(answers);
696
+ const name = String(answers['name'] ?? '');
697
+ const email = String(answers['email'] ?? '');
698
+ return 'this machine\'s account registry: ' + account + ' = ' + name + ' ' + email;
699
+ }
700
+ function gitChange(argv) {
701
+ if (argv.includes('push.autoSetupRemote'))
702
+ return 'push.autoSetupRemote = true';
703
+ return 'repown.allowOwner += ' + (argv.at(-1) ?? '');
704
+ }
705
+ function fixChanges(ctx) {
706
+ return (ctx.fixLines ?? []).filter((line) => line.trim() !== '');
707
+ }
708
+ function guardChange(ctx) {
709
+ const hook = ctx.hookPath ?? 'this clone\'s pre-push hook';
710
+ return 'pre-push hook: ' + hook + ' runs repown guard check';
711
+ }
712
+ function useChanges(argv, answers, ctx) {
713
+ const keys = ctx.credentialPinned ? ctx.credentialKeys : [];
714
+ const lines = pinWrites(identityOf(answers, ctx), keys).map(([key, value]) => key + ' = ' + value);
715
+ const gh = ghChange(argv, answers, ctx);
716
+ return gh ? [...lines, gh] : lines;
717
+ }
718
+ function identityOf(answers, ctx) {
719
+ return { name: nameOf(answers, ctx) ?? '', email: emailOf(answers, ctx) ?? '', account: accountOf(answers) };
720
+ }
721
+ function ghChange(argv, answers, ctx) {
722
+ if (!argv.includes('--gh'))
723
+ return null;
724
+ const account = accountOf(answers);
725
+ if (inGh(account, ctx))
726
+ return 'gh: switch the active account to ' + account;
727
+ return 'gh: sign in as ' + account + ' (opens a browser)';
728
+ }