@niwa-labs/git 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +17 -4
- package/src/actions.ts +124 -0
- package/src/git.ts +247 -0
- package/src/index.ts +753 -0
- package/src/record-types.ts +141 -0
- package/src/records.ts +5 -0
- package/src/registration.ts +61 -0
- package/src/workflows/worktree-cleanup.ts +54 -0
- package/test/fixtures/git-worktree-host.ts +43 -0
- package/test/git-repo.ts +45 -0
- package/test/git-worktree-replay.test.ts +126 -0
- package/test/registration.test.ts +56 -0
- package/test/replay.ts +89 -0
- package/test/served.ts +46 -0
- package/test/worktree-create.test.ts +74 -0
- package/test/worktree-matched-removal.test.ts +101 -0
- package/test/worktree-observe.test.ts +49 -0
- package/test/worktree-removal.test.ts +156 -0
- package/test/worktree-replay-steps.test.ts +181 -0
- package/tsconfig.json +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Niwa Labs contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/git
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The local git repository: remotes, head movements and worktrees, recorded as facts.
|
package/package.json
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/git",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts",
|
|
8
|
+
"./records": "./src/records.ts"
|
|
9
|
+
},
|
|
10
|
+
"dependencies": {
|
|
11
|
+
"@niwa-labs/core": "0.0.0",
|
|
12
|
+
"@niwa-labs/plugin": "0.0.0",
|
|
13
|
+
"@niwa-labs/script": "0.0.0",
|
|
14
|
+
"zod": "^4.6.7"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@niwa-labs/testing": "0.0.0"
|
|
18
|
+
}
|
|
19
|
+
}
|
package/src/actions.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The actions of the git module, as typed references.
|
|
3
|
+
*
|
|
4
|
+
* The module's factory builds its real actions from the same references, so the schemas here are
|
|
5
|
+
* the ones the host checks against. `WorktreeOption` is what `session.start` and `ask()` take as
|
|
6
|
+
* `worktree`: the sugar that makes a worktree and starts the session in it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { EntityDescription, SessionRefSchema, actionRef, getRef, listRef } from "@niwa-labs/core";
|
|
12
|
+
|
|
13
|
+
import { CommitId, RemovalMatch, Worktree, WorktreeId, WorktreeRemote } from "./record-types.ts";
|
|
14
|
+
|
|
15
|
+
/** What a worktree is made from for `session.start`, `session()` and `ask()`: `true`, or the parts to choose. */
|
|
16
|
+
export const WorktreeOption = z.union([
|
|
17
|
+
z.literal(true),
|
|
18
|
+
z.strictObject({
|
|
19
|
+
/** The repository: any directory inside it. Default: the session's cwd, else the host's directory. */
|
|
20
|
+
repo: z.string().min(1).optional(),
|
|
21
|
+
/** The branch or commit to start from. Default: the repository's current branch (its commit when HEAD is detached). */
|
|
22
|
+
base: z.string().min(1).optional(),
|
|
23
|
+
description: EntityDescription.optional(),
|
|
24
|
+
}),
|
|
25
|
+
]);
|
|
26
|
+
export type WorktreeOption = z.infer<typeof WorktreeOption>;
|
|
27
|
+
export type WorktreeOptionGiven = z.input<typeof WorktreeOption>;
|
|
28
|
+
|
|
29
|
+
/** The worktree a session runs in, as `session.start` answers it. */
|
|
30
|
+
export const SessionWorktree = Worktree.pick({ id: true, path: true, branch: true });
|
|
31
|
+
export type SessionWorktree = z.infer<typeof SessionWorktree>;
|
|
32
|
+
|
|
33
|
+
export const gitWorktreeCreate = actionRef("git.worktree.create", {
|
|
34
|
+
description:
|
|
35
|
+
"Make a git worktree: a checkout of `repo` (any directory inside it) on a new branch named like its id, in a directory niwa keeps. " +
|
|
36
|
+
"`base` is the branch or commit to start from; without it, the repository's current branch (its commit when HEAD is detached). " +
|
|
37
|
+
"The ignored files that `<repo>/.worktreeinclude` lists (gitignore syntax) are copied in. Niwa never merges: the branch is the result.",
|
|
38
|
+
input: z.strictObject({
|
|
39
|
+
repo: z.string().min(1),
|
|
40
|
+
base: z.string().min(1).optional(),
|
|
41
|
+
description: EntityDescription,
|
|
42
|
+
}),
|
|
43
|
+
output: Worktree,
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
/** Where a worktree in the list stands: as recorded, its directory gone, or a directory with no record. */
|
|
47
|
+
export const WorktreeState = z.enum(["ok", "missing", "orphan"]);
|
|
48
|
+
export type WorktreeState = z.infer<typeof WorktreeState>;
|
|
49
|
+
|
|
50
|
+
export const gitWorktreeList = listRef("git.worktree.list", {
|
|
51
|
+
kind: "worktree",
|
|
52
|
+
noun: "git worktree",
|
|
53
|
+
detail:
|
|
54
|
+
"Each recorded one shows its age in days and how it stands now (dirty, commits ahead of its base, live sessions), which is what a cleanup reads, " +
|
|
55
|
+
"its head commit, and the remote a push of its base goes to (`host` and `path` of the project) when the repository's configuration verifies one. " +
|
|
56
|
+
"`state` flags the odd ones: `missing` is a worktree whose directory is gone, `orphan` a directory in niwa's store that no record names.",
|
|
57
|
+
item: {
|
|
58
|
+
state: WorktreeState,
|
|
59
|
+
path: z.string().min(1),
|
|
60
|
+
branch: z.string().min(1).optional(),
|
|
61
|
+
repo: z.string().min(1).optional(),
|
|
62
|
+
base: z.string().min(1).optional(),
|
|
63
|
+
/** Days since it was made; absent for an orphan. */
|
|
64
|
+
ageDays: z.number().nonnegative().optional(),
|
|
65
|
+
/** How it stands now, as `git.worktree.get` says; absent for an orphan. */
|
|
66
|
+
dirty: z.boolean().optional(),
|
|
67
|
+
aheadOfBase: z.number().int().nonnegative().optional(),
|
|
68
|
+
sessions: z.array(z.string()).optional(),
|
|
69
|
+
/** The commit its head is on now; absent for an orphan and a worktree whose directory is gone. */
|
|
70
|
+
head: CommitId.optional(),
|
|
71
|
+
/** The verified remote of its base; absent when none is. */
|
|
72
|
+
remote: WorktreeRemote.optional(),
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** One worktree as `git.worktree.get` shows it: as made, and how it stands now. */
|
|
77
|
+
export const WorktreeEntity = Worktree.extend({
|
|
78
|
+
/** Uncommitted changes or untracked files (ignored files do not count). */
|
|
79
|
+
dirty: z.boolean(),
|
|
80
|
+
/** The commits on its branch that its base does not have. */
|
|
81
|
+
aheadOfBase: z.number().int().nonnegative(),
|
|
82
|
+
/** The niwa sessions alive in it now. */
|
|
83
|
+
sessions: z.array(z.string()),
|
|
84
|
+
/** The commit its head is on now; absent when its directory is gone. */
|
|
85
|
+
head: CommitId.optional(),
|
|
86
|
+
/** The verified remote of its base; absent when none is. */
|
|
87
|
+
remote: WorktreeRemote.optional(),
|
|
88
|
+
});
|
|
89
|
+
export type WorktreeEntity = z.infer<typeof WorktreeEntity>;
|
|
90
|
+
|
|
91
|
+
export const gitWorktreeGet = getRef("git.worktree.get", {
|
|
92
|
+
kind: "worktree",
|
|
93
|
+
noun: "git worktree",
|
|
94
|
+
detail: "It shows what the worktree was made from and how it stands: dirty, commits ahead of its base, the live sessions in it, its head and the verified remote of its base.",
|
|
95
|
+
entity: WorktreeEntity,
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export const gitWorktreeRemove = actionRef("git.worktree.remove", {
|
|
99
|
+
description:
|
|
100
|
+
"Remove a git worktree: its directory and its branch. It is refused when the worktree is dirty, has commits its base does not have " +
|
|
101
|
+
"(on its branch or on the head of its checkout), a live niwa session runs in it, or it cannot be read, unless `force`; " +
|
|
102
|
+
"git's own refusals (a locked worktree) stand without it. An orphan directory (no record, or one that took the place of a removed worktree) " +
|
|
103
|
+
"is removed only with `force`. A worktree that is gone already is a no-op. With `onlyIf`, remove only the clean registered " +
|
|
104
|
+
"checkout matching the local repository, branch, head and forge project. This mode retains the branch and uses no force.",
|
|
105
|
+
input: z.strictObject({ id: z.string().min(1), force: z.boolean().optional(), onlyIf: RemovalMatch.optional() })
|
|
106
|
+
.refine((input) => input.force !== true || input.onlyIf === undefined, { message: "onlyIf cannot be combined with force" }),
|
|
107
|
+
output: z.object({ id: z.string().min(1), removed: z.boolean() }),
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
export const gitHeadObserve = actionRef("git.head.observe", {
|
|
111
|
+
description:
|
|
112
|
+
"Look at the heads of the worktrees niwa keeps (or of `worktree` alone) and record `git.head.moved` for each that is on another commit than " +
|
|
113
|
+
"the last one recorded for it, and `git.remote.updated` for each whose verified remote is another than the last one recorded for it. " +
|
|
114
|
+
"`session` names the session, as `<harness> <native>`, that moved them; without it the record is of the caller. " +
|
|
115
|
+
"A head that has not moved is not recorded again. The module looks by itself when a session's turn ends in a worktree.",
|
|
116
|
+
input: z.strictObject({ worktree: z.string().min(1).optional(), session: SessionRefSchema.optional() }),
|
|
117
|
+
output: z.object({ moved: z.array(z.object({ worktree: WorktreeId, head: CommitId })) }),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
export const gitCleanupConfig = actionRef("git.cleanup.config", {
|
|
121
|
+
description: "How the built-in cleanup of old worktrees is set: how many days a worktree is kept before it may be removed.",
|
|
122
|
+
input: z.object({}),
|
|
123
|
+
output: z.object({ days: z.number().int().min(0) }),
|
|
124
|
+
});
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The git commands the module runs, and the copy of `.worktreeinclude` files.
|
|
3
|
+
*
|
|
4
|
+
* Every command is `git -C <dir> ...` with the output read whole; a command that fails is an
|
|
5
|
+
* error carrying what git said, except where the caller asks for the exit code.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { constants, copyFileSync, existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
|
|
9
|
+
import { basename, dirname, join } from "node:path";
|
|
10
|
+
|
|
11
|
+
/** What a git command answered. */
|
|
12
|
+
interface GitResult {
|
|
13
|
+
readonly code: number;
|
|
14
|
+
readonly stdout: string;
|
|
15
|
+
readonly stderr: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Run git in a directory; `input` goes to its stdin. */
|
|
19
|
+
export async function gitRun(dir: string, args: readonly string[], input?: string): Promise<GitResult> {
|
|
20
|
+
const child = Bun.spawn(["git", "-C", dir, ...args], {
|
|
21
|
+
stdin: input === undefined ? "ignore" : new TextEncoder().encode(input),
|
|
22
|
+
stdout: "pipe",
|
|
23
|
+
stderr: "pipe",
|
|
24
|
+
// A prompt for credentials or an editor would hang the host.
|
|
25
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_EDITOR: "true" },
|
|
26
|
+
});
|
|
27
|
+
const [stdout, stderr, code] = await Promise.all([
|
|
28
|
+
new Response(child.stdout).text(),
|
|
29
|
+
new Response(child.stderr).text(),
|
|
30
|
+
child.exited,
|
|
31
|
+
]);
|
|
32
|
+
return { code, stdout, stderr };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Run git and give its output; a failure is an error with what git said. */
|
|
36
|
+
export async function gitOut(dir: string, args: readonly string[], input?: string): Promise<string> {
|
|
37
|
+
const result = await gitRun(dir, args, input);
|
|
38
|
+
if (result.code !== 0) {
|
|
39
|
+
throw new Error(`git ${args.join(" ")} (in ${dir}) failed: ${result.stderr.trim() || result.stdout.trim()}`);
|
|
40
|
+
}
|
|
41
|
+
return result.stdout;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The top of the repository a directory is in, or undefined when it is in none. */
|
|
45
|
+
export async function topOf(dir: string): Promise<string | undefined> {
|
|
46
|
+
if (!existsSync(dir)) return undefined;
|
|
47
|
+
const result = await gitRun(dir, ["rev-parse", "--show-toplevel"]);
|
|
48
|
+
return result.code === 0 ? result.stdout.trim() : undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The directory of the repository a checkout belongs to: the top of the repository, or, for a linked worktree,
|
|
53
|
+
* the top of the repository that owns it, so the answer does not depend on the checkout it was asked from. A
|
|
54
|
+
* repository whose git directory is not named `.git` (a submodule) is its own top.
|
|
55
|
+
*/
|
|
56
|
+
export async function repoOf(dir: string): Promise<string | undefined> {
|
|
57
|
+
const top = await topOf(dir);
|
|
58
|
+
if (top === undefined) return undefined;
|
|
59
|
+
const common = await gitRun(top, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
60
|
+
const gitDir = common.code === 0 ? common.stdout.trim() : "";
|
|
61
|
+
if (basename(gitDir) === ".git" && existsSync(dirname(gitDir))) return dirname(gitDir);
|
|
62
|
+
return top;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The git directory a checkout shares with the others of its repository, with its links resolved. */
|
|
66
|
+
export async function commonDirOf(dir: string): Promise<string | undefined> {
|
|
67
|
+
const result = await gitRun(dir, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
68
|
+
if (result.code !== 0) return undefined;
|
|
69
|
+
try {
|
|
70
|
+
return realpathSync(result.stdout.trim());
|
|
71
|
+
} catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The current branch of a checkout, or its commit when HEAD is detached. */
|
|
77
|
+
export async function currentBase(dir: string): Promise<string> {
|
|
78
|
+
const branch = await gitRun(dir, ["symbolic-ref", "--short", "-q", "HEAD"]);
|
|
79
|
+
if (branch.code === 0 && branch.stdout.trim() !== "") return branch.stdout.trim();
|
|
80
|
+
return (await gitOut(dir, ["rev-parse", "HEAD"])).trim();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The commit a name points at, or undefined when it names none. */
|
|
84
|
+
export async function commitOf(dir: string, name: string): Promise<string | undefined> {
|
|
85
|
+
const result = await gitRun(dir, ["rev-parse", "--verify", "-q", `${name}^{commit}`]);
|
|
86
|
+
return result.code === 0 ? result.stdout.trim() : undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Whether a checkout has changes: tracked files changed, or untracked files that are not ignored. */
|
|
90
|
+
export async function isDirty(dir: string): Promise<boolean> {
|
|
91
|
+
return (await gitOut(dir, ["status", "--porcelain", "--untracked-files=normal"])).trim() !== "";
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** How many commits are reachable from the tips that `base` has not: work that would be lost with them. */
|
|
95
|
+
export async function aheadOf(dir: string, base: string, tips: readonly string[]): Promise<number> {
|
|
96
|
+
return Number((await gitOut(dir, ["rev-list", "--count", ...tips, `^${base}`])).trim());
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The commit the head of a checkout is on, or undefined when it has none. */
|
|
100
|
+
export async function headOf(dir: string): Promise<string | undefined> {
|
|
101
|
+
const result = await gitRun(dir, ["rev-parse", "--verify", "-q", "HEAD^{commit}"]);
|
|
102
|
+
return result.code === 0 ? result.stdout.trim() : undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The branch the head of a checkout is on, or undefined when it is detached. */
|
|
106
|
+
export async function branchOf(dir: string): Promise<string | undefined> {
|
|
107
|
+
const result = await gitRun(dir, ["symbolic-ref", "--short", "-q", "HEAD"]);
|
|
108
|
+
const branch = result.stdout.trim();
|
|
109
|
+
return result.code === 0 && branch !== "" ? branch : undefined;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A host name as a forge names its server: lower case, no port, no scheme. */
|
|
113
|
+
const HOST = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
|
|
114
|
+
/** One group or the name of a project in its path. */
|
|
115
|
+
const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/;
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The server and the project path a remote URL names: `https://host/group/name.git`, `ssh://user@host:22/group/name`,
|
|
119
|
+
* `user@host:group/name.git`. A user, a token, a port and the `.git` ending are not part of it. A path on this machine
|
|
120
|
+
* (`/srv/git/x.git`, `file://`), or a URL that names no group and name on a host, names none.
|
|
121
|
+
*/
|
|
122
|
+
export function remoteProject(url: string): { host: string; path: string } | undefined {
|
|
123
|
+
let host: string;
|
|
124
|
+
let path: string;
|
|
125
|
+
const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url);
|
|
126
|
+
if (scheme !== null) {
|
|
127
|
+
if (!["https", "http", "ssh", "git", "git+ssh", "ssh+git"].includes(scheme[1]!.toLowerCase())) return undefined;
|
|
128
|
+
let parsed: URL;
|
|
129
|
+
try {
|
|
130
|
+
parsed = new URL(url);
|
|
131
|
+
} catch {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
host = parsed.hostname;
|
|
135
|
+
try {
|
|
136
|
+
path = decodeURIComponent(parsed.pathname);
|
|
137
|
+
} catch {
|
|
138
|
+
// A path that is not valid percent-encoding names no project.
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
} else {
|
|
142
|
+
// The scp-like form: [user@]host:path. A colon after a slash is a local path.
|
|
143
|
+
const scp = /^(?:[^@/]+@)?([^:/]+):(.+)$/.exec(url);
|
|
144
|
+
if (scp === null) return undefined;
|
|
145
|
+
host = scp[1]!;
|
|
146
|
+
path = scp[2]!;
|
|
147
|
+
}
|
|
148
|
+
host = host.toLowerCase();
|
|
149
|
+
path = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
|
|
150
|
+
const segments = path.split("/");
|
|
151
|
+
if (!HOST.test(host) || segments.length < 2 || !segments.every((segment) => SEGMENT.test(segment))) return undefined;
|
|
152
|
+
return { host, path };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** What a repository's configuration says for a key, or "" when it says nothing. */
|
|
156
|
+
async function configured(repo: string, key: string): Promise<string> {
|
|
157
|
+
const result = await gitRun(repo, ["config", "--get", key]);
|
|
158
|
+
return result.code === 0 ? result.stdout.trim() : "";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The remote a push of `base` goes to, by the rules git pushes by: the push remote of the branch, else
|
|
163
|
+
* `remote.pushDefault`, else the remote the branch tracks, else the only remote or `origin`. A branch that
|
|
164
|
+
* tracks a local branch (remote ".") goes to no remote.
|
|
165
|
+
*/
|
|
166
|
+
async function pushRemoteOf(repo: string, base: string): Promise<string | undefined> {
|
|
167
|
+
const named = (await configured(repo, `branch.${base}.pushRemote`)) || (await configured(repo, "remote.pushDefault"));
|
|
168
|
+
const name = named || (await configured(repo, `branch.${base}.remote`));
|
|
169
|
+
if (name !== "") return name === "." ? undefined : name;
|
|
170
|
+
const remotes = (await gitRun(repo, ["remote"])).stdout.trim().split("\n");
|
|
171
|
+
return remotes.length === 1 && remotes[0] !== "" ? remotes[0] : "origin";
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* The remote the work on `base` goes to, verified from the repository's configuration: the remote a push of `base`
|
|
176
|
+
* goes to. It is undefined when that remote is not configured, its URL names no project on a server, or any of its
|
|
177
|
+
* push URLs names another project than its fetch URL.
|
|
178
|
+
*/
|
|
179
|
+
export async function verifiedRemote(repo: string, base: string): Promise<{ name: string; host: string; path: string } | undefined> {
|
|
180
|
+
const name = await pushRemoteOf(repo, base);
|
|
181
|
+
if (name === undefined) return undefined;
|
|
182
|
+
const fetch = await gitRun(repo, ["remote", "get-url", name]);
|
|
183
|
+
if (fetch.code !== 0) return undefined;
|
|
184
|
+
const project = remoteProject(fetch.stdout.trim());
|
|
185
|
+
if (project === undefined) return undefined;
|
|
186
|
+
const push = await gitRun(repo, ["remote", "get-url", "--push", "--all", name]);
|
|
187
|
+
const urls = push.stdout.split("\n").map((line) => line.trim()).filter((line) => line !== "");
|
|
188
|
+
if (push.code !== 0 || urls.length === 0) return undefined;
|
|
189
|
+
for (const url of urls) {
|
|
190
|
+
const pushed = remoteProject(url);
|
|
191
|
+
if (pushed === undefined || pushed.host !== project.host || pushed.path !== project.path) return undefined;
|
|
192
|
+
}
|
|
193
|
+
return { name, ...project };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The paths, relative to the top, that a NUL-separated git listing gives. */
|
|
197
|
+
function paths(listing: string): string[] {
|
|
198
|
+
return listing.split("\0").filter((path) => path !== "");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Prepare the in-tree directory for a copy, without traversing any links. */
|
|
202
|
+
function prepareCopyDirectory(root: string, parts: readonly string[]): boolean {
|
|
203
|
+
let dir = root;
|
|
204
|
+
for (const part of parts) {
|
|
205
|
+
dir = join(dir, part);
|
|
206
|
+
const entry = lstatSync(dir, { throwIfNoEntry: false });
|
|
207
|
+
if (entry === undefined) mkdirSync(dir);
|
|
208
|
+
else if (!entry.isDirectory()) return false;
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Copy into a new worktree the files of the repository that are ignored by git and listed in
|
|
215
|
+
* `<repo>/.worktreeinclude` (gitignore syntax): `.env`, local settings. A tracked file, or an
|
|
216
|
+
* untracked one git does not ignore, is never copied, whatever the include says; neither is a file
|
|
217
|
+
* the new checkout tracks (the base may track what the source ignores), nor one that is there
|
|
218
|
+
* already (a create made again), nor one that would land outside the checkout. The copy is a
|
|
219
|
+
* clone where the file system makes one (APFS), a plain copy elsewhere; a link is followed, never
|
|
220
|
+
* made. Answers how many files were copied.
|
|
221
|
+
*/
|
|
222
|
+
export async function copyIncluded(repo: string, into: string): Promise<number> {
|
|
223
|
+
const include = join(repo, ".worktreeinclude");
|
|
224
|
+
if (!existsSync(include)) return 0;
|
|
225
|
+
// The untracked files the include names, then those of them git ignores.
|
|
226
|
+
const named = paths(await gitOut(repo, ["ls-files", "-z", "--others", "--ignored", `--exclude-from=${include}`]));
|
|
227
|
+
if (named.length === 0) return 0;
|
|
228
|
+
const ignored = await gitRun(repo, ["check-ignore", "-z", "--stdin"], `${named.join("\0")}\0`);
|
|
229
|
+
// check-ignore answers 1 when none is ignored.
|
|
230
|
+
if (ignored.code !== 0 && ignored.code !== 1) throw new Error(`git check-ignore failed: ${ignored.stderr.trim()}`);
|
|
231
|
+
const candidates = paths(ignored.stdout);
|
|
232
|
+
if (candidates.length === 0) return 0;
|
|
233
|
+
const tracked = new Set(paths(await gitOut(into, ["ls-files", "-z"])));
|
|
234
|
+
const inside = realpathSync(into);
|
|
235
|
+
let copied = 0;
|
|
236
|
+
for (const path of candidates) {
|
|
237
|
+
const parts = path.split("/");
|
|
238
|
+
// The path, or a directory on the way to it, is a tracked file of the new checkout.
|
|
239
|
+
if (parts.some((_, at) => tracked.has(parts.slice(0, at + 1).join("/")))) continue;
|
|
240
|
+
const target = join(inside, path);
|
|
241
|
+
if (!prepareCopyDirectory(inside, parts.slice(0, -1))) continue;
|
|
242
|
+
if (lstatSync(target, { throwIfNoEntry: false }) !== undefined) continue;
|
|
243
|
+
copyFileSync(join(repo, path), target, constants.COPYFILE_FICLONE | constants.COPYFILE_EXCL);
|
|
244
|
+
copied += 1;
|
|
245
|
+
}
|
|
246
|
+
return copied;
|
|
247
|
+
}
|