repown 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
@@ -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
  }
package/dist/program.js CHANGED
@@ -6,6 +6,7 @@ export const COMMANDS = {
6
6
  off: async () => (await import("./commands/off.js")).default,
7
7
  doctor: async () => (await import("./commands/doctor.js")).default,
8
8
  fix: async () => (await import("./commands/fix.js")).default,
9
+ reauthor: async () => (await import("./commands/reauthor.js")).default,
9
10
  guard: async () => (await import("./commands/guard.js")).default,
10
11
  accounts: async () => (await import("./commands/accounts.js")).default,
11
12
  scan: async () => (await import("./commands/scan.js")).default,
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')
@@ -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
  }