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.
@@ -0,0 +1,148 @@
1
+ // The start screen: a summary of this folder, then one menu. Each action prints
2
+ // the command it stands for and runs that command's own run(). Loaded only
3
+ // through the runner start.ts returns, so a typed command never imports it.
4
+ //
5
+ // Quit exits 0. Esc and Ctrl-C exit 130, the same cancel setup uses. Neither writes.
6
+ import fixCommand from "../commands/fix.js";
7
+ import doctorCommand from "../commands/doctor.js";
8
+ import accountsGroup from "../commands/accounts.js";
9
+ import { COMMANDS } from "../program.js";
10
+ import { parseArgs } from "../ui/args.js";
11
+ import { specFor } from "../ui/command.js";
12
+ import { loadEntries } from "../ui/dispatch.js";
13
+ import * as out from "../ui/format.js";
14
+ import { renderTopHelp } from "../ui/help.js";
15
+ import { BACK, CANCEL } from "./engine.js";
16
+ import { readHome } from "./home-context.js";
17
+ import { BACK as HOME_BACK, MENU, commandFor, homeNote, listedClones, menuItems, summaryLines } from "./home-flow.js";
18
+ import { BACK_LABEL, BUSY, CANCELLED, LOGIN_HINT, LOGIN_MESSAGE, QUIT, WHAT_NEXT, WHICH_CLONE, homeTitle } from "./home-text.js";
19
+ import { formatCommand, loginProblem, printable } from "./setup-flow.js";
20
+ import { choosePrompter, runSetup } from "./setup-run.js";
21
+ const CANCELLED_CODE = 130;
22
+ const LOGIN_STEP = {
23
+ id: 'login', kind: 'text', message: LOGIN_MESSAGE, hint: LOGIN_HINT, flag: '<account>',
24
+ validate: (value) => loginProblem(String(value)),
25
+ };
26
+ const LOGIN_ASKED = { initial: undefined, choices: [], detail: undefined, canGoBack: true };
27
+ export async function runHome(deps = {}) {
28
+ const prompter = deps.prompter ?? await choosePrompter();
29
+ try {
30
+ return await openHome(prompter, deps);
31
+ }
32
+ finally {
33
+ prompter.close();
34
+ }
35
+ }
36
+ async function openHome(prompter, deps) {
37
+ const cwd = deps.cwd ?? process.cwd();
38
+ prompter.intro?.(homeTitle(printable(cwd)));
39
+ prompter.busy?.(BUSY);
40
+ const home = await (deps.read ?? readHome)(cwd);
41
+ showLines(prompter, summaryLines(home));
42
+ const note = homeNote(home);
43
+ if (note)
44
+ prompter.note(note);
45
+ return chooseNext(prompter, home);
46
+ }
47
+ async function chooseNext(prompter, home) {
48
+ for (;;) {
49
+ const picked = await prompter.choose(WHAT_NEXT, menuItems(home));
50
+ if (picked === CANCEL)
51
+ return finish(prompter, CANCELLED, CANCELLED_CODE);
52
+ const code = await dispatchChoice(picked, prompter, home);
53
+ if (code !== null)
54
+ return code;
55
+ }
56
+ }
57
+ async function dispatchChoice(picked, prompter, home) {
58
+ if (picked === MENU.quit)
59
+ return finish(prompter, QUIT, 0);
60
+ if (picked === MENU.help)
61
+ return showTopHelp(prompter);
62
+ if (picked === MENU.setup)
63
+ return pickClone(prompter, home);
64
+ if (picked === MENU.fix)
65
+ return runOwn(prompter, fixCommand, [], commandFor({ kind: 'fix' }));
66
+ if (picked === MENU.doctor)
67
+ return runOwn(prompter, doctorCommand, [], commandFor({ kind: 'doctor' }));
68
+ if (picked === MENU.account)
69
+ return recordAccount(prompter);
70
+ return finish(prompter, QUIT, 0);
71
+ }
72
+ async function pickClone(prompter, home) {
73
+ const list = listedClones(home);
74
+ if (list.more)
75
+ showLines(prompter, [list.more]);
76
+ const options = [...list.clones, { value: HOME_BACK, label: BACK_LABEL }];
77
+ const picked = await prompter.choose(WHICH_CLONE, options);
78
+ if (picked === CANCEL)
79
+ return finish(prompter, CANCELLED, CANCELLED_CODE);
80
+ if (picked === HOME_BACK)
81
+ return null;
82
+ return runInClone(prompter, picked);
83
+ }
84
+ async function runInClone(prompter, cwd) {
85
+ const argv = commandFor({ kind: 'setup', path: cwd });
86
+ handOver(prompter, argv);
87
+ return runSetup(setupArgs(cwd), { interactive: true, prompter });
88
+ }
89
+ async function recordAccount(prompter) {
90
+ const login = await askLogin(prompter);
91
+ if (login === CANCEL)
92
+ return finish(prompter, CANCELLED, CANCELLED_CODE);
93
+ if (login === BACK)
94
+ return null;
95
+ const argv = commandFor({ kind: 'account', login });
96
+ return runOwn(prompter, accountsGroup.actions['add'], ['--', login], argv);
97
+ }
98
+ async function askLogin(prompter) {
99
+ for (;;) {
100
+ const reply = await prompter.ask(LOGIN_STEP, LOGIN_ASKED);
101
+ if (reply === CANCEL || reply === BACK)
102
+ return reply;
103
+ const problem = loginProblem(String(reply));
104
+ if (!problem)
105
+ return String(reply).trim();
106
+ prompter.note(problem);
107
+ }
108
+ }
109
+ async function runOwn(prompter, command, tokens, argv) {
110
+ handOver(prompter, argv);
111
+ prompter.suspend?.();
112
+ const parsed = parseArgs(tokens, specFor(command));
113
+ if (!parsed.ok) {
114
+ out.fail('repown', parsed.error);
115
+ return 2;
116
+ }
117
+ return command.run(parsed.value);
118
+ }
119
+ function setupArgs(cwd) {
120
+ return { positional: [], flags: new Map([['cwd', cwd]]) };
121
+ }
122
+ function finish(prompter, message, code) {
123
+ prompter.outro?.(message, code === CANCELLED_CODE);
124
+ return code;
125
+ }
126
+ function showLines(prompter, lines) {
127
+ if (prompter.show) {
128
+ prompter.show(lines);
129
+ return;
130
+ }
131
+ for (const line of lines)
132
+ out.line(' ' + line);
133
+ }
134
+ /** Closes the start screen's frame on the command it hands over to. */
135
+ function handOver(prompter, argv) {
136
+ const line = '> ' + formatCommand(argv);
137
+ if (prompter.outro)
138
+ prompter.outro(line);
139
+ else
140
+ out.detail(line);
141
+ }
142
+ async function showTopHelp(prompter) {
143
+ handOver(prompter, ['--help']);
144
+ const entries = await loadEntries(COMMANDS);
145
+ for (const line of renderTopHelp(entries))
146
+ out.line(line);
147
+ return 0;
148
+ }
@@ -0,0 +1,50 @@
1
+ // The words on the start screen, in one place, so the summary and both prompters
2
+ // say the same thing. What is shown when comes from home-flow.ts.
3
+ import { displayPath } from "../ui/format.js";
4
+ export const WHAT_NEXT = 'What next?';
5
+ export const WHICH_CLONE = 'Which clone?';
6
+ export const SETUP_CLONE = 'Set up a clone found here';
7
+ export const STOP_GH = 'Stop gh serving credentials';
8
+ export const RECORD_ACCOUNT = 'Record an account';
9
+ export const CHECK_MACHINE = 'Check this machine';
10
+ export const SHOW_HELP = 'Show help';
11
+ export const QUIT = 'Quit';
12
+ export const BACK_LABEL = '← Back';
13
+ export const BUSY = 'Reading this folder';
14
+ export const CD_NOTE = 'cd into a clone (or git clone one), then run repown';
15
+ export const NONE_RECORDED = 'none recorded';
16
+ export const HELPER_LINE = 'gh serves git\'s credentials: run repown fix';
17
+ export const HINT_FIX = 'repown fix';
18
+ export const HINT_ACCOUNT = 'repown accounts add';
19
+ export const HINT_DOCTOR = 'repown doctor';
20
+ export const NOT_SET_UP = 'not set up';
21
+ export const SET_UP = 'set up';
22
+ export const LOGIN_MESSAGE = 'The account\'s user name (login)';
23
+ export const LOGIN_HINT = 'the name you sign in with, e.g. octocat; not your email address';
24
+ export const CANCELLED = 'Cancelled: nothing was changed.';
25
+ export function homeTitle(cwd) {
26
+ return 'repown · not a clone: ' + displayPath(cwd);
27
+ }
28
+ export function recordedLine(names) {
29
+ return names.length + ' recorded: ' + names.join(', ');
30
+ }
31
+ /** Entries the registry file has, but that could not be read as accounts. */
32
+ export function unreadableLine(recorded, unreadable, path) {
33
+ const tail = unreadable + ' unreadable in ' + path + ': run repown accounts list';
34
+ return recorded === 0 ? tail : recorded + ' recorded, ' + tail;
35
+ }
36
+ export function couldNotRead(path) {
37
+ return 'could not read ' + path;
38
+ }
39
+ export function clonesNone(depth) {
40
+ return 'none below this folder (' + depth + ' levels)';
41
+ }
42
+ export function clonesSome(total, pending, ready) {
43
+ return total + ' below this folder: ' + pending + ' not set up, ' + ready + ' set up';
44
+ }
45
+ export function setupHint(pending, total) {
46
+ return pending > 0 ? pending + ' not set up' : total + ' set up';
47
+ }
48
+ export function moreClones(count) {
49
+ return 'and ' + count + ' more: repown scan';
50
+ }
@@ -20,8 +20,9 @@ export function plainPrompter(streams) {
20
20
  ask: (step, asked) => askStep(wide(), step, asked),
21
21
  review: (review) => showReview(session.io(), review, width),
22
22
  pickStep: (steps) => pickPlain(session.io(), steps),
23
- note: (message) => { for (const line of wrap(message, width))
24
- session.io().say(' ' + line); },
23
+ choose: (message, options) => choosePlain(session.io(), message, options),
24
+ note: (message) => sayIndented(session.io(), wrap(message, width)),
25
+ show: (lines) => sayIndented(session.io(), lines.flatMap((text) => wrap(text, width))),
25
26
  close: () => session.close(),
26
27
  outro: (message) => session.io().say(message),
27
28
  confirmStep: (confirm) => askStepConfirm(wide(), confirm),
@@ -50,6 +51,10 @@ function plainSession(streams) {
50
51
  function openReadline(streams, terminal) {
51
52
  return createInterface({ input: streams.input, output: streams.output, terminal });
52
53
  }
54
+ function sayIndented(io, lines) {
55
+ for (const line of lines)
56
+ io.say(' ' + line);
57
+ }
53
58
  /** On a terminal, readline shows the prompt, so it can redraw it while the line is edited. */
54
59
  function ioFor(rl, output, terminal) {
55
60
  const lines = queue(rl);
@@ -107,6 +112,12 @@ async function askStep(io, step, asked) {
107
112
  return BACK;
108
113
  return line || (typeof initial === 'string' ? initial : '');
109
114
  }
115
+ async function choosePlain(io, message, options) {
116
+ io.say(message);
117
+ const labels = options.map((option) => option.label + (option.hint ? ' -- ' + option.hint : ''));
118
+ const index = await pickNumber(io, labels, 1);
119
+ return index === CANCEL ? CANCEL : options[index].value;
120
+ }
110
121
  async function pickPlain(io, steps) {
111
122
  io.say(PICK_QUESTION);
112
123
  const index = await pickNumber(io, [...steps.map((step) => step.message), BACK_TO_REVIEW], 1);
@@ -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(),