@juanem1/pi-git 0.0.0-stage → 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.
- package/CHANGELOG.md +6 -0
- package/LICENSE +21 -0
- package/README.md +99 -2
- package/extensions/git.js +105 -0
- package/package.json +29 -4
- package/src/git.js +379 -0
package/CHANGELOG.md
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 juanem1
|
|
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,100 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Package pi-git
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A Pi package for Git, with no npm dependencies or installation scripts.
|
|
4
|
+
Commits, pushes, and worktree changes require individual confirmation.
|
|
5
|
+
It does not add co-authors or impose a commit message format.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- [Pi](https://pi.dev)
|
|
10
|
+
- Git
|
|
11
|
+
- Node.js 22 or later
|
|
12
|
+
|
|
13
|
+
## Install in Pi
|
|
14
|
+
|
|
15
|
+
Install from npm:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pi install npm:@juanem1/pi-git
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or from a local clone:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
git clone https://github.com/juanem1/pi-git.git
|
|
25
|
+
pi install ./pi-git
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Add `-l` to install it only for the current project (`.pi/settings.json`).
|
|
29
|
+
Restart Pi or run `/reload` if it is already open.
|
|
30
|
+
|
|
31
|
+
To try it without installing, from a local clone:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pi -e ./pi-git
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
To update or uninstall:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
pi update npm:@juanem1/pi-git
|
|
41
|
+
pi remove npm:@juanem1/pi-git
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Tools
|
|
45
|
+
|
|
46
|
+
| Tool | Behavior |
|
|
47
|
+
|---|---|
|
|
48
|
+
| `git_status` | Branch, staged, modified, and new files. |
|
|
49
|
+
| `git_diff` | Local or staged diff, or diff against a revision; optional literal paths. |
|
|
50
|
+
| `git_log` | Up to 200 commits; 20 by default. |
|
|
51
|
+
| `git_show` | Commit message and diff. |
|
|
52
|
+
| `git_commit` | Confirms the message, branch, and files; commits only those complete files, without pushing. |
|
|
53
|
+
| `git_push` | Confirms the remote, destination, branch, and commit; pushes only the current branch. |
|
|
54
|
+
| `git_worktree_list` | Lists existing worktrees. |
|
|
55
|
+
| `git_worktree_add` | Confirms a new path and branch; does not change the current worktree's branch. |
|
|
56
|
+
| `git_worktree_remove` | Confirms removal of a clean worktree; preserves its branch. |
|
|
57
|
+
| `git_worktree_prune` | Previews and confirms cleanup of metadata for missing worktrees. |
|
|
58
|
+
|
|
59
|
+
File paths are relative to the root of the current repository. Commit does not
|
|
60
|
+
accept directories: list individual files and both paths of a renamed file.
|
|
61
|
+
If a file is partially staged, its entire working tree content is committed.
|
|
62
|
+
Other already-staged files are excluded from the commit.
|
|
63
|
+
|
|
64
|
+
## Security limits
|
|
65
|
+
|
|
66
|
+
- Runs only `git`, with separate arguments and no shell. It does not use `eval`,
|
|
67
|
+
downloads, cleanup commands, or background processes.
|
|
68
|
+
- Does not offer reset, discarding changes, rebase, amend, force push, branch
|
|
69
|
+
deletion, or forced worktree removal.
|
|
70
|
+
- Refuses to remove worktrees with modified, new, or ignored files, as well as
|
|
71
|
+
the main, current, or locked worktrees.
|
|
72
|
+
- Push requires an explicit remote with a single HTTPS/SSH URL. It does not
|
|
73
|
+
accept local paths, remote helpers, tags, or refspecs from the model.
|
|
74
|
+
- Mutations are rejected without a Pi confirmation interface.
|
|
75
|
+
- Does not disable hooks or configured signing. Git hooks, filters, and transports
|
|
76
|
+
can run programs from the repository or environment: use trusted repositories
|
|
77
|
+
and Git configurations.
|
|
78
|
+
|
|
79
|
+
This **is not a sandbox** and does not block Pi's general Bash access or other
|
|
80
|
+
extensions. Queries disable external diff, textconv, and signature verification.
|
|
81
|
+
Large outputs are explicitly limited; a process that exceeds 120 seconds or
|
|
82
|
+
4 MiB of output fails. If a mutation fails, check the status before retrying.
|
|
83
|
+
|
|
84
|
+
## Development
|
|
85
|
+
|
|
86
|
+
No `npm install` is needed.
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
npm test
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Release
|
|
93
|
+
|
|
94
|
+
Publishing runs in GitHub Actions with npm trusted publishing when a `v*` tag is
|
|
95
|
+
pushed. Add the version's entry to `CHANGELOG.md`, then:
|
|
96
|
+
|
|
97
|
+
```sh
|
|
98
|
+
npm version patch # or minor / major; commits and tags vX.Y.Z
|
|
99
|
+
git push --follow-tags
|
|
100
|
+
```
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createGitOperations } from "../src/git.js";
|
|
2
|
+
|
|
3
|
+
const string = (description) => ({ type: "string", minLength: 1, description });
|
|
4
|
+
const paths = {
|
|
5
|
+
type: "array",
|
|
6
|
+
items: string("Literal path relative to the repository root, not a glob."),
|
|
7
|
+
minItems: 1,
|
|
8
|
+
uniqueItems: true,
|
|
9
|
+
};
|
|
10
|
+
const ref = string("Git revision or range, never a command-line option.");
|
|
11
|
+
|
|
12
|
+
export default function (pi) {
|
|
13
|
+
const operations = createGitOperations();
|
|
14
|
+
const register = (name, description, properties = {}, required = [], mutating = false) => {
|
|
15
|
+
pi.registerTool({
|
|
16
|
+
name,
|
|
17
|
+
label: name.replaceAll("_", " "),
|
|
18
|
+
description,
|
|
19
|
+
promptSnippet: description,
|
|
20
|
+
annotations: {
|
|
21
|
+
readOnlyHint: !mutating,
|
|
22
|
+
destructiveHint: name === "git_worktree_remove" || name === "git_worktree_prune",
|
|
23
|
+
idempotentHint: !mutating,
|
|
24
|
+
openWorldHint: name === "git_push",
|
|
25
|
+
},
|
|
26
|
+
executionMode: mutating ? "sequential" : "parallel",
|
|
27
|
+
parameters: { type: "object", properties, required, additionalProperties: false },
|
|
28
|
+
async execute(_id, params, signal, _update, ctx) {
|
|
29
|
+
const output = await operations[name](params, ctx, signal);
|
|
30
|
+
const limit = 40_000;
|
|
31
|
+
const truncated = output.length > limit;
|
|
32
|
+
return {
|
|
33
|
+
content: [{
|
|
34
|
+
type: "text",
|
|
35
|
+
text: truncated
|
|
36
|
+
? `${output.slice(0, limit)}\n[Output truncated; narrow the paths, revision or count.]`
|
|
37
|
+
: output || "No output.",
|
|
38
|
+
}],
|
|
39
|
+
details: { truncated },
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
register("git_status", "Read the current repository's branch and staged, unstaged, and untracked paths.");
|
|
46
|
+
register("git_diff", "Read a diff of the working tree, index, or a revision; external diff programs are disabled.", {
|
|
47
|
+
staged: { type: "boolean", description: "Compare the index instead of the working tree." },
|
|
48
|
+
base: ref,
|
|
49
|
+
paths,
|
|
50
|
+
stat: { type: "boolean", description: "Show only the diffstat." },
|
|
51
|
+
});
|
|
52
|
+
register("git_log", "Read recent commits without running signature verification.", {
|
|
53
|
+
ref,
|
|
54
|
+
count: { type: "integer", minimum: 1, maximum: 200, description: "Maximum commits; default 20." },
|
|
55
|
+
paths,
|
|
56
|
+
});
|
|
57
|
+
register("git_show", "Read one commit's message and diff without external diff programs or text conversion.", {
|
|
58
|
+
ref: string("One commit or tag; default HEAD."),
|
|
59
|
+
paths,
|
|
60
|
+
stat: { type: "boolean", description: "Show metadata and diffstat, without the patch." },
|
|
61
|
+
});
|
|
62
|
+
register(
|
|
63
|
+
"git_commit",
|
|
64
|
+
"After user confirmation, stage and commit only explicitly named files on the current branch. Never push or append coauthors. Include both paths of a rename.",
|
|
65
|
+
{
|
|
66
|
+
message: string("Complete commit message, passed verbatim without automatic attribution."),
|
|
67
|
+
paths,
|
|
68
|
+
},
|
|
69
|
+
["message", "paths"],
|
|
70
|
+
true,
|
|
71
|
+
);
|
|
72
|
+
register(
|
|
73
|
+
"git_push",
|
|
74
|
+
"After separate user confirmation, push only the current branch to one named HTTPS/SSH remote. Never force, delete, mirror, or push tags.",
|
|
75
|
+
{ remote: string("Existing remote name, for example origin. No URL or command.") },
|
|
76
|
+
["remote"],
|
|
77
|
+
true,
|
|
78
|
+
);
|
|
79
|
+
register("git_worktree_list", "Read this repository's worktrees without changing them.");
|
|
80
|
+
register(
|
|
81
|
+
"git_worktree_add",
|
|
82
|
+
"After user confirmation, create a worktree at an explicit path without switching the current worktree's branch or overwriting files.",
|
|
83
|
+
{
|
|
84
|
+
branch: string("Branch to create or check out in the new worktree."),
|
|
85
|
+
path: string("Destination directory, absolute or relative to the repository root."),
|
|
86
|
+
base: string("Starting commit for a new branch; default HEAD. Omit for an existing branch."),
|
|
87
|
+
},
|
|
88
|
+
["branch", "path"],
|
|
89
|
+
true,
|
|
90
|
+
);
|
|
91
|
+
register(
|
|
92
|
+
"git_worktree_remove",
|
|
93
|
+
"After user confirmation, remove only a clean linked worktree. Refuse modified, untracked, ignored, locked, main, or current worktrees. Keep the branch.",
|
|
94
|
+
{ path: string("Worktree directory, absolute or relative to the repository root.") },
|
|
95
|
+
["path"],
|
|
96
|
+
true,
|
|
97
|
+
);
|
|
98
|
+
register(
|
|
99
|
+
"git_worktree_prune",
|
|
100
|
+
"Preview stale worktree metadata, then ask for confirmation before pruning it. Never delete worktree directories.",
|
|
101
|
+
{},
|
|
102
|
+
[],
|
|
103
|
+
true,
|
|
104
|
+
);
|
|
105
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juanem1/pi-git",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Focused Git tools for Pi with explicit confirmation for mutations.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "juanem1",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/juanem1/pi-git.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/juanem1/pi-git#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/juanem1/pi-git/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": ["pi-package", "pi", "git"],
|
|
17
|
+
"engines": {
|
|
18
|
+
"node": ">=22"
|
|
19
|
+
},
|
|
20
|
+
"files": ["extensions", "src", "README.md", "CHANGELOG.md", "LICENSE"],
|
|
21
|
+
"pi": {
|
|
22
|
+
"extensions": ["./extensions/git.js"]
|
|
23
|
+
},
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public",
|
|
26
|
+
"registry": "https://registry.npmjs.org/"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/git.js
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { lstat, realpath } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, isAbsolute, normalize, relative, resolve, sep } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
|
|
8
|
+
export async function runGit(args, cwd, signal, includeStderr = false) {
|
|
9
|
+
const env = {
|
|
10
|
+
...process.env,
|
|
11
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
12
|
+
GIT_PAGER: "cat",
|
|
13
|
+
GIT_EDITOR: "true",
|
|
14
|
+
GIT_SEQUENCE_EDITOR: "true",
|
|
15
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
16
|
+
GIT_NO_LAZY_FETCH: "1",
|
|
17
|
+
LC_ALL: "C",
|
|
18
|
+
};
|
|
19
|
+
for (const key of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE",
|
|
20
|
+
"GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_NAMESPACE"]) {
|
|
21
|
+
delete env[key];
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const result = await exec("git", [
|
|
25
|
+
"--no-pager", "--literal-pathspecs", "-c", "core.fsmonitor=false", ...args,
|
|
26
|
+
], { cwd, env, signal, timeout: 120_000, maxBuffer: 4 * 1024 * 1024, shell: false });
|
|
27
|
+
return result.stdout + (includeStderr ? result.stderr : "");
|
|
28
|
+
} catch (error) {
|
|
29
|
+
const detail = error.stderr?.trim() || error.message;
|
|
30
|
+
throw Object.assign(new Error(`Git failed: ${detail}`, { cause: error }), { code: error.code });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function text(value, label) {
|
|
35
|
+
if (typeof value !== "string" || !value.trim() || /[\x00-\x1f\x7f]/.test(value)) {
|
|
36
|
+
throw new Error(`${label} must be nonempty and contain no control characters.`);
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function revision(value) {
|
|
42
|
+
text(value, "Revision");
|
|
43
|
+
if (value.startsWith("-") || value !== value.trim()) {
|
|
44
|
+
throw new Error("Revision must not be an option or contain surrounding whitespace.");
|
|
45
|
+
}
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function literalPaths(values, required = false) {
|
|
50
|
+
if (values === undefined && !required) {
|
|
51
|
+
return [];
|
|
52
|
+
}
|
|
53
|
+
if (!Array.isArray(values) || !values.length) {
|
|
54
|
+
throw new Error("Name at least one explicit file.");
|
|
55
|
+
}
|
|
56
|
+
return values.map((value) => {
|
|
57
|
+
text(value, "Path");
|
|
58
|
+
if (isAbsolute(value) || value.startsWith("-") || value.startsWith(":")
|
|
59
|
+
|| value.split(/[\\/]/).some((part) => part === ".." || part.toLowerCase() === ".git")
|
|
60
|
+
|| !value.split("/").some((part) => part && part !== ".")
|
|
61
|
+
|| value === "*" || value === "**") {
|
|
62
|
+
throw new Error(`Not an explicit repository-relative path: ${JSON.stringify(value)}`);
|
|
63
|
+
}
|
|
64
|
+
return normalize(value);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function validateFiles(selected, cwd, signal, run) {
|
|
69
|
+
for (const path of selected) {
|
|
70
|
+
const parent = await canonicalPath(dirname(resolve(cwd, path)));
|
|
71
|
+
if (!inside(parent, cwd)) {
|
|
72
|
+
throw new Error("File parent resolves outside the repository.");
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
if ((await lstat(resolve(cwd, path))).isDirectory()) {
|
|
76
|
+
throw new Error("Name individual files, not directories.");
|
|
77
|
+
}
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error.code !== "ENOENT") {
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const tracked = (await run(["ls-files", "-z", "--", path], cwd, signal)).split("\0").filter(Boolean);
|
|
84
|
+
if (tracked.some((entry) => entry !== path)) {
|
|
85
|
+
throw new Error("Name individual files, not deleted directories.");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function canonicalPath(path) {
|
|
91
|
+
const missing = [];
|
|
92
|
+
while (true) {
|
|
93
|
+
try {
|
|
94
|
+
return resolve(await realpath(path), ...missing);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if (error.code !== "ENOENT") {
|
|
97
|
+
throw error;
|
|
98
|
+
}
|
|
99
|
+
missing.unshift(basename(path));
|
|
100
|
+
path = dirname(path);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function parseWorktrees(output) {
|
|
106
|
+
return output.split("\0\0").filter(Boolean).map((record) => {
|
|
107
|
+
const fields = record.split("\0");
|
|
108
|
+
return {
|
|
109
|
+
path: fields.find((field) => field.startsWith("worktree "))?.slice(9),
|
|
110
|
+
locked: fields.some((field) => field === "locked" || field.startsWith("locked ")),
|
|
111
|
+
bare: fields.includes("bare"),
|
|
112
|
+
};
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function inside(path, parent) {
|
|
117
|
+
const rest = relative(parent, path);
|
|
118
|
+
return !rest || (!isAbsolute(rest) && rest !== ".." && !rest.startsWith(`..${sep}`));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function confirm(ctx, signal, title, description) {
|
|
122
|
+
signal?.throwIfAborted();
|
|
123
|
+
if (!ctx.hasUI) {
|
|
124
|
+
throw new Error("Interactive confirmation is required; no changes were made.");
|
|
125
|
+
}
|
|
126
|
+
if (!await ctx.ui.confirm(title, description)) {
|
|
127
|
+
throw new Error("Cancelled; no changes were made.");
|
|
128
|
+
}
|
|
129
|
+
signal?.throwIfAborted();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function createGitOperations(run = runGit) {
|
|
133
|
+
const root = async (ctx, signal) => realpath(
|
|
134
|
+
(await run(["rev-parse", "--show-toplevel"], ctx.cwd, signal)).replace(/\r?\n$/, ""),
|
|
135
|
+
);
|
|
136
|
+
const branch = async (cwd, signal) => {
|
|
137
|
+
let ref;
|
|
138
|
+
try {
|
|
139
|
+
ref = (await run(["symbolic-ref", "--quiet", "HEAD"], cwd, signal)).trim();
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (error.code !== 1) {
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
throw new Error("Not on a branch (detached HEAD); commit and push need a branch.", { cause: error });
|
|
145
|
+
}
|
|
146
|
+
if (!ref.startsWith("refs/heads/")) {
|
|
147
|
+
throw new Error("Not on a branch; commit and push need a branch.");
|
|
148
|
+
}
|
|
149
|
+
return revision(ref.slice("refs/heads/".length));
|
|
150
|
+
};
|
|
151
|
+
const commitId = async (ref, cwd, signal) => {
|
|
152
|
+
const sha = (await run(
|
|
153
|
+
["rev-parse", "--verify", "--end-of-options", `${revision(ref)}^{commit}`], cwd, signal,
|
|
154
|
+
)).trim();
|
|
155
|
+
if (!/^[a-f0-9]{40,64}$/.test(sha)) {
|
|
156
|
+
throw new Error("Git returned an invalid commit ID.");
|
|
157
|
+
}
|
|
158
|
+
return sha;
|
|
159
|
+
};
|
|
160
|
+
const unchangedBranch = async (expected, cwd, signal) => {
|
|
161
|
+
if (await branch(cwd, signal) !== expected) {
|
|
162
|
+
throw new Error("The current branch changed during confirmation. Review and retry.");
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
const entries = async (cwd, signal) => parseWorktrees(
|
|
166
|
+
await run(["worktree", "list", "--porcelain", "-z"], cwd, signal),
|
|
167
|
+
);
|
|
168
|
+
|
|
169
|
+
async function removable(target, cwd, ctx, signal) {
|
|
170
|
+
const list = await entries(cwd, signal);
|
|
171
|
+
const entry = list.find((item) => item.path === target);
|
|
172
|
+
if (!entry || entry === list[0] || entry.bare || entry.locked) {
|
|
173
|
+
throw new Error("Refusing to remove an unknown, main, bare, or locked worktree.");
|
|
174
|
+
}
|
|
175
|
+
if (inside(await realpath(ctx.cwd), target) || inside(cwd, target)) {
|
|
176
|
+
throw new Error("Refusing to remove the current worktree or a parent directory.");
|
|
177
|
+
}
|
|
178
|
+
const status = await run([
|
|
179
|
+
"status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored=matching",
|
|
180
|
+
"--ignore-submodules=none",
|
|
181
|
+
], target, signal);
|
|
182
|
+
if (status) {
|
|
183
|
+
throw new Error("Worktree contains modified, untracked, or ignored files; nothing was removed.");
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async function pushUrl(remote, cwd, signal) {
|
|
188
|
+
if (typeof remote !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(remote)) {
|
|
189
|
+
throw new Error("Use an existing remote name, not a URL, option, or command.");
|
|
190
|
+
}
|
|
191
|
+
const urls = (await run(["remote", "get-url", "--push", "--all", remote], cwd, signal))
|
|
192
|
+
.replace(/\r?\n$/, "").split("\n");
|
|
193
|
+
if (urls.length !== 1) {
|
|
194
|
+
throw new Error("Remote must have exactly one push URL.");
|
|
195
|
+
}
|
|
196
|
+
const url = text(urls[0], "Push URL");
|
|
197
|
+
if (!/^(?:https|ssh):\/\/[^/\s]+\/\S+$/.test(url)
|
|
198
|
+
&& !/^[^@\s/:]+@[^@\s/:]+:(?!:|\/\/)\S+$/.test(url)) {
|
|
199
|
+
throw new Error("Only HTTPS and SSH remotes are supported; no local paths or remote helpers.");
|
|
200
|
+
}
|
|
201
|
+
return url;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
async git_status(_params, ctx, signal) {
|
|
206
|
+
return run(["status", "--short", "--branch", "--untracked-files=all"], await root(ctx, signal), signal);
|
|
207
|
+
},
|
|
208
|
+
|
|
209
|
+
async git_diff(params, ctx, signal) {
|
|
210
|
+
const selected = literalPaths(params.paths);
|
|
211
|
+
return run([
|
|
212
|
+
"diff", "--no-color", "--no-ext-diff", "--no-textconv",
|
|
213
|
+
...(params.staged ? ["--cached"] : []),
|
|
214
|
+
...(params.stat ? ["--stat"] : []),
|
|
215
|
+
...(params.base === undefined ? [] : ["--end-of-options", revision(params.base)]),
|
|
216
|
+
"--", ...selected,
|
|
217
|
+
], await root(ctx, signal), signal);
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
async git_log(params, ctx, signal) {
|
|
221
|
+
const count = params.count ?? 20;
|
|
222
|
+
if (!Number.isInteger(count) || count < 1 || count > 200) {
|
|
223
|
+
throw new Error("Count must be between 1 and 200.");
|
|
224
|
+
}
|
|
225
|
+
return run([
|
|
226
|
+
"log", "--no-color", "--no-show-signature", `--max-count=${count}`,
|
|
227
|
+
"--format=%h %aI %an: %s",
|
|
228
|
+
...(params.ref === undefined ? [] : ["--end-of-options", revision(params.ref)]),
|
|
229
|
+
"--", ...literalPaths(params.paths),
|
|
230
|
+
], await root(ctx, signal), signal);
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
async git_show(params, ctx, signal) {
|
|
234
|
+
const cwd = await root(ctx, signal);
|
|
235
|
+
const sha = await commitId(params.ref ?? "HEAD", cwd, signal);
|
|
236
|
+
return run([
|
|
237
|
+
"show", "--no-color", "--no-ext-diff", "--no-textconv", "--no-show-signature",
|
|
238
|
+
"--format=fuller", "--stat", ...(params.stat ? [] : ["--patch"]),
|
|
239
|
+
"--end-of-options", sha, "--", ...literalPaths(params.paths),
|
|
240
|
+
], cwd, signal);
|
|
241
|
+
},
|
|
242
|
+
|
|
243
|
+
async git_commit(params, ctx, signal) {
|
|
244
|
+
const selected = literalPaths(params.paths, true);
|
|
245
|
+
if (typeof params.message !== "string" || !params.message.trim()
|
|
246
|
+
|| /[\x00-\x08\x0b-\x1f\x7f]/.test(params.message)) {
|
|
247
|
+
throw new Error("Provide a nonempty commit message without control characters other than tabs/newlines.");
|
|
248
|
+
}
|
|
249
|
+
const cwd = await root(ctx, signal);
|
|
250
|
+
const expected = await branch(cwd, signal);
|
|
251
|
+
await validateFiles(selected, cwd, signal, run);
|
|
252
|
+
await confirm(ctx, signal, "Confirm Git commit",
|
|
253
|
+
`Repository: ${JSON.stringify(cwd)}\nBranch: ${JSON.stringify(expected)}\n`
|
|
254
|
+
+ `Files: ${JSON.stringify(selected)}\nMessage: ${JSON.stringify(params.message)}\n\n`
|
|
255
|
+
+ "Commit the complete working-tree contents of these files only. No push or automatic coauthors.\n"
|
|
256
|
+
+ "Hooks and configured signing will run. A failure may leave these files staged.");
|
|
257
|
+
await unchangedBranch(expected, cwd, signal);
|
|
258
|
+
await validateFiles(selected, cwd, signal, run);
|
|
259
|
+
const deleted = new Set((await run(
|
|
260
|
+
["diff", "--cached", "--name-only", "--diff-filter=D", "-z", "--", ...selected], cwd, signal,
|
|
261
|
+
)).split("\0"));
|
|
262
|
+
const toAdd = selected.filter((path) => !deleted.has(path));
|
|
263
|
+
try {
|
|
264
|
+
if (toAdd.length) {
|
|
265
|
+
await run(["add", "--", ...toAdd], cwd, signal);
|
|
266
|
+
}
|
|
267
|
+
await unchangedBranch(expected, cwd, signal);
|
|
268
|
+
const output = await run([
|
|
269
|
+
"commit", "--only", "--cleanup=verbatim", "-m", params.message, "--", ...selected,
|
|
270
|
+
], cwd, signal);
|
|
271
|
+
return `${output.trimEnd()}\nCommit completed. No push performed.`;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
throw new Error(
|
|
274
|
+
`${error.message}\nThe index may contain the selected files. Inspect git_status and git_log before retrying; do not assume no commit was created.`,
|
|
275
|
+
{ cause: error },
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
|
|
280
|
+
async git_push(params, ctx, signal) {
|
|
281
|
+
const cwd = await root(ctx, signal);
|
|
282
|
+
const expected = await branch(cwd, signal);
|
|
283
|
+
const sha = await commitId("HEAD", cwd, signal);
|
|
284
|
+
const url = await pushUrl(params.remote, cwd, signal);
|
|
285
|
+
await confirm(ctx, signal, "Confirm Git push",
|
|
286
|
+
`Repository: ${JSON.stringify(cwd)}\nRemote: ${JSON.stringify(params.remote)}\n`
|
|
287
|
+
+ `Destination: ${JSON.stringify(url)}\nBranch: ${JSON.stringify(expected)}\nCommit: ${sha}\n\n`
|
|
288
|
+
+ "Publish only this commit to the same branch name. No force, tags, deletion, or upstream changes.");
|
|
289
|
+
await unchangedBranch(expected, cwd, signal);
|
|
290
|
+
if (await commitId("HEAD", cwd, signal) !== sha || await pushUrl(params.remote, cwd, signal) !== url) {
|
|
291
|
+
throw new Error("HEAD or the push destination changed during confirmation. Review and retry.");
|
|
292
|
+
}
|
|
293
|
+
return run([
|
|
294
|
+
"-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "protocol.ssh.allow=always",
|
|
295
|
+
"push", "--porcelain", "--no-force", "--no-mirror", "--no-follow-tags", "--recurse-submodules=no",
|
|
296
|
+
params.remote, `${sha}:refs/heads/${expected}`,
|
|
297
|
+
], cwd, signal);
|
|
298
|
+
},
|
|
299
|
+
|
|
300
|
+
async git_worktree_list(_params, ctx, signal) {
|
|
301
|
+
return run(["worktree", "list"], await root(ctx, signal), signal);
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
async git_worktree_add(params, ctx, signal) {
|
|
305
|
+
const name = revision(params.branch);
|
|
306
|
+
text(params.path, "Worktree path");
|
|
307
|
+
const cwd = await root(ctx, signal);
|
|
308
|
+
await run(["check-ref-format", `refs/heads/${name}`], cwd, signal);
|
|
309
|
+
const target = await canonicalPath(resolve(cwd, params.path));
|
|
310
|
+
const main = (await entries(cwd, signal))[0]?.path ?? cwd;
|
|
311
|
+
if ([cwd, main].some((repo) => inside(repo, target) || inside(target, repo))) {
|
|
312
|
+
throw new Error("New worktree must be outside the current and main repository.");
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
await lstat(target);
|
|
316
|
+
throw new Error("Destination already exists; choose a new directory.");
|
|
317
|
+
} catch (error) {
|
|
318
|
+
if (error.code !== "ENOENT") {
|
|
319
|
+
throw error;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
let exists = true;
|
|
323
|
+
try {
|
|
324
|
+
await run(["show-ref", "--verify", "--quiet", `refs/heads/${name}`], cwd, signal);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
if (error.code !== 1) {
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
exists = false;
|
|
330
|
+
}
|
|
331
|
+
if (exists && params.base !== undefined) {
|
|
332
|
+
throw new Error("Branch already exists; omit base.");
|
|
333
|
+
}
|
|
334
|
+
const base = exists ? undefined : await commitId(params.base ?? "HEAD", cwd, signal);
|
|
335
|
+
await confirm(ctx, signal, "Confirm worktree creation",
|
|
336
|
+
`Repository: ${JSON.stringify(cwd)}\nDestination: ${JSON.stringify(target)}\n`
|
|
337
|
+
+ `Branch: ${JSON.stringify(name)} (${exists ? "existing" : `new from ${base}`})\n\n`
|
|
338
|
+
+ "Create a separate worktree. The current worktree stays on its current branch.");
|
|
339
|
+
if (await canonicalPath(resolve(cwd, params.path)) !== target) {
|
|
340
|
+
throw new Error("Worktree destination changed during confirmation. Review and retry.");
|
|
341
|
+
}
|
|
342
|
+
await run([
|
|
343
|
+
"worktree", "add", "--no-guess-remote", ...(exists ? [] : ["-b", name]),
|
|
344
|
+
"--", target, exists ? name : base,
|
|
345
|
+
], cwd, signal);
|
|
346
|
+
return `Created worktree at ${JSON.stringify(target)} on ${JSON.stringify(name)}.`;
|
|
347
|
+
},
|
|
348
|
+
|
|
349
|
+
async git_worktree_remove(params, ctx, signal) {
|
|
350
|
+
text(params.path, "Worktree path");
|
|
351
|
+
const cwd = await root(ctx, signal);
|
|
352
|
+
const target = await realpath(resolve(cwd, params.path));
|
|
353
|
+
await removable(target, cwd, ctx, signal);
|
|
354
|
+
await confirm(ctx, signal, "Confirm worktree removal",
|
|
355
|
+
`Repository: ${JSON.stringify(cwd)}\nWorktree: ${JSON.stringify(target)}\n\n`
|
|
356
|
+
+ "Remove this clean worktree directory. Keep its branch. Never force removal.");
|
|
357
|
+
await removable(target, cwd, ctx, signal);
|
|
358
|
+
await run(["worktree", "remove", "--", target], cwd, signal);
|
|
359
|
+
return `Removed worktree at ${JSON.stringify(target)}. Its branch was kept.`;
|
|
360
|
+
},
|
|
361
|
+
|
|
362
|
+
async git_worktree_prune(_params, ctx, signal) {
|
|
363
|
+
const cwd = await root(ctx, signal);
|
|
364
|
+
const dryRun = () => run(["worktree", "prune", "--dry-run", "--verbose"], cwd, signal, true);
|
|
365
|
+
const preview = await dryRun();
|
|
366
|
+
if (!preview.trim()) {
|
|
367
|
+
return "No stale worktree metadata to prune.";
|
|
368
|
+
}
|
|
369
|
+
await confirm(ctx, signal, "Confirm worktree metadata pruning",
|
|
370
|
+
`Repository: ${JSON.stringify(cwd)}\nPreview: ${JSON.stringify(preview)}\n\n`
|
|
371
|
+
+ "Remove stale administrative records only, using Git's default expiration. No directory deletion.");
|
|
372
|
+
if (await dryRun() !== preview) {
|
|
373
|
+
throw new Error("Prune candidates changed during confirmation. Review and retry.");
|
|
374
|
+
}
|
|
375
|
+
await run(["worktree", "prune", "--verbose"], cwd, signal);
|
|
376
|
+
return "Stale worktree metadata pruned. No worktree directories were deleted.";
|
|
377
|
+
},
|
|
378
|
+
};
|
|
379
|
+
}
|