repown 0.5.1 → 0.5.3

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.
@@ -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';
@@ -15,12 +15,13 @@ export async function readPushFacts(git, unpushed, env = process.env) {
15
15
  const head = await git.currentBranch();
16
16
  const branch = head?.kind === 'branch' ? head.name : null;
17
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),
18
+ const rewritable = await rewritableOf(git, target);
19
+ const [configOverrides, signin, repoint, destination, laterUrls, divergence, elsewhere, upstream] = await Promise.all([
20
+ overridesIn(git), signinOf(git, target, rewritable !== null), repointOf(git, branch), rewritable ? null : destinationOf(git, target), laterUrlsOf(git, target),
20
21
  divergenceOf(git, target), elsewhereOf(git, target), upstreamOf(git, branch, target),
21
22
  ]);
22
23
  return {
23
- unpushed, env: hostileSet(env), configOverrides, elsewhere, signinKey, repoint, destination, divergence,
24
+ unpushed, env: hostileSet(env), configOverrides, elsewhere, signin, repoint, destination, laterUrls, rewritable, divergence,
24
25
  detached: head?.kind === 'detached', upstream,
25
26
  };
26
27
  }
@@ -33,23 +34,55 @@ function carriesSecret(raw) {
33
34
  const user = raw ? parseGitUrl(raw)?.user : null;
34
35
  return !!user && (user.includes(':') || /^(gh[pousr]_|github_pat_)/i.test(user));
35
36
  }
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
- }
37
+ async function signinOf(git, target, rewritable) {
38
+ const found = target?.isRemote ? await remoteSignin(git, target.name) : target && !rewritable ? await bareSignin(git, target) : null;
39
+ if (found)
40
+ return found;
45
41
  const headers = await git.configOrigins('^http\\.(.*\\.)?extraheader$');
46
- return headers[0]?.key ?? null;
42
+ if (!headers[0])
43
+ return null;
44
+ // The key's <url> can hold a password: then only a fixed description is printed.
45
+ return headers[0].key.includes('@') ? { named: 'an http.<url>.extraheader setting' } : { key: headers[0].key };
46
+ }
47
+ /** A push straight to a URL, as typed and after insteadOf; a pushInsteadOf one is not judged (rewritableOf). */
48
+ async function bareSignin(git, target) {
49
+ if (target.key === null)
50
+ return null;
51
+ if (carriesSecret(target.name))
52
+ return { key: target.key };
53
+ return carriesSecret(await bareTargetUrl(git, target.name)) ? { remote: target.key } : null;
54
+ }
55
+ /**
56
+ * Judged on every URL git pushes `remote` with, after its own rewriting, so a token a rule
57
+ * adds is found and one a rule takes out is not. A URL that is a configured value is named
58
+ * by its key; any other came from a rewrite, and only the remote is named.
59
+ */
60
+ async function remoteSignin(git, remote) {
61
+ const pushed = await git.remoteUrls(remote, true);
62
+ if (!pushed.ok)
63
+ return configuredSignin(git, remote);
64
+ const signed = pushed.value.find(carriesSecret);
65
+ if (!signed)
66
+ return null;
67
+ for (const key of ['remote.' + remote + '.pushurl', 'remote.' + remote + '.url']) {
68
+ if ((await git.getAllConfig(key)).includes(signed))
69
+ return { key };
70
+ }
71
+ return { remote };
72
+ }
73
+ /** A git that cannot list the URLs (before 2.7, or config it refuses): every configured value, without rewrites. */
74
+ async function configuredSignin(git, remote) {
75
+ // A push uses pushurl when there is one, so a token in the fetch url does not sign it in.
76
+ const pushurl = 'remote.' + remote + '.pushurl';
77
+ const pushurls = await git.getAllConfig(pushurl);
78
+ const [key, values] = pushurls.length > 0 ? [pushurl, pushurls] : ['remote.' + remote + '.url', await git.getAllConfig('remote.' + remote + '.url')];
79
+ return values.some(carriesSecret) ? { key } : null;
47
80
  }
48
81
  async function repointOf(git, branch) {
49
82
  const unknown = branch ? await unknownDestination(git, branch) : null;
50
83
  if (unknown?.kind !== 'url' || !unknown.remote)
51
84
  return null;
52
- const tracked = await git.hasTrackingRefs(unknown.remote);
85
+ const tracked = await hasTrackingRefs(git, unknown.remote);
53
86
  return { key: unknown.key, remote: unknown.remote, tracked: tracked.ok && tracked.value };
54
87
  }
55
88
  async function destinationOf(git, target) {
@@ -63,10 +96,48 @@ async function destinationOf(git, target) {
63
96
  const allowed = (await git.getAllConfig('repown.allowOwner', 'local')).map((value) => value.toLowerCase());
64
97
  return { remote: target.isRemote ? target.name : null, owner, allowed };
65
98
  }
99
+ async function laterUrlsOf(git, target) {
100
+ if (!target?.isRemote)
101
+ return null;
102
+ const urls = [...new Set(await pushUrlsOf(git, target.name))];
103
+ if (urls.length < 2)
104
+ return null;
105
+ const owners = urls.slice(1).flatMap((raw) => {
106
+ const url = parseGitUrl(raw);
107
+ const provider = providerFor(url);
108
+ const owner = url ? provider.ownerOf(url) : null;
109
+ return owner ? [{ owner, host: provider.label }] : [];
110
+ });
111
+ const allowed = (await git.getAllConfig('repown.allowOwner', 'local')).map((value) => value.toLowerCase());
112
+ return { remote: target.name, owners, allowed };
113
+ }
114
+ /** Every URL git pushes `remote` with; a git that cannot list them gets the configured values. */
115
+ async function pushUrlsOf(git, remote) {
116
+ const listed = await git.remoteUrls(remote, true);
117
+ if (listed.ok)
118
+ return listed.value;
119
+ const pushurls = await git.getAllConfig('remote.' + remote + '.pushurl');
120
+ return pushurls.length > 0 ? pushurls : git.getAllConfig('remote.' + remote + '.url');
121
+ }
66
122
  function pushUrlOf(git, remote) {
67
123
  return git.remotePushUrl(remote);
68
124
  }
69
- /** A push straight to a URL, as git rewrites it (insteadOf; see rewrittenUrl). */
125
+ /**
126
+ * A push straight to a URL that a pushInsteadOf value prefixes (an empty or missing one
127
+ * matches all). No offline git command resolves pushInsteadOf for a bare URL, and git's
128
+ * rules (first-read ties, empty values) were measured as too many to copy, so repown says it
129
+ * can't tell; a failed read can't either. A `remote."<URL>"` section needs nothing here: it
130
+ * makes the URL a remote, whose push URL git itself resolves.
131
+ */
132
+ async function rewritableOf(git, target) {
133
+ if (!target || target.isRemote)
134
+ return null;
135
+ const url = target.name;
136
+ const rules = await git.configValues('^url\\..*\\.pushinsteadof$');
137
+ const ruled = !rules.ok || rules.value.some((value) => value === null || url.startsWith(value));
138
+ return ruled ? { key: target.key ?? 'its push URL' } : null;
139
+ }
140
+ /** A push straight to a URL after insteadOf (see rewrittenUrl); only when no pushInsteadOf may apply (rewritableOf). */
70
141
  async function bareTargetUrl(git, url) {
71
142
  return (await git.rewrittenUrl(url)) ?? url;
72
143
  }
@@ -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
+ }
@@ -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,7 +14,7 @@ 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
19
  import { BACK_LABEL, BUSY, CANCELLED, QUIT, WHAT_NEXT, WHICH_ACCOUNT, WHICH_CLONE, homeTitle, recordBlocked, removeLabel, removeNote, removeQuestion } from './home-text.js';
20
20
  import { writeProblem } from '../core/registry.js';
@@ -110,7 +110,7 @@ async function recordAccount(prompter, home, deps) {
110
110
  prompter.note(recordBlocked(printable(blocked)));
111
111
  return null;
112
112
  }
113
- const ctx = accountContext(home, deps);
113
+ const ctx = accountContext(home, deps, await (deps.identity ?? identityOf)(home.cwd));
114
114
  const walk = await runFlow({ steps: [loginStep(ctx), ...profileSteps(ctx)] }, ctx, FIRST_PASS, prompter);
115
115
  if (walk.status === 'cancelled')
116
116
  return finish(prompter, CANCELLED, CANCELLED_CODE);
@@ -143,10 +143,10 @@ async function again(ran) {
143
143
  await ran;
144
144
  return AGAIN;
145
145
  }
146
- function accountContext(home, deps) {
146
+ function accountContext(home, deps, machineIdentity) {
147
147
  const recorded = home.registry.ok ? home.registry.value.accounts : {};
148
148
  return {
149
- recorded, host: 'github', machineIdentity: home.identity,
149
+ recorded, host: 'github', machineIdentity,
150
150
  suggest: deps.suggest ?? suggester(), signedIn: deps.signedIn ?? once(() => readSignedIn(home.cwd)),
151
151
  };
152
152
  }
@@ -162,7 +162,8 @@ async function runOwn(prompter, command, tokens, argv) {
162
162
  out.fail('repown', parsed.error);
163
163
  return 2;
164
164
  }
165
- 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);
166
167
  }
167
168
  function setupArgs(cwd) {
168
169
  return { positional: [], flags: new Map([['cwd', cwd]]) };
@@ -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
  }