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.
@@ -2,68 +2,132 @@
2
2
  //
3
3
  // Pinning does not rewrite them (ADR-013). The guard refuses them at push
4
4
  // (ADR-002, ADR-011), so `use` and setup's review say so first, with a copyable
5
- // `git rebase` onto the parent of the oldest of those commits (`--root` when it
6
- // has none). The identities come from `git log` through Git.identitiesIn
7
- // (`--no-show-signature`). The base is `rev-list` and `rev-parse` on Git.
5
+ // `git rebase` onto the parent of the oldest of those commits by another address
6
+ // (`--root` when it has none), so the user's own commits before it are left alone.
7
+ // The identities come from `git log` through Git.identitiesIn (`--no-show-signature`),
8
+ // the parents from Git.firstParentsIn.
9
+ // Where the branch pushes may have no remote-tracking ref at all; then the range can
10
+ // hold published commits, and the rebase is offered only for when it has none of
11
+ // them (push-destination.ts, ADR-025).
8
12
  // scan's address totals are a different question: every ref, counts only, and
9
13
  // setup loads them only for the guard question.
10
14
  import { ok } from "./result.js";
15
+ import { unknownDestination } from "./push-destination.js";
16
+ import { shellWord } from "./guard/check.js";
11
17
  const ADDRESS_CAP = 3;
12
- const AMEND = '--exec "git commit --amend --no-edit --reset-author --allow-empty"';
18
+ /** The one re-author command: the advice prints it, and `repown reauthor` runs it. */
19
+ export const AMEND_COMMAND = 'git commit --amend --no-edit --reset-author --allow-empty';
20
+ const AMEND = '--exec "' + AMEND_COMMAND + '"';
13
21
  export async function readUnpushed(git) {
14
22
  const head = await git.currentBranch();
15
23
  if (head?.kind !== 'branch')
16
24
  return quiet(null);
17
25
  const commits = await commitsOf(git);
18
26
  if (!commits.ok || commits.value.length === 0)
19
- return { branch: head.name, commits, rebaseBase: null };
20
- return { branch: head.name, commits, rebaseBase: await rebaseBase(git) };
27
+ return { branch: head.name, commits, unknown: null };
28
+ return { branch: head.name, commits, unknown: await unknownDestination(git, head.name) };
21
29
  }
22
30
  function quiet(branch) {
23
- return { branch, commits: ok([]), rebaseBase: null };
24
- }
25
- /** Parent of the oldest unpushed commit, or `--root` when that commit has none. */
26
- async function rebaseBase(git) {
27
- const oldest = await git.oldestIn(['HEAD', '--not', '--remotes']);
28
- if (!oldest)
29
- return null;
30
- return (await git.parentShort(oldest)) ?? '--root';
31
+ return { branch, commits: ok([]), unknown: null };
31
32
  }
32
33
  /** No commit yet is an empty list. A log git could not print stays an error. */
33
34
  async function commitsOf(git) {
34
35
  if (!await git.hasCommit('HEAD'))
35
36
  return ok([]);
36
- const found = await git.identitiesIn(['HEAD', '--not', '--remotes']);
37
+ const range = ['HEAD', '--not', '--remotes'];
38
+ const [found, parents] = await Promise.all([git.identitiesIn(range), git.firstParentsIn(range)]);
37
39
  if (!found.ok)
38
40
  return found;
39
- return ok(found.value.map(brief));
40
- }
41
- function brief(commit) {
42
- return { authorEmail: commit.authorEmail, committerEmail: commit.committerEmail };
43
- }
44
- /** Lines to show. Empty when there is nothing to say. The first is the fact; any other is how to fix it. */
45
- export function unpushedLines(fact, email) {
41
+ if (!parents.ok)
42
+ return parents;
43
+ return ok(found.value.map((commit) => brief(commit, parents.value.get(commit.sha) ?? null)));
44
+ }
45
+ function brief(commit, parent) {
46
+ return { authorEmail: commit.authorEmail, committerEmail: commit.committerEmail, parent };
47
+ }
48
+ /**
49
+ * Lines to show. Empty when there is nothing to say. The first is the fact; any other is how
50
+ * to fix it. `account` is what to pin again to count again. `guarded` false: the guard is off, so
51
+ * the first line says they push as they are rather than that the guard will refuse them.
52
+ */
53
+ export function unpushedLines(fact, email, account, guarded = true) {
46
54
  if (fact.branch === null)
47
55
  return [];
48
56
  if (!fact.commits.ok)
49
57
  return [unread(fact.branch, fact.commits.error)];
50
- return foreignLines(fact.branch, fact.commits.value, email, fact.rebaseBase);
51
- }
52
- function foreignLines(branch, commits, email, base) {
53
- const found = collect(commits, fold(email));
58
+ const found = collect(fact.commits.value, fold(email));
54
59
  if (found.count === 0)
55
60
  return [];
56
- return [sentence(branch, found), ...reauthorLine(found.count, base)];
57
- }
58
- function reauthorLine(count, base) {
59
- if (!base)
60
- return [];
61
- const them = count === 1 ? 'it' : 'them';
62
- return ['re-author ' + them + ': git rebase ' + base + ' ' + AMEND + ', or pin that address'];
61
+ return [sentence(fact.branch, found, guarded), ...advice(fact, found, account)];
62
+ }
63
+ /** How many unpushed commits carry an address other than `email`. Zero when they could not be read. */
64
+ export function foreignCount(fact, email) {
65
+ return fact.commits.ok ? collect(fact.commits.value, fold(email)).count : 0;
66
+ }
67
+ /** The addresses other than `email` on those commits, as they appear. Empty when they could not be read. */
68
+ export function foreignAddresses(fact, email) {
69
+ return fact.commits.ok ? collect(fact.commits.value, fold(email)).addresses : [];
70
+ }
71
+ /** Behind an unknown destination the rebase is right only when it has none of these commits. */
72
+ function advice(fact, found, account) {
73
+ const rebase = reauthorLine(found);
74
+ if (!fact.unknown)
75
+ return rebase;
76
+ const holder = holderOf(fact.unknown);
77
+ return [unknownLine(fact.unknown, account), ...rebase.map((line) => 'if ' + holder + ' has none of them, ' + line)];
78
+ }
79
+ function holderOf(unknown) {
80
+ return unknown.kind === 'remote' || unknown.kind === 'pushurl' ? show(unknown.name) : 'it';
81
+ }
82
+ /** The guard excludes what the pushed branch's remote tip has, not everything the remote holds. */
83
+ const GUARD = ' (the guard skips any already on the branch you push to)';
84
+ const THERE = ', so some of these may already be there' + GUARD;
85
+ function unknownLine(unknown, account) {
86
+ switch (unknown.kind) {
87
+ case 'remote': return trackingLine(unknown.name, account);
88
+ case 'pushurl': return show(unknown.name) + ' pushes to another URL than it fetches from' + THERE;
89
+ case 'url': return urlLine(unknown.key, unknown.remote, account);
90
+ case 'unnamed': return 'this branch pushes to "' + show(unknown.name) + '", which is not a remote here' + THERE;
91
+ case 'unread': return 'the remotes could not be read, so some of these may already be on one' + GUARD;
92
+ }
93
+ }
94
+ function trackingLine(name, account) {
95
+ const lead = show(name) + ' has no remote-tracking refs, so some of these may already be on it' + GUARD;
96
+ if (!copyable(name))
97
+ return lead;
98
+ return lead + ': git fetch ' + shellWord(show(name)) + ', ' + recount(account);
99
+ }
100
+ function urlLine(key, remote, account) {
101
+ const lead = 'this branch pushes to a URL, not a remote' + THERE;
102
+ if (!remote || !copyable(remote))
103
+ return lead;
104
+ const word = shellWord(show(remote));
105
+ return lead + ': git config --local ' + shellWord(show(key)) + ' ' + word + ', git fetch ' + word + ', ' + recount(account);
106
+ }
107
+ function recount(account) {
108
+ return 'then repown use ' + shellWord(show(account)) + ' to count again';
109
+ }
110
+ /** Quoting keeps a shell from splitting a word, not git from reading `-x` as an option. */
111
+ function copyable(word) {
112
+ return !word.startsWith('-');
113
+ }
114
+ /** Pinning is an alternative only when one address made them all. */
115
+ function reauthorLine(found) {
116
+ const them = found.count === 1 ? 'it' : 'them';
117
+ const pin = found.addresses.length === 1 ? ', or pin that address' : '';
118
+ return ['re-author ' + them + ': git rebase ' + found.base + ' ' + AMEND + pin];
63
119
  }
64
120
  function collect(commits, wanted) {
65
121
  const foreign = commits.filter((commit) => !own(commit, wanted));
66
- return { count: foreign.length, addresses: distinct(foreign, wanted) };
122
+ return { count: foreign.length, addresses: distinct(foreign, wanted), base: foreign.at(-1)?.parent ?? '--root' };
123
+ }
124
+ /** Author and committer are both `email`, in any case. */
125
+ export function isOwn(commit, email) {
126
+ return own(commit, fold(email));
127
+ }
128
+ /** The addresses other than `email` on these commits, each once, as first spelled. */
129
+ export function otherAddresses(commits, email) {
130
+ return distinct(commits, fold(email));
67
131
  }
68
132
  function own(commit, wanted) {
69
133
  return fold(commit.authorEmail) === wanted && fold(commit.committerEmail) === wanted;
@@ -86,12 +150,13 @@ function remember(seen, address, wanted) {
86
150
  function fold(address) {
87
151
  return address.toLowerCase();
88
152
  }
89
- function sentence(branch, found) {
90
- const noun = found.count === 1 ? '1 commit' : found.count + ' commits';
91
- const verb = found.count === 1 ? 'is' : 'are';
92
- const them = found.count === 1 ? 'it' : 'them';
93
- return noun + ' on ' + show(branch) + ' not on any remote ' + verb + ' by ' +
94
- list(found.addresses) + '; the guard will refuse ' + them;
153
+ function sentence(branch, found, guarded) {
154
+ const one = found.count === 1;
155
+ const noun = one ? '1 commit' : found.count + ' commits';
156
+ const guard = guarded ? 'the guard will refuse ' + (one ? 'it' : 'them')
157
+ : 'the guard is off, so ' + (one ? 'it pushes as it is' : 'they push as they are');
158
+ return noun + ' on ' + show(branch) + ' not on any remote ' + (one ? 'is' : 'are') + ' by ' +
159
+ list(found.addresses) + '; ' + guard;
95
160
  }
96
161
  function list(addresses) {
97
162
  const shown = addresses.slice(0, ADDRESS_CAP).map(show);
@@ -103,8 +168,11 @@ function unread(branch, error) {
103
168
  return 'commits on ' + show(branch) + ' not on any remote could not be read (' +
104
169
  show(error) + '), so repown can\'t say whether the guard will refuse them';
105
170
  }
106
- /** Control characters could redraw the terminal around a line taken from a commit. */
171
+ /**
172
+ * Control characters could redraw the terminal around a line taken from a commit, and
173
+ * bidi or zero-width ones make a copyable command read differently from what it pastes.
174
+ */
107
175
  function show(text) {
108
- const cleaned = text.replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
176
+ const cleaned = text.replace(/[\x00-\x1f\x7f-\x9f\u200b-\u200f\u202a-\u202e\u2066-\u2069\u2028\u2029\ufeff]/g, '?');
109
177
  return cleaned.length > 0 ? cleaned : '(none)';
110
178
  }
@@ -0,0 +1,14 @@
1
+ // The command table. cli.ts starts the program; the start screen's Show help
2
+ // loads this same table. Importing this file does not run repown.
3
+ export const COMMANDS = {
4
+ status: async () => (await import("./commands/status.js")).default,
5
+ use: async () => (await import("./commands/use.js")).default,
6
+ off: async () => (await import("./commands/off.js")).default,
7
+ doctor: async () => (await import("./commands/doctor.js")).default,
8
+ fix: async () => (await import("./commands/fix.js")).default,
9
+ reauthor: async () => (await import("./commands/reauthor.js")).default,
10
+ guard: async () => (await import("./commands/guard.js")).default,
11
+ accounts: async () => (await import("./commands/accounts.js")).default,
12
+ scan: async () => (await import("./commands/scan.js")).default,
13
+ setup: async () => (await import("./commands/setup.js")).default,
14
+ };
@@ -11,10 +11,14 @@ import { renderHelpFor } from "./help.js";
11
11
  import { suggest } from "./suggest.js";
12
12
  import { ok, err } from "../core/result.js";
13
13
  import * as out from "./format.js";
14
+ /** Every command the program declares, in declaration order. Help uses this, and so can a runner. */
15
+ export async function loadEntries(commands) {
16
+ const names = Object.keys(commands);
17
+ const loaded = await Promise.all(names.map((name) => commands[name]()));
18
+ return new Map(names.map((name, index) => [name, loaded[index]]));
19
+ }
14
20
  async function loadAll(program) {
15
- const names = Object.keys(program.commands);
16
- const entries = await Promise.all(names.map((name) => program.commands[name]()));
17
- return new Map(names.map((name, index) => [name, entries[index]]));
21
+ return loadEntries(program.commands);
18
22
  }
19
23
  function reportUsageError(tag, message) {
20
24
  const [first, ...rest] = message.split('\n');
@@ -122,6 +126,8 @@ export async function runProgram(program, argv) {
122
126
  if (argv[0] === 'help')
123
127
  return runHelp(program, argv.slice(1));
124
128
  const words = await bareArgv(program, argv);
129
+ if (typeof words === 'function')
130
+ return words();
125
131
  if (words === 'help')
126
132
  return runHelp(program, []);
127
133
  if (words.length === 0 && program.defaultCommand === undefined)
@@ -133,11 +139,13 @@ export async function runProgram(program, argv) {
133
139
  }
134
140
  return dispatch(program, top.value);
135
141
  }
136
- /** Empty argv with a chooser becomes that command, or `'help'` for the top help. */
142
+ /** Empty argv with a chooser becomes that command, `'help'` for the top help, or a runner. */
137
143
  async function bareArgv(program, argv) {
138
144
  if (argv.length > 0 || program.chooseDefault === undefined)
139
145
  return argv;
140
146
  const chosen = await program.chooseDefault();
147
+ if (typeof chosen === 'function')
148
+ return chosen;
141
149
  return chosen === 'help' ? 'help' : [chosen];
142
150
  }
143
151
  /** The whole life of the process: run, set the exit code, and report a crash as a failure. */
package/dist/ui/format.js CHANGED
@@ -75,6 +75,14 @@ export function heading(text) {
75
75
  export function dim(text) {
76
76
  return paint(process.stdout, 'dim', text);
77
77
  }
78
+ /**
79
+ * Control characters, and the invisible, line-breaking or direction-changing ones, as visible
80
+ * escapes: text read from git, a remote URL or a commit must neither redraw the screen nor
81
+ * read as another name.
82
+ */
83
+ export function printable(text) {
84
+ return text.replace(/[\x00-\x1f\x7f-\x9f\xad\u061c\u180e\u200b-\u200f\u202a-\u202e\u2028\u2029\u2060-\u2064\u2066-\u2069\ufeff\ufff9-\ufffb\u{e0000}-\u{e007f}]/gu, (char) => '\\u' + char.codePointAt(0).toString(16).padStart(4, '0'));
85
+ }
78
86
  /** Shown to a person. Windows uses native separators; any other platform is unchanged. */
79
87
  export function displayPath(path) {
80
88
  if (process.platform !== 'win32')
package/dist/ui/help.js CHANGED
@@ -20,9 +20,10 @@ function topHeader(entries) {
20
20
  const lines = ['', ' repown <command> [options]', ''];
21
21
  for (const [name, entry] of entries)
22
22
  lines.push(' ' + name.padEnd(10) + entry.summary);
23
- lines.push('', ' Bare `repown`, in a terminal: `repown setup` in a clone that isn\'t set up, status in');
24
- lines.push(' one that is, and this help outside a clone (exit 0). Without a terminal, or with its');
25
- lines.push(' output redirected, it is always status (exit 1 outside a clone).');
23
+ lines.push('', ' Bare `repown`, with stdin, stdout and stderr all terminals: `repown setup` in a');
24
+ lines.push(' clone, and a start screen outside a clone or in a bare repository. With only');
25
+ lines.push(' stdout redirected: status in a clone, and this help outside one (exit 0). With');
26
+ lines.push(' no terminal on stdin or stderr, it is status (exit 1 outside a clone).');
26
27
  lines.push(' Run `repown help <command>` for its options.', '');
27
28
  return lines;
28
29
  }
@@ -1,6 +1,6 @@
1
1
  // The wizard drawn with @clack/prompts: arrow-key choices with a hint each, defaults,
2
2
  // a line while state is read, the review in a box. The ONLY file that imports the
3
- // library, and it is loaded with a dynamic import() by `repown setup` alone (ADR-016),
3
+ // library, and it is loaded with a dynamic import() from choosePrompter (ADR-016),
4
4
  // so no other command -- and never the pre-push hook -- depends on it.
5
5
  //
6
6
  // Everything is drawn on the stream it's given (stderr), so stdout keeps carrying only
@@ -16,20 +16,12 @@ const GO_BACK = '\u0000back';
16
16
  export function clackPrompter(streams) {
17
17
  const io = { input: streams.input, output: streams.output };
18
18
  return {
19
- ask: (step, asked) => {
20
- if (asked.detail)
21
- p.log.info(wrap(asked.detail, widthOf(io, GUTTER)).join('\n'), io);
22
- return askStep(step, asked, io);
23
- },
19
+ ask: (step, asked) => askDrawn(step, asked, io),
24
20
  review: (review) => showReview(review, io),
25
- pickStep: async (steps) => {
26
- const id = await p.select({ ...io, message: PICK_QUESTION,
27
- options: [...steps.map((step) => ({ value: step.id, label: step.message })), { value: GO_BACK, label: '← ' + BACK_TO_REVIEW }] });
28
- if (p.isCancel(id))
29
- return CANCEL;
30
- return id === GO_BACK ? BACK : id;
31
- },
21
+ pickStep: (steps) => pickClack(steps, io),
22
+ choose: (message, options) => chooseClack(message, options, io),
32
23
  note: (message) => p.log.warn(wrap(message, widthOf(io, GUTTER)).join('\n'), io),
24
+ show: (lines) => logLines(io, lines),
33
25
  confirmStep: (confirm) => showStep(confirm, io),
34
26
  close: () => { },
35
27
  intro: (title) => p.intro(title, io),
@@ -40,6 +32,27 @@ export function clackPrompter(streams) {
40
32
  busy: (message) => p.log.step(message, io),
41
33
  };
42
34
  }
35
+ function askDrawn(step, asked, io) {
36
+ if (asked.detail)
37
+ p.log.info(wrap(asked.detail, widthOf(io, GUTTER)).join('\n'), io);
38
+ return askStep(step, asked, io);
39
+ }
40
+ async function pickClack(steps, io) {
41
+ const id = await p.select({ ...io, message: PICK_QUESTION, options: pickOptions(steps) });
42
+ if (p.isCancel(id))
43
+ return CANCEL;
44
+ return id === GO_BACK ? BACK : id;
45
+ }
46
+ function pickOptions(steps) {
47
+ return [...steps.map((step) => ({ value: step.id, label: step.message })), { value: GO_BACK, label: '← ' + BACK_TO_REVIEW }];
48
+ }
49
+ async function chooseClack(message, options, io) {
50
+ const value = await p.select({ ...io, message, options: options.map(choiceOption) });
51
+ return p.isCancel(value) ? CANCEL : value;
52
+ }
53
+ function choiceOption(option) {
54
+ return option.hint === undefined ? { value: option.value, label: option.label } : option;
55
+ }
43
56
  /**
44
57
  * Columns to leave free. clack wraps a list question 13 columns short of the window and
45
58
  * a box's text 6 short, but never a text question's hint or a log line; wrapping every
@@ -101,10 +114,12 @@ function messageOf(step, io, extra) {
101
114
  return [step.message, ...(hint ? wrap(hint, widthOf(io, GUTTER)) : [])].join('\n' + gutter);
102
115
  }
103
116
  async function showStep(confirm, io) {
104
- const lines = stepConfirmLines(confirm).flatMap((text) => wrap(text, widthOf(io, GUTTER)));
105
- p.log.message(lines.join('\n'), io);
117
+ logLines(io, stepConfirmLines(confirm));
106
118
  return chosen(confirm, io);
107
119
  }
120
+ function logLines(io, lines) {
121
+ p.log.message(lines.flatMap((text) => wrap(text, widthOf(io, GUTTER))).join('\n'), io);
122
+ }
108
123
  async function chosen(confirm, io) {
109
124
  const choice = await p.select({ ...io, message: RUN_THIS_STEP, options: stepOptions(), initialValue: confirm.initial });
110
125
  return p.isCancel(choice) ? CANCEL : choice;
@@ -9,6 +9,9 @@
9
9
  // can drive it without a terminal.
10
10
  export const BACK = Symbol('back');
11
11
  export const CANCEL = Symbol('cancel');
12
+ function isResume(choice) {
13
+ return choice === 'account' || choice === 'gh' || choice === 'reauthor';
14
+ }
12
15
  /** Asks every reachable step from `pass.start` on, with a history for going back. */
13
16
  export async function runFlow(flow, context, pass, prompter) {
14
17
  const answers = { ...pass.answers };
@@ -137,7 +140,7 @@ function openingChoice(scene, choice) {
137
140
  const stopped = stoppedChoice(choice);
138
141
  if (stopped)
139
142
  return { outcome: stopped, pass: scene.pass };
140
- if (choice === 'account' || choice === 'gh')
143
+ if (isResume(choice))
141
144
  return { outcome: null, pass: resumed(scene, choice, null) };
142
145
  if (choice === 'edit')
143
146
  scene.prompter.note('nothing has been asked yet');
@@ -164,7 +167,7 @@ function resumed(scene, choice, walk) {
164
167
  function branchAnswers(choice, freshAnswers, walk) {
165
168
  if (!walk)
166
169
  return freshAnswers;
167
- return choice === 'gh' ? { ...walk.answers, gh: true } : walk.answers;
170
+ return choice === 'account' ? walk.answers : { ...walk.answers, [choice]: true };
168
171
  }
169
172
  async function takePass(flow, context, pass, prompter) {
170
173
  const walk = await runFlow(flow, context, pass, prompter);
@@ -180,7 +183,7 @@ async function afterReview(scene, walk) {
180
183
  const direct = directChoice(choice, shown, walk.answers);
181
184
  if (direct)
182
185
  return { outcome: direct, pass: scene.pass };
183
- if (choice === 'account' || choice === 'gh')
186
+ if (isResume(choice))
184
187
  return { outcome: null, pass: resumed(scene, choice, walk) };
185
188
  return restart(scene, walk, choice);
186
189
  }
@@ -0,0 +1,101 @@
1
+ // What the start screen reads before it asks: the registry, whether gh is git's
2
+ // credential helper, and the clones below this folder. Read-only. A directory
3
+ // it cannot list is skipped; `repown scan` is the command that reports those.
4
+ import { readdir } from 'node:fs/promises';
5
+ import { join, relative, resolve, sep } from 'node:path';
6
+ import { Git } from "../core/git.js";
7
+ import { inspectRepo } from "../core/inspect.js";
8
+ import { planRepair } from "../core/credential/repair.js";
9
+ import { loadRegistry } from "../core/registry.js";
10
+ import { identityProblems } from "../commands/status.js";
11
+ import { CONCURRENCY, discover, mapLimited } from "../commands/scan.js";
12
+ /** How many levels below this folder the start screen looks. `repown scan` looks further. */
13
+ export const HOME_DEPTH = 2;
14
+ export async function readHome(cwd, deps = {}) {
15
+ const [registry, ghIsHelper, clones] = await Promise.all([
16
+ registryOf(deps), helperOf(cwd, deps), clonesOf(cwd, deps),
17
+ ]);
18
+ return { cwd: resolve(cwd), registry, ghIsHelper, clones };
19
+ }
20
+ function registryOf(deps) {
21
+ return deps.registry ? deps.registry() : loadRegistry();
22
+ }
23
+ /** The same question `repown fix` previews: gh's helper entries are there to remove. */
24
+ function helperOf(cwd, deps) {
25
+ return deps.ghIsHelper ? deps.ghIsHelper(cwd) : ghHelper(cwd);
26
+ }
27
+ async function ghHelper(cwd) {
28
+ return (await planRepair(new Git(cwd))).length > 0;
29
+ }
30
+ async function clonesOf(cwd, deps) {
31
+ const found = await findClones(cwd, deps);
32
+ const described = await mapLimited(found, CONCURRENCY, (dir) => describeClone(dir, deps));
33
+ return described.filter(isClone);
34
+ }
35
+ async function findClones(cwd, deps) {
36
+ if (deps.findClones)
37
+ return deps.findClones(cwd);
38
+ if (await new Git(cwd).isBare())
39
+ return [];
40
+ return clonesWithin(cwd, HOME_DEPTH);
41
+ }
42
+ /**
43
+ * Repositories at most `depth` levels down, counting a repository at `dir`.
44
+ * Git accepting a directory stops the walk. Git refusing one is not a clone;
45
+ * the levels still left are searched inside it. This folder is that rule at depth 0.
46
+ */
47
+ async function clonesWithin(dir, depth) {
48
+ if (depth < 0)
49
+ return [];
50
+ const found = await search(dir, depth);
51
+ const parts = await mapLimited(found, CONCURRENCY, (path) => keepOrEnter(dir, path, depth));
52
+ return parts.flat();
53
+ }
54
+ async function keepOrEnter(searched, path, budget) {
55
+ if (await new Git(path).isRepo())
56
+ return [path];
57
+ return enterRefused(path, budget - levelsBelow(searched, path));
58
+ }
59
+ /** One of `remaining` is spent stepping into `dir`; what is left is searched below it. */
60
+ async function enterRefused(dir, remaining) {
61
+ if (remaining <= 0)
62
+ return [];
63
+ const names = await childNames(dir);
64
+ const nested = await mapLimited(names, CONCURRENCY, (name) => clonesWithin(join(dir, name), remaining - 1));
65
+ return nested.flat();
66
+ }
67
+ function levelsBelow(root, path) {
68
+ const rel = relative(resolve(root), resolve(path));
69
+ return rel === '' ? 0 : rel.split(sep).length;
70
+ }
71
+ async function search(dir, depth) {
72
+ const unreadable = [];
73
+ const found = await discover({ root: dir, path: dir }, depth, unreadable, skipHomeEntry);
74
+ return found.map((entry) => entry.path);
75
+ }
76
+ /** Child directories the start screen would enter. An unlistable folder is skipped. */
77
+ async function childNames(cwd) {
78
+ try {
79
+ const entries = await readdir(cwd, { withFileTypes: true });
80
+ return entries.filter((entry) => entry.isDirectory() && !skipHomeEntry(entry.name)).map((entry) => entry.name);
81
+ }
82
+ catch {
83
+ return [];
84
+ }
85
+ }
86
+ async function describeClone(dir, deps) {
87
+ const inspect = deps.inspect ?? inspectRepo;
88
+ const repo = await inspect(new Git(dir));
89
+ if (!repo.isRepo)
90
+ return null;
91
+ return { path: resolve(dir), setUp: identityProblems(repo).length === 0 };
92
+ }
93
+ function isClone(clone) {
94
+ return clone !== null;
95
+ }
96
+ /** Dot-directories, node_modules, and on Windows AppData. Only the start screen passes this. */
97
+ function skipHomeEntry(name) {
98
+ if (name.startsWith('.') || name === 'node_modules')
99
+ return true;
100
+ return process.platform === 'win32' && name.toLowerCase() === 'appdata';
101
+ }
@@ -0,0 +1,90 @@
1
+ // Pure: the summary, the menu and the clone list, and the command an action
2
+ // stands for. Drawing and running live in home-run.ts.
3
+ import { relative } from 'node:path';
4
+ import { registryPath } from "../core/registry.js";
5
+ import { HOME_DEPTH } from "./home-context.js";
6
+ import { CD_NOTE, CHECK_MACHINE, HELPER_LINE, HINT_ACCOUNT, HINT_DOCTOR, HINT_FIX, NONE_RECORDED, NOT_SET_UP, QUIT, RECORD_ACCOUNT, SET_UP, SETUP_CLONE, SHOW_HELP, STOP_GH, clonesNone, clonesSome, couldNotRead, moreClones, recordedLine, setupHint, unreadableLine, } from "./home-text.js";
7
+ import { printable } from "./setup-flow.js";
8
+ /** Shown choices. `back` returns to the menu; the others run a command or leave. */
9
+ export const MENU = {
10
+ setup: 'setup', fix: 'fix', account: 'account', doctor: 'doctor', help: 'help', quit: 'quit',
11
+ };
12
+ export const BACK = 'back';
13
+ const LIST_CAP = 20;
14
+ export function summaryLines(home) {
15
+ const lines = [row('Accounts', accountsText(home.registry)), row('Clones', clonesText(home.clones))];
16
+ if (home.ghIsHelper)
17
+ lines.splice(1, 0, row('Helper', HELPER_LINE));
18
+ return lines;
19
+ }
20
+ export function homeNote(home) {
21
+ return home.clones.length === 0 ? CD_NOTE : null;
22
+ }
23
+ export function menuItems(home) {
24
+ return [...setupItem(home), ...fixItem(home), ...STANDING];
25
+ }
26
+ export function listedClones(home) {
27
+ const ordered = orderClones(home);
28
+ const shown = ordered.slice(0, LIST_CAP);
29
+ const rest = ordered.length - shown.length;
30
+ return { clones: shown.map((clone) => cloneChoice(home.cwd, clone)), more: rest > 0 ? moreClones(rest) : null };
31
+ }
32
+ /**
33
+ * The command the action stands for. `--cwd=<path>` is how setup's own plans spell
34
+ * it. `accounts add` puts `--` before the login, as that plan does, so a login
35
+ * that starts with a dash stays the account.
36
+ */
37
+ export function commandFor(action) {
38
+ if (action.kind === 'setup')
39
+ return ['setup', '--cwd=' + action.path];
40
+ if (action.kind === 'fix')
41
+ return ['fix'];
42
+ if (action.kind === 'account')
43
+ return ['accounts', 'add', '--', action.login];
44
+ return ['doctor'];
45
+ }
46
+ function accountsText(registry) {
47
+ if (!registry.ok)
48
+ return couldNotRead(registryPath());
49
+ return accountsSummary(registry.value);
50
+ }
51
+ function accountsSummary(registry) {
52
+ const names = Object.keys(registry.accounts).sort();
53
+ const unread = registry.unreadable.length;
54
+ if (unread > 0)
55
+ return unreadableLine(names.length, unread, registryPath());
56
+ return names.length === 0 ? NONE_RECORDED : recordedLine(names.map(printable));
57
+ }
58
+ function clonesText(clones) {
59
+ if (clones.length === 0)
60
+ return clonesNone(HOME_DEPTH);
61
+ const pending = clones.filter((clone) => !clone.setUp).length;
62
+ return clonesSome(clones.length, pending, clones.length - pending);
63
+ }
64
+ function setupItem(home) {
65
+ if (home.clones.length === 0)
66
+ return [];
67
+ const pending = home.clones.filter((clone) => !clone.setUp).length;
68
+ return [{ value: MENU.setup, label: SETUP_CLONE, hint: setupHint(pending, home.clones.length) }];
69
+ }
70
+ function fixItem(home) {
71
+ if (!home.ghIsHelper)
72
+ return [];
73
+ return [{ value: MENU.fix, label: STOP_GH, hint: HINT_FIX }];
74
+ }
75
+ const STANDING = [
76
+ { value: MENU.account, label: RECORD_ACCOUNT, hint: HINT_ACCOUNT },
77
+ { value: MENU.doctor, label: CHECK_MACHINE, hint: HINT_DOCTOR },
78
+ { value: MENU.help, label: SHOW_HELP },
79
+ { value: MENU.quit, label: QUIT },
80
+ ];
81
+ function orderClones(home) {
82
+ const rank = (clone) => (clone.setUp ? '1' : '0') + relative(home.cwd, clone.path);
83
+ return [...home.clones].sort((a, b) => rank(a).localeCompare(rank(b)));
84
+ }
85
+ function cloneChoice(cwd, clone) {
86
+ return { value: clone.path, label: printable(relative(cwd, clone.path)), hint: clone.setUp ? SET_UP : NOT_SET_UP };
87
+ }
88
+ function row(label, value) {
89
+ return label.padEnd(10) + ' ' + value;
90
+ }