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.
- package/CHANGELOG.md +58 -1
- package/README.md +16 -6
- package/dist/cli.js +7 -15
- package/dist/commands/reauthor.js +64 -0
- package/dist/commands/scan.js +13 -6
- package/dist/commands/setup.js +4 -1
- package/dist/commands/start.js +28 -10
- package/dist/commands/status.js +51 -11
- package/dist/commands/use.js +3 -3
- package/dist/core/blockers.js +132 -0
- package/dist/core/git.js +136 -8
- package/dist/core/guard/check.js +4 -0
- package/dist/core/push-destination.js +82 -0
- package/dist/core/push-state.js +109 -0
- package/dist/core/reauthor.js +145 -0
- package/dist/core/unpushed.js +110 -42
- package/dist/program.js +14 -0
- package/dist/ui/dispatch.js +12 -4
- package/dist/ui/format.js +8 -0
- package/dist/ui/help.js +4 -3
- package/dist/wizard/clack.js +30 -15
- package/dist/wizard/engine.js +6 -3
- package/dist/wizard/home-context.js +101 -0
- package/dist/wizard/home-flow.js +90 -0
- package/dist/wizard/home-run.js +148 -0
- package/dist/wizard/home-text.js +50 -0
- package/dist/wizard/plain.js +13 -2
- package/dist/wizard/review-text.js +17 -10
- package/dist/wizard/setup-changes.js +9 -5
- package/dist/wizard/setup-context.js +12 -5
- package/dist/wizard/setup-flow.js +163 -27
- package/dist/wizard/setup-run.js +107 -28
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/core/git.js
CHANGED
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
// `git config --get` EXITS 1 WHEN A KEY IS NOT SET. That is an answer, not a
|
|
14
14
|
// failure, and it is why nothing here treats a non-zero code as an error by
|
|
15
15
|
// itself. See the note in exec.ts.
|
|
16
|
+
import { existsSync } from 'node:fs';
|
|
17
|
+
import { join, resolve } from 'node:path';
|
|
18
|
+
import { tmpdir } from 'node:os';
|
|
19
|
+
import { randomUUID } from 'node:crypto';
|
|
16
20
|
import { run, succeeded, output, lines } from "./exec.js";
|
|
17
21
|
import { ok, err } from "./result.js";
|
|
18
22
|
export class Git {
|
|
@@ -66,6 +70,20 @@ export class Git {
|
|
|
66
70
|
async remotes() {
|
|
67
71
|
return lines(await this.exec(['remote']));
|
|
68
72
|
}
|
|
73
|
+
/** Remote names, in the order git lists them. A failed read is an error, not "none". */
|
|
74
|
+
async readRemotes() {
|
|
75
|
+
const listed = await this.exec(['remote']);
|
|
76
|
+
if (!succeeded(listed))
|
|
77
|
+
return err(listed.stderr.trim() || 'git remote failed');
|
|
78
|
+
return ok(lines(listed));
|
|
79
|
+
}
|
|
80
|
+
/** Whether any ref exists under `refs/remotes/<remote>/`. A failed read is an error, not "none". */
|
|
81
|
+
async hasTrackingRefs(remote) {
|
|
82
|
+
const listed = await this.exec(['for-each-ref', '--count=1', '--format=%(refname)', 'refs/remotes/' + remote + '/']);
|
|
83
|
+
if (!succeeded(listed))
|
|
84
|
+
return err(listed.stderr.trim() || 'git for-each-ref failed');
|
|
85
|
+
return ok(lines(listed).length > 0);
|
|
86
|
+
}
|
|
69
87
|
/**
|
|
70
88
|
* The directory every worktree shares -- where hooks and config actually live.
|
|
71
89
|
* In a linked worktree `.git` is a FILE, so joining '.git' to the root gives a
|
|
@@ -198,14 +216,91 @@ export class Git {
|
|
|
198
216
|
}
|
|
199
217
|
return err('tag chain longer than ' + MAX_TAG_CHAIN + ' starting at ' + sha);
|
|
200
218
|
}
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
return
|
|
219
|
+
// ---- rewriting (repown reauthor only) -------------------------------------
|
|
220
|
+
/** A long or networked call: its own environment and timeout. Still only exec.ts spawns. */
|
|
221
|
+
execLong(args, env, timeoutMs) {
|
|
222
|
+
return run('git', ['--no-replace-objects', ...args], { cwd: this.cwd, env, timeoutMs });
|
|
223
|
+
}
|
|
224
|
+
/** Fetch with every prompt off: a sign-in that would ask fails instead. The reason is cleaned for display. */
|
|
225
|
+
async fetchQuietly(remote) {
|
|
226
|
+
const fetched = await this.execLong([...QUIET, 'fetch', '--quiet', '--no-recurse-submodules', remote], await this.quietEnvHere(), NETWORK_MS);
|
|
227
|
+
return succeeded(fetched) ? ok(undefined) : err(networkReason(fetched));
|
|
228
|
+
}
|
|
229
|
+
/** How many branches the remote lists (network, prompts off). */
|
|
230
|
+
async remoteHeadCount(remote) {
|
|
231
|
+
const listed = await this.execLong([...QUIET, 'ls-remote', '--heads', remote], await this.quietEnvHere(), NETWORK_MS);
|
|
232
|
+
return succeeded(listed) ? ok(lines(listed).length) : err(networkReason(listed));
|
|
233
|
+
}
|
|
234
|
+
/** Prompts off. ssh gets BatchMode only where neither the shell nor this clone names an ssh command. */
|
|
235
|
+
async quietEnvHere() {
|
|
236
|
+
return quietEnv(process.env, await this.getConfig('core.sshCommand') !== null);
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* `git rebase <base> --exec <cmd>`, without moving other branches' refs, without folding
|
|
240
|
+
* commits (autosquash), and with no hook at all: hooksPath names a directory that does not
|
|
241
|
+
* exist, and `-c` reaches the --exec child too, so its `git commit` runs none either.
|
|
242
|
+
*/
|
|
243
|
+
async rebaseExec(base, exec) {
|
|
244
|
+
const noHooks = join(tmpdir(), 'repown-no-hooks-' + randomUUID());
|
|
245
|
+
const off = ['-c', 'rebase.updateRefs=false', '-c', 'rebase.autoSquash=false', '-c', 'core.hooksPath=' + noHooks];
|
|
246
|
+
const args = [...off, 'rebase', '--quiet', base, '--exec', exec];
|
|
247
|
+
const rebased = await this.execLong(args, process.env, REBASE_MS);
|
|
248
|
+
return succeeded(rebased) ? ok(undefined) : err(rebased.timedOut ? 'timed out' : networkReason(rebased));
|
|
249
|
+
}
|
|
250
|
+
async abortRebase() {
|
|
251
|
+
return succeeded(await this.exec(['rebase', '--abort']));
|
|
252
|
+
}
|
|
253
|
+
/** Creates `ref` at `sha`; refuses when it exists already, so nothing is overwritten. */
|
|
254
|
+
async createRef(ref, sha) {
|
|
255
|
+
return succeeded(await this.exec(['update-ref', ref, sha, '']));
|
|
256
|
+
}
|
|
257
|
+
/** Full hash of `rev`, or null when it does not resolve. */
|
|
258
|
+
async revParse(rev) {
|
|
259
|
+
return output(await this.exec(['rev-parse', '--verify', '--quiet', rev + '^{commit}']));
|
|
260
|
+
}
|
|
261
|
+
/** Full hash of the first parent; null for a root commit. */
|
|
262
|
+
async parentOf(sha) {
|
|
263
|
+
return output(await this.exec(['rev-parse', '--verify', '--quiet', sha + '^']));
|
|
205
264
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
265
|
+
async countIn(range) {
|
|
266
|
+
const counted = await this.exec(['rev-list', '--count', ...range]);
|
|
267
|
+
const count = Number(counted.stdout.trim());
|
|
268
|
+
return succeeded(counted) && Number.isInteger(count) ? ok(count) : err(counted.stderr.trim() || 'git rev-list failed');
|
|
269
|
+
}
|
|
270
|
+
/** Tracked changes, or entries hidden with skip-worktree / assume-unchanged, that a rebase could clobber. */
|
|
271
|
+
async hasTrackedChanges() {
|
|
272
|
+
const [status, files] = await Promise.all([
|
|
273
|
+
this.exec(['status', '--porcelain', '--untracked-files=no']), this.exec(['ls-files', '-v']),
|
|
274
|
+
]);
|
|
275
|
+
if (!succeeded(status) || !succeeded(files))
|
|
276
|
+
return err('git status failed');
|
|
277
|
+
const hidden = lines(files).some((line) => /^([a-z]|S) /.test(line));
|
|
278
|
+
return ok(status.stdout.trim().length > 0 || hidden);
|
|
279
|
+
}
|
|
280
|
+
/** The operation a half-finished rebase, merge, cherry-pick, revert or bisect left, or null. */
|
|
281
|
+
async operationInProgress() {
|
|
282
|
+
for (const [path, name] of IN_PROGRESS) {
|
|
283
|
+
const where = output(await this.exec(['rev-parse', '--git-path', path]));
|
|
284
|
+
if (where && existsSync(resolve(this.cwd, where)))
|
|
285
|
+
return name;
|
|
286
|
+
}
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
/** `git rev-list --left-right --count A...B`: commits only on the left, and only on the right. */
|
|
290
|
+
async leftRightCount(range) {
|
|
291
|
+
const counted = await this.exec(['rev-list', '--left-right', '--count', range]);
|
|
292
|
+
const [left, right] = (succeeded(counted) ? counted.stdout.trim() : '').split(/\s+/).map(Number);
|
|
293
|
+
if (!succeeded(counted) || !Number.isInteger(left) || !Number.isInteger(right)) {
|
|
294
|
+
return err(counted.stderr.trim() || 'git rev-list could not count ' + range);
|
|
295
|
+
}
|
|
296
|
+
return ok({ left: left, right: right });
|
|
297
|
+
}
|
|
298
|
+
/** Each commit in `range` (full hash) and its first parent's short hash, null for a root. */
|
|
299
|
+
async firstParentsIn(range) {
|
|
300
|
+
const listed = await this.exec(['log', '--no-show-signature', '--format=%H %p', ...range]);
|
|
301
|
+
if (!succeeded(listed))
|
|
302
|
+
return err(listed.stderr.trim() || 'git log failed');
|
|
303
|
+
return ok(new Map(lines(listed).map(parentPair)));
|
|
209
304
|
}
|
|
210
305
|
/** Whether this clone has the commit at all -- a remote tip it never fetched is absent. */
|
|
211
306
|
async hasCommit(sha) {
|
|
@@ -220,7 +315,9 @@ export class Git {
|
|
|
220
315
|
* clone. Excluding the mirror branch leaves the commits written HERE.
|
|
221
316
|
*/
|
|
222
317
|
async emailCounts(exclude) {
|
|
223
|
-
|
|
318
|
+
// repown reauthor's backups keep the old commits alive; they are not this clone's history.
|
|
319
|
+
const all = ['--exclude=refs/repown/*', '--all'];
|
|
320
|
+
const range = exclude ? [...all, '--not', exclude] : all;
|
|
224
321
|
// --no-show-signature: a scanned repository's own log.showSignature + gpg.program
|
|
225
322
|
// would otherwise run a program of its choosing.
|
|
226
323
|
const result = await this.exec(['log', '--no-show-signature', ...range, '--format=%ae%n%ce']);
|
|
@@ -250,6 +347,37 @@ function parseOriginLine(line) {
|
|
|
250
347
|
* so nothing an author writes can shift them; the subject cannot reach past its
|
|
251
348
|
* own terminator either. Records are a fixed IDENTITY_FIELDS long.
|
|
252
349
|
*/
|
|
350
|
+
const NETWORK_MS = 120_000;
|
|
351
|
+
const REBASE_MS = 600_000;
|
|
352
|
+
/** Empty askPass: git asks no helper for a password (GIT_TERMINAL_PROMPT covers the terminal). */
|
|
353
|
+
const QUIET = ['-c', 'core.askPass=', '-c', 'credential.interactive=false'];
|
|
354
|
+
const IN_PROGRESS = [
|
|
355
|
+
['rebase-merge', 'rebase'], ['rebase-apply', 'rebase'], ['MERGE_HEAD', 'merge'],
|
|
356
|
+
['CHERRY_PICK_HEAD', 'cherry-pick'], ['REVERT_HEAD', 'revert'], ['BISECT_LOG', 'bisect'],
|
|
357
|
+
];
|
|
358
|
+
/**
|
|
359
|
+
* The whole environment, with every way git could prompt turned off. ssh is made
|
|
360
|
+
* non-interactive only where nothing names an ssh command already: GIT_SSH_COMMAND outranks
|
|
361
|
+
* core.sshCommand and GIT_SSH, so setting it would replace a per-account key (`ssh -i ...`).
|
|
362
|
+
*/
|
|
363
|
+
export function quietEnv(env, sshConfigured) {
|
|
364
|
+
const { GIT_ASKPASS: _git, SSH_ASKPASS: _ssh, ...rest } = env;
|
|
365
|
+
const ownSsh = sshConfigured || !!env['GIT_SSH_COMMAND'] || !!env['GIT_SSH'];
|
|
366
|
+
const batch = ownSsh ? {} : { GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' };
|
|
367
|
+
return { ...rest, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', ...batch };
|
|
368
|
+
}
|
|
369
|
+
/** git's last error line, with a URL's credentials and query masked and control characters removed. */
|
|
370
|
+
export function networkReason(result) {
|
|
371
|
+
if (result.timedOut)
|
|
372
|
+
return 'timed out';
|
|
373
|
+
const last = result.stderr.trim().split('\n').filter(Boolean).at(-1) ?? 'git failed';
|
|
374
|
+
return last.replace(/(\w+:\/\/)\S*@/g, '$1***@').replace(/(\w+:\/\/[^\s?]*)\?[^\s'"]*/g, '$1?***').replace(/[\x00-\x1f\x7f-\x9f]/g, '?');
|
|
375
|
+
}
|
|
376
|
+
/** `<sha> <parent> [<parent>...]`; a root has none. */
|
|
377
|
+
function parentPair(line) {
|
|
378
|
+
const [sha = '', first = ''] = line.trim().split(' ');
|
|
379
|
+
return [sha, first || null];
|
|
380
|
+
}
|
|
253
381
|
const IDENTITY_FORMAT = '%H%x00%ae%x00%ce%x00%an%x00%cn%x00%s%x00';
|
|
254
382
|
const IDENTITY_FIELDS = 6;
|
|
255
383
|
const MAX_TAG_CHAIN = 16;
|
package/dist/core/guard/check.js
CHANGED
|
@@ -58,6 +58,10 @@ export async function check(input) {
|
|
|
58
58
|
const destination = checkDestination({ url, owner, allowed }, input.onNote);
|
|
59
59
|
return [...destination, ...await checkCommits(input, identity.email)];
|
|
60
60
|
}
|
|
61
|
+
/** The names of the variables above that are set (non-empty) in `env`, in that order. */
|
|
62
|
+
export function hostileSet(env) {
|
|
63
|
+
return HOSTILE.filter(([name]) => !!env[name]).map(([name]) => name);
|
|
64
|
+
}
|
|
61
65
|
function checkEnvironment() {
|
|
62
66
|
return HOSTILE.flatMap(([name, why]) => {
|
|
63
67
|
if (!process.env[name])
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Where `git push` with no arguments sends a branch, and whether this clone can
|
|
2
|
+
// tell what is already there (ADR-025).
|
|
3
|
+
//
|
|
4
|
+
// `HEAD --not --remotes` only knows remote-tracking refs. A destination with none
|
|
5
|
+
// (a remote never fetched, an empty one, or a URL, which never gets any) may
|
|
6
|
+
// already hold commits that range calls unpushed, so a rebase from its base would
|
|
7
|
+
// rewrite published history. Nothing offline tells an empty remote from an
|
|
8
|
+
// unfetched one, and FETCH_HEAD is no answer: a FAILED fetch writes it too, and it
|
|
9
|
+
// belongs to whichever remote was fetched last. So the destination is only ever
|
|
10
|
+
// "known" (it has tracking refs, and pushes where it fetches from) or "unknown",
|
|
11
|
+
// and a read that fails is unknown.
|
|
12
|
+
import { parseGitUrl } from "./url.js";
|
|
13
|
+
/** Null when the branch pushes nowhere, to `.` (this repository), or where tracking refs reach. */
|
|
14
|
+
export async function unknownDestination(git, branch) {
|
|
15
|
+
const listed = await git.readRemotes();
|
|
16
|
+
if (!listed.ok)
|
|
17
|
+
return { kind: 'unread' };
|
|
18
|
+
const set = await configuredTarget(git, branch);
|
|
19
|
+
// No "only remote" fallback: git push has none, it fails "No configured push destination".
|
|
20
|
+
const name = set?.value ?? (listed.value.includes('origin') ? 'origin' : null);
|
|
21
|
+
if (!name || name === '.')
|
|
22
|
+
return null;
|
|
23
|
+
if (listed.value.includes(name))
|
|
24
|
+
return remoteState(git, name);
|
|
25
|
+
if (!set || !looksLikeUrl(name))
|
|
26
|
+
return { kind: 'unnamed', name };
|
|
27
|
+
return { kind: 'url', key: set.key, remote: await remoteWithUrl(git, listed.value, name) };
|
|
28
|
+
}
|
|
29
|
+
/** Null when there is no destination, it is `.`, or the remotes could not be listed. */
|
|
30
|
+
export async function pushTarget(git, branch) {
|
|
31
|
+
const listed = await git.readRemotes();
|
|
32
|
+
if (!listed.ok)
|
|
33
|
+
return null;
|
|
34
|
+
const set = await configuredTarget(git, branch);
|
|
35
|
+
const name = set?.value ?? (listed.value.includes('origin') ? 'origin' : null);
|
|
36
|
+
if (!name || name === '.')
|
|
37
|
+
return null;
|
|
38
|
+
return { name, isRemote: listed.value.includes(name), key: set?.key ?? null };
|
|
39
|
+
}
|
|
40
|
+
/** git's own order for a push with no arguments. */
|
|
41
|
+
async function configuredTarget(git, branch) {
|
|
42
|
+
const keys = ['branch.' + branch + '.pushRemote', 'remote.pushDefault', 'branch.' + branch + '.remote'];
|
|
43
|
+
for (const key of keys) {
|
|
44
|
+
const value = await git.getConfig(key);
|
|
45
|
+
if (value)
|
|
46
|
+
return { key, value };
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
async function remoteState(git, name) {
|
|
51
|
+
if (!await isTracked(git, name))
|
|
52
|
+
return { kind: 'remote', name };
|
|
53
|
+
return await pushesElsewhere(git, name) ? { kind: 'pushurl', name } : null;
|
|
54
|
+
}
|
|
55
|
+
async function isTracked(git, remote) {
|
|
56
|
+
const found = await git.hasTrackingRefs(remote);
|
|
57
|
+
return found.ok && found.value;
|
|
58
|
+
}
|
|
59
|
+
/** Tracking refs come from the fetch URL; a different pushurl is somewhere never fetched. */
|
|
60
|
+
async function pushesElsewhere(git, remote) {
|
|
61
|
+
const push = await git.getConfig('remote.' + remote + '.pushurl');
|
|
62
|
+
if (!push)
|
|
63
|
+
return false;
|
|
64
|
+
return urlKey(push) !== urlKey(await git.getConfig('remote.' + remote + '.url') ?? '');
|
|
65
|
+
}
|
|
66
|
+
/** A URL or a path, as git would read it where a remote name was expected. */
|
|
67
|
+
function looksLikeUrl(value) {
|
|
68
|
+
return parseGitUrl(value) !== null || /[\\/:]/.test(value);
|
|
69
|
+
}
|
|
70
|
+
/** The configured remote at the same host and path, credentials aside. */
|
|
71
|
+
async function remoteWithUrl(git, remotes, url) {
|
|
72
|
+
const wanted = urlKey(url);
|
|
73
|
+
for (const name of remotes) {
|
|
74
|
+
if (urlKey(await git.getConfig('remote.' + name + '.url') ?? '') === wanted)
|
|
75
|
+
return name;
|
|
76
|
+
}
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
function urlKey(raw) {
|
|
80
|
+
const url = parseGitUrl(raw);
|
|
81
|
+
return url ? url.host.toLowerCase() + '/' + url.path : raw.trim();
|
|
82
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// The facts about this clone that decide whether its next commit, pull or push works:
|
|
2
|
+
// read once, offline, for setup and status to turn into blockers (src/core/blockers.ts).
|
|
3
|
+
//
|
|
4
|
+
// Every read that fails is kept as a failure (a Result), never as "nothing found", so
|
|
5
|
+
// a clone that could not be read is never reported ready. The push target is resolved
|
|
6
|
+
// the way a plain `git push` resolves it (push-destination.ts), and a secret in a URL is
|
|
7
|
+
// only ever reported by the config key that holds it.
|
|
8
|
+
import { ok } from "./result.js";
|
|
9
|
+
import { pushTarget, unknownDestination } from "./push-destination.js";
|
|
10
|
+
import { parseGitUrl } from "./url.js";
|
|
11
|
+
import { providerFor } from "./hosts/index.js";
|
|
12
|
+
import { hostileSet } from "./guard/check.js";
|
|
13
|
+
const OVERRIDES = ['author.email', 'committer.email'];
|
|
14
|
+
export async function readPushFacts(git, unpushed, env = process.env) {
|
|
15
|
+
const head = await git.currentBranch();
|
|
16
|
+
const branch = head?.kind === 'branch' ? head.name : null;
|
|
17
|
+
const target = branch ? await pushTarget(git, branch) : null;
|
|
18
|
+
const [configOverrides, signinKey, repoint, destination, divergence, elsewhere, upstream] = await Promise.all([
|
|
19
|
+
overridesIn(git), signinOf(git, target), repointOf(git, branch), destinationOf(git, target),
|
|
20
|
+
divergenceOf(git, target), elsewhereOf(git, target), upstreamOf(git, branch, target),
|
|
21
|
+
]);
|
|
22
|
+
return {
|
|
23
|
+
unpushed, env: hostileSet(env), configOverrides, elsewhere, signinKey, repoint, destination, divergence,
|
|
24
|
+
detached: head?.kind === 'detached', upstream,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
async function overridesIn(git) {
|
|
28
|
+
const values = await Promise.all(OVERRIDES.map((key) => git.getConfig(key)));
|
|
29
|
+
return OVERRIDES.filter((_, index) => values[index]);
|
|
30
|
+
}
|
|
31
|
+
/** A password or a token in the userinfo. A bare username (GCM's own advice) is not a secret. */
|
|
32
|
+
function carriesSecret(raw) {
|
|
33
|
+
const user = raw ? parseGitUrl(raw)?.user : null;
|
|
34
|
+
return !!user && (user.includes(':') || /^(gh[pousr]_|github_pat_)/i.test(user));
|
|
35
|
+
}
|
|
36
|
+
async function signinOf(git, target) {
|
|
37
|
+
if (target && !target.isRemote && carriesSecret(target.name))
|
|
38
|
+
return target.key;
|
|
39
|
+
if (target?.isRemote) {
|
|
40
|
+
// A push uses pushurl when there is one, so a token in the fetch url does not sign it in.
|
|
41
|
+
const key = await git.getConfig('remote.' + target.name + '.pushurl') !== null ? 'remote.' + target.name + '.pushurl' : 'remote.' + target.name + '.url';
|
|
42
|
+
if (carriesSecret(await git.getConfig(key)))
|
|
43
|
+
return key;
|
|
44
|
+
}
|
|
45
|
+
const headers = await git.configOrigins('^http\\.(.*\\.)?extraheader$');
|
|
46
|
+
return headers[0]?.key ?? null;
|
|
47
|
+
}
|
|
48
|
+
async function repointOf(git, branch) {
|
|
49
|
+
const unknown = branch ? await unknownDestination(git, branch) : null;
|
|
50
|
+
if (unknown?.kind !== 'url' || !unknown.remote)
|
|
51
|
+
return null;
|
|
52
|
+
const tracked = await git.hasTrackingRefs(unknown.remote);
|
|
53
|
+
return { key: unknown.key, remote: unknown.remote, tracked: tracked.ok && tracked.value };
|
|
54
|
+
}
|
|
55
|
+
async function destinationOf(git, target) {
|
|
56
|
+
if (!target)
|
|
57
|
+
return null;
|
|
58
|
+
const raw = target.isRemote ? await pushUrlOf(git, target.name) : target.name;
|
|
59
|
+
const url = raw ? parseGitUrl(raw) : null;
|
|
60
|
+
const owner = url ? providerFor(url).ownerOf(url) : null;
|
|
61
|
+
if (!owner)
|
|
62
|
+
return null;
|
|
63
|
+
const allowed = (await git.getAllConfig('repown.allowOwner', 'local')).map((value) => value.toLowerCase());
|
|
64
|
+
return { remote: target.isRemote ? target.name : null, owner, allowed };
|
|
65
|
+
}
|
|
66
|
+
async function pushUrlOf(git, remote) {
|
|
67
|
+
return (await git.getConfig('remote.' + remote + '.pushurl')) ?? git.getConfig('remote.' + remote + '.url');
|
|
68
|
+
}
|
|
69
|
+
/** Only the tracked ref ON the destination: a triangular workflow's upstream does not block its push. */
|
|
70
|
+
async function divergenceOf(git, target) {
|
|
71
|
+
if (!target?.isRemote)
|
|
72
|
+
return ok(null);
|
|
73
|
+
const tracked = await git.upstreamRef();
|
|
74
|
+
if (!tracked || !tracked.startsWith(target.name + '/'))
|
|
75
|
+
return ok(null);
|
|
76
|
+
const counts = await git.leftRightCount(tracked + '...HEAD');
|
|
77
|
+
if (!counts.ok)
|
|
78
|
+
return counts;
|
|
79
|
+
return ok({ tracked, behind: counts.value.left, ahead: counts.value.right });
|
|
80
|
+
}
|
|
81
|
+
/** The guard excludes only the destination's refs; `--remotes` excludes every remote's. */
|
|
82
|
+
async function elsewhereOf(git, target) {
|
|
83
|
+
if (!target?.isRemote || !await git.hasCommit('HEAD'))
|
|
84
|
+
return ok([]);
|
|
85
|
+
const [guarded, anywhere] = await Promise.all([
|
|
86
|
+
git.identitiesIn(['HEAD', '--not', '--remotes=' + target.name]),
|
|
87
|
+
git.identitiesIn(['HEAD', '--not', '--remotes']),
|
|
88
|
+
]);
|
|
89
|
+
if (!guarded.ok)
|
|
90
|
+
return guarded;
|
|
91
|
+
if (!anywhere.ok)
|
|
92
|
+
return anywhere;
|
|
93
|
+
const unpushed = new Set(anywhere.value.map((commit) => commit.sha));
|
|
94
|
+
return ok(guarded.value.filter((commit) => !unpushed.has(commit.sha))
|
|
95
|
+
.map((commit) => ({ authorEmail: commit.authorEmail, committerEmail: commit.committerEmail, parent: null })));
|
|
96
|
+
}
|
|
97
|
+
/** `missing` only where git would refuse a plain push: default push.default, no pushRemote, no autoSetupRemote. */
|
|
98
|
+
async function upstreamOf(git, branch, target) {
|
|
99
|
+
if (!branch || !target?.isRemote)
|
|
100
|
+
return null;
|
|
101
|
+
if (await git.upstreamRef())
|
|
102
|
+
return 'set';
|
|
103
|
+
if (target.key && target.key !== 'branch.' + branch + '.remote')
|
|
104
|
+
return null;
|
|
105
|
+
const [mode, auto] = await Promise.all([git.getConfig('push.default'), git.getBoolConfig('push.autoSetupRemote')]);
|
|
106
|
+
if (auto === true || (mode && !['simple', 'upstream', 'tracking'].includes(mode.toLowerCase())))
|
|
107
|
+
return null;
|
|
108
|
+
return 'missing';
|
|
109
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Re-authoring this branch's unpushed commits by another address (ADR-026).
|
|
2
|
+
//
|
|
3
|
+
// The one place repown rewrites history, so it refuses rather than guesses. It fetches the
|
|
4
|
+
// push destination first and rewrites only commits no remote has, from the parent of the
|
|
5
|
+
// topologically oldest one by another address; a merge in that range, a commit a remote has
|
|
6
|
+
// inside it, or a destination whose branches this clone does not track is a refusal. The
|
|
7
|
+
// rebase runs with no hook at all, without autosquash and without moving other branches,
|
|
8
|
+
// behind a backup ref that is never overwritten, and is checked afterwards: every commit
|
|
9
|
+
// still there, each by the pin. Nothing here pushes.
|
|
10
|
+
import { ok, err } from "./result.js";
|
|
11
|
+
import { pushTarget, unknownDestination } from "./push-destination.js";
|
|
12
|
+
import { AMEND_COMMAND, isOwn, otherAddresses } from "./unpushed.js";
|
|
13
|
+
const IDENTITY_ENV = ['GIT_AUTHOR_NAME', 'GIT_AUTHOR_EMAIL', 'GIT_COMMITTER_NAME', 'GIT_COMMITTER_EMAIL'];
|
|
14
|
+
const IDENTITY_CONFIG = ['author.email', 'committer.email', 'author.name', 'committer.name'];
|
|
15
|
+
/** Null: nothing by another address. An error is a refusal, and nothing was changed. */
|
|
16
|
+
export async function planReauthor(git, email, interactive) {
|
|
17
|
+
const ready = await preconditions(git, interactive);
|
|
18
|
+
if (!ready.ok)
|
|
19
|
+
return ready;
|
|
20
|
+
const { branch, remote } = ready.value;
|
|
21
|
+
const fetched = await git.fetchQuietly(remote);
|
|
22
|
+
if (!fetched.ok)
|
|
23
|
+
return err('could not fetch ' + remote + ' (' + fetched.error + '); nothing rewritten');
|
|
24
|
+
const empty = await destinationEmpty(git, remote);
|
|
25
|
+
if (!empty.ok)
|
|
26
|
+
return empty;
|
|
27
|
+
return foreignRange(git, { branch, remote, email, empty: empty.value });
|
|
28
|
+
}
|
|
29
|
+
async function preconditions(git, interactive) {
|
|
30
|
+
const head = await git.currentBranch();
|
|
31
|
+
if (head?.kind !== 'branch')
|
|
32
|
+
return err('HEAD is detached: switch to a branch first');
|
|
33
|
+
const blocked = await firstRefusal(git, interactive);
|
|
34
|
+
if (blocked)
|
|
35
|
+
return err(blocked);
|
|
36
|
+
const unknown = await unknownDestination(git, head.name);
|
|
37
|
+
if (unknown && unknown.kind !== 'remote')
|
|
38
|
+
return err('this branch does not push to a remote repown can fetch: point the branch at a remote first');
|
|
39
|
+
const target = await pushTarget(git, head.name);
|
|
40
|
+
if (!target?.isRemote)
|
|
41
|
+
return err('this branch has no remote to push to');
|
|
42
|
+
return ok({ branch: head.name, remote: target.name });
|
|
43
|
+
}
|
|
44
|
+
/** Each check that would make the rewrite unsafe, or not use the pinned identity. */
|
|
45
|
+
async function firstRefusal(git, interactive) {
|
|
46
|
+
if (!await git.getConfig('repown.account', 'local'))
|
|
47
|
+
return 'this clone is not pinned: repown use <account> first';
|
|
48
|
+
const env = IDENTITY_ENV.find((name) => process.env[name]);
|
|
49
|
+
if (env)
|
|
50
|
+
return env + ' is set: the rewrite would not use the pinned address (unset it)';
|
|
51
|
+
for (const key of IDENTITY_CONFIG)
|
|
52
|
+
if (await git.getConfig(key))
|
|
53
|
+
return key + ' is set: the rewrite would not use the pinned address';
|
|
54
|
+
const busy = await git.operationInProgress();
|
|
55
|
+
if (busy)
|
|
56
|
+
return 'a ' + busy + ' is in progress: finish or abort it first';
|
|
57
|
+
const dirty = await git.hasTrackedChanges();
|
|
58
|
+
if (!dirty.ok || dirty.value)
|
|
59
|
+
return 'this clone has uncommitted changes (or files hidden with skip-worktree): commit or stash them first';
|
|
60
|
+
if (!interactive && await git.getBoolConfig('commit.gpgsign') === true)
|
|
61
|
+
return 'commit.gpgsign is on and there is no terminal to sign in: run repown reauthor in a terminal';
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
/** True only when a successful fetch left no tracking refs AND the remote lists no branches. */
|
|
65
|
+
async function destinationEmpty(git, remote) {
|
|
66
|
+
const tracked = await git.hasTrackingRefs(remote);
|
|
67
|
+
if (!tracked.ok)
|
|
68
|
+
return tracked;
|
|
69
|
+
if (tracked.value)
|
|
70
|
+
return ok(false);
|
|
71
|
+
const heads = await git.remoteHeadCount(remote);
|
|
72
|
+
if (!heads.ok)
|
|
73
|
+
return err('could not list ' + remote + '\'s branches (' + heads.error + '); nothing rewritten');
|
|
74
|
+
if (heads.value > 0)
|
|
75
|
+
return err('this clone does not track ' + remote + '\'s branches, so it can\'t tell what ' + remote + ' already has');
|
|
76
|
+
return ok(true);
|
|
77
|
+
}
|
|
78
|
+
async function foreignRange(git, scope) {
|
|
79
|
+
const listed = await git.identitiesIn(['--topo-order', 'HEAD', '--not', '--remotes']);
|
|
80
|
+
if (!listed.ok)
|
|
81
|
+
return listed;
|
|
82
|
+
const foreign = listed.value.filter((commit) => !isOwn(commit, scope.email));
|
|
83
|
+
const oldest = foreign.at(-1);
|
|
84
|
+
if (!oldest)
|
|
85
|
+
return ok(null);
|
|
86
|
+
const parent = await git.parentOf(oldest.sha);
|
|
87
|
+
if (!parent && !scope.empty)
|
|
88
|
+
return err('the oldest of these commits is a root, and ' + scope.remote + ' is not empty');
|
|
89
|
+
const base = parent ?? '--root';
|
|
90
|
+
const checked = await checkRange(git, base);
|
|
91
|
+
if (!checked.ok)
|
|
92
|
+
return checked;
|
|
93
|
+
return ok({ branch: scope.branch, remote: scope.remote, base, count: checked.value, addresses: otherAddresses(foreign, scope.email) });
|
|
94
|
+
}
|
|
95
|
+
/** The range must be linear and unpublished: a rebase flattens merges and rewrites all it covers. */
|
|
96
|
+
async function checkRange(git, base) {
|
|
97
|
+
const range = base === '--root' ? ['HEAD'] : [base + '..HEAD'];
|
|
98
|
+
const [all, merges, unpushed] = await Promise.all([
|
|
99
|
+
git.countIn(range), git.countIn(['--merges', ...range]), git.countIn([...range, '--not', '--remotes']),
|
|
100
|
+
]);
|
|
101
|
+
if (!all.ok)
|
|
102
|
+
return all;
|
|
103
|
+
if (!merges.ok)
|
|
104
|
+
return merges;
|
|
105
|
+
if (!unpushed.ok)
|
|
106
|
+
return unpushed;
|
|
107
|
+
if (merges.value > 0)
|
|
108
|
+
return err('the commits to rewrite include a merge, which a rebase would flatten: re-author them by hand');
|
|
109
|
+
if (unpushed.value !== all.value)
|
|
110
|
+
return err('a remote already has some commits in that range; nothing rewritten');
|
|
111
|
+
return ok(all.value);
|
|
112
|
+
}
|
|
113
|
+
/** Backup, rebase, check. On any failure HEAD is put back where it was, or the backup is named. */
|
|
114
|
+
export async function applyReauthor(git, plan, email) {
|
|
115
|
+
const head = await git.revParse('HEAD');
|
|
116
|
+
const backup = 'refs/repown/backup/' + plan.branch + '/' + Math.floor(Date.now() / 1000);
|
|
117
|
+
if (!head || !await git.createRef(backup, head))
|
|
118
|
+
return err('could not write a new backup ref (one from this second exists?); nothing rewritten');
|
|
119
|
+
const rebased = await git.rebaseExec(plan.base, AMEND_COMMAND);
|
|
120
|
+
if (!rebased.ok)
|
|
121
|
+
return err(await restored(git, { head, branch: plan.branch, backup }, rebased.error));
|
|
122
|
+
return checked(git, plan, email, backup);
|
|
123
|
+
}
|
|
124
|
+
/** Every planned commit is still there, and each is by the pin; otherwise the backup is named. */
|
|
125
|
+
async function checked(git, plan, email, backup) {
|
|
126
|
+
const range = plan.base === '--root' ? ['HEAD'] : [plan.base + '..HEAD'];
|
|
127
|
+
const after = await git.identitiesIn(range);
|
|
128
|
+
if (!after.ok)
|
|
129
|
+
return err('the rewritten commits could not be read (' + after.error + '); the original is at ' + backup);
|
|
130
|
+
if (after.value.length !== plan.count) {
|
|
131
|
+
return err(plan.count + ' commits were planned but ' + after.value.length + ' came out; the original is at ' + backup);
|
|
132
|
+
}
|
|
133
|
+
if (after.value.some((commit) => !isOwn(commit, email)))
|
|
134
|
+
return err('the rewritten commits do not all carry ' + email + '; the original is at ' + backup);
|
|
135
|
+
return ok({ count: after.value.length, backup });
|
|
136
|
+
}
|
|
137
|
+
/** "Nothing rewritten" only when the abort worked and the branch is back on its old commit. */
|
|
138
|
+
async function restored(git, before, why) {
|
|
139
|
+
const aborted = await git.abortRebase() || await git.operationInProgress() === null;
|
|
140
|
+
const [now, branch] = await Promise.all([git.revParse('HEAD'), git.currentBranch()]);
|
|
141
|
+
const back = aborted && now === before.head && branch?.kind === 'branch' && branch.name === before.branch;
|
|
142
|
+
return back
|
|
143
|
+
? 'the rebase failed (' + why + '); nothing rewritten'
|
|
144
|
+
: 'the rebase failed (' + why + ') and the branch did not return; finish with git rebase --abort, and the original is at ' + before.backup;
|
|
145
|
+
}
|