repown 0.1.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,59 @@
1
+ // Azure DevOps.
2
+ //
3
+ // WHAT WAS ACTUALLY PROBED, on a machine with five Azure Repos clones:
4
+ //
5
+ // remote https://octo-org.visualstudio.com/<project>/_git/<repo>
6
+ // -- the legacy *.visualstudio.com form, where the ORGANISATION is the
7
+ // subdomain and the first path segment is the PROJECT. The modern
8
+ // form is https://dev.azure.com/<org>/<project>/_git/<repo>, where
9
+ // the organisation is the first path segment instead. Both are live
10
+ // in the wild, and they disagree about what the first segment means
11
+ // -- which is exactly why this host cannot be left to the generic
12
+ // provider, whose "first segment is the owner" would report the
13
+ // project as the owner and let a push to another organisation pass.
14
+ //
15
+ // system credential.https://dev.azure.com.usehttppath = true
16
+ // -- shipped by Git for Windows. It does NOT apply to a
17
+ // *.visualstudio.com remote: different host, no match.
18
+ //
19
+ // global credential.azreposcredentialtype = pat
20
+ // -- PAT mode rather than OAuth, which is why
21
+ // `git-credential-manager azure-repos list` returns nothing here:
22
+ // a PAT is stored against the generic credential key and never
23
+ // appears in that namespace.
24
+ //
25
+ // SO CREDENTIALS ARE DELIBERATELY NOT PINNED HERE. `credentialKeys` is empty,
26
+ // and `repown` says so in as many words rather than writing a key that would look
27
+ // like configuration while selecting nothing. Commit identity is still pinned
28
+ // and every push is still guarded -- an author address is the same fact on any
29
+ // host.
30
+ //
31
+ // Making credential selection work here is a real piece of work: it needs the
32
+ // PAT-vs-OAuth paths separated and each verified against a live remote. Until
33
+ // that happens this provider claims only what was measured.
34
+ const MODERN_HOST = 'dev.azure.com';
35
+ const LEGACY_SUFFIX = '.visualstudio.com';
36
+ /** SSH remotes: `git@ssh.dev.azure.com:v3/<org>/...` and `<org>@vs-ssh.visualstudio.com:v3/<org>/...`. */
37
+ const SSH_HOSTS = ['ssh.dev.azure.com', 'vs-ssh.visualstudio.com'];
38
+ export function azureDevOpsProvider() {
39
+ return {
40
+ id: 'azdo',
41
+ label: 'Azure DevOps',
42
+ matches,
43
+ ownerOf,
44
+ credentialKeys: () => [],
45
+ resolveProfile: async () => null,
46
+ };
47
+ }
48
+ function matches(url) {
49
+ return url.host === MODERN_HOST || url.host.endsWith(LEGACY_SUFFIX) || SSH_HOSTS.includes(url.host);
50
+ }
51
+ /** The ORGANISATION: the subdomain in one URL form, a path segment in the others. */
52
+ function ownerOf(url) {
53
+ if (SSH_HOSTS.includes(url.host))
54
+ return url.segments[0] === 'v3' ? url.segments[1] ?? null : null;
55
+ if (url.host === MODERN_HOST)
56
+ return url.segments[0] ?? null;
57
+ const subdomain = url.host.slice(0, -LEGACY_SUFFIX.length);
58
+ return subdomain.length > 0 ? subdomain : null;
59
+ }
@@ -0,0 +1,16 @@
1
+ // The provider for every host no other provider claims.
2
+ //
3
+ // It pins commit identity and it guards pushes, because an author address is the
4
+ // same fact on any host. It does NOT pretend to select credentials: an unknown
5
+ // host's credential model is unknown, and half-working credential config is
6
+ // worse than none -- it looks configured while doing nothing.
7
+ export function genericProvider() {
8
+ return {
9
+ id: 'generic',
10
+ label: 'this host',
11
+ matches: () => true,
12
+ ownerOf: (url) => url.segments[0] ?? null,
13
+ credentialKeys: () => [],
14
+ resolveProfile: async () => null,
15
+ };
16
+ }
@@ -0,0 +1,35 @@
1
+ // GitHub. The one host whose mechanics were established empirically rather than
2
+ // assumed -- see ADR-001.
3
+ //
4
+ // The pin is `credential.https://github.com.username`, which Git Credential
5
+ // Manager reads to choose between the credentials it stores, one per account,
6
+ // keyed `git:https://<user>@github.com`. That is what makes switching
7
+ // unnecessary: each clone authenticates as its own account, permanently.
8
+ //
9
+ // Over SSH there is no credential helper at all -- the SSH key decides -- so an
10
+ // SSH remote pins no credential key rather than one that selects nothing.
11
+ import { credentialPrefix } from "../url.js";
12
+ import { ghProfileField } from "../credential/gh.js";
13
+ const HOSTS = ['github.com', 'gist.github.com', 'www.github.com', 'ssh.github.com'];
14
+ export function githubProvider() {
15
+ return {
16
+ id: 'github',
17
+ label: 'GitHub',
18
+ matches: (url) => HOSTS.includes(url.host),
19
+ ownerOf: (url) => url.segments[0] ?? null,
20
+ credentialKeys: (url) => url.scheme === 'https' ? [`credential.${credentialPrefix(url)}.username`] : [],
21
+ resolveProfile: async (account) => {
22
+ const [name, id] = await Promise.all([
23
+ ghProfileField(account, 'name'),
24
+ ghProfileField(account, 'id'),
25
+ ]);
26
+ // GitHub's own noreply address: publishable by design, and it still links
27
+ // the commit to the account. Offered as a default so a private address
28
+ // need never be published to get working attribution.
29
+ const email = id ? `${id}+${account}@users.noreply.github.com` : undefined;
30
+ if (!name && !email)
31
+ return null;
32
+ return { ...(name ? { name } : {}), ...(email ? { email } : {}) };
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,14 @@
1
+ // Provider resolution. Ordered, with `generic` always last so every URL resolves
2
+ // to something and no caller has to handle "no provider".
3
+ import { githubProvider } from "./github.js";
4
+ import { azureDevOpsProvider } from "./azdo.js";
5
+ import { genericProvider } from "./generic.js";
6
+ export function providers() {
7
+ return [githubProvider(), azureDevOpsProvider(), genericProvider()];
8
+ }
9
+ export function providerFor(url) {
10
+ const all = providers();
11
+ if (!url)
12
+ return all[all.length - 1];
13
+ return all.find((provider) => provider.matches(url)) ?? all[all.length - 1];
14
+ }
@@ -0,0 +1,9 @@
1
+ // A host provider: everything that differs between GitHub, Azure DevOps and
2
+ // whatever comes next, behind one interface.
3
+ //
4
+ // Strategy rather than a chain of `if (host === ...)`, so adding a host is a new
5
+ // file and a registry entry, and so the parts that are NOT host-specific --
6
+ // commit identity, the guard, the account registry -- never learn about hosts at
7
+ // all. Author email is host-independent, which is why the guard keeps working on
8
+ // a host no provider claims.
9
+ export {};
@@ -0,0 +1,96 @@
1
+ // This clone's identity: who authors its commits, and which stored account its
2
+ // pushes authenticate as.
3
+ //
4
+ // IT IS ALL PLAIN GIT CONFIG, DELIBERATELY. An earlier design kept a JSON
5
+ // profile store with capture/define/use/list/forget/restore around it, to switch
6
+ // identity inside one clone. Nothing needs that: a clone belongs to ONE account
7
+ // permanently. What you switch is the CLI's active account, which is a
8
+ // machine-wide mode and the CLI's own business.
9
+ //
10
+ // So the identity lives in .git/config -- per clone, never tracked, already the
11
+ // place git looks. No bespoke store, no snapshot, no second format, and nothing
12
+ // for a public repository to leak.
13
+ //
14
+ // NO NAMES OR ADDRESSES APPEAR IN THIS FILE.
15
+ import { credentialPrefix } from "./url.js";
16
+ export const NAME_KEY = 'user.name';
17
+ export const EMAIL_KEY = 'user.email';
18
+ export const USE_CONFIG_ONLY_KEY = 'user.useConfigOnly';
19
+ /**
20
+ * The account this clone belongs to, on ANY host. The credential key names it
21
+ * too, but only on a host whose credentials repown pins (GitHub over https);
22
+ * the guard's destination check needs it everywhere.
23
+ */
24
+ export const ACCOUNT_KEY = 'repown.account';
25
+ /**
26
+ * `credential.<scheme>://<host>.username`, which repown used to write for EVERY
27
+ * remote -- SSH included -- before repown.account existed. Read as the account
28
+ * when repown.account is missing, so clones pinned back then keep their
29
+ * destination check; removed by `off`.
30
+ */
31
+ export function legacyAccountKey(url) {
32
+ return 'credential.' + credentialPrefix(url) + '.username';
33
+ }
34
+ export function isPinned(identity) {
35
+ return Boolean(identity.name && identity.email);
36
+ }
37
+ export async function readIdentity(git, credentialKey) {
38
+ const [name, email, useConfigOnly, owner] = await Promise.all([
39
+ git.getConfig(NAME_KEY, 'local'),
40
+ git.getConfig(EMAIL_KEY, 'local'),
41
+ git.getConfig(USE_CONFIG_ONLY_KEY, 'local'),
42
+ git.getConfig(ACCOUNT_KEY, 'local'),
43
+ ]);
44
+ const [inheritedName, inheritedEmail] = await Promise.all([
45
+ git.getConfig(NAME_KEY),
46
+ git.getConfig(EMAIL_KEY),
47
+ ]);
48
+ const account = credentialKey ? await git.getConfig(credentialKey, 'local') : null;
49
+ const inheritedAccount = credentialKey ? await git.getConfig(credentialKey) : null;
50
+ return {
51
+ name, email, account, owner, useConfigOnly,
52
+ inheritedName, inheritedEmail, inheritedAccount,
53
+ };
54
+ }
55
+ /**
56
+ * Writes the identity to `scope`, plus user.useConfigOnly so git refuses to
57
+ * invent an identity from the hostname rather than silently using one. That does
58
+ * NOT stop inheritance of an explicitly-set global address -- which is what the
59
+ * commit-range check in the guard is for, not a substitute for it.
60
+ */
61
+ export async function pinIdentity(git, values, credentialKeys, scope = 'local') {
62
+ const writes = [
63
+ [NAME_KEY, values.name],
64
+ [EMAIL_KEY, values.email],
65
+ [USE_CONFIG_ONLY_KEY, 'true'],
66
+ [ACCOUNT_KEY, values.account],
67
+ ...credentialKeys.map((key) => [key, values.account]),
68
+ ];
69
+ return writeAll(writes, (key, value) => git.setConfig(key, value, scope));
70
+ }
71
+ export async function clearIdentity(git, credentialKeys, scope = 'local') {
72
+ const keys = [NAME_KEY, EMAIL_KEY, USE_CONFIG_ONLY_KEY, ACCOUNT_KEY, ...credentialKeys];
73
+ return writeAll(keys.map((key) => [key, '']), (key) => git.unsetConfig(key, scope));
74
+ }
75
+ /**
76
+ * ONE AT A TIME, NEVER Promise.all.
77
+ *
78
+ * `git config --local` writes through a `.lock` file in the config's own
79
+ * directory, so concurrent invocations race for it and the losers fail --
80
+ * quietly, because each is a separate process exiting non-zero rather than
81
+ * throwing. Running these four in parallel dropped exactly one key per
82
+ * repository across a twenty-repository rollout, most often `user.name`, and
83
+ * every command still reported success because the write results were
84
+ * discarded.
85
+ *
86
+ * Which is the failure this whole tool exists to prevent: a repository that
87
+ * reports itself configured while its commits carry the machine's identity. So
88
+ * the outcomes are returned, and callers are expected to look at them.
89
+ */
90
+ async function writeAll(entries, write) {
91
+ const outcomes = [];
92
+ for (const [key, value] of entries) {
93
+ outcomes.push({ key, value, written: await write(key, value) });
94
+ }
95
+ return outcomes;
96
+ }
@@ -0,0 +1,74 @@
1
+ // One reading of the whole picture, so every command agrees rather than each
2
+ // asking its own slightly different question.
3
+ //
4
+ // Split in two because the two halves have different lifetimes. The REPO state
5
+ // is per clone and cheap. The AUTH state is machine-wide, costs subprocesses
6
+ // (`git --exec-path`, GCM, gh) and is identical for every clone on the machine,
7
+ // so the commands that need it ask for it separately -- and `repown scan`, which
8
+ // walks many repositories, never asks for it at all.
9
+ import { parseGitUrl } from "./url.js";
10
+ import { providerFor } from "./hosts/index.js";
11
+ import { readIdentity } from "./identity.js";
12
+ import { guardState, hookLocation } from "./guard/hook.js";
13
+ import { findGcm, listAccounts, isGcm } from "./credential/gcm.js";
14
+ import { ghState, ghInstalled, isGh } from "./credential/gh.js";
15
+ const DEFAULT_PROBE_URL = 'https://github.com/';
16
+ export async function inspectRepo(git) {
17
+ const isRepo = await git.isRepo();
18
+ const originUrl = isRepo ? await git.getConfig('remote.origin.url') : null;
19
+ const url = originUrl ? parseGitUrl(originUrl) : null;
20
+ const provider = providerFor(url);
21
+ const credentialKeys = url ? provider.credentialKeys(url) : [];
22
+ const [root, hook, identity, guard, helper] = await Promise.all([
23
+ isRepo ? git.root() : Promise.resolve(null),
24
+ isRepo ? hookLocation(git) : Promise.resolve(null),
25
+ readIdentity(git, credentialKeys[0] ?? null),
26
+ isRepo ? guardState(git) : Promise.resolve('off'),
27
+ git.getUrlMatch('credential.helper', originUrl ?? DEFAULT_PROBE_URL),
28
+ ]);
29
+ return {
30
+ git, isRepo, root, originUrl, url, provider,
31
+ owner: url ? provider.ownerOf(url) : null,
32
+ identity, credentialKeys, guard, hook, helper,
33
+ };
34
+ }
35
+ export async function inspectAuth(git, probeUrl) {
36
+ const gcmPath = await findGcm();
37
+ const [stored, gh, present, helper, ghHelperOrigins] = await Promise.all([
38
+ listAccounts(gcmPath, 'github'),
39
+ ghState(),
40
+ ghInstalled(),
41
+ git.getUrlMatch('credential.helper', probeUrl ?? DEFAULT_PROBE_URL),
42
+ git.configOrigins('credential\\..*github\\.com\\.helper'),
43
+ ]);
44
+ return {
45
+ gcmPath,
46
+ gcmPresent: gcmPath !== null,
47
+ stored,
48
+ ghPresent: present,
49
+ gh,
50
+ helper,
51
+ ghIsHelper: isGh(helper),
52
+ helperIsGcm: isGcm(helper),
53
+ ghHelperOrigins,
54
+ };
55
+ }
56
+ /**
57
+ * How the active CLI account should be DISPLAYED. Three outcomes, never
58
+ * collapsed into one another -- "unknown" is the entire point of keeping the
59
+ * error case distinct from the empty case.
60
+ */
61
+ export function activeAccountLabel(auth) {
62
+ if (!auth.ghPresent)
63
+ return 'not installed';
64
+ if (!auth.gh.ok)
65
+ return 'unknown -- gh could not be queried';
66
+ return auth.gh.value.active ?? 'none';
67
+ }
68
+ export function storedAccountsLabel(auth) {
69
+ if (!auth.gcmPresent)
70
+ return 'not installed';
71
+ if (!auth.stored.ok)
72
+ return 'unknown -- ' + auth.stored.error;
73
+ return auth.stored.value.length > 0 ? auth.stored.value.join(', ') : 'none stored yet';
74
+ }
@@ -0,0 +1,122 @@
1
+ // The per-machine account registry: name and email per account, recorded once.
2
+ //
3
+ // THIS IS WHAT MAKES `repown use <account>` A ONE-WORD COMMAND. Without it, pinning
4
+ // a clone means looking the name up from the host API and then asking the user,
5
+ // every time, in every repository. With it that happens once per machine and
6
+ // every clone afterwards is instant and non-interactive -- as short as
7
+ // `gh auth switch`, without being the global mode-switch that caused the problem
8
+ // this tool exists to solve.
9
+ //
10
+ // IT LIVES OUTSIDE EVERY REPOSITORY, AND THAT IS NOT NEGOTIABLE. It holds real
11
+ // names and real addresses. A repository may be public, may be forked, mirrored
12
+ // and scraped, and anything committed to one is published permanently. So the
13
+ // identifiers live here and the repository gets only what git already stores in
14
+ // .git/config, which git never tracks.
15
+ import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises';
16
+ import { homedir } from 'node:os';
17
+ import { join, dirname } from 'node:path';
18
+ import { ok, err } from "./result.js";
19
+ const EMPTY = { accounts: {}, unreadable: [] };
20
+ export function configDirectory() {
21
+ const explicit = process.env['REPOWN_CONFIG_DIR'];
22
+ if (explicit)
23
+ return explicit;
24
+ if (process.platform === 'win32' && process.env['APPDATA']) {
25
+ return join(process.env['APPDATA'], 'repown');
26
+ }
27
+ const xdg = process.env['XDG_CONFIG_HOME'];
28
+ return xdg ? join(xdg, 'repown') : join(homedir(), '.config', 'repown');
29
+ }
30
+ export function registryPath() {
31
+ return join(configDirectory(), 'accounts.json');
32
+ }
33
+ /**
34
+ * No file yet is an EMPTY registry. Anything else that fails is an error --
35
+ * reading a broken file as empty made the next save replace it, and every
36
+ * account in it, with a single entry.
37
+ */
38
+ export async function loadRegistry() {
39
+ let raw;
40
+ try {
41
+ raw = await readFile(registryPath(), 'utf8');
42
+ }
43
+ catch (cause) {
44
+ if (cause.code === 'ENOENT')
45
+ return ok(EMPTY);
46
+ return err('could not read ' + registryPath() + ': ' + cause.message);
47
+ }
48
+ try {
49
+ return ok(readAccounts(JSON.parse(raw).accounts));
50
+ }
51
+ catch (cause) {
52
+ return err(registryPath() + ' is not valid JSON (' + cause.message +
53
+ ') -- fix it or remove it; repown will not overwrite it');
54
+ }
55
+ }
56
+ /** Entries with a string name and email, in an object with no prototype to collide with. */
57
+ function readAccounts(value) {
58
+ const accounts = Object.create(null);
59
+ const unreadable = [];
60
+ if (typeof value !== 'object' || value === null)
61
+ return { accounts, unreadable };
62
+ for (const [key, entry] of Object.entries(value)) {
63
+ const { name, email, host } = (entry ?? {});
64
+ if (typeof name !== 'string' || typeof email !== 'string') {
65
+ unreadable.push(key);
66
+ continue;
67
+ }
68
+ accounts[key] = typeof host === 'string' ? { name, email, host } : { name, email };
69
+ }
70
+ return { accounts, unreadable };
71
+ }
72
+ /** The registry, but only if a write would keep every entry in it. */
73
+ async function loadForWrite() {
74
+ 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');
79
+ }
80
+ export async function lookupAccount(account) {
81
+ const registry = await loadRegistry();
82
+ if (!registry.ok)
83
+ return registry;
84
+ return ok(Object.hasOwn(registry.value.accounts, account) ? registry.value.accounts[account] : null);
85
+ }
86
+ export async function saveAccount(account, entry) {
87
+ const registry = await loadForWrite();
88
+ if (!registry.ok)
89
+ return registry;
90
+ return write({ ...registry.value.accounts, [account]: entry });
91
+ }
92
+ export async function removeAccount(account) {
93
+ const registry = await loadForWrite();
94
+ if (!registry.ok)
95
+ return registry;
96
+ if (!Object.hasOwn(registry.value.accounts, account))
97
+ return ok(false);
98
+ const accounts = { ...registry.value.accounts };
99
+ delete accounts[account];
100
+ const written = await write(accounts);
101
+ return written.ok ? ok(true) : err(written.error);
102
+ }
103
+ /**
104
+ * Written via a temporary file and renamed, so an interrupted write cannot
105
+ * truncate it. Owner-only, since it holds names and addresses -- and a
106
+ * leftover temporary file is removed first, because `mode` applies only when
107
+ * the file is created, and rename would carry an old one's permissions over.
108
+ */
109
+ async function write(accounts) {
110
+ const target = registryPath();
111
+ const temporary = `${target}.tmp`;
112
+ try {
113
+ await mkdir(dirname(target), { recursive: true });
114
+ await rm(temporary, { force: true });
115
+ await writeFile(temporary, JSON.stringify({ accounts }, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
116
+ await rename(temporary, target);
117
+ return ok(undefined);
118
+ }
119
+ catch (cause) {
120
+ return err(`could not write ${target}: ${cause.message}`);
121
+ }
122
+ }
@@ -0,0 +1,13 @@
1
+ // A recoverable outcome. Used wherever a failure is an ANSWER rather than a bug:
2
+ // "gh could not be queried", "this host has no provider", "GCM is not installed".
3
+ //
4
+ // The distinction that matters, and that the PowerShell version had to learn the
5
+ // hard way: a check that was SKIPPED must never look like one that PASSED. An
6
+ // `ok: false` carries a reason and callers are forced to handle it, where a bare
7
+ // `null` let a failed lookup silently disappear into a falsy branch.
8
+ export function ok(value) {
9
+ return { ok: true, value };
10
+ }
11
+ export function err(error) {
12
+ return { ok: false, error };
13
+ }
@@ -0,0 +1,82 @@
1
+ // Parsing a git remote URL into the pieces a host provider needs.
2
+ //
3
+ // Done by hand rather than with `new URL()` because the scp-like form
4
+ // `git@host:owner/repo` is not a URL and `new URL()` rejects it, while it is
5
+ // still one of the two forms every host documents.
6
+ //
7
+ // The userinfo is kept SEPARATE from the host, and that separation is the point:
8
+ // the guard this replaces substring-matched the whole URL, so
9
+ // `https://octocat@github.com/SomeoneElse/repo` passed the ownership check on
10
+ // the userinfo alone while pushing somewhere else entirely.
11
+ export function parseGitUrl(raw) {
12
+ const text = raw.trim();
13
+ if (!text || isFilesystemPath(text))
14
+ return null;
15
+ return parseSchemed(text) ?? parseScpLike(text);
16
+ }
17
+ /**
18
+ * A local path is not a URL, and must not be coerced into one.
19
+ *
20
+ * `C:/Users/me/remote.git` matches the scp-like shape exactly -- host `C`, path
21
+ * `/Users/me/remote.git` -- so without this it parsed as a remote owned by
22
+ * "Users". That is not a cosmetic slip: the guard compares the destination owner
23
+ * against the pinned account, so a fabricated owner means refusing a legitimate
24
+ * push to a local remote. Returning null instead leaves such a remote with no
25
+ * host and no owner, which is the truth, and the destination check correctly
26
+ * declines to have an opinion about it.
27
+ */
28
+ const SEPARATOR = '[\\\\/]';
29
+ function isFilesystemPath(text) {
30
+ return /^file:/i.test(text) // file:///..., which the scp form reads as host "file"
31
+ || new RegExp('^[A-Za-z]:' + SEPARATOR).test(text) // C:/... and C:\...
32
+ || new RegExp('^' + SEPARATOR).test(text) // /abs/path and \\unc\share
33
+ || new RegExp('^\\.\\.?' + SEPARATOR).test(text); // ./rel and ../rel
34
+ }
35
+ function parseSchemed(text) {
36
+ const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):\/\/(?:([^@/]+)@)?([^/:]+)(?::\d+)?\/(.*)$/.exec(text);
37
+ if (!match)
38
+ return null;
39
+ return build(text, { scheme: match[1].toLowerCase(), user: match[2] ?? null, host: match[3], rawPath: match[4] });
40
+ }
41
+ function parseScpLike(text) {
42
+ const match = /^(?:([^@/]+)@)?([^/:]+):(.+)$/.exec(text);
43
+ if (!match)
44
+ return null;
45
+ return build(text, { scheme: 'ssh', user: match[1] ?? null, host: match[2], rawPath: match[3] });
46
+ }
47
+ function build(raw, { scheme, user, host, rawPath }) {
48
+ const path = rawPath.replace(/^\/+/, '').replace(/\/+$/, '').replace(/\.git$/i, '');
49
+ const segments = collapseDots(path.split('/').filter((s) => s.length > 0).map(decodeSegment));
50
+ return { raw, scheme, user, host: host.toLowerCase(), path, segments };
51
+ }
52
+ /**
53
+ * git and curl collapse `.` and `..` before sending (RFC 3986), `%2e%2e`
54
+ * included. The owner must be read from that collapsed path: otherwise
55
+ * `github.com/octocat/../someone-else/r` reads as octocat's while the push
56
+ * goes to someone-else.
57
+ */
58
+ function collapseDots(segments) {
59
+ const kept = [];
60
+ for (const segment of segments) {
61
+ if (segment === '..')
62
+ kept.pop();
63
+ else if (segment !== '.')
64
+ kept.push(segment);
65
+ }
66
+ return kept;
67
+ }
68
+ // Azure DevOps organisation and project names may contain spaces, which arrive
69
+ // percent-encoded (`Some%20Long%20Project%20Name`). Comparing an encoded segment
70
+ // against a plain name never matches.
71
+ function decodeSegment(segment) {
72
+ try {
73
+ return decodeURIComponent(segment);
74
+ }
75
+ catch {
76
+ return segment;
77
+ }
78
+ }
79
+ /** The scheme+host prefix git uses to key credential config, e.g. `https://github.com`. */
80
+ export function credentialPrefix(url) {
81
+ return `${url.scheme}://${url.host}`;
82
+ }