repown 0.5.0 → 0.5.2

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.
@@ -17,22 +17,60 @@ export async function inspectRepo(git) {
17
17
  const isRepo = await git.isRepo();
18
18
  const originUrl = isRepo ? await git.getConfig('remote.origin.url') : null;
19
19
  const url = originUrl ? parseGitUrl(originUrl) : null;
20
- const provider = providerFor(url);
21
- const credentialKeys = url ? provider.credentialKeys(url) : [];
20
+ const sides = await originSides(git, originUrl);
22
21
  const [root, branch, hook, identity, guard, helper] = await Promise.all([
23
22
  isRepo ? git.root() : Promise.resolve(null),
24
23
  isRepo ? git.currentBranch() : Promise.resolve(null),
25
24
  isRepo ? hookLocation(git) : Promise.resolve(null),
26
- readIdentity(git, credentialKeys[0] ?? null),
25
+ readIdentity(git, sides.credential.keys[0] ?? null),
27
26
  isRepo ? guardState(git) : Promise.resolve('off'),
28
- git.getUrlMatch('credential.helper', originUrl ?? DEFAULT_PROBE_URL),
27
+ git.getUrlMatch('credential.helper', sides.credential.url ?? DEFAULT_PROBE_URL),
29
28
  ]);
30
29
  return {
31
- git, isRepo, root, branch, originUrl, url, provider,
32
- owner: url ? provider.ownerOf(url) : null,
33
- identity, credentialKeys, guard, hook, helper,
30
+ git, isRepo, root, branch, originUrl, url, provider: providerFor(url),
31
+ owner: sides.owner, ownerProvider: sides.ownerProvider,
32
+ identity, credentialKeys: sides.credential.keys, credentialUrl: sides.credential.url,
33
+ credentialHost: sides.credential.host, guard, hook, helper,
34
34
  };
35
35
  }
36
+ /** Origin's URLs as git uses them, read once for both the push owner and the credential side. */
37
+ async function originSides(git, originUrl) {
38
+ if (!originUrl)
39
+ return { owner: null, ownerProvider: providerFor(null), credential: { keys: [], url: null, host: providerFor(null) } };
40
+ const [fetched, pushed] = await Promise.all([git.remoteUrls('origin', false), git.remoteUrls('origin', true)]);
41
+ const owner = await pushSide(git, originUrl, pushed);
42
+ return { owner: owner.owner, ownerProvider: owner.provider, credential: credentialSide(originUrl, [fetched, pushed]) };
43
+ }
44
+ /**
45
+ * Who origin's pushes go to, and on which host: the URL git pushes to (pushurl,
46
+ * pushInsteadOf, insteadOf), the one the guard checks (the first, when there are several).
47
+ * The owner and its host always come from that same URL.
48
+ */
49
+ async function pushSide(git, originUrl, pushed) {
50
+ const url = parseGitUrl((pushed.ok ? pushed.value[0] : await git.remotePushUrl('origin')) ?? originUrl);
51
+ const provider = providerFor(url);
52
+ return { owner: url ? provider.ownerOf(url) : null, provider };
53
+ }
54
+ /**
55
+ * Every credential request git makes for origin goes to one of these URLs, after insteadOf
56
+ * and pushInsteadOf; each gets its own host's keys. When git can't list them nothing is
57
+ * claimed, and the configured URL is the one described.
58
+ */
59
+ function credentialSide(originUrl, listed) {
60
+ const urls = listed.every((urls) => urls.ok) ? listed.flatMap((urls) => (urls.ok ? urls.value : [])) : [];
61
+ const keyed = urls.map((raw) => ({ raw, keys: keysOf(raw) }));
62
+ const url = keyed.find((entry) => entry.keys.length > 0)?.raw ?? urls[0] ?? originUrl;
63
+ return { keys: [...new Set(keyed.flatMap((entry) => entry.keys))], url, host: providerFor(parseGitUrl(url)) };
64
+ }
65
+ /** Whether repown pins a credential for this clone: only where it measured one (ADR-009). */
66
+ export function pinsCredential(repo) {
67
+ return repo.credentialKeys.length > 0;
68
+ }
69
+ /** The credential keys repown pins for one URL; empty where it can't pin (ADR-009). */
70
+ export function keysOf(raw) {
71
+ const url = parseGitUrl(raw);
72
+ return url ? providerFor(url).credentialKeys(url) : [];
73
+ }
36
74
  export async function inspectAuth(git, probeUrl) {
37
75
  const gcmPath = await findGcm();
38
76
  const [stored, gh, present, helper, ghHelperOrigins] = await Promise.all([
@@ -8,10 +8,17 @@
8
8
  // unfetched one, and FETCH_HEAD is no answer: a FAILED fetch writes it too, and it
9
9
  // belongs to whichever remote was fetched last. So the destination is only ever
10
10
  // "known" (it has tracking refs, and pushes where it fetches from) or "unknown",
11
- // and a read that fails is unknown.
11
+ // and a read that fails is unknown. A remote that fetches only some branches (a
12
+ // --single-branch clone, a negative refspec) is unknown for a branch it leaves out:
13
+ // pushing that branch updates no tracking ref (refspec.ts).
12
14
  import { parseGitUrl } from './url.js';
15
+ import { ok } from './result.js';
16
+ import { trackingPrefixes, trackingRefOf } from './refspec.js';
17
+ import { readerOf } from './config-snapshot.js';
13
18
  /** Null when the branch pushes nowhere, to `.` (this repository), or where tracking refs reach. */
14
- export async function unknownDestination(git, branch) {
19
+ export async function unknownDestination(given, branch) {
20
+ // Read-only: one config list answers every key read below (ADR-029).
21
+ const git = readerOf(given);
15
22
  const listed = await git.readRemotes();
16
23
  if (!listed.ok)
17
24
  return { kind: 'unread' };
@@ -21,13 +28,14 @@ export async function unknownDestination(git, branch) {
21
28
  if (!name || name === '.')
22
29
  return null;
23
30
  if (listed.value.includes(name))
24
- return remoteState(git, name);
31
+ return remoteState(git, { name, branch, remotes: listed.value });
25
32
  if (!set || !looksLikeUrl(name))
26
33
  return { kind: 'unnamed', name };
27
34
  return { kind: 'url', key: set.key, remote: await remoteWithUrl(git, listed.value, name) };
28
35
  }
29
36
  /** Null when there is no destination, it is `.`, or the remotes could not be listed. */
30
- export async function pushTarget(git, branch) {
37
+ export async function pushTarget(given, branch) {
38
+ const git = readerOf(given);
31
39
  const listed = await git.readRemotes();
32
40
  if (!listed.ok)
33
41
  return null;
@@ -47,21 +55,53 @@ async function configuredTarget(git, branch) {
47
55
  }
48
56
  return null;
49
57
  }
50
- async function remoteState(git, name) {
51
- if (!await isTracked(git, name))
58
+ async function remoteState(git, remote) {
59
+ const { name } = remote;
60
+ const tracked = await trackingRefsOf(git, name, remote.remotes);
61
+ if (!tracked.ok || !tracked.value)
52
62
  return { kind: 'remote', name };
53
- return await pushesElsewhere(git, name) ? { kind: 'pushurl', name } : null;
63
+ if (await pushesElsewhere(git, name))
64
+ return { kind: 'pushurl', name };
65
+ const branch = await destinationBranch(git, remote);
66
+ const specs = await git.getAllConfig('remote.' + name + '.fetch');
67
+ return trackingRefOf(specs, 'refs/heads/' + branch) ? null : { kind: 'untracked', name, branch };
54
68
  }
55
- async function isTracked(git, remote) {
56
- const found = await git.hasTrackingRefs(remote);
57
- return found.ok && found.value;
69
+ /** Whether the remote has any tracking ref where its own refspecs write them. */
70
+ export async function hasTrackingRefs(given, remote) {
71
+ const git = readerOf(given);
72
+ const listed = await git.readRemotes();
73
+ if (!listed.ok)
74
+ return listed;
75
+ return trackingRefsOf(git, remote, listed.value);
76
+ }
77
+ /** Another remote's namespace nested inside this one's (`origin/x` in `origin`'s) is not this one's. */
78
+ async function trackingRefsOf(git, remote, remotes) {
79
+ const prefixes = trackingPrefixes(await git.getAllConfig('remote.' + remote + '.fetch'));
80
+ if (prefixes.length === 0)
81
+ return ok(false);
82
+ const others = await Promise.all(remotes.filter((other) => other !== remote).map((other) => git.getAllConfig('remote.' + other + '.fetch')));
83
+ const nested = others.flatMap(trackingPrefixes).filter((other) => prefixes.some((own) => other.length > own.length && other.startsWith(own)));
84
+ return git.hasRefsUnder(prefixes, nested);
85
+ }
86
+ /** The branch a plain push updates: the upstream's under push.default=upstream, else its own name. */
87
+ async function destinationBranch(git, remote) {
88
+ if (await git.getConfig('push.default') !== 'upstream')
89
+ return remote.branch;
90
+ if (await git.getConfig('branch.' + remote.branch + '.remote') !== remote.name)
91
+ return remote.branch;
92
+ const merge = await git.getConfig('branch.' + remote.branch + '.merge');
93
+ return merge ? merge.replace(/^refs\/heads\//, '') : remote.branch;
58
94
  }
59
- /** Tracking refs come from the fetch URL; a different pushurl is somewhere never fetched. */
95
+ /**
96
+ * Tracking refs come from the first fetch URL; any push URL elsewhere (a pushurl, a second
97
+ * url, a pushInsteadOf rewrite) is somewhere never fetched. A failed read is elsewhere.
98
+ */
60
99
  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') ?? '');
100
+ const [push, fetch] = await Promise.all([git.remoteUrls(remote, true), git.remoteUrls(remote, false)]);
101
+ if (!push.ok || !fetch.ok)
102
+ return true;
103
+ const fetched = urlKey(fetch.value[0] ?? '');
104
+ return push.value.some((url) => urlKey(url) !== fetched);
65
105
  }
66
106
  /** A URL or a path, as git would read it where a remote name was expected. */
67
107
  function looksLikeUrl(value) {
@@ -6,7 +6,7 @@
6
6
  // the way a plain `git push` resolves it (push-destination.ts), and a secret in a URL is
7
7
  // only ever reported by the config key that holds it.
8
8
  import { ok } from './result.js';
9
- import { pushTarget, unknownDestination } from './push-destination.js';
9
+ import { hasTrackingRefs, pushTarget, unknownDestination } from './push-destination.js';
10
10
  import { parseGitUrl } from './url.js';
11
11
  import { providerFor } from './hosts/index.js';
12
12
  import { hostileSet } from './guard/check.js';
@@ -49,13 +49,13 @@ async function repointOf(git, branch) {
49
49
  const unknown = branch ? await unknownDestination(git, branch) : null;
50
50
  if (unknown?.kind !== 'url' || !unknown.remote)
51
51
  return null;
52
- const tracked = await git.hasTrackingRefs(unknown.remote);
52
+ const tracked = await hasTrackingRefs(git, unknown.remote);
53
53
  return { key: unknown.key, remote: unknown.remote, tracked: tracked.ok && tracked.value };
54
54
  }
55
55
  async function destinationOf(git, target) {
56
56
  if (!target)
57
57
  return null;
58
- const raw = target.isRemote ? await pushUrlOf(git, target.name) : target.name;
58
+ const raw = target.isRemote ? await pushUrlOf(git, target.name) : await bareTargetUrl(git, target.name);
59
59
  const url = raw ? parseGitUrl(raw) : null;
60
60
  const owner = url ? providerFor(url).ownerOf(url) : null;
61
61
  if (!owner)
@@ -63,8 +63,12 @@ async function destinationOf(git, target) {
63
63
  const allowed = (await git.getAllConfig('repown.allowOwner', 'local')).map((value) => value.toLowerCase());
64
64
  return { remote: target.isRemote ? target.name : null, owner, allowed };
65
65
  }
66
- async function pushUrlOf(git, remote) {
67
- return (await git.getConfig('remote.' + remote + '.pushurl')) ?? git.getConfig('remote.' + remote + '.url');
66
+ function pushUrlOf(git, remote) {
67
+ return git.remotePushUrl(remote);
68
+ }
69
+ /** A push straight to a URL, as git rewrites it (insteadOf; see rewrittenUrl). */
70
+ async function bareTargetUrl(git, url) {
71
+ return (await git.rewrittenUrl(url)) ?? url;
68
72
  }
69
73
  /** Only the tracked ref ON the destination: a triangular workflow's upstream does not block its push. */
70
74
  async function divergenceOf(git, target) {
@@ -2,13 +2,14 @@
2
2
  //
3
3
  // The one place repown rewrites history, so it refuses rather than guesses. It fetches the
4
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
5
+ // topologically oldest one by another address, leaving out what the destination's branches
6
+ // and tags reach (ls-remote); a merge in that range, a commit a remote has inside it, or a
7
+ // destination with branches this clone has not fetched is a refusal. The
7
8
  // rebase runs with no hook at all, without autosquash and without moving other branches,
8
9
  // behind a backup ref that is never overwritten, and is checked afterwards: every commit
9
10
  // still there, each by the pin. Nothing here pushes.
10
11
  import { ok, err } from './result.js';
11
- import { pushTarget, unknownDestination } from './push-destination.js';
12
+ import { hasTrackingRefs, pushTarget, unknownDestination } from './push-destination.js';
12
13
  import { AMEND_COMMAND, isOwn, otherAddresses } from './unpushed.js';
13
14
  const IDENTITY_ENV = ['GIT_AUTHOR_NAME', 'GIT_AUTHOR_EMAIL', 'GIT_COMMITTER_NAME', 'GIT_COMMITTER_EMAIL'];
14
15
  const IDENTITY_CONFIG = ['author.email', 'committer.email', 'author.name', 'committer.name'];
@@ -24,7 +25,10 @@ export async function planReauthor(git, email, interactive) {
24
25
  const empty = await destinationEmpty(git, remote);
25
26
  if (!empty.ok)
26
27
  return empty;
27
- return foreignRange(git, { branch, remote, email, empty: empty.value });
28
+ const published = await publishedHere(git, remote);
29
+ if (!published.ok)
30
+ return published;
31
+ return foreignRange(git, { branch, remote, email, empty: empty.value, published: published.value });
28
32
  }
29
33
  async function preconditions(git, interactive) {
30
34
  const head = await git.currentBranch();
@@ -34,7 +38,7 @@ async function preconditions(git, interactive) {
34
38
  if (blocked)
35
39
  return err(blocked);
36
40
  const unknown = await unknownDestination(git, head.name);
37
- if (unknown && unknown.kind !== 'remote')
41
+ if (unknown && unknown.kind !== 'remote' && unknown.kind !== 'untracked')
38
42
  return err('this branch does not push to a remote repown can fetch: point the branch at a remote first');
39
43
  const target = await pushTarget(git, head.name);
40
44
  if (!target?.isRemote)
@@ -63,7 +67,7 @@ async function firstRefusal(git, interactive) {
63
67
  }
64
68
  /** True only when a successful fetch left no tracking refs AND the remote lists no branches. */
65
69
  async function destinationEmpty(git, remote) {
66
- const tracked = await git.hasTrackingRefs(remote);
70
+ const tracked = await hasTrackingRefs(git, remote);
67
71
  if (!tracked.ok)
68
72
  return tracked;
69
73
  if (tracked.value)
@@ -75,8 +79,31 @@ async function destinationEmpty(git, remote) {
75
79
  return err('this clone does not track ' + remote + '\'s branches, so it can\'t tell what ' + remote + ' already has');
76
80
  return ok(true);
77
81
  }
82
+ /**
83
+ * The commits the remote's branches and tags point at, as commits here: what a fetch
84
+ * refspec that leaves branches out, or a pushed tag, hides from `--not --remotes`.
85
+ * A branch tip this clone lacks may sit on top of these commits, so that is a refusal;
86
+ * a tag on a commit this clone lacks is skipped (tags are fetched only when they follow).
87
+ */
88
+ async function publishedHere(git, remote) {
89
+ const tips = await git.remoteTips(remote);
90
+ if (!tips.ok)
91
+ return err('could not list ' + remote + '\'s branches (' + tips.error + '); nothing rewritten');
92
+ const [heads, tags] = await Promise.all([git.localCommits(tips.value.heads), git.localCommits(tips.value.tags)]);
93
+ if (!heads.ok)
94
+ return heads;
95
+ if (!tags.ok)
96
+ return tags;
97
+ if (heads.value.includes(null))
98
+ return err(unfetched(remote));
99
+ return ok([...heads.value, ...tags.value].filter((sha) => sha !== null));
100
+ }
101
+ function unfetched(remote) {
102
+ return remote + ' has commits this clone has not fetched (remote.' + remote + '.fetch leaves some of its branches out, ' +
103
+ 'or something was pushed since the fetch), so repown can\'t tell which of these it already has; nothing rewritten';
104
+ }
78
105
  async function foreignRange(git, scope) {
79
- const listed = await git.identitiesIn(['--topo-order', 'HEAD', '--not', '--remotes']);
106
+ const listed = await git.identitiesIn(['--topo-order', 'HEAD', '--not', '--remotes'], scope.published);
80
107
  if (!listed.ok)
81
108
  return listed;
82
109
  const foreign = listed.value.filter((commit) => !isOwn(commit, scope.email));
@@ -87,16 +114,16 @@ async function foreignRange(git, scope) {
87
114
  if (!parent && !scope.empty)
88
115
  return err('the oldest of these commits is a root, and ' + scope.remote + ' is not empty');
89
116
  const base = parent ?? '--root';
90
- const checked = await checkRange(git, base);
117
+ const checked = await checkRange(git, base, scope.published);
91
118
  if (!checked.ok)
92
119
  return checked;
93
120
  return ok({ branch: scope.branch, remote: scope.remote, base, count: checked.value, addresses: otherAddresses(foreign, scope.email) });
94
121
  }
95
122
  /** The range must be linear and unpublished: a rebase flattens merges and rewrites all it covers. */
96
- async function checkRange(git, base) {
123
+ async function checkRange(git, base, published) {
97
124
  const range = base === '--root' ? ['HEAD'] : [base + '..HEAD'];
98
125
  const [all, merges, unpushed] = await Promise.all([
99
- git.countIn(range), git.countIn(['--merges', ...range]), git.countIn([...range, '--not', '--remotes']),
126
+ git.countIn(range), git.countIn(['--merges', ...range]), git.countIn([...range, '--not', '--remotes'], published),
100
127
  ]);
101
128
  if (!all.ok)
102
129
  return all;
@@ -0,0 +1,45 @@
1
+ // A remote's fetch refspecs (`remote.<name>.fetch`), read the way git reads them: which
2
+ // tracking ref a branch gets, and where the remote's tracking refs live (ADR-025).
3
+ //
4
+ // A clone made with --single-branch fetches only its one branch, and a negative refspec
5
+ // (`^refs/heads/x`) leaves a branch out. A push of such a branch updates no tracking ref,
6
+ // so `HEAD --not --remotes` cannot see what that push published.
7
+ /** `HEAD --not --remotes` counts only these: a tracking ref anywhere else proves nothing. */
8
+ const REMOTES = 'refs/remotes/';
9
+ /** The tracking ref the refspecs give `ref` (a full `refs/heads/...` name) under refs/remotes/, or null. */
10
+ export function trackingRefOf(specs, ref) {
11
+ const parsed = specs.map(parse);
12
+ if (parsed.some((spec) => spec.negative && matched(spec.src, ref) !== null))
13
+ return null;
14
+ for (const spec of parsed) {
15
+ const middle = spec.negative || !spec.dst ? null : matched(spec.src, ref);
16
+ const tracking = middle === null ? null : spec.dst.replace('*', middle);
17
+ if (tracking?.startsWith(REMOTES))
18
+ return tracking;
19
+ }
20
+ return null;
21
+ }
22
+ /** Where the refspecs write under refs/remotes/: the namespace before a glob's star, or the exact ref. */
23
+ export function trackingPrefixes(specs) {
24
+ const written = specs.map(parse).flatMap((spec) => spec.negative || !spec.dst ? [] : [spec.dst.split('*')[0]]);
25
+ return written.filter((prefix) => prefix.startsWith(REMOTES));
26
+ }
27
+ function parse(raw) {
28
+ const text = raw.trim().replace(/^\+/, '');
29
+ if (text.startsWith('^'))
30
+ return { src: text.slice(1), dst: null, negative: true };
31
+ const colon = text.indexOf(':');
32
+ if (colon < 0)
33
+ return { src: text, dst: null, negative: false };
34
+ return { src: text.slice(0, colon), dst: text.slice(colon + 1) || null, negative: false };
35
+ }
36
+ /** What the star stands for ('' for an exact match), or null when `ref` does not match. */
37
+ function matched(src, ref) {
38
+ const full = src.startsWith('refs/') ? src : 'refs/heads/' + src;
39
+ const star = full.indexOf('*');
40
+ if (star < 0)
41
+ return full === ref ? '' : null;
42
+ const [before, after] = [full.slice(0, star), full.slice(star + 1)];
43
+ const fits = ref.length >= before.length + after.length && ref.startsWith(before) && ref.endsWith(after);
44
+ return fits ? ref.slice(before.length, ref.length - after.length) : null;
45
+ }
@@ -69,13 +69,20 @@ function readAccounts(value) {
69
69
  }
70
70
  return { accounts, unreadable };
71
71
  }
72
+ /** Why a write would fail or drop entries, or null when it would keep every entry. */
73
+ export function writeProblem(registry) {
74
+ if (!registry.ok)
75
+ return registry.error;
76
+ if (registry.value.unreadable.length === 0)
77
+ return null;
78
+ return registryPath() + ' has entries repown cannot read (' + registry.value.unreadable.join(', ') +
79
+ ') -- saving would drop them; fix or remove them first';
80
+ }
72
81
  /** The registry, but only if a write would keep every entry in it. */
73
82
  async function loadForWrite() {
74
83
  const registry = await loadRegistry();
75
- if (!registry.ok || registry.value.unreadable.length === 0)
76
- return registry;
77
- return err(registryPath() + ' has entries repown cannot read (' + registry.value.unreadable.join(', ') +
78
- ') -- saving would drop them; fix or remove them first');
84
+ const problem = writeProblem(registry);
85
+ return problem === null || !registry.ok ? registry : err(problem);
79
86
  }
80
87
  export async function lookupAccount(account) {
81
88
  const registry = await loadRegistry();
@@ -0,0 +1,32 @@
1
+ // Commands printed for someone to copy and paste, quoted so every shell reads them the same
2
+ // (test/paste.test.ts runs each). Build any copyable word here, never by hand.
3
+ /**
4
+ * A word of a command printed to copy, as sh, bash, dash, zsh, fish, PowerShell and cmd all
5
+ * read it (test/paste.test.ts runs each). Bare when no shell treats any of it specially: a
6
+ * leading `@` is a PowerShell splat, and PowerShell splits a dashed word at `.` or `:`.
7
+ * `--` is quoted, since PowerShell drops a bare one from the `$args` of repown.ps1.
8
+ * Otherwise double quotes, unless they would expand or end early somewhere: `$` and a
9
+ * backtick (POSIX, PowerShell), `%` and `!` (cmd), a curly double quote (PowerShell), a
10
+ * backslash that escapes (`\\`, or one before the closing quote), a control character, or
11
+ * nothing at all (Windows PowerShell drops `""`). Then it is null and the caller prints no
12
+ * command: single quotes are no quotes in cmd, and PowerShell would run the rest of a
13
+ * POSIX `'\''` as code.
14
+ */
15
+ export function shellWord(value) {
16
+ if (value === '--')
17
+ return '"--"';
18
+ if (/^(?:-[\w-]*|[\w./][\w.@+/:-]*)$/.test(value))
19
+ return value;
20
+ if (value === '' || /["$`%!“”„\x00-\x1f\x7f-\x9f]|\\\\|\\$/.test(value))
21
+ return null;
22
+ return '"' + value + '"';
23
+ }
24
+ /** A whole command to copy, or null when one of its words can't be printed safely (shellWord). */
25
+ export function copyableCommand(words) {
26
+ const quoted = words.map(shellWord);
27
+ return quoted.every((word) => word !== null) ? quoted.join(' ') : null;
28
+ }
29
+ /** A git positional (a remote name) as argv words: after `--` when git would read it as an option. */
30
+ export function positional(word) {
31
+ return word.startsWith('-') ? ['--', word] : [word];
32
+ }
@@ -13,7 +13,7 @@
13
13
  // setup loads them only for the guard question.
14
14
  import { ok } from './result.js';
15
15
  import { unknownDestination } from './push-destination.js';
16
- import { copyableCommand, shellWord } from './guard/check.js';
16
+ import { copyableCommand, positional, shellWord } from './shell.js';
17
17
  const ADDRESS_CAP = 3;
18
18
  /** The one re-author command: the advice prints it, and `repown reauthor` runs it. */
19
19
  export const AMEND_COMMAND = 'git commit --amend --no-edit --reset-author --allow-empty';
@@ -77,7 +77,7 @@ function advice(fact, found, account) {
77
77
  return [unknownLine(fact.unknown, account), ...rebase.map((line) => 'if ' + holder + ' has none of them, ' + line)];
78
78
  }
79
79
  function holderOf(unknown) {
80
- return unknown.kind === 'remote' || unknown.kind === 'pushurl' ? show(unknown.name) : 'it';
80
+ return unknown.kind === 'remote' || unknown.kind === 'pushurl' || unknown.kind === 'untracked' ? show(unknown.name) : 'it';
81
81
  }
82
82
  /** The guard excludes what the pushed branch's remote tip has, not everything the remote holds. */
83
83
  const GUARD = ' (the guard skips any already on the branch you push to)';
@@ -86,6 +86,7 @@ function unknownLine(unknown, account) {
86
86
  switch (unknown.kind) {
87
87
  case 'remote': return trackingLine(unknown.name, account);
88
88
  case 'pushurl': return show(unknown.name) + ' pushes to another URL than it fetches from' + THERE;
89
+ case 'untracked': return untrackedLine(unknown.name, unknown.branch);
89
90
  case 'url': return urlLine(unknown.key, unknown.remote, account);
90
91
  case 'unnamed': return 'this branch pushes to "' + show(unknown.name) + '", which is not a remote here' + THERE;
91
92
  case 'unread': return 'the remotes could not be read, so some of these may already be on one' + GUARD;
@@ -93,25 +94,25 @@ function unknownLine(unknown, account) {
93
94
  }
94
95
  function trackingLine(name, account) {
95
96
  const lead = show(name) + ' has no remote-tracking refs, so some of these may already be on it' + GUARD;
96
- const fetch = copyable(name) ? copyableCommand(['git', 'fetch', show(name)]) : null;
97
+ const fetch = copyableCommand(['git', 'fetch', ...positional(show(name))]);
97
98
  return fetch ? lead + ': ' + fetch + ', ' + recount(account) : lead;
98
99
  }
100
+ /** No fetch helps: the refspec itself leaves the branch out, so no tracking ref ever records it. */
101
+ function untrackedLine(remote, branch) {
102
+ return show(remote) + '\'s ' + show(branch) + ' is not fetched here (remote.' + show(remote) + '.fetch leaves it out)' + THERE;
103
+ }
99
104
  function urlLine(key, remote, account) {
100
105
  const lead = 'this branch pushes to a URL, not a remote' + THERE;
101
- if (!remote || !copyable(remote))
106
+ if (!remote)
102
107
  return lead;
103
108
  const repoint = copyableCommand(['git', 'config', '--local', show(key), show(remote)]);
104
- const fetch = copyableCommand(['git', 'fetch', show(remote)]);
109
+ const fetch = copyableCommand(['git', 'fetch', ...positional(show(remote))]);
105
110
  return repoint && fetch ? lead + ': ' + repoint + ', ' + fetch + ', ' + recount(account) : lead;
106
111
  }
107
112
  function recount(account) {
108
113
  const word = shellWord(show(account));
109
114
  return word ? 'then repown use ' + word + ' to count again' : 'then run repown use again to count again';
110
115
  }
111
- /** Quoting keeps a shell from splitting a word, not git from reading `-x` as an option. */
112
- function copyable(word) {
113
- return !word.startsWith('-');
114
- }
115
116
  /** Pinning is an alternative only when one address made them all. */
116
117
  function reauthorLine(found) {
117
118
  const them = found.count === 1 ? 'it' : 'them';
package/dist/ui/format.js CHANGED
@@ -114,6 +114,17 @@ export function dim(text) {
114
114
  export function printable(text) {
115
115
  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'));
116
116
  }
117
+ /** No column: combining marks, format characters (zero-width, bidi), variation selectors. */
118
+ const ZERO_WIDTH = /[\p{Mn}\p{Me}\p{Cf}\u{fe00}-\u{fe0f}]/u;
119
+ /** Two columns: East Asian Wide and Fullwidth, and the emoji blocks. */
120
+ const WIDE = /[\u{1100}-\u{115f}\u{2e80}-\u{303e}\u{3041}-\u{33ff}\u{3400}-\u{4dbf}\u{4e00}-\u{9fff}\u{a000}-\u{a4cf}\u{ac00}-\u{d7a3}\u{f900}-\u{faff}\u{fe30}-\u{fe4f}\u{ff00}-\u{ff60}\u{ffe0}-\u{ffe6}\u{1f004}\u{1f0cf}\u{1f300}-\u{1f64f}\u{1f680}-\u{1f6ff}\u{1f900}-\u{1f9ff}\u{1fa70}-\u{1faff}\u{20000}-\u{3fffd}]/u;
121
+ /** The columns `text` takes in a terminal, for wrapping: not its length in UTF-16 units. */
122
+ export function displayWidth(text) {
123
+ let width = 0;
124
+ for (const char of text)
125
+ width += ZERO_WIDTH.test(char) ? 0 : WIDE.test(char) ? 2 : 1;
126
+ return width;
127
+ }
117
128
  /** Shown to a person. Windows uses native separators; any other platform is unchanged. */
118
129
  export function displayPath(path) {
119
130
  if (process.platform !== 'win32')
package/dist/ui/help.js CHANGED
@@ -12,7 +12,8 @@ export function renderTopHelp(entries) {
12
12
  ...topHeader(entries),
13
13
  ...globalOptionsHelp(),
14
14
  ...environmentHelp(),
15
- ' Exit codes: 0 success, 1 failure or refusal, 2 usage error.',
15
+ ' Exit codes: 0 success, 1 failure or refusal, 2 usage error,',
16
+ ' 130 cancelled (setup, the start screen).',
16
17
  '',
17
18
  ];
18
19
  }
@@ -14,13 +14,14 @@ import { signedInLogins } from './setup-flow.js';
14
14
  /** How many levels below this folder the start screen looks. `repown scan` looks further. */
15
15
  export const HOME_DEPTH = 2;
16
16
  export async function readHome(cwd, deps = {}) {
17
- const [registry, ghIsHelper, clones, identity] = await Promise.all([
18
- registryOf(deps), helperOf(cwd, deps), clonesOf(cwd, deps), (deps.identity ?? identityOf)(cwd),
19
- ]);
20
- return { cwd: resolve(cwd), registry, ghIsHelper, clones, identity };
17
+ const [registry, ghIsHelper, clones] = await Promise.all([registryOf(deps), helperOf(cwd, deps), clonesOf(cwd, deps)]);
18
+ return { cwd: resolve(cwd), registry, ghIsHelper, clones };
21
19
  }
22
- /** Outside a clone, git's own lookup is the global (or system) value. */
23
- async function identityOf(cwd) {
20
+ /**
21
+ * Global user.name and user.email, shown beside a new account's and never filled in: read only
22
+ * when Record an account is chosen. Outside a clone, git's own lookup is the global (or system) value.
23
+ */
24
+ export async function identityOf(cwd) {
24
25
  const git = new Git(cwd);
25
26
  const [name, email] = await Promise.all([git.getConfig('user.name'), git.getConfig('user.email')]);
26
27
  return { name, email };
@@ -6,7 +6,7 @@
6
6
  // Quit exits 0. Esc and Ctrl-C exit 130, the same cancel setup uses. Neither writes.
7
7
  import fixCommand from '../commands/fix.js';
8
8
  import doctorCommand from '../commands/doctor.js';
9
- import accountsGroup from '../commands/accounts.js';
9
+ import accountsGroup, { asked } from '../commands/accounts.js';
10
10
  import { COMMANDS } from '../program.js';
11
11
  import { parseArgs } from '../ui/args.js';
12
12
  import { specFor } from '../ui/command.js';
@@ -14,9 +14,10 @@ import { loadEntries } from '../ui/dispatch.js';
14
14
  import * as out from '../ui/format.js';
15
15
  import { renderTopHelp } from '../ui/help.js';
16
16
  import { CANCEL, runFlow } from './engine.js';
17
- import { readHome, readSignedIn } from './home-context.js';
17
+ import { identityOf, readHome, readSignedIn } from './home-context.js';
18
18
  import { BACK as HOME_BACK, MENU, accountChoices, accountOfChoice, commandFor, homeNote, listedClones, menuItems, summaryLines } from './home-flow.js';
19
- import { BACK_LABEL, BUSY, CANCELLED, QUIT, WHAT_NEXT, WHICH_ACCOUNT, WHICH_CLONE, homeTitle, removeLabel, removeNote, removeQuestion } from './home-text.js';
19
+ import { BACK_LABEL, BUSY, CANCELLED, QUIT, WHAT_NEXT, WHICH_ACCOUNT, WHICH_CLONE, homeTitle, recordBlocked, removeLabel, removeNote, removeQuestion } from './home-text.js';
20
+ import { writeProblem } from '../core/registry.js';
20
21
  import { formatCommand, loginStep, newAccountOf, printable, profileSteps } from './setup-flow.js';
21
22
  import { COMMAND_MARK } from './review-text.js';
22
23
  import { suggester } from './setup-context.js';
@@ -103,7 +104,13 @@ async function runInClone(prompter, cwd) {
103
104
  * then `accounts add` with every answer as a flag, so it has nothing left to ask.
104
105
  */
105
106
  async function recordAccount(prompter, home, deps) {
106
- const ctx = accountContext(home, deps);
107
+ // The same reasons accounts add would give on save, before anyone answers four questions for nothing.
108
+ const blocked = writeProblem(home.registry);
109
+ if (blocked) {
110
+ prompter.note(recordBlocked(printable(blocked)));
111
+ return null;
112
+ }
113
+ const ctx = accountContext(home, deps, await (deps.identity ?? identityOf)(home.cwd));
107
114
  const walk = await runFlow({ steps: [loginStep(ctx), ...profileSteps(ctx)] }, ctx, FIRST_PASS, prompter);
108
115
  if (walk.status === 'cancelled')
109
116
  return finish(prompter, CANCELLED, CANCELLED_CODE);
@@ -136,10 +143,10 @@ async function again(ran) {
136
143
  await ran;
137
144
  return AGAIN;
138
145
  }
139
- function accountContext(home, deps) {
146
+ function accountContext(home, deps, machineIdentity) {
140
147
  const recorded = home.registry.ok ? home.registry.value.accounts : {};
141
148
  return {
142
- recorded, host: 'github', machineIdentity: home.identity,
149
+ recorded, host: 'github', machineIdentity,
143
150
  suggest: deps.suggest ?? suggester(), signedIn: deps.signedIn ?? once(() => readSignedIn(home.cwd)),
144
151
  };
145
152
  }
@@ -155,7 +162,8 @@ async function runOwn(prompter, command, tokens, argv) {
155
162
  out.fail('repown', parsed.error);
156
163
  return 2;
157
164
  }
158
- return command.run(parsed.value);
165
+ // Record an account said while asking what accounts add would warn about a typed login.
166
+ return command.run(command === accountsGroup.actions['add'] ? asked(parsed.value) : parsed.value);
159
167
  }
160
168
  function setupArgs(cwd) {
161
169
  return { positional: [], flags: new Map([['cwd', cwd]]) };
@@ -44,6 +44,10 @@ export function unreadableLine(recorded, unreadable, path) {
44
44
  const tail = unreadable + ' unreadable in ' + path + ': run repown accounts list';
45
45
  return recorded === 0 ? tail : recorded + ' recorded, ' + tail;
46
46
  }
47
+ /** Said instead of the account questions when the answers could not be saved anyway. */
48
+ export function recordBlocked(reason) {
49
+ return 'Record an account needs an account list it can save: ' + reason.replace(/\.$/, '') + '. Nothing was asked.';
50
+ }
47
51
  export function couldNotRead(path) {
48
52
  return 'could not read ' + path;
49
53
  }
@@ -2,6 +2,7 @@
2
2
  // screens say the same thing: the numbered steps, the closing lines, the question, its
3
3
  // choices and which one Enter takes, and "Change an answer". What goes IN the review
4
4
  // comes from the flow (setup-flow.ts).
5
+ import { displayWidth } from '../ui/format.js';
5
6
  /** "Change an answer": the question, and the choice that returns to the review. */
6
7
  export const PICK_QUESTION = 'Which answer do you want to change?';
7
8
  export const BACK_TO_REVIEW = 'Back to the review';
@@ -75,13 +76,13 @@ export function labelOf(text) {
75
76
  * past any indent, a "1. " step number, or a "label " column.
76
77
  */
77
78
  export function wrap(text, width) {
78
- if (text.length <= width)
79
+ if (displayWidth(text) <= width)
79
80
  return [text];
80
- const hang = ' '.repeat(HANG.exec(text)[0].length);
81
+ const hang = ' '.repeat(displayWidth(HANG.exec(text)[0]));
81
82
  const lines = [];
82
83
  let line = '';
83
84
  for (const word of text.split(/(?<=\S) (?=\S)/)) {
84
- if (line && line.length + 1 + word.length > width) {
85
+ if (line && displayWidth(line) + 1 + displayWidth(word) > width) {
85
86
  lines.push(line);
86
87
  line = hang + word.trimStart();
87
88
  }