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,110 @@
1
+ // The words around a review, shared by both prompters so the plain and the drawn
2
+ // screens say the same thing: the numbered steps, the closing lines, the question, its
3
+ // choices and which one Enter takes, and "Change an answer". What goes IN the review
4
+ // comes from the flow (setup-flow.ts).
5
+ /** "Change an answer": the question, and the choice that returns to the review. */
6
+ export const PICK_QUESTION = 'Which answer do you want to change?';
7
+ export const BACK_TO_REVIEW = 'Back to the review';
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. */
10
+ export function stepDefault(command) {
11
+ return changesMachine(command) ? 'skip' : 'yes';
12
+ }
13
+ export function stepOptions() {
14
+ return [
15
+ { value: 'yes', label: 'Yes' },
16
+ { value: 'skip', label: 'Skip' },
17
+ { value: 'stop', label: 'Stop' },
18
+ ];
19
+ }
20
+ /** What a step changes, why, and the command, in that order. */
21
+ export function stepConfirmLines(brief) {
22
+ return [...brief.changes, '', brief.why, '> ' + brief.command];
23
+ }
24
+ function changesMachine(command) {
25
+ return command.startsWith('repown fix');
26
+ }
27
+ /**
28
+ * The body of the review, line by line, wrapped to `width`. `command` styles each
29
+ * command line (dimmed where the prompter can draw colour), so the plain words stay
30
+ * the eye's first stop.
31
+ */
32
+ export function reviewLines(review, width = Infinity, command = (text) => text) {
33
+ const words = (text) => wrap(text, width);
34
+ // A command's continuation sits deeper, so it can't read as the next command.
35
+ const code = (text) => wrap(' ' + text, width - 2).map((line, index) => command(index ? ' ' + line : line));
36
+ if (review.settled)
37
+ return [...review.headline.flatMap(words), '', 'Nothing needs to change.', ...notesOf(review).flatMap(words)];
38
+ const steps = review.steps.flatMap((step, index) => [
39
+ ...words((index + 1) + '. ' + step.what),
40
+ ...code(step.command),
41
+ ...step.detail.flatMap(code),
42
+ ]);
43
+ return [...review.headline.flatMap(words), '', 'When you choose Run:', ...steps, ...notesOf(review).flatMap(words), '',
44
+ ...words('These are ordinary commands: run them yourself, or in a script.'),
45
+ ...words('This clone\'s settings go in its .git/config, which is never pushed.')];
46
+ }
47
+ /** The widest a line of text gets, however wide the window: longer lines are hard to read. */
48
+ export const MAX_WIDTH = 72;
49
+ /** The text width for a window `columns` wide, less `margin` for borders and gutters. */
50
+ export function textWidth(columns, margin) {
51
+ return Math.max(24, Math.min(MAX_WIDTH, (columns ?? 80) - margin));
52
+ }
53
+ /**
54
+ * One line, wrapped at spaces to `width`. Continuation lines line up under the text:
55
+ * past any indent, a "1. " step number, or a "label " column.
56
+ */
57
+ export function wrap(text, width) {
58
+ if (text.length <= width)
59
+ return [text];
60
+ const hang = ' '.repeat(/^\s*(?:\d+\. |\S+(?: \S+)? {2,})?/.exec(text)[0].length);
61
+ const lines = [];
62
+ let line = '';
63
+ for (const word of text.split(/(?<=\S) (?=\S)/)) {
64
+ if (line && line.length + 1 + word.length > width) {
65
+ lines.push(line);
66
+ line = hang + word.trimStart();
67
+ }
68
+ else
69
+ line = line ? line + ' ' + word : word;
70
+ }
71
+ return [...lines, line];
72
+ }
73
+ function notesOf(review) {
74
+ return review.notes.length > 0 ? ['', ...review.notes] : [];
75
+ }
76
+ export function reviewQuestion(review) {
77
+ if (review.settled)
78
+ return 'What now?';
79
+ return review.steps.length === 1 ? RUN_THIS_STEP : 'Run these ' + review.steps.length + ' steps?';
80
+ }
81
+ export function reviewOptions(review) {
82
+ if (review.settled)
83
+ return settledOptions(review);
84
+ return [
85
+ { value: 'run', label: review.steps.length === 1 ? 'Run it' : 'Run them' },
86
+ { value: 'back', label: 'Back', hint: 'to the last question' },
87
+ { value: 'edit', label: 'Change an answer' },
88
+ { value: 'decline', label: 'Decline', hint: 'change nothing and exit' },
89
+ ];
90
+ }
91
+ /** Done, then a way to pick another account or sign in to gh. Change an answer stays once questions were asked. */
92
+ function settledOptions(review) {
93
+ const options = [
94
+ { value: 'done', label: 'Done', hint: 'change nothing' },
95
+ { value: 'account', label: 'Use another account', hint: 'choose a different account for this clone' },
96
+ ];
97
+ if (review.ghSignIn)
98
+ options.push({ value: 'gh', label: review.ghSignIn });
99
+ if (review.edits !== false)
100
+ options.push({ value: 'edit', label: 'Change an answer' });
101
+ return options;
102
+ }
103
+ /**
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.
106
+ */
107
+ export function reviewDefault(review) {
108
+ const machineWide = review.steps.some((step) => changesMachine(step.command));
109
+ return !review.settled && machineWide ? 'decline' : reviewOptions(review)[0].value;
110
+ }
@@ -0,0 +1,73 @@
1
+ // What one setup run changed. The diff is pure. The read is this clone's local
2
+ // config and the guard, through the Git wrapper. A credential helper is never
3
+ // run: it can print a live password, and this report shows config values only.
4
+ import { ACCOUNT_KEY, EMAIL_KEY, NAME_KEY, USE_CONFIG_ONLY_KEY } from "../core/identity.js";
5
+ import { guardState } from "../core/guard/hook.js";
6
+ const ALLOW_OWNER = 'repown.allowOwner';
7
+ const AUTO_UPSTREAM = 'push.autoSetupRemote';
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];
11
+ const found = await Promise.all(keys.map((key) => git.getConfig(key, 'local')));
12
+ const [allowOwner, autoUpstream, guard] = await Promise.all([
13
+ git.getAllConfig(ALLOW_OWNER, 'local'),
14
+ git.getConfig(AUTO_UPSTREAM, 'local'),
15
+ guardState(git),
16
+ ]);
17
+ return {
18
+ values: keys.map((key, index) => [key, found[index] ?? null]),
19
+ allowOwner, autoUpstream, guard,
20
+ };
21
+ }
22
+ /** Lines for keys whose local value changed. Empty when the clone matches. */
23
+ export function cloneChangeLines(before, after) {
24
+ const next = new Map(after.values);
25
+ return [
26
+ ...before.values.flatMap(([key, old]) => keep(valueChange(key, old, next.get(key) ?? null))),
27
+ ...allowChange(before.allowOwner, after.allowOwner),
28
+ ...keep(valueChange(AUTO_UPSTREAM, before.autoUpstream, after.autoUpstream)),
29
+ ...keep(guardChange(before.guard, after.guard)),
30
+ ];
31
+ }
32
+ /** Registry and gh are this machine, not this clone. Null means that one did not change. */
33
+ export function machineChangeLines(registryAdded, ghAccount) {
34
+ const registry = registryAdded === null ? null : " this machine's account registry: added " + registryAdded;
35
+ const gh = ghAccount === null ? null : " gh: " + ghAccount + " is now gh's active account (every terminal)";
36
+ return [...keep(registry), ...keep(gh)];
37
+ }
38
+ function keep(line) {
39
+ return line === null ? [] : [line];
40
+ }
41
+ function valueChange(key, before, after) {
42
+ if (before === after)
43
+ return null;
44
+ if (before === null)
45
+ return ' ' + key + ': (added) ' + after;
46
+ if (after === null)
47
+ return ' ' + key + ': ' + before + ' -> (removed)';
48
+ return ' ' + key + ': ' + before + ' -> ' + after;
49
+ }
50
+ function guardChange(before, after) {
51
+ if (before === after)
52
+ return null;
53
+ return ' push guard: ' + before + ' -> ' + after;
54
+ }
55
+ function allowChange(before, after) {
56
+ const added = missing(after, before);
57
+ const removed = missing(before, after);
58
+ return [
59
+ ...keep(added.length === 0 ? null : ' ' + ALLOW_OWNER + ': (added) ' + added.join(', ')),
60
+ ...keep(removed.length === 0 ? null : ' ' + ALLOW_OWNER + ': ' + removed.join(', ') + ' -> (removed)'),
61
+ ];
62
+ }
63
+ /** Values in `source` that `other` does not already hold, extras included. */
64
+ function missing(source, other) {
65
+ const left = [...other];
66
+ return source.filter((value) => {
67
+ const at = left.indexOf(value);
68
+ if (at < 0)
69
+ return true;
70
+ left.splice(at, 1);
71
+ return false;
72
+ });
73
+ }
@@ -0,0 +1,256 @@
1
+ // Everything `repown setup` needs to know before its first question, read once and
2
+ // read-only: the registry, this clone (origin, owner, pin, hook, push.autoSetupRemote),
3
+ // and the machine (gh, the credential helper, the global identity, git's version).
4
+ // Nothing here writes.
5
+ import { gitSupportsAutoUpstream } from "../core/version.js";
6
+ import { inspectRepo, inspectAuth } from "../core/inspect.js";
7
+ import { pinHolds } from "../core/identity.js";
8
+ import { loadRegistry } from "../core/registry.js";
9
+ import { planRepair } from "../core/credential/repair.js";
10
+ import { isGh } from "../core/credential/gh.js";
11
+ import { providers } from "../core/hosts/index.js";
12
+ import { ok, err } from "../core/result.js";
13
+ import { previewLines } from "../commands/fix.js";
14
+ import { readUnpushed } from "../core/unpushed.js";
15
+ import { SOURCE_GCM, SOURCE_GH, SOURCE_OWNS } from "./setup-flow.js";
16
+ /**
17
+ * Candidate logins not already recorded, one entry each. The first spelling
18
+ * wins; every source joins it, in the order owner, gh, then Git Credential
19
+ * Manager. A failed lookup contributes nothing: it only shortens a suggestion
20
+ * list, and the failure itself stays a Result. An organisation owner is left
21
+ * out of every source; an owner of unknown kind is kept.
22
+ */
23
+ export function detectedAccounts(input) {
24
+ if (!input.github)
25
+ return [];
26
+ const found = new Map();
27
+ const taken = takenLogins(input);
28
+ for (const sighting of sightings(input))
29
+ note(found, sighting, taken);
30
+ return [...found.values()];
31
+ }
32
+ function sightings(input) {
33
+ return [
34
+ ...ownerSighting(input),
35
+ ...tagged(input.gh, SOURCE_GH),
36
+ ...tagged(input.stored, SOURCE_GCM),
37
+ ];
38
+ }
39
+ function ownerSighting(input) {
40
+ if (!input.owner)
41
+ return [];
42
+ return [{ login: input.owner, from: SOURCE_OWNS }];
43
+ }
44
+ /** A failed or absent lookup is no logins. That is a shorter list, not a passed check. */
45
+ function tagged(result, from) {
46
+ if (!result?.ok)
47
+ return [];
48
+ return result.value.map((login) => ({ login, from }));
49
+ }
50
+ /** Recorded accounts, plus an owner known to be an organisation: never an account name. */
51
+ function takenLogins(input) {
52
+ const taken = new Set(input.recorded.map((account) => account.toLowerCase()));
53
+ if (input.owner && input.ownerIsUser === false)
54
+ taken.add(input.owner.toLowerCase());
55
+ return taken;
56
+ }
57
+ function note(found, sighting, taken) {
58
+ const key = sighting.login.toLowerCase();
59
+ if (taken.has(key))
60
+ return;
61
+ const existing = found.get(key);
62
+ if (!existing)
63
+ found.set(key, { login: sighting.login, from: [sighting.from] });
64
+ else if (!existing.from.includes(sighting.from))
65
+ existing.from.push(sighting.from);
66
+ }
67
+ /**
68
+ * The registry, refused when saving to it would drop entries it can't read. An entry
69
+ * with an empty name or email counts as not recorded: `use` would stop and ask for it.
70
+ */
71
+ export async function readRegistry() {
72
+ const registry = await loadRegistry();
73
+ if (!registry.ok)
74
+ return registry;
75
+ // No prototype, as in the registry itself: an account named like a built-in must not collide.
76
+ const accounts = Object.assign(Object.create(null), Object.fromEntries(Object.entries(registry.value.accounts).filter(([, entry]) => entry.name && entry.email)));
77
+ if (registry.value.unreadable.length === 0)
78
+ return ok({ ...registry.value, accounts });
79
+ return err('the account registry has entries repown cannot read (' + registry.value.unreadable.join(', ') +
80
+ ') -- fix or remove them first');
81
+ }
82
+ export async function readContext(git, cwd, options = {}) {
83
+ const registry = await readRegistry();
84
+ if (!registry.ok)
85
+ return registry;
86
+ const repo = await inspectRepo(git);
87
+ const recorded = registry.value.accounts;
88
+ const facts = await readFacts(git, repo, recorded, options);
89
+ return ok(assemble(cwd, recorded, repo, facts));
90
+ }
91
+ async function readFacts(git, repo, recorded, options) {
92
+ const loaded = await loadClone(git, repo, options);
93
+ return finishFacts(git, repo, recorded, loaded);
94
+ }
95
+ async function loadClone(git, repo, options) {
96
+ 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
+ authPromise,
99
+ git.getConfig('repown.account', 'local'),
100
+ git.getAllConfig('repown.allowOwner', 'local'),
101
+ planRepair(git),
102
+ historyFor(git, repo),
103
+ git.getAllConfigRaw('credential.helper'),
104
+ authPromise.then((auth) => askOwnerIsUser(repo, auth, options)),
105
+ readUpstream(git),
106
+ readUnpushed(git),
107
+ ]);
108
+ const { machineName: name, machineEmail: email } = repo.identity;
109
+ return { auth, pinned, allowed, planned, addresses, unpushed, helpers, name, email, ownerIsUser, upstream };
110
+ }
111
+ /** Version, effective push.autoSetupRemote, the branch and its tracked ref. One read; nothing is written. */
112
+ async function readUpstream(git) {
113
+ const [version, enabled, head, tracked] = await Promise.all([
114
+ git.version(), git.getBoolConfig('push.autoSetupRemote'), git.currentBranch(), git.upstreamRef(),
115
+ ]);
116
+ return {
117
+ supported: gitSupportsAutoUpstream(version ?? ''), enabled,
118
+ branch: branchOf(head), tracked: trackedOf(head, tracked),
119
+ };
120
+ }
121
+ function branchOf(head) {
122
+ return head?.kind === 'branch' ? head.name : null;
123
+ }
124
+ function trackedOf(head, tracked) {
125
+ return head?.kind === 'branch' ? tracked : null;
126
+ }
127
+ async function finishFacts(git, repo, recorded, loaded) {
128
+ const ghIsHelper = anyGhHelper(loaded.auth, loaded.planned, loaded.helpers);
129
+ return {
130
+ pinned: loaded.pinned, allowed: loaded.allowed, addresses: loaded.addresses, unpushed: loaded.unpushed,
131
+ name: loaded.name, email: loaded.email, ownerIsUser: loaded.ownerIsUser, ghIsHelper, stored: loaded.auth.stored,
132
+ gh: loaded.auth.ghPresent ? loaded.auth.gh : null,
133
+ pinIntact: await pinIntact(git, loaded.pinned, recorded[loaded.pinned ?? ''], repo),
134
+ detected: detectedAccounts(detectionOf(repo, loaded.auth, recorded, loaded.ownerIsUser)),
135
+ fixLines: fixPreview(repo, ghIsHelper, loaded.planned),
136
+ upstream: loaded.upstream,
137
+ };
138
+ }
139
+ function assemble(cwd, recorded, repo, facts) {
140
+ return {
141
+ cwd, recorded,
142
+ pinned: facts.pinned,
143
+ pinIntact: facts.pinIntact,
144
+ host: offeredHost(repo),
145
+ owner: repo.owner,
146
+ detected: facts.detected,
147
+ ownerIsUser: facts.ownerIsUser,
148
+ allowed: facts.allowed.map((owner) => owner.toLowerCase()),
149
+ credentialPinned: repo.credentialKeys.length > 0, credentialKeys: repo.credentialKeys,
150
+ gh: facts.gh, ghIsHelper: facts.ghIsHelper,
151
+ guard: repo.guard,
152
+ redirected: repo.hook?.redirected ?? false, hookPath: repo.hook?.path ?? null,
153
+ fixLines: facts.fixLines,
154
+ addresses: facts.addresses, unpushed: facts.unpushed,
155
+ machineIdentity: { name: facts.name, email: facts.email },
156
+ upstream: facts.upstream, stored: facts.stored,
157
+ suggest: suggester(),
158
+ };
159
+ }
160
+ /** gh anywhere in the helper list may answer sign-ins: git asks the helpers in order. */
161
+ function anyGhHelper(auth, planned, helpers) {
162
+ return auth.ghIsHelper || planned.length > 0 || helpers.some(isGh);
163
+ }
164
+ /** Without an origin there is no host to go by; GitHub is only the default offered. */
165
+ function offeredHost(repo) {
166
+ return repo.url ? repo.provider.id : 'github';
167
+ }
168
+ function fixPreview(repo, ghIsHelper, planned) {
169
+ if (repo.provider.id !== 'github' || !ghIsHelper || planned.length === 0)
170
+ return null;
171
+ return previewLines(planned);
172
+ }
173
+ function detectionOf(repo, auth, recorded, ownerIsUser) {
174
+ return {
175
+ github: repo.provider.id === 'github',
176
+ owner: repo.owner,
177
+ ownerIsUser,
178
+ gh: ghLogins(auth.gh),
179
+ stored: auth.stored,
180
+ recorded: Object.keys(recorded),
181
+ };
182
+ }
183
+ function ghLogins(gh) {
184
+ if (!gh.ok)
185
+ return gh;
186
+ return ok(gh.value.accounts.map((account) => account.login));
187
+ }
188
+ /**
189
+ * True when the owner is a user, false for an organisation, null when unknown.
190
+ * A gh account on github.com is a user: gh lists sign-ins, never organisations.
191
+ * No lookup when setup will not prompt. A recorded owner is still classified.
192
+ */
193
+ export async function askOwnerIsUser(repo, auth, options = {}) {
194
+ if (options.classifyOwner === false)
195
+ return null;
196
+ if (repo.provider.id !== 'github' || !repo.owner)
197
+ return null;
198
+ if (signedIn(auth, repo.owner))
199
+ return true;
200
+ const ask = options.accountKind ?? repo.provider.accountKind;
201
+ if (!ask)
202
+ return null;
203
+ return asUser(await ask(repo.owner));
204
+ }
205
+ function signedIn(auth, owner) {
206
+ if (!auth.gh.ok)
207
+ return false;
208
+ return auth.gh.value.accounts.some((account) => account.login.toLowerCase() === owner.toLowerCase());
209
+ }
210
+ function asUser(kind) {
211
+ if (kind === 'user')
212
+ return true;
213
+ if (kind === 'organization')
214
+ return false;
215
+ return null;
216
+ }
217
+ /** Every ref, for the guard question only. Unpushed commits on this branch are readUnpushed. */
218
+ function historyFor(git, repo) {
219
+ const guardAsked = repo.guard === 'off' && !repo.hook?.redirected;
220
+ return guardAsked ? git.emailCounts() : Promise.resolve(ok(new Map()));
221
+ }
222
+ /**
223
+ * Whether `use <pinned>` would write nothing new AND git would use what it wrote: the
224
+ * pinned account, as recorded, holds in .git/config, and nothing git reads besides it
225
+ * -- an include, worktree config, a credential entry for the same URL spelt otherwise --
226
+ * says something else.
227
+ */
228
+ async function pinIntact(git, pinned, entry, repo) {
229
+ if (!pinned || !entry)
230
+ return false;
231
+ const values = { name: entry.name, email: entry.email, account: pinned };
232
+ const [written, used] = await Promise.all([pinHolds(git, values, repo.credentialKeys), gitUses(git, values, repo)]);
233
+ return written && used;
234
+ }
235
+ /** The identity and push account git resolves for this clone, from every scope it reads. */
236
+ async function gitUses(git, values, repo) {
237
+ const pinsCredential = repo.credentialKeys.length > 0 && repo.originUrl !== null;
238
+ const [name, email, user] = await Promise.all([
239
+ git.getConfig('user.name'),
240
+ git.getConfig('user.email'),
241
+ pinsCredential ? git.getUrlMatch('credential.username', repo.originUrl) : Promise.resolve(values.account),
242
+ ]);
243
+ return name === values.name && email === values.email && user === values.account;
244
+ }
245
+ /** Profile lookups are network calls: one per account and host, however often a step is re-asked. */
246
+ function suggester() {
247
+ const cache = new Map();
248
+ return (account, host) => {
249
+ const key = host + '\n' + account;
250
+ if (!cache.has(key)) {
251
+ const provider = providers().find((candidate) => candidate.id === host);
252
+ cache.set(key, (provider?.resolveProfile?.(account) ?? Promise.resolve(null)).then((found) => found ?? {}));
253
+ }
254
+ return cache.get(key);
255
+ };
256
+ }