repown 0.1.1 → 0.3.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,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
+ }