just-git 1.1.11 → 1.2.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.
package/README.md CHANGED
@@ -18,12 +18,19 @@ npm install just-git
18
18
 
19
19
  ### Client
20
20
 
21
- Provide any `FileSystem` implementation and call `git.exec()`:
22
-
23
21
  ```ts
24
- import { createGit } from "just-git";
22
+ import { createGit, MemoryFileSystem } from "just-git";
25
23
 
26
- const git = createGit({ identity: { name: "Alice", email: "alice@example.com" } });
24
+ const fs = new MemoryFileSystem();
25
+ const git = createGit({
26
+ identity: { name: "Alice", email: "alice@example.com" },
27
+ credentials: (url) => ({ type: "bearer", token: process.env.GITHUB_TOKEN! }),
28
+ hooks: {
29
+ beforeCommand: ({ command }) => {
30
+ if (command === "push") return { reject: true, message: "push requires approval" };
31
+ },
32
+ },
33
+ });
27
34
 
28
35
  await git.exec("git init", { fs, cwd: "/repo" });
29
36
  await git.exec("git add .", { fs, cwd: "/repo" });
@@ -31,9 +38,7 @@ await git.exec('git commit -m "initial commit"', { fs, cwd: "/repo" });
31
38
  await git.exec("git log --oneline", { fs, cwd: "/repo" });
32
39
  ```
33
40
 
34
- Tokenization handles single and double quotes. Pass `env` as a plain object when needed (e.g. `GIT_AUTHOR_NAME`).
35
-
36
- For a full virtual shell with file I/O, pipes, and scripting, pair with [just-bash](https://github.com/vercel-labs/just-bash):
41
+ `MemoryFileSystem` is a minimal in-memory filesystem for standalone use. Tokenization handles single and double quotes; pass `env` as a plain object when needed (e.g. `GIT_AUTHOR_NAME`). The `FileSystem` interface is built around [just-bash](https://github.com/vercel-labs/just-bash)'s implementations. For anything beyond bare git commands, it's recommended to use just-git as a custom command in just-bash:
37
42
 
38
43
  ```ts
39
44
  import { Bash } from "just-bash";
@@ -53,10 +58,10 @@ await bash.exec("git add . && git commit -m 'initial commit'");
53
58
  Stand up a git server with built-in storage (SQLite or [PostgreSQL](docs/SERVER.md#pgstorage)), branch protection, and push hooks:
54
59
 
55
60
  ```ts
56
- import { createGitServer, SqliteStorage } from "just-git/server";
61
+ import { createGitServer, BunSqliteStorage } from "just-git/server";
57
62
  import { Database } from "bun:sqlite";
58
63
 
59
- const storage = new SqliteStorage(new Database("repos.sqlite"));
64
+ const storage = new BunSqliteStorage(new Database("repos.sqlite"));
60
65
 
61
66
  const server = createGitServer({
62
67
  resolveRepo: (path) => storage.repo(path),
@@ -75,223 +80,79 @@ Bun.serve({ fetch: server.fetch });
75
80
  // git clone http://localhost:3000/my-repo ← works with real git
76
81
  ```
77
82
 
78
- Uses web-standard `Request`/`Response` works with Bun, Hono, Cloudflare Workers, or any fetch-compatible runtime. For Node.js, use `toNodeHandler(server)` with `http.createServer` and `wrapBetterSqlite3` for `better-sqlite3`. See [SERVER.md](docs/SERVER.md) for the full API.
83
+ Uses web-standard `Request`/`Response`. Works with Bun, Hono, Cloudflare Workers, or any fetch-compatible runtime. For Node.js, use `toNodeHandler(server)` with `http.createServer` and `BetterSqlite3Storage` for `better-sqlite3`. See [SERVER.md](docs/SERVER.md) for the full API.
79
84
 
80
- ## Options
85
+ ## createGit options
81
86
 
82
87
  `createGit(options?)` accepts:
83
88
 
84
- | Option | Description |
85
- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
86
- | `identity` | Author/committer override. With `locked: true`, always wins over env vars and git config. Without `locked`, acts as a fallback. |
87
- | `credentials` | `(url) => HttpAuth \| null` callback for Smart HTTP transport auth. |
88
- | `disabled` | `GitCommandName[]` of subcommands to block (e.g. `["push", "rebase"]`). |
89
- | `network` | `{ allowed?: string[], fetch?: FetchFunction }` to restrict HTTP access and/or provide a custom `fetch`. `allowed` accepts hostnames (`"github.com"`) or URL prefixes (`"https://github.com/myorg/"`). Set to `false` to block all network access. |
90
- | `hooks` | `GitHooks` config object with named callback properties. See [Hooks](#hooks). |
91
- | `resolveRemote` | `(url) => GitRepo \| null` callback for cross-VFS remote resolution. See [Multi-agent collaboration](#multi-agent-collaboration). |
92
-
93
- ```ts
94
- const git = createGit({
95
- identity: { name: "Agent Bot", email: "bot@company.com", locked: true },
96
- credentials: async (url) => ({ type: "bearer", token: "ghp_..." }),
97
- disabled: ["rebase"],
98
- network: false, // no HTTP access
99
- });
100
- ```
89
+ | Option | Description |
90
+ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | `identity` | Author/committer override. With `locked: true`, always wins over env vars and git config. Without `locked`, acts as a fallback. |
92
+ | `credentials` | `(url) => HttpAuth \| null` callback for Smart HTTP transport auth. |
93
+ | `disabled` | `GitCommandName[]` of subcommands to block (e.g. `["push", "rebase"]`). |
94
+ | `network` | `{ allowed?: string[], fetch? }` to restrict HTTP access. Set to `false` to block all network access. |
95
+ | `config` | `{ locked?, defaults? }` config overrides. `locked` values always win over `.git/config`; `defaults` supply fallbacks when a key is absent. |
96
+ | `hooks` | Lifecycle hooks for pre/post command interception, commit gating, message enforcement, and audit logging. |
97
+ | `resolveRemote` | `(url) => GitRepo \| null` callback for cross-VFS remote resolution (multi-agent setups). |
101
98
 
102
- ## Hooks
99
+ See [CLIENT.md](docs/CLIENT.md) for detailed usage, config overrides, and multi-agent collaboration.
103
100
 
104
- Hooks fire at specific points inside command execution. Specified as a `GitHooks` config object at construction time. All hook event payloads include `repo: GitRepo`, providing access to the [repo module helpers](src/repo/) inside hooks.
101
+ ## Client hooks
105
102
 
106
- Pre-hooks can reject the operation by returning `{ reject: true, message? }`. Post-hooks are observational return value is ignored.
103
+ Hooks fire at specific points inside command execution. Pre-hooks can reject the operation by returning `{ reject: true, message? }`. Post-hooks are observational. All hook payloads include `repo: GitRepo` for [programmatic repo access](docs/REPO.md).
107
104
 
108
105
  ```ts
109
- import { createGit, type GitHooks } from "just-git";
106
+ import { createGit } from "just-git";
110
107
  import { getChangedFiles } from "just-git/repo";
111
108
 
112
109
  const git = createGit({
113
110
  hooks: {
114
- // Block secrets from being committed
115
111
  preCommit: ({ index }) => {
116
112
  const forbidden = index.entries.filter((e) => /\.(env|pem|key)$/.test(e.path));
117
113
  if (forbidden.length) {
118
114
  return { reject: true, message: `Blocked: ${forbidden.map((e) => e.path).join(", ")}` };
119
115
  }
120
116
  },
121
-
122
- // Enforce conventional commit messages
123
- commitMsg: (event) => {
124
- if (!/^(feat|fix|docs|refactor|test|chore)(\(.+\))?:/.test(event.message)) {
125
- return { reject: true, message: "Commit message must follow conventional commits format" };
126
- }
127
- },
128
-
129
- // Feed agent activity to your UI — with changed file list
130
117
  postCommit: async ({ repo, hash, branch, parents }) => {
131
118
  const files = await getChangedFiles(repo, parents[0] ?? null, hash);
132
119
  onAgentCommit({ hash, branch, changedFiles: files });
133
120
  },
134
-
135
- // Audit log — record every command
136
- afterCommand: ({ command, args, result }) => {
137
- auditLog.push({ command: `git ${command}`, exitCode: result.exitCode });
138
- },
139
-
140
- // Gate pushes on human approval
141
- beforeCommand: async ({ command }) => {
142
- if (command === "push" && !(await getHumanApproval())) {
143
- return { reject: true, message: "Push blocked — awaiting approval." };
144
- }
145
- },
146
121
  },
147
122
  });
148
123
  ```
149
124
 
150
- Use `composeGitHooks()` to combine multiple hook sets:
151
-
152
- ```ts
153
- import { createGit, composeGitHooks } from "just-git";
154
-
155
- const git = createGit({
156
- hooks: composeGitHooks(auditHooks, policyHooks, loggingHooks),
157
- });
158
- ```
159
-
160
- Available pre-hooks: `preCommit`, `commitMsg`, `mergeMsg`, `preMergeCommit`, `preCheckout`, `prePush`, `preFetch`, `preClone`, `prePull`, `preRebase`, `preReset`, `preClean`, `preRm`, `preCherryPick`, `preRevert`, `preStash`. Available post-hooks: `postCommit`, `postMerge`, `postCheckout`, `postPush`, `postFetch`, `postClone`, `postPull`, `postReset`, `postClean`, `postRm`, `postCherryPick`, `postRevert`, `postStash`. Low-level events: `onRefUpdate`, `onRefDelete`, `onObjectWrite`. Command-level: `beforeCommand`, `afterCommand`.
125
+ Combine multiple hook sets with `composeGitHooks(auditHooks, policyHooks, loggingHooks)`. See [HOOKS.md](docs/HOOKS.md) for the full type reference and [CLIENT.md](docs/CLIENT.md) for more examples.
161
126
 
162
127
  ## Repo module
163
128
 
164
- `just-git/repo` provides a high-level API for working with repositories programmatically — reading commits, diffing trees, creating objects, and merging without going through command execution. This is what you use inside hooks (all hook payloads include `repo: GitRepo`) and anywhere else you need direct repo access.
129
+ `just-git/repo` provides programmatic access to git repositories: reading commits, diffing trees, creating objects, and merging, all without going through command execution.
130
+
131
+ Everything operates on `GitRepo`, a minimal `{ objectStore, refStore }` interface shared by the client and server. A `GitRepo` can be backed by a virtual filesystem, SQLite, Postgres, or any custom storage. The same helpers work inside both client-side hooks and server-side hooks, and `createWorktree` lets you spin up a full git client against a database-backed repo.
165
132
 
166
133
  ```ts
167
- import {
168
- readCommit,
169
- readFileAtCommit,
170
- getChangedFiles,
171
- resolveRef,
172
- listBranches,
173
- diffTrees,
174
- flattenTree,
175
- createCommit,
176
- writeBlob,
177
- writeTree,
178
- mergeTrees,
179
- checkoutTo,
180
- readonlyRepo,
181
- } from "just-git/repo";
182
-
183
- // Read a file at a specific commit
184
- const content = await readFileAtCommit(repo, commitHash, "src/index.ts");
134
+ import { readFileAtCommit, getChangedFiles, mergeTrees } from "just-git/repo";
185
135
 
186
- // Diff two commits
136
+ const content = await readFileAtCommit(repo, commitHash, "src/index.ts");
187
137
  const changes = await getChangedFiles(repo, parentHash, commitHash);
188
-
189
- // Merge two branches at the tree level (no worktree needed)
190
138
  const result = await mergeTrees(repo, oursCommit, theirsCommit);
191
- if (!result.clean) console.log("conflicts:", result.conflicts);
192
139
  ```
193
140
 
194
- Also re-exports `PackedObjectStore` and `FileSystemRefStore` for custom storage backends, and `readonlyRepo()` to wrap a repo so all write operations throw.
141
+ See [REPO.md](docs/REPO.md) for the full API, the `GitRepo` interface, and the hybrid worktree pattern.
195
142
 
196
143
  ## Multi-agent collaboration
197
144
 
198
- Multiple agents can work on clones of the same repository in the same process, each with full VFS isolation. The `resolveRemote` option maps remote URLs to `GitRepo` instances (any object/ref store VFS-backed, SQLite, etc.), so clone/fetch/push/pull cross VFS boundaries without any network or shared filesystem.
199
-
200
- ```ts
201
- import { Bash, InMemoryFs } from "just-bash";
202
- import { createGit, findRepo } from "just-git";
145
+ Multiple agents can clone, fetch, push, and pull across isolated in-memory filesystems within the same process via the `resolveRemote` option, without needing a network or shared filesystem. Concurrent pushes are automatically serialized with proper non-fast-forward rejection. See [CLIENT.md](docs/CLIENT.md#multi-agent-collaboration) and [`examples/multi-agent.ts`](examples/multi-agent.ts).
203
146
 
204
- // Origin repo on its own filesystem
205
- const originFs = new InMemoryFs();
206
- const setupBash = new Bash({
207
- fs: originFs,
208
- cwd: "/repo",
209
- customCommands: [
210
- createGit({ identity: { name: "Setup", email: "setup@example.com", locked: true } }),
211
- ],
212
- });
213
- await setupBash.exec("git init");
214
- await setupBash.exec("echo 'hello' > README.md");
215
- await setupBash.exec("git add . && git commit -m 'initial'");
216
-
217
- const alice = new Bash({
218
- fs: new InMemoryFs(),
219
- cwd: "/repo",
220
- customCommands: [
221
- createGit({
222
- identity: { name: "Alice", email: "alice@example.com", locked: true },
223
- resolveRemote: () => findRepo(originFs, "/repo"),
224
- }),
225
- ],
226
- });
227
-
228
- const bob = new Bash({
229
- fs: new InMemoryFs(),
230
- cwd: "/repo",
231
- customCommands: [
232
- createGit({
233
- identity: { name: "Bob", email: "bob@example.com", locked: true },
234
- resolveRemote: () => findRepo(originFs, "/repo"),
235
- }),
236
- ],
237
- });
238
-
239
- await alice.exec("git clone /origin /repo");
240
- await bob.exec("git clone /origin /repo");
241
-
242
- // Alice and Bob work independently, push to origin, fetch each other's changes
243
- ```
147
+ ## Commands
244
148
 
245
- Concurrent pushes to the same remote are automatically serialized if two agents push simultaneously, one succeeds and the other gets a proper non-fast-forward rejection, just like real git.
246
-
247
- See [`examples/multi-agent.ts`](examples/multi-agent.ts) for a full working example with a coordinator agent that merges feature branches.
248
-
249
- ## Command coverage
250
-
251
- See [CLI.md](docs/CLI.md) for full usage details.
252
-
253
- | Command | Flags / options |
254
- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
255
- | `init [<dir>]` | `--bare`, `--initial-branch` |
256
- | `clone <repo> [<dir>]` | `--bare`, `-b <branch>` |
257
- | `blame <file>` | `-L <start>,<end>`, `-l`/`--long`, `-e`/`--show-email`, `-s`/`--suppress`, `-p`/`--porcelain`, `--line-porcelain` |
258
- | `add <paths>` | `.`, `--all`/`-A`, `--update`/`-u`, `--force`/`-f`, `-n`/`--dry-run`, glob pathspecs |
259
- | `rm <paths>` | `--cached`, `-r`, `-f`, `-n`/`--dry-run`, glob pathspecs |
260
- | `mv <src> <dst>` | `-f`, `-n`/`--dry-run`, `-k` |
261
- | `commit` | `-m`, `-F <file>` / `-F -`, `--allow-empty`, `--amend`, `--no-edit`, `-a` |
262
- | `status` | `-s`/`--short`, `--porcelain`, `-b`/`--branch` |
263
- | `log` | `--oneline`, `-n`, `--all`, `--reverse`, `--decorate`, `--graph`, `--format`/`--pretty`, `-p`/`--patch`, `--stat`, `--name-status`, `--name-only`, `--shortstat`, `--numstat`, `A..B`, `A...B`, `-- <path>`, `--author=`, `--grep=`, `--since`/`--after`, `--until`/`--before` |
264
- | `show [<object>]` | Commits (with diff), annotated tags, trees, blobs |
265
- | `diff` | `--cached`/`--staged`, `<commit>`, `<commit> <commit>`, `A..B`, `A...B`, `-- <path>`, `--stat`, `--shortstat`, `--numstat`, `--name-only`, `--name-status` |
266
- | `branch` | `-d`, `-D`, `-m`, `-M`, `-r`, `-a`/`--all`, `-v`/`-vv`, `-u`/`--set-upstream-to` |
267
- | `tag [<name>] [<commit>]` | `-a -m` (annotated), `-d`, `-l <pattern>`, `-f` |
268
- | `switch` | `-c`/`-C` (create/force-create), `--detach`/`-d`, `--orphan`, `-` (previous branch), `--guess`/`--no-guess` |
269
- | `restore` | `-s`/`--source`, `-S`/`--staged`, `-W`/`--worktree`, `-S -W` (both), `--ours`/`--theirs`, pathspec globs |
270
- | `checkout` | `-b`, `-B`, `--orphan`, `--detach`/`-d`, detached HEAD, `-- <paths>`, `--ours`/`--theirs`, pathspec globs |
271
- | `reset [<commit>]` | `-- <paths>`, `--soft`, `--mixed`, `--hard`, pathspec globs |
272
- | `merge <branch>` | `--no-ff`, `--ff-only`, `--squash`, `-m`, `--abort`, `--continue`, conflict markers |
273
- | `revert <commit>` | `--abort`, `--continue`, `-n`/`--no-commit`, `--no-edit`, `-m`/`--mainline` |
274
- | `cherry-pick <commit>` | `--abort`, `--continue`, `--skip`, `-x`, `-m`/`--mainline`, `-n`/`--no-commit`, preserves original author |
275
- | `rebase <upstream>` | `--onto <newbase>`, `--abort`, `--continue`, `--skip` |
276
- | `stash` | `push`, `pop`, `apply`, `list`, `drop`, `show`, `clear`, `-m`, `-u`/`--include-untracked`, `stash@{N}` |
277
- | `remote` | `add`, `remove`/`rm`, `rename`, `set-url`, `get-url`, `-v` |
278
- | `config` | `get`, `set`, `unset`, `list`, `--list`/`-l`, `--unset` |
279
- | `fetch [<remote>] [<refspec>...]` | `--all`, `--tags`, `--prune`/`-p` |
280
- | `push [<remote>] [<refspec>...]` | `--force`/`-f`, `-u`/`--set-upstream`, `--all`, `--tags`, `--delete`/`-d` |
281
- | `pull [<remote>] [<branch>]` | `--ff-only`, `--no-ff`, `--rebase`/`-r`, `--no-rebase` |
282
- | `bisect` | `start`, `bad`/`good`/`new`/`old`, `skip`, `reset`, `log`, `replay`, `run`, `terms`, `visualize`/`view`, `--term-new`/`--term-old`, `--no-checkout`, `--first-parent` |
283
- | `clean` | `-f`, `-n`/`--dry-run`, `-d`, `-x`, `-X`, `-e`/`--exclude` |
284
- | `reflog` | `show [<ref>]`, `exists`, `-n`/`--max-count` |
285
- | `gc` | `--aggressive` |
286
- | `repack` | `-a`/`--all`, `-d`/`--delete` |
287
- | `rev-parse` | `--verify`, `--short`, `--abbrev-ref`, `--symbolic-full-name`, `--show-toplevel`, `--git-dir`, `--is-inside-work-tree`, `--is-bare-repository`, `--show-prefix`, `--show-cdup` |
288
- | `ls-files` | `-c`/`--cached`, `-m`/`--modified`, `-d`/`--deleted`, `-o`/`--others`, `-u`/`--unmerged`, `-s`/`--stage`, `--exclude-standard`, `-z`, `-t` |
149
+ 34 commands: `init`, `clone`, `fetch`, `push`, `pull`, `add`, `rm`, `mv`, `commit`, `status`, `log`, `show`, `diff`, `blame`, `branch`, `tag`, `checkout`, `switch`, `restore`, `reset`, `merge`, `rebase`, `cherry-pick`, `revert`, `stash`, `remote`, `config`, `bisect`, `clean`, `reflog`, `gc`, `repack`, `rev-parse`, `ls-files`. See [CLI.md](docs/CLI.md) for full usage details.
289
150
 
290
151
  ### Transport
291
152
 
292
- - **Local paths** -- direct filesystem transfer between repositories.
293
- - **Cross-VFS** -- clone, fetch, and push between isolated in-memory filesystems via `resolveRemote`. See [Multi-agent collaboration](#multi-agent-collaboration).
294
- - **Smart HTTP** -- clone, fetch, and push against real Git servers (e.g. GitHub) via Git Smart HTTP protocol. Auth via `credentials` option or `GIT_HTTP_BEARER_TOKEN` / `GIT_HTTP_USER` + `GIT_HTTP_PASSWORD` env vars.
153
+ - **Local paths**: direct filesystem transfer between repositories.
154
+ - **Cross-VFS**: clone, fetch, and push between isolated in-memory filesystems via `resolveRemote`. See [CLIENT.md](docs/CLIENT.md#multi-agent-collaboration).
155
+ - **Smart HTTP**: clone, fetch, and push against real Git servers (e.g. GitHub) via Git Smart HTTP protocol. Auth via `credentials` option or `GIT_HTTP_BEARER_TOKEN` / `GIT_HTTP_USER` + `GIT_HTTP_PASSWORD` env vars.
295
156
 
296
157
  ### Internals
297
158