# https://grit-scm.com/docs/index.md # Docs > How to use grit, a simple Git client built on grit-lib. Start with the tutorial, then look up any command or open the library guide. Grit is two things: - **`grit`** — a Git client with a small, modern command line. It works on any Git repository and talks to any Git remote, but its commands are its own: one obvious way to do the common thing, plain-language output, and `--json` on every command. - **`grit-lib`** — a fast, linkable Git library for Rust. Everything the CLI does goes through the library; you can embed the same engine in your own tools. ## How these docs are organized | Section | What you'll find | | --- | --- | | **Getting started** | [Install](https://grit-scm.com/docs/install/index.md) grit, follow the [tutorial](https://grit-scm.com/docs/tutorial/index.md), or try the [library quick start](https://grit-scm.com/docs/library-quickstart/index.md). | | **The grit CLI** | [Global options](https://grit-scm.com/docs/global-options/index.md), [scripting with `--json`](https://grit-scm.com/docs/scripting/index.md), [agent guide](https://grit-scm.com/docs/agents/index.md), and a man page for every command. | | **Library guide** | Rust-oriented guides for `grit-lib` (growing over time), plus the [API reference on docs.rs](https://docs.rs/grit-lib). | | **Benchmarks** | How `grit` and `grit-lib` compare to system Git on core operations. | If you're new to the command line, start with the [tutorial](https://grit-scm.com/docs/tutorial/index.md). If you're wiring Git into a Rust program, start with the [library quick start](https://grit-scm.com/docs/library-quickstart/index.md) and the [library guide overview](https://grit-scm.com/docs/library/index.md). ## CLI vs library Use **`grit`** when you want a day-to-day Git client from the terminal or in scripts (`--json` / `--filter`). Use **`grit-lib`** when you need programmatic access — opening repositories, reading objects and refs, diffing, revwalking, fetch/push, and the rest of Git's core — inside a Rust binary or service. On-disk formats and the wire protocol stay compatible with Git; the CLI's argv and messages are deliberately *not* a Git mirror. See [Install](https://grit-scm.com/docs/install/index.md) for download options, [Global options](https://grit-scm.com/docs/global-options/index.md) for flags shared by every command, [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for `--json` and `--filter`, and the [Agent guide](https://grit-scm.com/docs/agents/index.md) for automation-focused details. ## For agents - [grit-cli.md](https://grit-scm.com/docs/grit-cli.md): the whole CLI in one file, to learn grit for everyday Git work. - [grit-lib.md](https://grit-scm.com/docs/grit-lib.md): the whole library guide in one file, to build Git-compatible Rust programs. - [llms.txt](https://grit-scm.com/llms.txt): an index of every page with a one-line summary. - [llms-full.txt](https://grit-scm.com/llms-full.txt): every docs page in one file. Every page also has a Markdown twin: replace `index.html` with `index.md` in its URL. Run `grit skill` to print an agent skill for the CLI. ## Commands ### Getting started | Command | Summary | | --- | --- | | [`grit init`](https://grit-scm.com/docs/init/index.md) | Create a new, empty repository. | | [`grit clone`](https://grit-scm.com/docs/clone/index.md) | Copy a remote repository into a new directory. | | [`grit checkout`](https://grit-scm.com/docs/checkout/index.md) | Start work on a repository from a snapshot of its main branch, or of some of its paths, instead of a clone. | | [`grit status`](https://grit-scm.com/docs/status/index.md) | Show where you are and what's changed. This is what plain grit runs. | | [`grit config`](https://grit-scm.com/docs/config/index.md) | Read, set, list or remove configuration values. | ### Making changes | Command | Summary | | --- | --- | | [`grit add`](https://grit-scm.com/docs/add/index.md) | Stage changes. With no paths, stages everything. | | [`grit commit`](https://grit-scm.com/docs/commit/index.md) | Stage every change and record a new commit. | | [`grit diff`](https://grit-scm.com/docs/diff/index.md) | Show uncommitted, staged, commit, or range changes. | | [`grit restore`](https://grit-scm.com/docs/restore/index.md) | Restore working tree and/or index paths from HEAD, the index, or another revision. | | [`grit rm`](https://grit-scm.com/docs/rm/index.md) | Remove tracked paths from the working tree and index. | | [`grit mv`](https://grit-scm.com/docs/mv/index.md) | Rename or move tracked paths. | | [`grit stash`](https://grit-scm.com/docs/stash/index.md) | Save and restore shelved work. | ### History | Command | Summary | | --- | --- | | [`grit log`](https://grit-scm.com/docs/log/index.md) | Show commits, newest first: the whole history in the pager on a terminal, a page at a time for scripts and agents. | | [`grit blame`](https://grit-scm.com/docs/blame/index.md) | Show who last modified each line of a file. | | [`grit reflog`](https://grit-scm.com/docs/reflog/index.md) | Show, delete, or expire reflog entries. | | [`grit shortlog`](https://grit-scm.com/docs/shortlog/index.md) | List the commits on this branch that aren't on the target branch yet. | | [`grit revs`](https://grit-scm.com/docs/revs/index.md) | List or count commits matching revision ranges. | | [`grit show`](https://grit-scm.com/docs/show/index.md) | Show a commit, tag or branch, and the change it introduced. | | [`grit merge-base`](https://grit-scm.com/docs/merge-base/index.md) | Find common ancestors or test whether one commit is an ancestor of another. | | [`grit notes`](https://grit-scm.com/docs/notes/index.md) | List, show, add, and remove Git notes on commits. | | [`grit describe`](https://grit-scm.com/docs/describe/index.md) | Nearest reachable tag, exact commit distance, and abbreviated id for a revision. | | [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) | Replay local commits onto a new base; recover from conflicts and exec commands that leave edits. | | [`grit history`](https://grit-scm.com/docs/history/index.md) | Stateless history rewrite helpers (reword, and more over time). | ### Branches and tags | Command | Summary | | --- | --- | | [`grit branch`](https://grit-scm.com/docs/branch/index.md) | List branches, or create, delete, rename, or configure one. | | [`grit switch`](https://grit-scm.com/docs/switch/index.md) | Switch to another branch, remote branch, or detached commit. | | [`grit merge`](https://grit-scm.com/docs/merge/index.md) | Merge another branch, tag or commit into the current one. | | [`grit reset`](https://grit-scm.com/docs/reset/index.md) | Move the branch tip and optionally reset the index or worktree. | | [`grit pick`](https://grit-scm.com/docs/pick/index.md) | Cherry-pick one or more commits onto the current branch. | | [`grit revert`](https://grit-scm.com/docs/revert/index.md) | Undo commits with new inverse commits. | | [`grit tag`](https://grit-scm.com/docs/tag/index.md) | List tags, or create or delete one (lightweight or annotated). | | [`grit worktree`](https://grit-scm.com/docs/worktree/index.md) | List, add, and remove linked worktrees for the same repository. | ### Remotes | Command | Summary | | --- | --- | | [`grit remote`](https://grit-scm.com/docs/remote/index.md) | List remotes, add one, show one, set URLs, rename or remove one, or list refs on a remote. | | [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) | Download new commits, branches and tags from a remote. | | [`grit pull`](https://grit-scm.com/docs/pull/index.md) | Fetch from the remote and bring the current branch up to date. | | [`grit push`](https://grit-scm.com/docs/push/index.md) | Publish branches, tags, or explicit refspecs to a remote. | | [`grit auth`](https://grit-scm.com/docs/auth/index.md) | Sign in to GitButler Code, GitHub or a grit serve host, or save a username and token for any HTTPS host, so pushes and fetches just work. | | [`grit bundle`](https://grit-scm.com/docs/bundle/index.md) | Create, verify, list, and unbundle git bundle files for offline transfer. | | [`grit serve`](https://grit-scm.com/docs/serve/index.md) | Serve repositories over HTTP, with a web view where people sign in with email and password. | | [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) | Send a snapshot checkout's branches back to the server, rebuilt on its real history. | | [`grit integrate`](https://grit-scm.com/docs/integrate/index.md) | Merge a branch into the server's target branch, from a snapshot checkout or a clone of a hosted project. | | [`grit slice`](https://grit-scm.com/docs/slice/index.md) | Name sets of paths to check out together, kept on the server's target branch. | | [`grit sync`](https://grit-scm.com/docs/sync/index.md) | Push and pull every active branch between a clone and your space on a grit hosting server. | | [`grit share`](https://grit-scm.com/docs/share/index.md) | Work on a branch together with other users of a grit hosting server, each with their own head of it. | ### Maintenance | Command | Summary | | --- | --- | | [`grit clean`](https://grit-scm.com/docs/clean/index.md) | Remove untracked files from the working tree. | | [`grit update`](https://grit-scm.com/docs/update/index.md) | Update grit to the latest release. | | [`grit repack`](https://grit-scm.com/docs/repack/index.md) | Pack reachable objects and remove redundant packs. | | [`grit skill`](https://grit-scm.com/docs/skill/index.md) | Print an agent skill that explains how to use grit. | | [`grit completions`](https://grit-scm.com/docs/completions/index.md) | Generate shell completion scripts for bash, zsh, and fish. | | [`grit gc`](https://grit-scm.com/docs/gc/index.md) | Run repository maintenance — pack refs, expire reflogs, repack, prune, and refresh commit-graph. | | [`grit fsck`](https://grit-scm.com/docs/fsck/index.md) | Check refs, objects, and pack indexes for problems. | ### Plumbing | Command | Summary | | --- | --- | | [`grit hooks`](https://grit-scm.com/docs/hooks/index.md) | List hook scripts and run them by name. | | [`grit upload-pack`](https://grit-scm.com/docs/upload-pack/index.md) | Serve a fetch or clone of a repository over stdin and stdout. | | [`grit patch-id`](https://grit-scm.com/docs/patch-id/index.md) | Stable patch-IDs for commits (cherry-pick equivalence). | | [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md) | Accept a push to a repository over stdin and stdout. | | [`grit manager`](https://grit-scm.com/docs/manager/index.md) | A credential helper that stores passwords and tokens in the Windows Credential Manager. | | [`grit resolve`](https://grit-scm.com/docs/resolve/index.md) | Resolve revision specs to object ids and types. | | [`grit cat`](https://grit-scm.com/docs/cat/index.md) | Show blob, tree, commit, or tag contents for a revision spec. | | [`grit ignore`](https://grit-scm.com/docs/ignore/index.md) | Query whether paths match exclude (gitignore) rules. | # https://grit-scm.com/docs/install/index.md # Install grit > Install the grit CLI on your machine, try nightly builds, and keep your copy up to date. ## Stable release (recommended) On macOS and Linux: ```bash curl -fsSL https://grit-scm.com/install | sh ``` On Windows, run this in PowerShell: ```bash irm https://grit-scm.com/install.ps1 | iex ``` The script downloads the latest release from GitHub, installs the `grit` binary (by default into `~/.local/bin` on Unix), and prints the version it installed. ## Linux GNU loader compatibility Linux x86_64 releases provide two GNU assets. Both preserve PIE and ASLR: | Asset | Loader support | | --- | --- | | `grit-x86_64-unknown-linux-gnu.tar.gz` | Default and fallback; glibc 2.34 or newer, standard relocations | | `grit-x86_64-unknown-linux-gnu-relr.tar.gz` | Manual opt-in; glibc 2.36 or newer, packed relative relocations (RELR) | The stable and nightly installers always choose the existing GNU asset on glibc systems, including glibc 2.36 and newer. The RELR asset is available only as a manual download for glibc 2.36+. Its smaller relocation metadata does not consistently improve startup: final-tip review measurements found tiny commands about **1–2% slower**, despite gains at earlier revisions. Automatic selection is deferred until measurements on the release artifacts demonstrate a benefit; see [benchmarks](https://grit-scm.com/docs/install/benchmarks.md/index.md#pie-startup-relocation-probe). The default asset's weak glibc 2.39 references do not require a newer loader. GNU aarch64, static musl, macOS and Windows keep their existing artifacts and selection. Static musl artifacts and source builds remain alternatives for other systems. ## Shell completions Tab completion helps you discover `grit`'s subcommands and flags. Generate a script with [`grit completions`](https://grit-scm.com/docs/completions/index.md) and load it from your shell config, or copy the pre-generated files from a release tarball's `completions/` directory. **bash** — add to `~/.bashrc`: ```bash eval "$(grit completions bash)" ``` **zsh** — add to `~/.zshrc`: ```bash eval "$(grit completions zsh)" ``` Or install once under a site-functions directory: ```bash grit completions zsh > ~/.local/share/zsh/site-functions/_grit ``` **fish** — write a completion file: ```bash mkdir -p ~/.config/fish/completions grit completions fish > ~/.config/fish/completions/grit.fish ``` After [`grit update`](https://grit-scm.com/docs/update/index.md), regenerate completions so new commands appear. ## Nightly builds CI publishes a rolling **nightly** prerelease when the release workflow is triggered manually. To install that build instead of the latest stable release: ```bash curl -fsSL https://grit-scm.com/install-nightly | sh ``` On Windows: ```bash irm https://grit-scm.com/install-nightly.ps1 | iex ``` Nightlies track recent `main`; use them when you want to test fixes before the next tagged release. ## Install with Cargo If you already have a Rust toolchain: ```bash cargo install grit-cli ``` This builds and installs the `grit` executable into Cargo's bin directory (usually `~/.cargo/bin`). Make sure that directory is on your `PATH`. ## Keep grit up to date After a script install, run [`grit update`](https://grit-scm.com/docs/update/index.md) to re-run the same installer and replace the binary you're running. If you installed with Cargo, update with: ```bash cargo install grit-cli ``` ## Build from source Clone [the repository](https://github.com/gitbutlerapp/grit) and build the CLI crate: ```bash cargo build --release -p grit-cli ``` The binary is `target/release/grit`. You can copy it anywhere on your `PATH`, or run it from the build tree. ### Toolchain **Contributors** building this repository: the workspace pins **1.99.0** in [`rust-toolchain.toml`](https://github.com/gitbutlerapp/grit/blob/main/rust-toolchain.toml) (with `rustfmt` and `clippy`). `rustup` picks that up automatically when you build in the repo. **Library and CLI consumers** (your own crate depending on `grit-lib` or `grit-cli` from [crates.io](https://crates.io/crates/grit-lib), without this repo's `rust-toolchain.toml`): the published crates require **Rust 1.95** or newer. Cargo prints that requirement before compiling if your toolchain is too old. To use `grit-lib` in your own project, see the [library quick start](https://grit-scm.com/docs/library-quickstart/index.md). # https://grit-scm.com/docs/tutorial/index.md # Tutorial > Fifteen minutes with grit. Create a repository, record some changes, work on a branch, and share it with a remote. This walkthrough covers the commands you'll use every day. It assumes you have [installed grit](https://grit-scm.com/docs/install/index.md) and know roughly what a commit and a branch are. The output shown is what `grit` prints, minus the colors. Regenerated on 2026-10-07 by running the listed commands with `grit` built from this repository (`cargo build --release -p grit-cli`), with `NO_COLOR=1` and author identity `Ada Lovelace `. ## Tell grit who you are Every commit records an author. Set your name and email once, in your global config: ```console $ grit config --global user.name "Ada Lovelace" $ grit config --global user.email ada@example.com ``` `grit` reads and writes the same config files as Git, so if you've already set these up for Git, you can skip this step. ## Create a repository ```console $ grit init project Initialized empty repository in /workspace/project/.git $ cd project ``` To work on an existing project instead, copy it with [`grit clone`](https://grit-scm.com/docs/clone/index.md) and skip ahead to the next section: ```console $ grit clone https://github.com/gitbutlerapp/grit.git ``` ## Your home base: grit status Running `grit` with no arguments shows where you are and what's changed. Add a couple of files and look: ```console $ echo "# Notes" > README.md $ echo "fn main() {}" > main.rs $ grit On main — no commits yet Untracked ? untracked README.md ? untracked main.rs → grit add to stage ``` The last line always suggests the next step. You'll come back to this screen a lot; [`grit status`](https://grit-scm.com/docs/status/index.md) (or `grit st`) shows the same thing. ## Record a commit [`grit commit`](https://grit-scm.com/docs/commit/index.md) stages every change in the working tree and records it in one step: ```console $ grit commit "Start the project" [main 310fdb0] Start the project 2 changes committed ``` By default `grit commit` records every change in one step. When you need tighter control, use [`grit add`](https://grit-scm.com/docs/add/index.md) (`--dry-run`, `-u`, or path lists) and [`grit commit --staged`](https://grit-scm.com/docs/commit/index.md) or `grit commit -m "…" -- ` to commit only part of the work while leaving other staged edits in the index. Each grit commit also gets a stable [change id](https://grit-scm.com/docs/change-ids/index.md) that stays with the same logical change when you amend or rewrite history; `grit log` shows a short `change …` prefix beside each commit. Look at the history with [`grit log`](https://grit-scm.com/docs/log/index.md): ```console $ grit log 310fdb0 ada just now Start the project ``` ## Work on a branch Create a branch and switch to it with [`grit switch -c`](https://grit-scm.com/docs/switch/index.md): ```console $ grit switch -c feature Created and switched to branch feature ``` Make a change and look at it with [`grit diff`](https://grit-scm.com/docs/diff/index.md) before committing: ```console $ printf 'fn main() {\n println!("hi");\n}\n' > main.rs $ grit diff main.rs @@ -1 +1 @@ 1 │ - fn main() {} 1 │ + fn main() { 2 │ + println!("hi"); 3 │ + } ``` The two number columns are the old and new line numbers. Commit the change: ```console $ grit commit "Say hi" [feature 2e409e2] Say hi 1 change committed ``` [`grit show`](https://grit-scm.com/docs/show/index.md) displays a commit, its message and the files it changed. With no argument, it shows the latest commit: ```console $ grit show branch feature commit 2e409e26f8b370ea1928a8fb93dcf2e025418e1f Author: Ada Lovelace Date: 2026-10-07 14:55:47 +0000 Say hi main.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) ``` ## Merge it back Switch back to `main` and [merge](https://grit-scm.com/docs/merge/index.md) the branch in. Nothing else has happened on `main`, so `grit` just moves `main` forward: ```console $ grit switch main Switched to branch main $ grit merge feature Fast-forwarded feature → 2e409e2 ``` The branch is done, so [delete it](https://grit-scm.com/docs/branch/index.md): ```console $ grit branch -d feature Deleted branch feature (was 2e409e2). ``` `grit branch -d` refuses to delete a branch whose commits haven't been merged into the branch you're on. Use `--force-delete` (or `-D`) when you really mean it. ## Share it with a remote A remote is another copy of the repository, usually on a server. Add one called `origin` with [`grit remote add`](https://grit-scm.com/docs/remote/index.md), then [push](https://grit-scm.com/docs/push/index.md): ```console $ grit remote add origin https://github.com/ada/project.git Added remote origin → https://github.com/ada/project.git $ grit push pushed main → origin refs/heads/main ``` `grit push` sends the current branch to a branch with the same name on `origin`, creating it if needed. To publish under another name, pass a refspec: `grit push origin HEAD:refs/heads/experiment`. Set upstream tracking with [`grit branch -u`](https://grit-scm.com/docs/branch/index.md) when you want `grit pull` to know which remote branch to follow. For GitHub over HTTPS, [`grit auth`](https://grit-scm.com/docs/auth/index.md) signs you in, and `grit` offers to run it if a push fails for lack of credentials. To download updates without moving your branch, [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) is enough. Fetch a single branch when you do not need every remote-tracking ref: ```console $ grit fetch origin main refs/remotes/origin/main ← refs/heads/main a8e620a → b52cca6 Fetched 1 update from origin. ``` To get other people's work into your branch, run [`grit pull`](https://grit-scm.com/docs/pull/index.md). It fetches and integrates: fast-forward when you have no local commits, a merge commit when both sides moved, or a rebase when you pass `--rebase` (or set `pull.rebase`): ```console $ grit pull Merged origin/main into the current branch (91275a2) $ grit pull --rebase Rebased onto origin/main (c4f1a9b) ``` Use [`grit pull --ff-only`](https://grit-scm.com/docs/pull/index.md) in scripts that must refuse merge commits (exit **128** with `refused_not_ff` when histories diverged). If someone pushed before you, a normal `grit push` is rejected: ```console $ grit push rejected origin refs/heads/main: not a fast-forward — run `grit pull` first ``` To replay your own commits onto another base without fetching first, use [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) (default upstream is `@{upstream}`; `--onto` for Git's `--onto`). After rewriting commits with [`grit history`](https://grit-scm.com/docs/history/index.md) (reword, drop, fixup, squash, or rebase), fetch so your remote-tracking refs are current, then push with a lease. A plain `grit push` after a rewrite is rejected with a hint to use `--force-with-lease` (or pull first): ```console $ grit fetch origin $ grit push --force-with-lease pushed main → origin refs/heads/main ``` ## Tag a release [`grit tag`](https://grit-scm.com/docs/tag/index.md) marks the current commit, and `grit push --tags` publishes your tags. Signed or `tree-sha256` annotated tags can be checked locally with `grit tag --verify`: ```console $ grit tag v0.1 -m 'release' Created tag v0.1 $ grit tag --verify v0.1 --no-signature tag v0.1 (…): ok $ grit push --tags pushed --tags → origin refs/tags/v0.1 ``` ## When things conflict When `grit merge`, `grit pull`, or `grit pick` hits conflicting changes, grit stops with conflict markers in the worktree and records in-progress state (for pick/revert, Git-compatible `CHERRY_PICK_HEAD` and `.git/sequencer/`). Fix the files, `grit add` the resolved paths, then run `grit merge` with a normal commit for merges, or `grit pick --continue` / `grit revert --continue` for cherry-picks and reverts. Use `--abort` on the same command to cancel. `grit` refuses to switch branches, merge, or pull when your local edits would be overwritten by files that differ on the other side. Unrelated uncommitted edits are kept, like Git. Use [`grit reset --soft HEAD~1`](https://grit-scm.com/docs/reset/index.md) to uncommit while keeping changes staged. ## Offline bundles and linked worktrees To move commits without a network, [`grit bundle create`](https://grit-scm.com/docs/bundle/index.md) writes a single file; [`grit bundle unbundle`](https://grit-scm.com/docs/bundle/index.md) ingests it into another repository. For a second checkout of the same repository, [`grit worktree add`](https://grit-scm.com/docs/worktree/index.md) creates a linked working tree; [`grit worktree lock`](https://grit-scm.com/docs/worktree/index.md) marks one as locked when you need to prevent accidental removal. ## Scripting Every command takes `--json` and prints a single JSON object, which is handy for scripts and agents. `--filter` picks out the part you need: ```console $ grit status --json --filter '{branch, clean}' { "branch": "main", "clean": true } ``` See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for details, and each command's page for its JSON fields. ## Where to go next Every command has a man page with its options and examples. Start from the [command list](https://grit-scm.com/docs/index.md#commands). # https://grit-scm.com/docs/change-ids/index.md # Change ids > Stable change identifiers on commits, Git interop, and revision selection. Every commit [`grit commit`](https://grit-scm.com/docs/commit/index.md) creates can carry a **`change-id`** header: an opaque token that names the same logical change across rewrites (amend, [`grit history`](https://grit-scm.com/docs/history/index.md) edits, and future rebases). Commits that never received the header still have a **derived** id (Jujutsu-compatible) computed from the commit object id. Grit never rewrites a commit solely to add a header. ## Header format - On disk: a normal commit header line `change-id ` (before any `gpgsig` block). - Legacy name: `gitbutler-change-id ` is still read for compatibility; new writes use `change-id` only. - Random ids use **reverse-hex**: 16 bytes encoded as 32 characters in the alphabet `k`–`z` (each nibble `n` maps to `'z' - n`). System **`git`** treats the line like any other commit header: it round-trips through clone and fetch, survives `git cat-file -p`, and passes `git fsck --strict`. Git’s `%(trailers)` pretty-format does not surface `change-id` (it is not a Git trailer), so use `cat-file` or grit’s JSON when you need the stored value. ## Interop with Jujutsu, GitButler, and Gerrit | Tool | How it relates | | --- | --- | | **Jujutsu (`jj`)** | Derives a change id from the commit id with the same algorithm grit uses when no header is present. After grit stores a derived id on rewrite, jj and grit agree on the logical change. | | **GitButler** | Historically wrote `gitbutler-change-id`; grit reads that name and writes `change-id` on new commits. Stacks and virtual branches can key off the same string grit shows in `log` and `--json`. | | **Gerrit** | Uses `Change-Id` in the commit message for review matching. Grit’s header is separate (object header, not message footer). Repos imported from Gerrit keep their message trailers; grit adds its own header only on commits it creates. | ## Configuration | Key | Default | Effect | | --- | --- | --- | | [`grit.changeIds`](https://grit-scm.com/docs/config/index.md) | `true` | When `false`, new commits omit the header (byte-identical with plain Git). Existing headers are preserved; history rewrites still copy them but do not invent derived ids. | | `grit.testing.changeId` | unset | Test-only: `content-hash` makes ids deterministic; any other non-empty value is used verbatim. | Disable headers when an importer rejects extra commit lines: ```console $ grit config grit.changeIds false ``` ## Display and JSON **Human [`grit log`](https://grit-scm.com/docs/log/index.md)** (default format) shows the short commit id, then `change` and the first eight reverse-hex characters of the stable id, then author, date, and subject. [`--oneline`](https://grit-scm.com/docs/log/index.md) omits the change column. **[`--json`](https://grit-scm.com/docs/commands/README.md/index.md#commit-json-object-commitjson)** on [`log`](https://grit-scm.com/docs/log/index.md), [`show`](https://grit-scm.com/docs/show/index.md), [`revs`](https://grit-scm.com/docs/revs/index.md), and [`status`](https://grit-scm.com/docs/status/index.md) includes: | Field | Meaning | | --- | --- | | `change_id` | Stable id (stored header or derived from `oid`). | | `change_id_stored` | `true` when `change_id` came from a `change-id` / `gitbutler-change-id` header in the object. | Mutation commands ([`commit`](https://grit-scm.com/docs/commit/index.md), [`pick`](https://grit-scm.com/docs/pick/index.md), [`revert`](https://grit-scm.com/docs/revert/index.md), [`merge`](https://grit-scm.com/docs/merge/index.md), [`pull`](https://grit-scm.com/docs/pull/index.md), [`history`](https://grit-scm.com/docs/history/index.md)) report `change_id` on the commits they create. [`grit commit --json`](https://grit-scm.com/docs/commit/index.md) sets `change_id` to the stored header value or JSON `null` when the header is absent (for example with `grit.changeIds=false`). ## Which commits get ids - **New ids:** ordinary commits, the initial commit, merge conclusions, pick, revert, and commits inserted during a history rewrite. - **Same id kept:** amend, history reword/fixup/squash/drop/replay when the logical change survives. - **Derived id stored on rewrite:** headerless commits (for example from plain `git commit`) receive a stored `change-id` equal to the derived value the first time grit rewrites them. Pick and revert always allocate a **new** id; they never copy the source commit’s id. ## Revisions After refs and abbreviated object ids, grit accepts **change ids** as revision tokens: - **Alphabet:** reverse-hex tokens use `k`–`z`, length 4–32. Such tokens are resolved as change-id prefixes, not Git object ids. - **Lookup:** grit walks commits reachable from refs and `HEAD`, matches [`resolved_change_id`](https://docs.rs/grit-lib/latest/grit_lib/change_id/fn.resolved_change_id.html) (stored or derived), and requires a unique prefix. - **Composition:** suffixes work as usual — `\~1`, `\^`, ranges, peel operators, and `:path` forms compose on the resolved commit. - **Precedence:** a branch or tag with the same name wins over a change-id token. Examples: ```console $ grit show krrtwksq --json $ grit log yrwyvtvk -n 1 --json $ grit history reword krrtwksq -m "new subject" ``` Ambiguous prefixes fail with a list of candidate commits (same as ambiguous short oids). ## Library API For embedders, see the [library guide on change ids](https://grit-scm.com/docs/library/change-ids/index.md) (`ChangeId`, `ChangeIdPolicy`, header helpers, and lookup). # https://grit-scm.com/docs/library-quickstart/index.md # Library quick start > Add grit-lib to a Rust project, open a repository, and read the current commit from HEAD. This page walks through a minimal program that discovers a Git repository in the current directory (or a parent), resolves `HEAD`, and prints the commit id and subject line. The source below is the real example binary in the Grit repository; it is included automatically so the docs cannot drift from compiled code. ## Add the dependency In your crate: ```bash cargo add grit-lib ``` Or add to `Cargo.toml`: ```toml [dependencies] grit-lib = "0.5.0" ``` Use the [latest version on crates.io](https://crates.io/crates/grit-lib) if the number above is stale. `grit-lib` requires **Rust 1.95** or newer (`rust-version` in the crate manifest). That applies when you add the dependency from crates.io or a path outside the Grit workspace. Building inside the Grit repository uses the contributor toolchain pin in [`rust-toolchain.toml`](https://github.com/gitbutlerapp/grit/blob/main/rust-toolchain.toml) (currently **1.99.0**), which does not propagate to downstream crates. ## Example program Save as `src/main.rs` (or copy from `grit-examples` in the Grit repo): ```rust //! Minimal grit-lib program: discover a repository and print HEAD's commit id. //! //! Source for the library quick start in the docs; kept in sync via an include directive. use grit_lib::config::environment::RepositoryOptions; use grit_lib::refs::store::RefName; use grit_lib::repo::Repository; fn main() -> Result<(), Box> { let repo = Repository::discover(None, &RepositoryOptions::from_process())?; let head_name = RefName::try_from("HEAD")?; let head = repo.references().resolve(&head_name)?; let commit = repo.objects().read_commit(&head)?; println!("{head}"); let subject = commit.message.lines().next().unwrap_or(""); if !subject.is_empty() { println!("{subject}"); } Ok(()) } ``` ## Run it From the root of any Git repository with at least one commit: ```bash cargo run ``` Example output (your commit id will differ): ```text 217c6f9a1b2c3d4e5f6789012345678901234567 Start the project ``` The first line is the full object id of `HEAD`; the second is the first line of the commit message. ## The environment The program opens the repository with [`RepositoryOptions::from_process`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.from_process), which snapshots the process environment (`HOME`, `GIT_*`, Windows `ProgramFiles`) so system and global config apply exactly as they do for `git` and `grit`: `core.autocrlf`, `user.name` and `user.email`, `safe.directory`, `core.excludesFile` and credential helpers. The library itself never reads the process environment. [`RepositoryOptions::empty`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.empty) is the hermetic alternative for tests: no home directory and no global config. See [Embedding grit-lib](https://grit-scm.com/docs/library/embedding/index.md#matching-git-and-grit-on-user-repositories). ## Next steps - [Library guide overview](https://grit-scm.com/docs/library/index.md) — longer-form guides for objects, refs, diff, and network code. - [grit-lib on docs.rs](https://docs.rs/grit-lib) — API reference for `Repository` and the rest of the public surface. - [Tutorial](https://grit-scm.com/docs/tutorial/index.md) — the same repository operations from the `grit` CLI. # https://grit-scm.com/docs/global-options/index.md # Global options > Options that apply to every grit command. These options work on any command (and on `grit` itself when you pass no subcommand). | Option | Description | | --- | --- | | `--json` | Print one JSON object instead of human-readable text. Errors become `{"error": "..."}`. | | `--markdown` | Print agent-friendly Markdown instead of human-readable text. Most commands render structured headings, lists, and tables (or fenced diffs) rather than dumping JSON. Mutually exclusive with `--json`. | | `--filter ` | Apply a jq expression to the JSON output. Requires `--json`. Iterator-style filters always emit a JSON array; singular filters emit one value (`null` when absent). | | `--threads ` | Worker threads for parallel library work inside this process. `0` selects all logical CPUs (Git-style auto); `1` forces serial paths. Does not change human, `--json`, or `--markdown` output shape. | | `--no-optional-locks` | Skip opportunistic index updates that take optional locks (same as `GIT_OPTIONAL_LOCKS=0`). Stat refresh still runs in memory; `.git/index` is left untouched. | | `-h`, `--help` | Print help for `grit` or for a command. | | `-v`, `--version` | Print the version of `grit`. `-V` works too. | Running `grit` with no command is the same as [`grit status`](https://grit-scm.com/docs/status/index.md). ## Repository and config options These go **before** the command name (`grit -C repo status`, not `grit status -C repo`), as in Git, so they never collide with a command's own short flags. | Option | Description | | --- | --- | | `-C ` | Run as if `grit` was started in ``. Repeatable: each one is relative to the previous (`-C a -C b` is `a/b`). An empty `` (`-C ""`) changes nothing. A directory that does not exist fails with exit `1`. | | `-c ` | Set a config value for this invocation only, without touching any config file. Repeatable; a later `-c` wins over an earlier one, over `GIT_CONFIG_COUNT` pairs and over every config file. A bare `` with no `=` means `true`, and `=` sets the empty string. An invalid key is a usage error (exit `2`). | | `--git-dir ` | Use this repository directory instead of discovering one. Same as `GIT_DIR`. Without `--work-tree`, the current directory is the work tree (unless the repository is bare or sets `core.worktree`). | | `--work-tree ` | Use this directory as the top of the work tree. Same as `GIT_WORK_TREE`. | `-C` is applied first, so a relative `--git-dir` or `--work-tree` is resolved from the new directory. The overrides are exported to everything `grit` starts, using the same `GIT_DIR`, `GIT_WORK_TREE` and `GIT_CONFIG_PARAMETERS` encoding Git uses, so hooks that run `git` see the same repository and config. ```console $ grit -C services/api status --json --filter .branch "main" $ grit -c user.name="CI Bot" -c user.email=ci@example.com commit -m "Update lockfile" [main 3f9c2ab] Update lockfile 1 change committed $ grit --git-dir /srv/site.git --work-tree /var/www/site status ``` On Unix, the final working directory after all `-C` options, and the paths supplied to `--git-dir` and `--work-tree`, must be valid UTF-8. Unsupported repository selections are rejected before discovery or command execution with exit **2**, so a raw-byte name cannot select a similarly named Unicode repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout; `--markdown` writes `**Error:**` on stdout. Traversing a non-UTF-8 directory with `-C` is supported when a subsequent `-C` returns to a UTF-8 working directory. Library embedders get the same behavior from [`Environment::with_git_dir`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html), [`Environment::with_work_tree`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) and [`Environment::push_config_override`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.Environment.html) with a parsed [`ConfigOverride`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.ConfigOverride.html). ## Environment variables The `grit` CLI snapshots the process environment into [`Environment`](https://grit-scm.com/docs/library/repository/index.md) when opening a repository. Library embedders should construct an [`Environment`](https://grit-scm.com/docs/library/repository/index.md) explicitly instead of relying on these variables. | Variable | Effect | | --- | --- | | `GIT_DIR`, `GIT_WORK_TREE`, `GIT_CEILING_DIRECTORIES`, `GIT_PREFIX` | Repository discovery | | `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`, `GIT_ALTERNATE_OBJECT_DIRECTORIES` | Index and object store paths. With `GIT_OBJECT_DIRECTORY` set, commands that open the repository (including `fetch`, `pull` and `push`) read and write objects there instead of `.git/objects`, which stays visible only when listed in `GIT_ALTERNATE_OBJECT_DIRECTORIES`. The directory must exist; an empty value is an error, as in Git | | `GIT_CONFIG`, `GIT_CONFIG_GLOBAL`, `GIT_CONFIG_SYSTEM`, `GIT_CONFIG_NOSYSTEM`, `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_n`, `GIT_CONFIG_VALUE_n`, `GIT_CONFIG_PARAMETERS` | Config cascade | | `HOME`, `XDG_CONFIG_HOME`, `USERPROFILE`, `USER`, `USERNAME` | Home and identity fallbacks | | `GIT_AUTHOR_*`, `GIT_COMMITTER_*` | Author/committer name, email, and date overrides for new objects | | `GIT_SSH`, `GIT_SSH_COMMAND` | SSH transport command (`GIT_SSH_COMMAND` overrides `core.sshCommand` and `GIT_SSH`; see Git precedence) | | `GIT_HTTP_LOW_SPEED_LIMIT`, `GIT_HTTP_LOW_SPEED_TIME` | HTTP low-speed abort thresholds (override `http.lowSpeedLimit` / `http.lowSpeedTime` from config) | | `http.timeout`, `http.lowSpeedLimit`, `http.lowSpeedTime` | Smart HTTP read timeouts in config (see [`fetch`](https://grit-scm.com/docs/fetch/index.md)): `http.timeout` caps the whole transfer (default 600s); low-speed settings abort when throughput stays below the limit for the configured window. Fetch and clone poll cancellation during these waits, not only between read chunks | | `GIT_NOTES_REF`, `GIT_NOTES_DISPLAY_REF` | Notes ref selection | | `GIT_ATTR_SOURCE` | Tree to read `.gitattributes` from | | `GIT_NAMESPACE`, `GIT_REPLACE_REF_BASE`, `GIT_NO_REPLACE_OBJECTS` | Ref namespaces and replace refs | | `GIT_OPTIONAL_LOCKS` | When set to `0`, `false`, `no`, or `off`, grit skips optional index writes during read-mostly commands such as `status` (same as `--no-optional-locks`). Unset means optional locks are allowed. | | `GRIT_TRACE` | Grit operation spans to stderr (`1` / `true` / `yes`), or appended to a file when set to an absolute path; see [Debugging and tracing](https://grit-scm.com/docs/debugging/index.md) | | `PATH` | Helper lookup (e.g. signing programs) | | `TZ` | Local timezone for dates when no explicit offset is given | | `GIT_EXEC_PATH`, `GIT_INSTALL_ROOT` | Git helper discovery (credentials) | Grit does not read `GIT_TEST_*` variables from Git's test suite. Use repository config instead (`pack.writeReverseIndex`, `index.version`, …), [`InitOptions::with_init_filesystem`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.InitOptions.html#method.with_init_filesystem) with [`PrecomposeDetection::Always`](https://docs.rs/grit-lib/latest/grit_lib/config/init_filesystem/enum.PrecomposeDetection.html#variant.Always) for NFD/NFC init probes, and [`RepositoryOptions::with_reftable_write`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_reftable_write) to disable reftable auto-compaction in tests. For `safe.directory` behavior in tests, implement [`OwnershipCheck`](https://docs.rs/grit-lib/latest/grit_lib/ownership_check/trait.OwnershipCheck.html) and pass it through [`RepositoryOptions::with_ownership_check`](https://docs.rs/grit-lib/latest/grit_lib/config/environment/struct.RepositoryOptions.html#method.with_ownership_check) (keep `GIT_TEST_ASSUME_DIFFERENT_OWNER` only when invoking the system `git` binary for cross-checks). `GIT_INDEX_VERSION` and `GIT_PRINT_SHA1_ELLIPSIS` are also ignored. # https://grit-scm.com/docs/debugging/index.md # Debugging and tracing > Environment knobs for diagnosing grit behavior without changing CLI flags. ## Operation tracing (`GRIT_TRACE`) Set **`GRIT_TRACE=1`** to print coarse **operation spans** from `grit-lib` to **stderr** while a command runs. Each line shows when a span opens and closes, with elapsed time on close. Spans cover repository open, config load, index read/write, status, revwalk setup, diffs, checkout, pack I/O, fetch negotiation, and push — not per-object work. This is intended for local debugging and factory performance work. There is **no `--trace` flag**; only the environment variable is supported. ```console $ GRIT_TRACE=1 grit status grit.repository.open: new grit.config.load: new grit.config.load: close time.busy=147µs time.idle=4.82µs grit.repository.open: close time.busy=297µs time.idle=26.2µs grit.status.scan: new grit.index.read: new grit.status.scan: close time.busy=18.3ms time.idle=3.13µs … ``` Set **`GRIT_TRACE`** to an **absolute path** instead to append the same tree to that file, like `GIT_TRACE2_PERF`. That keeps the trace when stderr is discarded or captured; the daily benchmark uses it to record where grit's time goes. ```console $ GRIT_TRACE=/tmp/grit-trace.txt grit push > /dev/null 2>&1 ``` Filter noise with the usual **`RUST_LOG`** / tracing env filter (for example `RUST_LOG=info`). Library embedders can enable the same spans by building `grit-lib` with the Cargo feature **`tracing`**, installing any `tracing` subscriber, and calling the same code paths. `grit-lib` does not install a global subscriber. ## Network trace (existing) Network fetch/push tracing still uses repository options and **`GRIT_NET_DEBUG`** (see the [network library guide](https://grit-scm.com/docs/library/network/index.md)). That path is separate from `GRIT_TRACE` operation spans. # https://grit-scm.com/docs/scripting/index.md # Scripting with grit > Use --json and --filter to build scripts on top of grit. With `--json`, a command prints exactly one JSON value on stdout, so you can pipe it straight into other tools. The shape of each command's outcome is documented on its command page and in the committed v1 JSON Schemas under [`/schemas/`](https://grit-scm.com/docs/schemas/index.md). Shared flag rules (`-n` as limit, long-only `--dry-run` on mutations, message and pathspec groups) are documented in [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md). `--filter` runs a [jq](https://jqlang.org) expression over that value without needing `jq` installed. Iterator-style filters — path `[]`, comma, `select`, and similar — always come back as a JSON array (`[]`, one element, or many). Singular filters such as `.branch` or `{branch, clean}` still emit one value; a missing field is `null`: ```console $ grit status --json --filter '{branch, clean}' { "branch": "main", "clean": true } $ grit log --json --filter '.commits[].subject' [ "Say hi", "Start the project" ] ``` ## JSON contract | Topic | Rule | | --- | --- | | **Success stdout** | Exactly one JSON value: the command outcome object. | | **Failure stdout** | One object `{"error": "…"}` (see [error schema](https://grit-scm.com/docs/scripting/schemas/error/v1.json/index.md)). Some failures add structured fields such as `kind`; parsers should accept unknown keys. | | **stderr** | Progress, auth hints, and human `error:` lines. Scripts should parse **stdout only** for the outcome when `--json` is set. | | **`--filter`** | Requires `--json`. Runs jq-like logic on the outcome. Iterator filters always emit a JSON array; singular filters emit one value (`null` if absent). | | **Exit codes** | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). `0` success, `1` command failure, `2` usage (including bad `--hunks` ids and `diff --exit-code` errors), `128`/`129` for cases in the table. With `--json`, usage and most failures still print `{"error":"…"}` on stdout. | Pass `--json` on every command you script. Plumbing commands ([`grit manager`](https://grit-scm.com/docs/manager/index.md), [`grit upload-pack`](https://grit-scm.com/docs/upload-pack/index.md), [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md)) speak wire protocols instead of JSON. ## Markdown output (`--markdown`) For agents and tools that prefer readable text, pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) instead of `--json`. The same field contract applies: each command page links the v1 JSON Schema in **both** the JSON output and Markdown output sections so parsers know the stable keys even when stdout is Markdown. Grit renders `--markdown` with these conventions (shared across commands): - **Headings** — `##` sections group related output (for example “Staged changes”, “Untracked”). - **Lists** — bullet lines for commits, paths, and simple enumerations; inline `` `short-oid` `` for object ids where helpful. - **Tables** — pipe-separated rows for tabular data. Cell text escapes `\|`, `\n`, and `\r` so pipes inside branch names or paths do not break the table. - **Fenced diffs** — unified patches use a `diff` code fence. If the patch body contains triple backticks, the opening and closing fence markers lengthen (four or more backticks) so the fence never terminates early. `--markdown` and `--json` are mutually exclusive; `--filter` applies only with `--json`. Color is used only when stdout is a terminal. Set `NO_COLOR` to turn it off. For autonomous agents — non-interactive auth, where to find `llms.txt`, credentials, and the full automation contract — see the [Agent guide](https://grit-scm.com/docs/agents/index.md). # https://grit-scm.com/docs/cli-conventions/index.md # CLI conventions > Shared rules for grit command paths, limits, dry-run, messages, pathspecs, and force flags — enforced by the cli_contract tests in grit-cli. Grit's CLI is intentionally small, but the flags that appear on many commands follow one contract. The `grit-cli` crate encodes that contract in `cli_contract.rs`: every **leaf command path** in the clap tree is classified, and tests fail when a new command is added without a classification or when a rule is broken without a tracked exception. This page states the rules in grit's own words. It does **not** change runtime behavior; later roadmap steps align commands that still have exceptions. ## Command kinds Each leaf path (for example `stash.list`, `gc.repack`, or top-level `commit`) has exactly one kind: | Kind | Meaning | | --- | --- | | **List** | Prints a bounded collection. Must expose `-n` as a **limit** (see below). | | **Mutation** | Changes refs, the index, the working tree, config, or remote state. Must expose long-only `--dry-run` to preview, except where noted. | | **Query** | Read-only inspection (diff, show, status, fsck, …). | | **Plumbing** | Wire protocols or credential plumbing (`upload-pack`, `receive-pack`, `manager`). | | **Generator** | Emits shell completion scripts or the agent skill (`completions`, `skill`). | Parent commands that run without a subcommand (for example bare `grit stash` for push, `grit remote` for list) are separate leaf paths alongside explicit subcommands such as `stash.push`. ## Limit (`-n`) On **every** command, `-n` always means **limit** — never “dry-run” or anything else. **List** commands must also expose that limit flag (see below). - The short flag is `-n`. - The long name is `--limit`, or `--max-count` when `--limit` is registered as a long alias (as on [`grit log`](https://grit-scm.com/docs/log/index.md) and [`grit revs`](https://grit-scm.com/docs/revs/index.md) today). - No other argument on the same command may use `-n` for a different meaning. ## Dry-run (`--dry-run`) On **mutation** commands, preview mode is long-only **`--dry-run`** (no `-n` shortcut). Mutations that support partial selection (`add`, `restore`, `commit` with hunks, …) use `--dry-run` the same way. If you pass unknown `-n` on **`add`**, **`rm`**, **`mv`**, **`clean`**, or **`push`**, grit prints a usage hint pointing at **`--dry-run`** instead of clap’s misleading “pass `-n` as a value” tip. **`grit clean`** is a mutation with different defaults: without `-f` / `--force`, it only prints what would be removed. Passing **`--force`** performs the deletion. That is the documented special case instead of an exception entry. ## Message input (`-m`, `-F`) Commands classified with **takes message** accept: - `-m` / `--message` for inline text, and - `-F` / `--message-file` for a file path (`-` reads stdin), with the two flags mutually exclusive. [`grit merge`](https://grit-scm.com/docs/merge/index.md) uses the shared message group for merge commits; history subcommands such as [`grit history reword`](https://grit-scm.com/docs/history/index.md) follow the same pattern where a message is optional or required per subcommand. ## Pathspecs (`--` paths) Commands classified with **takes paths** accept: - trailing `-- ` arguments, plus - `--pathspec-from-file` and `--pathspec-file-nul` (Git-compatible path lists), shared via the same Rust argument group in the CLI. [`grit status`](https://grit-scm.com/docs/status/index.md), [`grit log`](https://grit-scm.com/docs/log/index.md), [`grit revs`](https://grit-scm.com/docs/revs/index.md), [`grit diff`](https://grit-scm.com/docs/diff/index.md), and [`grit show`](https://grit-scm.com/docs/show/index.md) use that group. ## Force (`-f`) Every **`--force`** flag exposes short **`-f`**, unless the command page and `EXCEPTIONS` in `cli_contract.rs` document a deliberate deviation. ## Enforcement and exceptions Two tests guard the contract: - `cli_contract_conventions` — every leaf path is classified; clap flags match the rules unless listed in `EXCEPTIONS`. - `cli_contract_exceptions_are_live` — each exception still describes a real violation; remove the row when the command is fixed. Exception rows name an **owner** (a later plan step such as `s4 limit`, `s5 dry-run`, or a roadmap bucket like `workspace-extras`). When you fix a violation, delete its exception and rely on the convention test. Adding a command requires a new row in `COMMAND_CONTRACTS` inside `grit-cli/src/cli_contract.rs`. CI fails with a message that names the path and the rule if you omit it. ## Three layers Each `grit` command is split into three layers. Later roadmap steps move command logic into this shape; the render layer landed first. | Layer | Location (today) | Responsibility | | --- | --- | --- | | **Parse** | `grit-cli/src/main.rs` (per-command args land in step 2) | Clap parsing, global flags, revision/pathspec helpers. Produces plain Rust input structs — no I/O. | | **Outcome** | Command modules under `grit-cli/src/commands/` and small `*_args.rs` helpers | Open `grit_lib::repo::Repository` handles, call library APIs, map errors. Returns a typed **outcome** (structs with `Serialize` for `--json`). | | **Render** | `grit-cli/src/render/` | Turn outcomes into human text, Markdown, or filtered JSON. **No** `Repository`, `context`, or `commands::` imports (see `render_layer_is_repository_free` in `grit-cli`). | **JSON DTO rule:** serde shapes on outcomes stay in the CLI. They are `From<&LibOutcome>` field mappings (or thin wrappers), not new public `grit-lib` types. The committed v1 JSON schemas remain the contract. `make cli-layer-ratchet-check` tracks line counts for `render/`, `args/`, `dispatch` (`main.rs`), and the rest of `grit-cli/src`. Non-render layers may not grow without updating `grit-cli/layer-ratchet.toml`. ## See also - [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) — `--json`, exit codes, and stdout discipline. - [Agent guide](https://grit-scm.com/docs/agents/index.md) — non-interactive use and schema links. - [Global options](https://grit-scm.com/docs/global-options/index.md) — `--json`, `--markdown`, `--filter`, `--threads`, and the repository options `-C`, `-c`, `--git-dir`, `--work-tree`. # https://grit-scm.com/docs/exit-codes/index.md # Exit codes > Process exit status for grit commands and structured JSON error kinds. Grit uses a small set of exit codes. Command-specific yes/no checks (for example `grit diff --exit-code`) reuse **failure** (1) when the answer is “no”. See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) and the [Agent guide](https://grit-scm.com/docs/agents/index.md) for `--json` behavior. ## Exit status | Slug | Code | Meaning | | --- | ---: | --- | | `success` | 0 | Command completed successfully (including some checks that answer “yes”). | | `failure` | 1 | Command failed, or a yes/no check answered “no” (`diff --exit-code`, `merge --check`, `pick --check`, `revert --check`, `pull --check`, `merge-base --is-ancestor`, `fsck`, `ignore check`, `tag --verify`, conflicts after `merge` / `pick` / `revert` / `rebase`, rejected `push`, and similar). With `--json`, stdout is usually `{"error":"…"}` or a full outcome object when the failure is part of the result (for example rejected push). | | `usage` | 2 | Invalid flags or arguments. With `--json`, stdout is still `{"error":"…"}` (clap usage errors and subcommand usage such as `grit branch`). Hunk selection mistakes (`add` / `commit` / `stash` / `restore` with unknown or stale `--hunks` ids) also exit 2. `grit diff --exit-code` / `--quiet` uses 2 when diff itself errors. | | `needs_decision` | 3 | [`grit push`](https://grit-scm.com/docs/push/index.md) or [`grit sync`](https://grit-scm.com/docs/sync/index.md) did its work, but another member's head of a [shared branch](https://grit-scm.com/docs/share/index.md) diverged from yours in a way someone has to decide about. The output (`shared[].heads[].divergence` in `--json`) names the scenario and what each side did; nothing is lost, since the server keeps every head. Scripts and agents should read the report rather than retry. | | `remote_unreadable` | 128 | `clone`, `fetch`, `pull`, `push`, or `remote refs` could not reach or read the remote: a missing repository path, a DNS, refused-connection, TLS, or timeout failure, an HTTP error status, or a transport that never spoke Git. With `--json`, stdout is `{"error":"…","kind":"remote_unreadable"}`. Rejected pushes and authentication failures are not in this class (they exit 1). | | `missing_prerequisite` | 128 | `grit bundle unbundle` when the repository lacks prerequisite commits. | | `refused_not_ff` | 128 | `grit merge --ff-only` or `grit pull --ff-only` when a fast-forward is not possible. | | `invalid_commit_filter` | 129 | Invalid `--author`, `--grep`, or pickaxe pattern on `grit log`, `grit revs`, or related commands (`kind`: `invalid_pattern`). | | `interrupted` | 130 | `grit clone`, `grit fetch`, or `grit push` stopped by Ctrl-C, `SIGTERM`, or `SIGHUP` on Unix (or Ctrl-Break on Windows). Partial work is rolled back (for example an incomplete clone directory, fetch temp pack, or push receive quarantine on the remote), so the same command can be run again. With `--json`, stdout is `{"error":"operation cancelled"}`. | | `custom` | *varies* | Passthrough from `grit hooks run` (hook exit code) or `grit rebase --exec` when a command fails. | ## Structured error kinds (`kind` in JSON) These values appear in the `kind` field of structured `--json` errors ([error schema](https://grit-scm.com/docs/exit-codes/schemas/error/v1.json/index.md)). Plain failures omit `kind`. When grit knows what to do next, the object also has a **`hint`** naming the command to run, and human output prints the same text on a `hint:` line after the `error:` line (Markdown output adds a `**Hint:**` paragraph). Failures about specific files list them in **`paths`** (or `conflicts` / `would_overwrite.paths`). ```console $ grit push error: no remote to push to hint: add one with `grit remote add origin `, or push to a URL with `grit push ` $ grit push --json {"error":"no remote to push to","hint":"add one with `grit remote add origin `, or push to a URL with `grit push `","kind":"no_remote"} ``` | Slug | When | | --- | --- | | `conflict` | Merge, pick, rebase, or similar would introduce conflicts (`conflicts`, optional `commit`). A `grit history` rewrite or `grit rebase` that fails replaying another branch it would move also sets `refs` (full branch names) and a `hint` to pass `--update-refs head`. | | `hash_collision` | Refusing to store content that triggers SHA-1 collision detection (`oid`). | | `would_overwrite` | Checkout, switch, merge, or pull would overwrite local or untracked files (`would_overwrite.reason`, `would_overwrite.paths`). The hint suggests `grit commit` or `grit stash` for local changes. | | `operation_in_progress` | `grit switch` refused while a merge, rebase, pick or revert is paused (grit's or one `git` started); finish or abort it first. | | `invalid_pattern` | Invalid filter pattern (exit 129). | | `usage` | Subcommand usage mistake (exit 2), e.g. `grit branch` flag combinations. | | `incompatible_flags` | Flags that cannot be combined (often `--json` with human-only options). | | `lock_held` | A lock file such as `.git/index.lock` or `refs/heads/main.lock` already exists (exit 1). The lock file is left alone on ordinary commands. Staging and committing stop before changing the index or recording a commit; retry after the holder finishes. `lock.path` names the lock, and `lock.holder.pid` / `lock.holder.running` are present when grit wrote a pid sidecar (default for grit-owned index locks; set `core.lockfilePid=false` to opt out). When `lock.holder.running` is `false`, the lock is stale; interrupted rewrite recovery removes it automatically on the next status or abort. | | `index_locked` | **Deprecated** alias of `lock_held`, emitted by v0.5.21 for a held index lock. grit no longer emits it; it stays in the [error schema](https://grit-scm.com/docs/exit-codes/schemas/error/v1.json/index.md) for one release so v0.5.21 output still validates, then it is removed. Match `lock_held` instead. | | `branch_already_exists` | Create branch when the name already exists. | | `branch_not_found` | Branch name not found. `grit switch` hints at `grit branch` and `grit switch -c `. | | `no_previous_branch` | `grit switch -` when HEAD has no earlier checkout in the reflog. | | `branch_invalid_name` | Invalid branch name. | | `branch_not_fully_merged` | Delete refused: not fully merged. | | `branch_checked_out` | Branch checked out in this or another worktree. | | `branch_no_commits` | No commits in repository. | | `branch_invalid_start_point` | Invalid `--start` / start point. | | `branch_upstream_not_tracking` | Upstream is not a tracking branch. | | `branch_no_upstream` | No upstream configured. `grit pull` hints at `grit pull origin ` and `grit push -u origin `. | | `branch_error` | Other branch operation failure. | | `hook_failed` | A hook such as `pre-commit` exited non-zero (`hook.name`, `hook.status`, and the hook's captured `hook.stdout` / `hook.stderr`). | | `revision_not_found` | A branch, tag, commit id or revision expression names nothing. Any command that resolves a revision may emit this `kind` when the spec names nothing (not only `grit merge`). | | `remote_unreadable` | The remote could not be reached or read (exit 128); see the exit status table above. When the server answers `404`, the hint asks you to check the URL. | | `no_remote` | `grit push` with no remote named, no push remote for the branch, and no `origin`. Hint: `grit remote add origin `. | | `remote_not_found` | A remote name that is not configured (`grit push origin main`, `grit pull`, `grit fetch nosuch`). Hint: `grit remote add `. | | `remote_no_url` | The remote is configured but has no URL. Hint: `grit remote set-url `. | | `auth_required` | An HTTPS remote wants credentials and neither a credential helper nor an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`) supplied them. The `error` names the repository URL; the hint is `grit auth` for github.com, otherwise a `credential.helper` or `GIT_ASKPASS`. | | `auth_rejected` | The remote refused the credentials that were sent. | | `unmerged_paths` | `grit merge --continue` while conflicts are unresolved, or resolved but not staged with `commit.autoStage=false` (`paths`). The hint names the files and `grit merge --continue` / `grit merge --abort` (or `grit add`). Also a plain or `--staged` `grit restore` of a conflicted path; the hint names `grit restore --ours` / `--theirs` / `--merge` and `grit add`. Also `grit add` / `grit commit` when a file still has conflict markers after its conflict stages were dropped, for example by `git restore --staged` after a merge, pick or stash pop (`paths`); the hint says to edit out the markers. | | `dirty_worktree` | Staged or unstaged changes block a merge, pick, revert, switch or `rebase --exec` (`paths`). Hint: `grit commit` or `grit stash`. | | `worktree_path_io` | Checkout, stash, add, diff, or reset could not read or replace a worktree file (`paths`, often one path). Typical causes: another program has the file open, or a permission problem. The hint to close the program and retry appears only when the operating system reports the file as in use. | | `checkout_incomplete` | A switch or checkout stopped part way (cancelled with Ctrl+C, or failed) and could not put some work-tree paths back (`paths`). `HEAD` and the index did not move; only the listed paths differ. Hint: `grit reset --hard` and `grit clean -f`. | | `clone_checkout_failed` | `grit clone` downloaded every object and set up the refs, but checking out the work tree failed (exit 1), usually because a partial clone could not fetch its missing blobs. The repository is kept, as `git clone` keeps it; `clone_checkout` has `path`, `commit`, `missing_object` (when a promised object was missing) and `failed_remotes` (`remote`, `error`). Hint: run `grit reset --hard` in the clone to finish the checkout. | | `git_dir_path_io` | Commit, gc, or ref update could not write under `.git/` (`paths`, often one path such as `.git/objects` or `.git/refs/heads/main`). Typical causes: read-only or root-owned `.git` metadata, or another thread/process updating the same index or ref (Windows often reports this as the file being in use). Hint: for permission problems check `ls -l .git` and fix ownership; when the message says the file is in use, retry after the other updater finishes. | | `nothing_staged` | `grit commit` with `commit.autoStage=false` or `--staged` while the index matches `HEAD` but the work tree has unstaged or untracked paths. Hint: `grit add` or `grit commit -- `. | | `nothing_to_commit` | `grit commit` on a genuinely clean tree (or after auto-staging cancels out against `HEAD`). | | `not_a_repository` | Command run outside any Git repository (or parent directory). | | `commit_message_required` | `grit commit` without `-m`, `-F`, amend/reuse, or a pending merge message. | | `empty_commit_message` | `grit commit -m ''`, empty `-F`, or a hook that cleared the message. | | `identity_unknown` | Author or committer identity could not be resolved (`hint` names `grit config --global user.name` / `user.email`). | | `tag_already_exists` | Create tag when the name already exists (hint mentions `--force`). | | `tag_not_found` | Delete or verify a tag when `refs/tags/` does not exist. | | `no_operation_in_progress` | `merge --abort`, `rebase --continue`, `pick --continue`, or similar when nothing is paused; the `error` text names the operation. | | `pathspec_no_match` | `grit add`, `rm`, `restore`, `commit -- `, or stash path selection with no matching files. | | `stash_not_found` | `grit stash pop` / `apply` / `drop` with an empty stash or an invalid index (`hint` for empty stash). | | `path_not_found` | `grit blame` (or similar) when the path is absent from the named revision and not on disk. | | `gitbutler_workspace` | `grit commit` while `HEAD` is on a GitButler workspace (`gitbutler/workspace`, topped by GitButler's workspace commit). GitButler rewrites that branch, so a commit there would be lost. Hint: commit with `but commit`, or switch to a branch first. | | `unsupported_object_store` | The operation needs the files-backed object store (loose objects and packs under `objects/`), but the repository's primary store is custom (exit 1). `operation` is the refused operation's stable name, such as `prune` (a custom store that cannot delete objects), `repack`, `commit_graph_write` or `partial_fetch`; the [object stores guide](https://grit-scm.com/docs/library/object-stores/index.md#what-works-with-a-custom-primary) lists every name. `grit` itself always opens the files backend, so this comes from repositories opened through `grit-lib` with a custom store. | # https://grit-scm.com/docs/agents/index.md # Agent guide > Run grit from scripts and autonomous agents — JSON output, exit codes, non-interactive use, credentials, and where to read the docs. This page is for programs and agents that drive [`grit`](https://grit-scm.com/docs/install/index.md) in automation. It describes **existing** CLI behavior only. Machine-readable **v1 JSON Schemas** for each command's `--json` success object are published at `/schemas//v1.json` (see the [JSON schemas](https://grit-scm.com/docs/schemas/index.md) index). Field-level tables on each command page remain the human-oriented reference; this guide covers the shared contract. Cross-command flag rules (limits, dry-run, messages, pathspecs) are summarized in [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md). Examples below were captured on 2026-10-08 with `grit` built from this repository (`cargo build --release -p grit-cli`), in a temporary repository on branch `main`, unless noted. ## Prefer `--json` (and `--filter`) Pass **`--json`** on every command when something other than a human reads the result. In that mode: - **stdout** carries exactly **one** JSON value: the command's outcome object on success, or `{"error": "…"}` on failure. - **stderr** carries progress lines, auth prompts, and human-style `error: …` diagnostics. Parsers should read **stdout only** for the outcome. - The process still exits non-zero on failure, so you can branch on the exit code **or** the presence of an `error` key. Use **`--filter`** with a [jq](https://jqlang.org)-like expression to narrow the JSON without piping through `jq`. It requires `--json`. Iterator-style filters (for example `.commits[].oid` or `.staged[].path`) always emit a JSON array, including `[]` when nothing matches. Singular filters such as `.branch` or `{branch, clean}` emit one value; a missing field is `null`. ```console $ grit status --json --filter '{branch, clean}' { "branch": "main", "clean": false } $ grit log --json --filter '.commits[].subject' [ "Say hi", "Start the project" ] ``` Plain `grit` with no subcommand is the same as [`grit status`](https://grit-scm.com/docs/status/index.md); `--json` works there too: ```console $ grit --json --filter '{branch, clean}' { "branch": "main", "clean": false } ``` See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for more `--filter` patterns. Per-command keys are documented under [The grit CLI](https://grit-scm.com/docs/global-options/index.md) command pages. ## JSON schema versioning Each command path has versioned schema files under `content/schemas/`: `.vN.json` (dotted paths for subcommands, such as `stash.list.v1.json`). The live contract is whatever **`current`** version the per-command table in `grit-cli/src/json_schema.rs` lists; older **`frozen`** versions stay on disk at stable `$id` URLs and are never regenerated. **Additive on the live version (no bump):** new optional properties, new enum variants, new `definitions`, adding an `enum` to a former free-form string (for example structured `kind`), or widening nullability. **Breaking (requires publishing vN+1):** property removed or renamed, JSON type narrowed, a property newly required, enum variant removed, `additionalProperties: false` where extra keys were previously allowed, or nullability removed from a field. CI runs three gates: - `json_schemas_are_current` — generated live schemas match committed bytes (or run update mode below). - `json_schema_backward_compatible` — every committed schema file (90 total) stays backward compatible: live files vs freshly generated types; frozen older files are checked against themselves so they never drift silently. - `json_snapshots_match_schemas` — golden `--json` snapshots validate against the matching schema. Regenerate live schemas after intentional **additive** contract changes: ```bash GRIT_UPDATE_SCHEMAS=1 cargo test json_schemas_are_current -p grit-cli -- --nocapture ``` Update mode refuses to overwrite the live file when the diff would be **breaking**; the test output lists each breaking JSON path and tells you to publish `vN+1` (add `.v{N+1}.json`, bump `current`, append `N` to `frozen`). Frozen files are never touched by update mode. ## Error object shape Schema: [v1](https://grit-scm.com/docs/agents/schemas/error/v1.json/index.md) On failure with `--json`, stdout is a single object with an **`error`** string (the same message a human sees after `error:` on stderr). Some failures add a **`kind`** and optional fields (for example merge/pick **conflicts**, **`would_overwrite`** with `reason` and `paths` on switch refusal, **`lock_held`** with a **`lock`** object (`path`, and `holder.pid` / `holder.running` when recorded) when an index or low-level loose-ref write encounters a held lock, or **`hash_collision`** with an **`oid`** digest when object ingestion detects an SHA-1 chosen-prefix collision); see the error schema for the plain vs structured union. When grit knows the next step, a **`hint`** names the command to run (`grit remote add origin `, `grit push -u origin main`, `grit auth`, `grit merge --continue`, …), and **`paths`** lists the files an `unmerged_paths` or `dirty_worktree` failure is about. Branch on `kind`, not on the `error` text. ```console $ grit commit --json {"error":"provide a commit message, e.g. grit commit \"what changed\""} ``` If `--filter` is set, it runs on `{"error": "…"}` like any other JSON value. A bad filter expression also yields `{"error": "…"}` on stdout: ```console $ grit status --json --filter 'invalid!!!' {"error":"invalid filter \"invalid!!!\": [(File { code: \"invalid!!!\", path: () }, Parse([(Nothing, \"!!!\")]))]"} ``` In **human** mode, errors print to **stderr** and stdout stays empty: ```console $ grit commit error: provide a commit message, e.g. grit commit "what changed" ``` ## Exit codes | Code | Meaning | | --- | --- | | **0** | Success (including some jq filters that evaluate to `null` when a path is missing). | | **1** | Command failed (missing repo, rejected push, validation error, and similar). With `--json`, stdout still contains `{"error": "…"}`. | | **2** | Usage error (unknown option, invalid subcommand flags, bad `--hunks` ids, or `diff --exit-code` when diff fails). Clap still prints help to stderr. With **`--json`**, stdout is `{"error":"…"}` even for clap usage errors. Without `--json`, usage errors may have empty stdout. | | **128** | Remote unreadable (`clone`, `fetch`, `pull`, `push`, `remote refs`; `kind: remote_unreadable`), bundle missing prerequisites, or `merge --ff-only` / `pull --ff-only` refused. | | **129** | Invalid `--author` / `--grep` / pickaxe pattern (`kind`: `invalid_pattern`). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for the full table and structured `kind` values. ```console $ grit --nope error: unexpected argument '--nope' found Usage: grit [OPTIONS] [COMMAND] For more information, try '--help'. ``` ```console $ grit --json --nope {"error":"unexpected argument '--nope' found"} ``` ```console $ grit status --filter '.branch' error: --filter requires --json ``` [`grit push`](https://grit-scm.com/docs/push/index.md) can exit **1** even after printing a full JSON outcome when a ref was rejected (same idea as Git: the outcome is reported, but the operation failed). ## Color and terminal detection Human output uses ANSI color only when **stdout is a terminal**, the environment supports ANSI (`grit_lib::porcelain::terminal::ansi_supported()`), and **`NO_COLOR` is unset** ([no-color.org](https://no-color.org)). Piped or redirected stdout is plain text; set `NO_COLOR=1` to force plain text on a TTY. JSON mode never depends on color; always pass `--json` for machines. ## Markdown output (`--markdown`) When a human-readable transcript is easier to consume than raw JSON, pass **`--markdown`**. It is mutually exclusive with `--json`; use JSON for strict parsing and Markdown for agent-oriented prose. Each command page documents real `--markdown` stdout under **Markdown output** and links the same v1 JSON Schema as the JSON section (for example `Schema: [v1](https://grit-scm.com/docs/agents/schemas/status/v1.json/index.md)`). Treat that schema as the stable field contract even when stdout is Markdown. Grit formats `--markdown` consistently: | Convention | Behavior | | --- | --- | | **Headings** | `##` titles introduce sections (status groups, file lists, subcommand results). | | **Bullets** | `-` lines for commits, paths, and simple lists; short oids often appear in backticks. | | **Tables** | Markdown tables for rows of refs, remotes, worktrees, and similar; `\|`, `\n`, and `\r` inside cells are escaped. | | **Diff fences** | One fenced `diff` block per changed file when a command emits patches; fence backticks lengthen if the patch text contains ``` so the fence stays unambiguous. | Do not combine `--markdown` with `--filter`. See [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) for exit codes, filters, and the shared JSON error object. ## Stay non-interactive `grit` does **not** open an external editor for commit messages. [`grit commit`](https://grit-scm.com/docs/commit/index.md) requires a message on the command line (positional or `-m`); there is no `$GIT_EDITOR` path. Commands and flows that can **block on a person**: | Area | Behavior | How to avoid blocking | | --- | --- | --- | | [`grit auth`](https://grit-scm.com/docs/auth/index.md) | OAuth device flow: instructions on stderr, then polls GitHub until you authorize in a browser. | Run `grit auth` once in an interactive session before automation. Store the token via `credential.helper` (see below). | | [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) / [`grit push`](https://grit-scm.com/docs/push/index.md) / [`grit pull`](https://grit-scm.com/docs/pull/index.md) | On HTTPS `github.com` auth failure, if **stdin is a TTY**, grit may ask `Sign in to GitHub now? [Y/n]` and run the device flow. | Use a stored token from `grit auth`, or ensure stdin is not a TTY so grit prints a hint and exits without prompting. | | [`grit clone`](https://grit-scm.com/docs/clone/index.md) / [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) / [`grit pull`](https://grit-scm.com/docs/pull/index.md) / [`grit push`](https://grit-scm.com/docs/push/index.md) over **SSH** | Grit runs `ssh` with protocol stdin/stdout piped but **stderr inherited**, so the SSH child can still talk to `/dev/tty` (host-key confirmation, passphrase prompts, `ssh-askpass`, and similar). `--json` does not disable this. | Preconfigure keys and known hosts; for unattended jobs set `GIT_SSH_COMMAND='ssh -o BatchMode=yes'` so SSH fails fast instead of prompting. Grit resolves the ssh command like Git: `GIT_SSH_COMMAND`, then `core.sshCommand` from config, then `GIT_SSH`, then `ssh` on `PATH`. | | [`grit update`](https://grit-scm.com/docs/update/index.md) | Runs the release installer (`curl \| sh` on Unix). | Do not invoke in unattended jobs unless you intend to upgrade the binary. | There is no global `--yes` flag. For commits, always pass `-m` / a message argument. [`grit auth logout`](https://grit-scm.com/docs/auth/index.md) is non-interactive and reports whether a helper had a token to erase: ```console $ grit auth logout --json { "logged_out": false, "host": "github.com" } ``` ### Plumbing commands (not JSON) These speak binary or line protocols on stdin/stdout and have **no** `--json` mode: [`grit manager`](https://grit-scm.com/docs/manager/index.md), [`grit upload-pack`](https://grit-scm.com/docs/upload-pack/index.md), [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md). Agents should not wrap them as JSON commands. `-v` / `--version` (or `-V`) prints a version string and does not emit JSON even if `--json` is passed: ```console $ grit --json --version grit 0.5.1 ``` ## Credentials (HTTPS) For `https://github.com` remotes, sign in once with [`grit auth`](https://grit-scm.com/docs/auth/index.md). Grit uses GitHub's device flow, then stores an access token through your configured **`credential.helper`** (same mechanism as Git). Override the OAuth app id with `GRIT_GITHUB_CLIENT_ID` or `grit config --global grit.githubClientId …`. Sign out with `grit auth logout`. You need a credential helper configured (for example `grit config --global credential.helper store` on Linux — see the [`grit auth`](https://grit-scm.com/docs/auth/index.md) page). The same helpers serve any HTTPS host, not only GitHub. For GitLab, Gitea, Bitbucket or any other host, save a user name and token once with `grit auth --username --token `: it stores them with your credential helper (setting one up if needed) for that host, without contacting it. `grit auth ` without `--username` signs in only to GitHub and `grit serve` hosts, and says so for anything else. In CI, a host-level line such as `https://ci:TOKEN@git.example.com` in the store file (`~/.git-credentials`) authenticates `grit clone`, `fetch` and `push` for every repository on that host, exactly as it does for Git. When no helper has the credentials, grit asks an **askpass** program for them, like Git: `GIT_ASKPASS`, then `core.askPass`, then `SSH_ASKPASS` (the first one set wins; an empty value turns askpass off). The program gets one prompt as its argument, `Username for 'https://git.example.com': ` and then `Password for 'https://ci@git.example.com': `, and prints the answer on stdout. That is how most CI systems inject a token: ```bash cat > askpass.sh <<'SH' #!/bin/sh case "$1" in Username*) echo ci;; *) echo "$CI_TOKEN";; esac SH chmod +x askpass.sh GIT_ASKPASS=$PWD/askpass.sh grit clone https://git.example.com/team/app.git ``` A credential an askpass program supplies is saved with your credential helper once the server accepts it. Grit never prompts on the terminal, even when one is attached: when neither a helper nor an askpass program has the credentials, the command fails with `kind` `auth_required`, and the hint names the helpers that were asked and `grit auth --username … --token …`. Set `credential.interactive=never` to skip askpass as well. When the server refuses a stored credential (an expired or rotated token), the error is `auth_rejected` and the helper erases the entry, as Git does; store the new token the same way. A `user:password@` in the URL is sent as it is; if the server refuses it the error is also `auth_rejected`. SSH remotes do not use the GitHub device-flow token; they can still block on SSH prompts (see the SSH row above). ## Documentation for agents | Resource | URL / path | Use | | --- | --- | --- | | **Agent skill** | [`grit skill`](https://grit-scm.com/docs/skill/index.md) | A `SKILL.md` for coding agents, printed by the installed binary: `grit skill > .agents/skills/grit/SKILL.md`. Includes CI-tested **Recipes** (precise commit, merge conflicts, rebase + lease push, fetch PR, shallow clone) and links to [CLI conventions](https://grit-scm.com/docs/cli-conventions/index.md). | | **llms.txt** | [grit-scm.com/llms.txt](https://grit-scm.com/llms.txt) | Curated index of every docs page (llmstxt.org format). | | **llms-full.txt** | [grit-scm.com/llms-full.txt](https://grit-scm.com/llms-full.txt) | Full text of all docs Markdown twins in site order. | | **Markdown twin** | Same URL as HTML but `index.md` instead of `index.html` (e.g. [status/index.md](https://grit-scm.com/docs/status/index.md)) | One page per command or guide; linked from HTML as "Markdown". | | **Command JSON fields** | Under [The grit CLI](https://grit-scm.com/docs/global-options/index.md) | Each command page lists real `--json` examples and field tables. | | **grit-lib API** | [docs.rs/grit-lib](https://docs.rs/grit-lib) | Rust library reference when embedding grit in your own binary. | | **Library guide** | [Library guide](https://grit-scm.com/docs/library/index.md) | Narrative Rust workflows on top of `grit-lib`. | [llms.txt](https://grit-scm.com/llms.txt), [llms-full.txt](https://grit-scm.com/llms-full.txt), the two one-file bundles ([grit-cli.md](https://grit-scm.com/docs/grit-cli.md) and [grit-lib.md](https://grit-scm.com/docs/grit-lib.md)) and every Markdown twin are built from the same sources as the HTML pages on each deploy, so they never drift from the docs. ## See also - [Scripting with grit](https://grit-scm.com/docs/scripting/index.md) — `--json`, `--filter`, and exit codes in brief - [Global options](https://grit-scm.com/docs/global-options/index.md) — flags shared by every command - [Docs overview](https://grit-scm.com/docs/index.md) — how the site is organized # https://grit-scm.com/docs/schemas/index.md # JSON schemas > Versioned v1 JSON Schemas for every grit command's --json success object. Every command that prints a JSON outcome object with `--json` has a versioned JSON Schema served at a stable URL (`https://grit-scm.com/schemas//vN.json`). Most commands are still on **v1**; `clone` publishes **v3** while **v1** and **v2** remain frozen; `config`, `merge`, `mv`, `pull`, `pick`, `remote` (and several `remote.*` subcommands), `switch`, `tag`, and `worktree.prune` publish **v2** while **v1** remains frozen for older clients. See the [Agent guide](https://grit-scm.com/docs/agents/index.md#json-schema-versioning) for additive vs breaking rules, the CI backward-compatibility gate, and how to regenerate live files under `content/schemas/` with `GRIT_UPDATE_SCHEMAS=1`. Plain command failures with `--json` validate against the shared [error schema](https://grit-scm.com/docs/schemas/schemas/error/v1.json/index.md). ## Command schemas | Command path | Schema | | --- | --- | | `add` | [v2](https://grit-scm.com/docs/schemas/schemas/add/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/add/v1.json/index.md) | | `auth` | [v1](https://grit-scm.com/docs/schemas/schemas/auth/v1.json/index.md) | | `auth.logout` | [v1](https://grit-scm.com/docs/schemas/schemas/auth.logout/v1.json/index.md) | | `blame` | [v1](https://grit-scm.com/docs/schemas/schemas/blame/v1.json/index.md) | | `branch` | [v1](https://grit-scm.com/docs/schemas/schemas/branch/v1.json/index.md) | | `bundle.create` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.create/v1.json/index.md) | | `bundle.list` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.list/v1.json/index.md) | | `bundle.unbundle` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.unbundle/v1.json/index.md) | | `bundle.verify` | [v1](https://grit-scm.com/docs/schemas/schemas/bundle.verify/v1.json/index.md) | | `cat` | [v1](https://grit-scm.com/docs/schemas/schemas/cat/v1.json/index.md) | | `clean` | [v1](https://grit-scm.com/docs/schemas/schemas/clean/v1.json/index.md) | | `clone` | [v3](https://grit-scm.com/docs/schemas/schemas/clone/v3.json/index.md), [v2](https://grit-scm.com/docs/schemas/schemas/clone/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/clone/v1.json/index.md) | | `commit` | [v1](https://grit-scm.com/docs/schemas/schemas/commit/v1.json/index.md) | | `config` | [v2](https://grit-scm.com/docs/schemas/schemas/config/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/config/v1.json/index.md) | | `diff` | [v1](https://grit-scm.com/docs/schemas/schemas/diff/v1.json/index.md) | | `error` | [v1](https://grit-scm.com/docs/schemas/schemas/error/v1.json/index.md) | | `fetch` | [v1](https://grit-scm.com/docs/schemas/schemas/fetch/v1.json/index.md) | | `fetch.all` | [v1](https://grit-scm.com/docs/schemas/schemas/fetch.all/v1.json/index.md) | | `fsck` | [v1](https://grit-scm.com/docs/schemas/schemas/fsck/v1.json/index.md) | | `gc` | [v1](https://grit-scm.com/docs/schemas/schemas/gc/v1.json/index.md) | | `gc.commit-graph` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.commit-graph/v1.json/index.md) | | `gc.drop-large-blobs` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.drop-large-blobs/v1.json/index.md) | | `gc.midx` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.midx/v1.json/index.md) | | `gc.pack-refs` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.pack-refs/v1.json/index.md) | | `gc.offload` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.offload/v1.json/index.md) | | `gc.prune` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.prune/v1.json/index.md) | | `gc.repack` | [v1](https://grit-scm.com/docs/schemas/schemas/gc.repack/v1.json/index.md) | | `history.absorb` | [v1](https://grit-scm.com/docs/schemas/schemas/history.absorb/v1.json/index.md) | | `history.drop` | [v1](https://grit-scm.com/docs/schemas/schemas/history.drop/v1.json/index.md) | | `history.fixup` | [v1](https://grit-scm.com/docs/schemas/schemas/history.fixup/v1.json/index.md) | | `history.move` | [v1](https://grit-scm.com/docs/schemas/schemas/history.move/v1.json/index.md) | | `history.rebase` | [v1](https://grit-scm.com/docs/schemas/schemas/history.rebase/v1.json/index.md) | | `history.reword` | [v1](https://grit-scm.com/docs/schemas/schemas/history.reword/v1.json/index.md) | | `history.split` | [v1](https://grit-scm.com/docs/schemas/schemas/history.split/v1.json/index.md) | | `history.squash` | [v1](https://grit-scm.com/docs/schemas/schemas/history.squash/v1.json/index.md) | | `history.undo` | [v1](https://grit-scm.com/docs/schemas/schemas/history.undo/v1.json/index.md) | | `hooks` | [v1](https://grit-scm.com/docs/schemas/schemas/hooks/v1.json/index.md) | | `hooks.list` | [v1](https://grit-scm.com/docs/schemas/schemas/hooks.list/v1.json/index.md) | | `hooks.run` | [v1](https://grit-scm.com/docs/schemas/schemas/hooks.run/v1.json/index.md) | | `ignore.check` | [v1](https://grit-scm.com/docs/schemas/schemas/ignore.check/v1.json/index.md) | | `init` | [v1](https://grit-scm.com/docs/schemas/schemas/init/v1.json/index.md) | | `log` | [v1](https://grit-scm.com/docs/schemas/schemas/log/v1.json/index.md) | | `merge` | [v2](https://grit-scm.com/docs/schemas/schemas/merge/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/merge/v1.json/index.md) | | `merge-base` | [v1](https://grit-scm.com/docs/schemas/schemas/merge-base/v1.json/index.md) | | `mv` | [v2](https://grit-scm.com/docs/schemas/schemas/mv/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/mv/v1.json/index.md) | | `notes` | [v1](https://grit-scm.com/docs/schemas/schemas/notes/v1.json/index.md) | | `notes.add` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.add/v1.json/index.md) | | `notes.list` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.list/v1.json/index.md) | | `notes.remove` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.remove/v1.json/index.md) | | `notes.show` | [v1](https://grit-scm.com/docs/schemas/schemas/notes.show/v1.json/index.md) | | `patch-id` | [v1](https://grit-scm.com/docs/schemas/schemas/patch-id/v1.json/index.md) | | `pick` | [v2](https://grit-scm.com/docs/schemas/schemas/pick/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/pick/v1.json/index.md) | | `history.move` | [v1](https://grit-scm.com/docs/schemas/schemas/history.move/v1.json/index.md) | | `history.reword` | [v1](https://grit-scm.com/docs/schemas/schemas/history.reword/v1.json/index.md) | | `history.fixup` | [v1](https://grit-scm.com/docs/schemas/schemas/history.fixup/v1.json/index.md) | | `history.absorb` | [v1](https://grit-scm.com/docs/schemas/schemas/history.absorb/v1.json/index.md) | | `pull` | [v2](https://grit-scm.com/docs/schemas/schemas/pull/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/pull/v1.json/index.md) | | `push` | [v1](https://grit-scm.com/docs/schemas/schemas/push/v1.json/index.md) | | `rebase` | [v1](https://grit-scm.com/docs/schemas/schemas/rebase/v1.json/index.md) | | `rebase.check` | [v1](https://grit-scm.com/docs/schemas/schemas/rebase.check/v1.json/index.md) | | `reflog` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog/v1.json/index.md) | | `reflog.list` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog.list/v1.json/index.md) | | `reflog.delete` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog.delete/v1.json/index.md) | | `reflog.expire` | [v1](https://grit-scm.com/docs/schemas/schemas/reflog.expire/v1.json/index.md) | | `remote` | [v2](https://grit-scm.com/docs/schemas/schemas/remote/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote/v1.json/index.md) | | `remote.add` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.add/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.add/v1.json/index.md) | | `remote.prune` | [v1](https://grit-scm.com/docs/schemas/schemas/remote.prune/v1.json/index.md) | | `remote.refs` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.refs/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.refs/v1.json/index.md) | | `remote.remove` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.remove/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.remove/v1.json/index.md) | | `remote.rename` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.rename/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.rename/v1.json/index.md) | | `remote.set-head` | [v1](https://grit-scm.com/docs/schemas/schemas/remote.set-head/v1.json/index.md) | | `remote.set-url` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.set-url/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.set-url/v1.json/index.md) | | `remote.show` | [v2](https://grit-scm.com/docs/schemas/schemas/remote.show/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/remote.show/v1.json/index.md) | | `repack` | [v1](https://grit-scm.com/docs/schemas/schemas/repack/v1.json/index.md) | | `reset` | [v1](https://grit-scm.com/docs/schemas/schemas/reset/v1.json/index.md) | | `resolve` | [v1](https://grit-scm.com/docs/schemas/schemas/resolve/v1.json/index.md) | | `restore` | [v1](https://grit-scm.com/docs/schemas/schemas/restore/v1.json/index.md) | | `revert` | [v1](https://grit-scm.com/docs/schemas/schemas/revert/v1.json/index.md) | | `revs` | [v1](https://grit-scm.com/docs/schemas/schemas/revs/v1.json/index.md) | | `rm` | [v1](https://grit-scm.com/docs/schemas/schemas/rm/v1.json/index.md) | | `shortlog` | [v1](https://grit-scm.com/docs/schemas/schemas/shortlog/v1.json/index.md) | | `show` | [v1](https://grit-scm.com/docs/schemas/schemas/show/v1.json/index.md) | | `skill` | [v1](https://grit-scm.com/docs/schemas/schemas/skill/v1.json/index.md) | | `stash` | [v1](https://grit-scm.com/docs/schemas/schemas/stash/v1.json/index.md) | | `stash.apply` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.apply/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.apply/v1.json/index.md) | | `stash.branch` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.branch/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.branch/v1.json/index.md) | | `stash.drop` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.drop/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.drop/v1.json/index.md) | | `stash.list` | [v2](https://grit-scm.com/docs/schemas/schemas/stash.list/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/stash.list/v1.json/index.md) | | `stash.pop` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.pop/v1.json/index.md) | | `stash.push` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.push/v1.json/index.md) | | `stash.show` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.show/v1.json/index.md) | | `stash.clear` | [v1](https://grit-scm.com/docs/schemas/schemas/stash.clear/v1.json/index.md) | | `status` | [v1](https://grit-scm.com/docs/schemas/schemas/status/v1.json/index.md) | | `switch` | [v2](https://grit-scm.com/docs/schemas/schemas/switch/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/switch/v1.json/index.md) | | `tag` | [v2](https://grit-scm.com/docs/schemas/schemas/tag/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/tag/v1.json/index.md) | | `update` | [v1](https://grit-scm.com/docs/schemas/schemas/update/v1.json/index.md) | | `worktree.add` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.add/v1.json/index.md) | | `worktree.list` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.list/v1.json/index.md) | | `worktree.lock` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.lock/v1.json/index.md) | | `worktree.move` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.move/v1.json/index.md) | | `worktree.prune` | [v2](https://grit-scm.com/docs/schemas/schemas/worktree.prune/v2.json/index.md), [v1](https://grit-scm.com/docs/schemas/schemas/worktree.prune/v1.json/index.md) | | `worktree.remove` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.remove/v1.json/index.md) | | `worktree.repair` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.repair/v1.json/index.md) | | `worktree.unlock` | [v1](https://grit-scm.com/docs/schemas/schemas/worktree.unlock/v1.json/index.md) | Plumbing commands (`manager`, `upload-pack`, `receive-pack`) and shell completion generation do not emit JSON outcome objects and have no schemas here. ## See also [Scripting with grit](https://grit-scm.com/docs/scripting/index.md), [Agent guide](https://grit-scm.com/docs/agents/index.md) # https://grit-scm.com/docs/init/index.md # grit init > Create a new, empty repository. ## Synopsis ```text grit init [-b|--initial-branch ] [--bare] [--object-format sha1|sha256] [--ref-format ] [--separate-git-dir ] [] ``` Global options [`--json`](https://grit-scm.com/docs/global-options/index.md) and [`--markdown`](https://grit-scm.com/docs/global-options/index.md) apply. ## Description Creates an empty Git repository at ``, or in the current directory when no path is given. The directory is created if it doesn't exist. A normal repository keeps its data in a `.git` directory next to your files. A bare repository has no working tree; the repository data is the directory itself, which is what you want for a repository that other people push to. The first branch defaults to `main`, or to `init.defaultBranch` from your global Git config when you omit `-b`. It has no commits until you make one. Use `--ref-format reftable` to initialize with Git's reftable ref backend (requires a reftable-capable Git for interoperability). The default is `files` (loose refs under `refs/`). Use `--object-format sha256` for a SHA-256 object database (Git repository format version 1 with `extensions.objectformat = sha256`). The default is `sha1`. Use `--separate-git-dir` to keep the git directory outside the work tree (a `gitdir:` gitfile in `.git` points at the real directory). ## Options | Option | Description | | --- | --- | | `` | Where to create the repository. Defaults to the current directory. | | `-b`, `--initial-branch` | Initial branch name (overrides `init.defaultBranch`). | | `--bare` | Create a bare repository, with no working tree. | | `--object-format` | Object hash algorithm: `sha1` (default) or `sha256`. | | `--ref-format` | Ref storage backend: `files` (default) or `reftable`. | | `--separate-git-dir` | Place the git directory at this path instead of `/.git`. | ## Examples Start a new project in a new directory: ```console $ grit init project Initialized empty repository in /home/ada/project/.git (ref-format: files) ``` Turn the current directory into a repository: ```console $ grit init ``` Create a bare repository to use as a shared remote: ```console $ grit init --bare /srv/git/project.git Initialized empty bare repository in /srv/git/project.git (ref-format: files) ``` Initialize with the reftable ref backend: ```console $ grit init --ref-format reftable reftable-demo Initialized empty repository in /home/ada/reftable-demo/.git (ref-format: reftable) ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/init/schemas/init/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `initialized` | boolean | `true` when a new repository was created. | | `reinitialized` | boolean | `true` when an existing repository was reinitialized in place (omitted when `false`). | | `path` | string | Repository directory (the `.git` directory for a normal repository). | | `bare` | boolean | Whether the repository is bare. | | `branch` | string | Initial branch name (actual `HEAD` branch after reinit). | | `object_format` | string | Object hash algorithm (`sha1` or `sha256`). | | `ref_format` | string | Ref storage backend (`files` or `reftable`). | | `git_dir` | string | Separate git directory when `--separate-git-dir` was used (omitted when co-located). | Example: ```json { "initialized": true, "path": "/home/ada/project/.git", "bare": false, "branch": "main", "object_format": "sha1", "ref_format": "files" } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/init/schemas/init/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a short prose summary: ```text Initialized empty repository at `/home/ada/project/.git` (default branch `main`, ref-format `reftable`). ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit clone](https://grit-scm.com/docs/clone/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md) # https://grit-scm.com/docs/clone/index.md # grit clone > Copy a remote repository into a new directory. ## Synopsis ```text grit clone [] [--depth ] [-b|--branch ] [--blobs ] [--config ]... [--shallow] [--single-branch | --no-single-branch] [--no-tags] [-o ] [--bare] [--no-checkout] [-q|--quiet] ``` ## Description Copies the repository at `` into a new directory and checks out the remote's default branch. The remote is saved as `origin`, so [`grit fetch`](https://grit-scm.com/docs/fetch/index.md), [`grit pull`](https://grit-scm.com/docs/pull/index.md) and [`grit push`](https://grit-scm.com/docs/push/index.md) work with no further setup. Clone fetches every remote tag under `refs/tags/` on a full multi-branch clone, including tags on commits that are not reachable from any branch tip (matching `git clone`). With `--single-branch` (or a shallow clone without `--no-single-branch`), only tags whose peeled commits are reachable from the fetched branch history are imported — the same tag-following default as `git clone --single-branch`. Later [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) uses tag-following by default; pass `--tags` to fetch all tags again. With files-based ref storage, clone packs imported tags and remote-tracking refs, including final peel records for nested annotated tags. Symbolic `HEAD` refs stay loose, and reflogs are preserved. Bare and shallow clones pack the tags they import; `--no-tags` imports none. This keeps bounded decorated logs from paying for a loose file and object lookup for every historical tag. Ordinary fetches keep their existing ref layout. Reftable repositories continue to use their ref backend. `` can be an `https://` or `http://` URL, an `ssh://` URL or `user@host:path` address, a `git://` URL, a `file://` URL, a path to a local repository, or a path to a [git bundle](https://git-scm.com/docs/git-bundle) file (recognized by its header signature). A local path is stored as an absolute path so that later fetches work from anywhere. Cloning a plain local path hard-links the source's packfiles, like `git clone --local`, so the new repository also gets objects no ref reaches. A `file://` URL gets only the objects reachable from the cloned refs, like any other transport. Use it when the source holds history you don't want copied, such as deleted branches or hidden refs. Without ``, the directory is named after the last path component of the URL with any `.git` suffix removed (splitting on both `/` and `\`, so Windows paths like `..\..\origin.git` clone into `origin`), so `https://github.com/gitbutlerapp/grit.git` clones into `grit`. The destination must not exist or must be empty. If the path already exists and is not empty, grit refuses the clone and leaves the directory and its files unchanged. For a local path or `file://` URL, grit checks that the source exists and is a repository (or a bundle file) **before** creating the destination directory. A typo or missing path fails with exit code **128** and leaves no new directory behind. Cloning from a real empty bare repository at another path is unchanged: grit still creates the destination and reports `empty_remote` when the remote has no commits. On an interactive terminal (human output, not `--json` or `--markdown`), each step of the clone gets one live line on stderr: **Receiving** (pack bytes), **Indexing** (objects), **Resolving** (deltas) and **Checkout** (files). Each line has a scrolling, colored graph of throughput over the last few seconds, a count, a completion bar when the total is known, the current rate and the elapsed time. When a step finishes, its line stays on screen with a graph of the whole step, the total and the average rate. While the pack streams in, grit counts its objects as they arrive (the total comes from the pack header), so the **Receiving** line shows `received/total` objects and a completion bar, as Git's does. Under the live line, an **Overall** bar estimates how far the whole clone is and how long is left: ```text ⠸ Receiving 253,612/421,673 ━━━━━━──── 60% 34.2 MiB/s 7.5s Overall ━━━━━━━━━━━━━━━━━━━━━━────────────────── 53% ~8s left ``` The step under way is projected from its own pace so far. Steps that have not started are sized from the pack's object and delta counts at typical indexing, delta and checkout rates. Before any objects arrive (while the remote is still preparing the pack), the bar shows `estimating`. The percentage never goes down, but the time left can grow when objects slow down, for example when large blobs follow many small commits. The overall bar needs an ANSI terminal; it is cleared once the clone finishes, before the summary. After the clone, stdout gets a summary: total time with a bar showing where it went, bytes received with average and peak throughput, objects by type, branches and tags, and the files and bytes in the work tree. Colors follow the terminal and are turned off by `NO_COLOR`. Over the network, the bar splits the wait before any pack data arrives into three parts: **handshake** (opening the connection — TCP, TLS or SSH, and starting the server's `upload-pack` — until its advertisement is read), **negotiate** (listing refs and the `want`/`have` exchange, until the final request is sent) and **pack prep** (the server counting and compressing objects, until the first pack byte). Local clones and bundles have no such stretch; any wait before their first step shows as **connect**. Time after the last step (writing refs and config) shows as **finish**, and gaps between steps as **other**. When `core.ignorecase` is enabled, grit stores every remote branch and tag during clone, including pairs that differ only by ASCII case (for example `Release` and `release`), in one `packed-refs` write — the same layout Git uses on APFS and NTFS. Later fetches into a loose files ref store can reject the second spelling of such a pair; see [`grit fetch`](https://grit-scm.com/docs/fetch/index.md). When `core.ignorecase` or `core.precomposeunicode` is set and the repository contains paths that collide on this filesystem (different ASCII case or NFC/NFD spellings mapping to one file), grit prints a **warning** on **stderr** (human mode only) listing every colliding index path. Only one path from each group exists on disk; the summary **files** and **worktree_bytes** counts reflect distinct on-disk files, not the number of index entries. With `commit.autoStage` (the default), grit does not auto-stage collision losers — their index blobs stay as recorded in the tree even though the work tree shows them as modified. When the checked-out tree contains **gitlinks** (mode `160000`), grit creates an empty directory at each path and does **not** fetch the nested repository. There is no `grit submodule` command and no `--recurse-submodules` flag. Paths listed in `.gitmodules` are **submodules**: human and `--markdown` output print a **note** on stderr that grit does not fetch them; `--json` includes `submodule_paths` (omitted when empty). Gitlinks with **no** `.gitmodules` entry are **bare gitlinks** (often from copying a nested repo into a parent tree): a separate note explains that the checkout directory is empty and is not a submodule; `--json` includes `bare_gitlink_paths` (omitted when empty). Use the system `git` command if you need submodule checkout or updates. ### Starting from the server's bundle When an HTTP(S) server offers a prebuilt bundle through Git's `bundle-uri` protocol command (as [`grit serve`](https://grit-scm.com/docs/serve/index.md) does), clone downloads that bundle first, unpacks it, and then fetches only what is newer than it. A bundle is a plain file, so the download resumes instead of starting over: - a connection that drops is picked up again from where it stopped, a few times, in the same run; - an interrupted clone (Ctrl-C, a lost network, a closed laptop) keeps what it downloaded in `$XDG_CACHE_HOME/grit/bundles` (`~/.cache/grit/bundles` by default). Run the same `grit clone` again and the download carries on from there. The bundle download has its own display: an arrow and the bundle's URL, then a bar. A resumed download says where it picked up, and its bar shows the bytes from the earlier run in grey: ```text ↻ Resuming bundle download at 14.1 MiB of 58.5 MiB (24%) example.com/demo/bundles/1792925548-38bec2f6f89f.bundle ━━━━━━━━━━━━━━━━━━━───────────── 60% 35.5 MiB of 58.5 MiB 5.22 MiB/s ~4s left ``` When it finishes, the line becomes `✓ bundle 58.5 MiB in 8.5s · 5.23 MiB/s · resumed at 14.1 MiB`, and the summary gets a `bundle` row. Shallow (`--depth`) and partial (`--blobs`) clones never use a bundle, and `transfer.bundleURI=false` in config turns bundles off. When the bundle cannot be used, clone warns and fetches everything as usual. The advertised bundle URL usually has no credentials in it. If the clone URL carries `user:password@` (typical for CI tokens), grit reuses that authentication for the bundle download when it is on the same host as the repository. Authentication failures are not retried like a dropped connection. For private GitHub repositories over HTTPS, sign in first with [`grit auth`](https://grit-scm.com/docs/auth/index.md). For other hosts, save a user name and token first with `grit auth --username --token `. When the remote has no commits yet (an empty bare repository), grit still creates the destination directory, configures `origin`, and points `HEAD` at the remote's default branch without checking out files. Human output includes a short note on stderr (`note: the remote repository is empty.`); `--json` reports `"files": 0`, `"no_checkout_reason": "empty_remote"`, and the configured branch name. When the remote advertises a default branch that has no commits yet but other branches (or tags) were fetched, grit configures `HEAD` to that default branch without checking out files — the same situation as `git clone` when `HEAD` on the server points at an unborn branch. Human output prints a **warning** on stderr that the default branch has no commits, lists remote branches that do have commits, and may suggest `grit switch `. `--json` sets `"no_checkout_reason": "unborn_default_branch"` and `"branches_with_commits"` to those branch names; `"files"` stays `0` until you switch. Pass `--depth ` for the same result as `git clone --depth`: only one ref is fetched (single-branch), with a `.git/shallow` boundary at its tip. Without `-b` / `--branch`, that ref is the remote's default branch. With `-b`, it is the named branch or tag (branches resolve under `refs/heads/` first, then `refs/tags/`). Tag checkouts detach `HEAD` at the peeled commit and do not create branch config. Other branches are not downloaded until you fetch them explicitly. Later [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) respects the shallow boundary. `--shallow` is a hidden alias for `--depth 1` and cannot be combined with `--depth`. ### Partial clone (`--blobs`) `--blobs none` creates a **blobless** (promisor) clone: commits and trees are present locally, but blob objects are omitted from the initial fetch and fetched on demand later (same idea as `git clone --filter=blob:none`). Grit writes Git-compatible promisor configuration (`remote..partialclonefilter`, `extensions.partialclone`, and related keys) so the system `git` command can lazy-fetch missing blobs through the same remote. `--blobs ` omits blobs whose inflated size is at or above the limit. `` accepts the same suffixes as Git's `blob:limit` filter (`512`, `1k`, `2m`, …). Smaller blobs stay in the first pack, which keeps checkouts working when only large assets are skipped. `--blobs auto` takes the filter from the server instead: from the [large-object promisors](#large-object-promisors) it advertises and the clone accepts, using the strictest `partialCloneFilter` they advertise (`blob:none` over any limit, else the smallest limit). Without an accepted remote that advertises a filter, nothing is filtered. The clone records `remote..partialclonefilter=auto`, so each later fetch picks its filter the same way, as Git 2.54 and newer do; older Git does not understand that value. Partial clone trades disk and bandwidth on the first fetch for extra round-trips when something needs blob bytes (for example `git log -p` or reading a large file). It works with `--depth`, `-b` / `--branch`, and the other clone options. The server must allow filter requests (`uploadpack.allowFilter` on bare repos served over smart HTTP or `file://`); a server that does not sends every blob, and the summary says the filter was ignored. A partial clone of a local path or `file://` URL runs grit's own upload-pack in-process, where Git would start `git upload-pack`, so it needs no `git` installed and follows the same `uploadpack.*` settings, read from the served repository's config and, as with Git, from your global and system config. When you pass `--blobs` but the server does not advertise filter support, grit warns on stderr (even with `-q`), fetches an unfiltered pack, and does not treat the clone as partial in human output or `--json` (`partial` is omitted or false). Promisor configuration is still written, matching `git clone --filter` when the server ignores the filter, so later commands may warn about a promisor remote even though every blob arrived in the first pack. `--config ` writes a config value into the new repository before anything is fetched, like `git clone -c`. It can be repeated, and a key given twice gets both values. A key without `=VALUE` is set to `true`. Unlike the global `-c`, which lasts for one command, these values stay in the clone's config. ### Large-object promisors A server can keep its large blobs on another remote, a large-object promisor (LOP), and say so with the protocol v2 `promisor-remote` capability (see [grit serve](https://grit-scm.com/docs/serve/index.md#large-object-promisors)). A clone that accepts the LOP lets the server leave those blobs out; they are then fetched from the LOP when something needs them, instead of through the server. Accepting takes two things in the new repository's config, so they go in with `--config`: the LOP itself as a promisor remote (`remote..url` and `remote..promisor=true`), and a policy in `promisor.acceptFromServer`: | Value | Accepts | | --- | --- | | `none` (default) | nothing | | `knownUrl` | a remote configured under the advertised name with the same URL (the safest choice) | | `knownName` | a remote configured under the advertised name, whatever its URL | | `all` | every advertised remote; only for servers you fully trust | `promisor.checkFields` (`partialCloneFilter`, `token`) also requires the advertised value of each listed field to equal the one configured for the remote. `promisor.storeFields` copies the advertised values of the listed fields into the config of a remote that is already configured; it never creates a remote or changes its URL. Lazy fetches always use the URL configured locally, never the advertised one. Accepting needs a partial clone (`--blobs`): a full clone needs every object from the server, so it declines (`not_partial`). The clone's summary says what it decided: ```console $ grit clone --blobs auto \ --config remote.lop.url=https://lop.example.com/project.git \ --config remote.lop.promisor=true \ --config promisor.acceptFromServer=knownUrl \ https://git.example.com/project.git Cloning into 'project' ... ✓ Cloned into project on main in 128ms partial partial clone; large blobs are fetched on demand promisor lop accepted · blob:limit=5k time ·······················█▓······▒▒▒▒▒▒▒▒▒ 128ms · connect 72ms █ receiving 0ms ▓ indexing 2ms · other 17ms ▒ checkout 28ms data 225 B received objects 3 · 1 commit · 1 tree · 1 blob refs 1 branch · 0 tags files 2 files · 19.5 KiB in the work tree ``` The checkout's missing blobs came from `lop`. Missing objects are always asked of the promisor remotes in config order, with the remote the clone came from (`extensions.partialClone`) last, so a LOP configured before it is tried first and the server is only asked for what the LOP did not have. A server refuses a request that names any object it lacks, so when the LOP holds only the large blobs, the missing objects are split into smaller requests until each remote is asked only for what it has. When an object cannot be fetched, the error names every remote that failed and why. `--bare` creates a bare repository at the destination (the directory itself is the git directory, named with a `.git` suffix when the URL is derived automatically), fetches `refs/heads/*` and tags directly, and configures only `remote..url` — matching `git clone --bare`. `--no-checkout` fetches and sets `HEAD` to the default branch without writing the index or work tree files, matching `git clone --no-checkout`. After `--no-checkout`, use [`grit switch`](https://grit-scm.com/docs/switch/index.md) to materialize the revision you need, for example `grit -C client switch --detach HEAD~1 --json`. The first switch writes the entire destination tree, including when you select the current branch or `HEAD`. Files you created at destination paths are protected by the usual untracked-file collision checks. `switch --dry-run` previews how many paths will be written without creating an index or changing files or refs. You can also clone from a shallow repository (including one created with `git clone --depth`); grit copies the shallow boundary into the new repository so history matches the source. Working-tree materialization after fetch uses the same parallel checkout path as [`grit switch`](https://grit-scm.com/docs/switch/index.md). Configure [`checkout.workers`](https://grit-scm.com/docs/library/parallelism.md/index.md) and `checkout.thresholdForParallelism` in the repository config. Global [`--threads`](https://grit-scm.com/docs/global-options.md/index.md) overrides checkout workers on non-Windows hosts; on **Windows**, set `checkout.workers` explicitly (see [parallelism](https://grit-scm.com/docs/library/parallelism.md/index.md)). ## Options | Option | Description | | --- | --- | | `` | The repository to clone: a URL or a local path. | | `` | The directory to clone into. Defaults to the repository's name. | | `--depth ` | Shallow clone: fetch at most `N` commits on the selected ref (`git clone --depth`). | | `-b`, `--branch ` | Branch or tag to check out instead of the remote default. | | `--shallow` | Hidden alias for `--depth 1` (conflicts with `--depth`). | | `--single-branch` | Fetch only the branch that is checked out and follow tags into that history only (`git clone --single-branch`). JSON `tag_fetch` is `following`. | | `--no-single-branch` | With `--depth`, fetch every branch tip (`git clone --no-single-branch --depth=1`). | | `--no-tags` | Do not fetch tags; sets `remote..tagOpt=--no-tags` like Git. | | `-o`, `--origin ` | Name of the remote (default `origin`). | | `--blobs ` | Partial clone: omit all blobs (`none`), blobs at/above `` (`1k`, `512`, …), or what the accepted promisor remotes hold (`auto`). | | `--config ` | Write a config value into the new repository before fetching (`git clone -c`). Repeatable. | | `--bare` | Bare repository; no working tree (`git clone --bare`). | | `--no-checkout` | Fetch refs but do not check out files (`git clone --no-checkout`). | | `-q`, `--quiet` | No progress, no `Cloning into` line and no human summary. Warnings (such as an empty remote) still go to stderr; `--json` and `--markdown` output is unchanged. | ## Examples Clone a repository from GitHub: ```console $ grit clone https://github.com/BurntSushi/ripgrep.git Cloning https://github.com/BurntSushi/ripgrep.git → ripgrep remote: Enumerating objects: 14184, done. remote: Counting objects: 100% (182/182), done. remote: Compressing objects: 100% (99/99), done. remote: Total 14184 (delta 128), reused 83 (delta 83), pack-reused 14002 (from 2) ✓ Receiving ███████████▅▅▅▅▅▅▅▅▅▅ 5.76 MiB 39.6 MiB/s 145ms ✓ Indexing █████████████████████ 14,184 objects 288.2k objects/s 49ms ✓ Resolving 9,918 deltas 833.1k deltas/s 11ms ✓ Checkout █████████████████████ 226 files 10.6k files/s 21ms ✓ Cloned into ripgrep on master in 1.2s time ·······························█████·▓▓▒ 1.2s · handshake 475ms · negotiate 197ms · pack prep 312ms █ receiving 145ms ▓ indexing 49ms ▒ resolving 11ms ░ checkout 21ms data 5.76 MiB received · 39.6 MiB/s avg · 45.3 MiB/s peak objects 14,184 · 2,343 commits · 6,420 trees · 5,147 blobs · 274 tags refs 16 branches · 274 tags files 226 files · 3.09 MiB in the work tree ``` Progress lines are written to stderr and update in place on a terminal; the time bar and legend are colored by step there. When stderr is not a TTY (for example in a CI log or with stderr redirected), only the initial `Cloning into …` line is written to stderr, and the summary still appears on stdout. Clone into a directory with a different name: ```console $ grit clone git@github.com:gitbutlerapp/grit.git grit-src ``` Clone a local repository: ```console $ grit clone /srv/git/project.git ``` Shallow clone (single commit of history on the default branch): ```console $ grit clone --depth 1 https://github.com/BurntSushi/ripgrep.git ``` Clone a specific branch with limited history: ```console $ grit clone --depth 3 -b feature file:///srv/git/project.git ``` Clone and detach at a tag: ```console $ grit clone -b v1.0.0 https://github.com/BurntSushi/ripgrep.git ``` ## JSON output Schema: [v3](https://grit-scm.com/docs/clone/schemas/clone/v3.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `url` | string | The URL or path that was cloned. For network URLs, embedded credentials are stripped from this display copy (the configured `remote..url` keeps the caller's URL). | | `path` | string | Directory the clone was created in. | | `remote` | string | Remote name configured for the source (`origin` by default). | | `single_branch` | boolean | Whether only one branch was fetched. | | `tag_fetch` | string | Tag fetch mode for the initial fetch: `all`, `following`, or `none`. Named `tag_fetch` because `tags` is already the count of tag refs fetched. | | `branch` | string or null | Branch checked out; `null` when detached at a tag. | | `detached` | boolean | True when `HEAD` is detached (tag checkout). | | `tag` | string or omitted | Tag name when `-b` named a tag. | | `depth` | integer or omitted | Shallow depth when `--depth` or `--shallow` was used. | | `blobs` | string or integer or omitted | The filter used: `"none"` or a byte limit. With `--blobs auto`, the filter it resolved to; omitted when nothing was filtered. | | `partial` | boolean or omitted | `true` when the server applied the `--blobs` filter on the initial fetch. Omitted or false when the server lacks filter support (see warning above). | | `filter_auto` | boolean or omitted | `true` with `--blobs auto`. | | `filter_ignored` | boolean or omitted | `true` when the server does not support filters, so `--blobs` was not sent and every blob was downloaded (`partial` is then omitted); the clone is still set up as a partial clone, as Git leaves it. The human summary then shows a `filter` line saying so instead of calling the clone blobless. | | `promisor_remotes` | array or omitted | The promisor remotes the server advertised: `name`, `url` (credentials removed), `accepted`, `filter` (the advertised `partialCloneFilter`, or `null`) and `rejected` (why it was not accepted: `policy_none`, `unknown_remote`, `url_mismatch`, `field_missing`, `field_mismatch` or `not_partial`; `null` when accepted). Omitted when the server advertised none. Tokens are never shown. | | `stored_fields` | array or omitted | Fields copied into config by `promisor.storeFields`: `remote` and `field` (`partialCloneFilter` or `token`), never the value. Omitted when nothing was stored. | | `promisor_warnings` | array or omitted | Promisor config or advertised values that were ignored: `code` is `unknown_accept_value` (`promisor.acceptFromServer` is not a known policy, so nothing is accepted), `unknown_field` (a `promisor.checkFields` / `promisor.storeFields` entry is not a known field), `invalid_advertised_value` (an advertised field was not stored because its value is invalid) or `unusable_auto_filter` (`--blobs auto` cannot use an accepted remote's filter, such as `tree:0`); `key`, `remote`, `field` and `value` say which, when they apply. A rejected advertised value is never shown. Shown as `promisor warning: …` lines in the human output and `promisor warning` bullets in `--markdown`. Omitted when there were none. | | `objects` | integer | Objects installed during fetch: for network clones, objects in the received pack; for local-path clones, objects in newly linked pack indexes plus any reachable loose objects hardlinked from the source. | | `bytes` | integer | On-disk payload bytes installed during fetch: for network clones, the received `.pack` size; for local-path clones, the sum of newly linked `.pack` files plus reachable loose object files (same bytes as hardlinked/copied object store data). | | `branches` | integer | Remote branches fetched. | | `tags` | integer | Remote tags fetched. | | `files` | integer | Working-tree files checked out (distinct on-disk paths when `core.ignorecase` or `core.precomposeunicode` collapsed spellings). | | `path_collisions` | array of strings | Index paths that collided during checkout when tracked paths share one on-disk file (case or Unicode normalization). Omitted when empty. | | `submodule_paths` | array of strings | Gitlink paths listed in `.gitmodules`. Grit does not fetch submodule repositories. Omitted when empty. | | `bare_gitlink_paths` | array of strings | Gitlink paths with no `.gitmodules` entry (empty directories after checkout). Omitted when empty. | | `object_types` | object or null | Objects received by type: `commits`, `trees`, `blobs` and `tags` (annotated tag objects). Populated when grit indexed the received pack or can tally every object in the transfer. `null` when a local pack link installed more objects than the transfer summary tracks individually (typical for a single linked pack on clone). | | `worktree_bytes` | integer | Total size of the checked-out files. | | `seconds` | number | Wall-clock seconds for the whole clone. | | `phases` | array | Time spent in each step, in order: `phase` (`bundle`, `receiving`, `indexing`, `resolving_deltas`, `copying` or `checkout`), `unit` (`bytes`, `objects` or `files`), `count` and `seconds`. Steps that processed nothing are left out. | | `bare` | boolean | `true` when `--bare` was used. | | `no_checkout_reason` | string or omitted | When no files were checked out: `empty_remote`, `unborn_default_branch`, `bare`, or `no_checkout`. Omitted when checkout succeeded. | | `branches_with_commits` | array of strings | Remote branch names that have commits when `no_checkout_reason` is `unborn_default_branch`. Omitted when empty. | | `bundle` | object or omitted | The server's prebuilt bundle the clone started from: `uri` (credentials stripped like `url`), `bytes` (its size) and `resumed_from` (bytes an earlier, interrupted clone had already downloaded). `objects` and `bytes` above include what it brought. Omitted when no bundle was used. | | `space` | string or omitted | For a clone of an organization's project on GitButler Code (the default grit host): your space's project, `/`. Pushes from the clone go there (`remote.origin.pushurl`), and a `space` remote fetches from it; see [`grit sync`](https://grit-scm.com/docs/sync/index.md). Omitted otherwise, or when you aren't signed in. | Example (repository with commits): ```json { "url": "/srv/git/project.git", "path": "project", "remote": "origin", "single_branch": false, "tag_fetch": "all", "branch": "main", "detached": false, "bare": false, "objects": 42, "bytes": 8192, "branches": 1, "tags": 0, "files": 3, "object_types": { "commits": 4, "trees": 9, "blobs": 29, "tags": 0 }, "worktree_bytes": 6144, "seconds": 0.21, "phases": [ { "phase": "copying", "unit": "objects", "count": 42, "seconds": 0.004 }, { "phase": "checkout", "unit": "files", "count": 3, "seconds": 0.002 } ] } ``` Empty remote (no branch tips yet): ```json { "url": "/tmp/origin.git", "path": "project", "remote": "origin", "single_branch": false, "tag_fetch": "all", "branch": "main", "detached": false, "bare": false, "objects": 0, "bytes": 0, "branches": 0, "tags": 0, "files": 0, "no_checkout_reason": "empty_remote", "object_types": null, "worktree_bytes": 0, "seconds": 0.013, "phases": [] } ``` Unborn remote default branch (`HEAD` on the server points at a branch with no commits, but `main` was pushed): ```json { "url": "/tmp/remote.git", "path": "clone2", "remote": "origin", "single_branch": false, "tag_fetch": "all", "branch": "master", "detached": false, "bare": false, "objects": 3, "bytes": 458, "branches": 1, "tags": 0, "files": 0, "no_checkout_reason": "unborn_default_branch", "branches_with_commits": ["main"], "object_types": null, "worktree_bytes": 0, "seconds": 0.003, "phases": [ { "phase": "copying", "unit": "objects", "count": 1, "seconds": 0.00006 } ] } ``` A clone that accepted a large-object promisor (`--blobs auto`): ```json { "url": "https://git.example.com/project.git", "path": "project", "remote": "origin", "single_branch": false, "tag_fetch": "all", "branch": "main", "detached": false, "blobs": 5120, "partial": true, "filter_auto": true, "promisor_remotes": [ { "name": "lop", "url": "https://lop.example.com/project.git", "accepted": true, "filter": "blob:limit=5k", "rejected": null } ], "objects": 3, "bytes": 225, "branches": 1, "tags": 0, "files": 2, "object_types": { "commits": 1, "trees": 1, "blobs": 1, "tags": 0 }, "worktree_bytes": 20006, "seconds": 0.13, "phases": [], "bare": false } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v3](https://grit-scm.com/docs/clone/schemas/clone/v3.json/index.md) Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract. ```text ## Clone complete - **path**: `cloned-markdown` - **branch**: `main` - **url**: `[UPSTREAM]` - **objects**: 8 - **object types**: 2 commits, 2 trees, 3 blobs, 1 tags - **bytes**: 685 ([SIZE]) - **branches**: 2 - **tags**: 1 - **files**: 2 - **worktree bytes**: 23 ([SIZE]) - **elapsed**: [DURATION] | Phase | Count | Unit | Seconds | | --- | ---: | --- | ---: | | copying | 8 | objects | [SECONDS] | | checkout | 2 | files | [SECONDS] | ``` When the server advertised promisor remotes, a bullet lists them, and one more names each stored field: ```text - **promisor remotes**: `lop` (accepted) - **stored**: `partialCloneFilter` for `lop` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Clone succeeded (including empty remote with no checkout). | | `1` | Destination not empty, checkout failure (the repository is kept: `kind` `clone_checkout_failed`, see [When the checkout fails](#when-the-checkout-fails)), or other error. Missing or refused credentials are `kind` `auth_required` / `auth_rejected` with a `hint` in `--json` and on the human `hint:` line. HTTPS credentials come from your credential helper (`grit auth --username --token ` saves one for any host), then an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`); see [Credentials](https://grit-scm.com/docs/agents/index.md#credentials-https). | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | | `128` | Could not reach or read the source: missing path, DNS or connection failure, HTTP error status ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)); a `404` adds a hint to check the URL. | | `130` | Interrupted with Ctrl-C, `SIGTERM`, or `SIGHUP` ([`interrupted`](https://grit-scm.com/docs/exit-codes/index.md)). The error is `operation cancelled` (`{"error":"operation cancelled"}` with `--json`). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ### When the checkout fails A failure while downloading or setting up the repository removes the destination again. Once every object and ref is in place and `HEAD` is set, a failure while writing the work tree keeps the repository, as `git clone` does, so the checkout can be finished without downloading everything again. The usual cause is a partial clone whose missing blobs cannot be fetched: a large-object promisor that is unreachable or does not have them yet, or lazy fetch turned off. The error says the clone was kept, the `hint` says how to finish, and `--json` reports `kind` `clone_checkout_failed` with a `clone_checkout` object (exit `1`): ```console $ GRIT_NO_LAZY_FETCH=1 grit clone --blobs none file:///srv/project.git project Cloning into 'project' ... error: the clone into 'project' succeeded, but its checkout failed: promised object not available locally: ce013625030ba8dba906f756967f9e9ca394464a hint: the repository was kept; run `grit reset --hard` in 'project' to finish the checkout once its promisor remotes can supply the missing objects $ grit -C project reset --hard Reset master to 284c599 (hard) ``` | Field | Type | Description | | --- | --- | --- | | `clone_checkout.path` | string | The clone's directory, where the repository was kept. | | `clone_checkout.commit` | string | The commit `HEAD` points at, whose files the checkout was writing. | | `clone_checkout.missing_object` | string or omitted | The first promised object that could not be fetched, when the checkout failed for lack of one. | | `clone_checkout.failed_remotes` | array | Each promisor remote that failed to supply the missing objects, in the order they were asked: `remote` (name) and `error` (its first error). Empty when no remote was asked, for example with lazy fetch off. | A clone interrupted during the checkout is still removed (see below). ### Interrupting a clone Ctrl-C, `SIGTERM`, and `SIGHUP` stop a clone at any point: while it downloads, copies objects or checks out files. The first signal asks the clone to stop; grit then rolls back the checkout, removes the destination directory it created (or empties one that already existed empty) and exits `130`. Nothing is left in the way, so the same `grit clone` command can simply be run again, and a bundle download carries on where it stopped. A duplicate signal that arrives with the first (`timeout -s INT` or `timeout -s TERM` signals both the process and its group) is ignored; sending the same signal again later ends grit at once, without the cleanup. Only an uncatchable `SIGKILL` (or that second signal after the duplicate window) skips rollback. In a Windows console Ctrl-C and Ctrl-Break behave the same way. Closing the console window still gives grit no chance to clean up, so delete the leftover directory by hand before you clone again. ```console $ grit clone ../git git Cloning into 'git' ... ^C error: operation cancelled $ echo $? 130 $ ls git ls: cannot access 'git': No such file or directory $ grit clone ../git git Cloning into 'git' ... ✓ Cloned into git on master in 602ms time ·█·············▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ 602ms █ copying 3ms · other 194ms ▓ checkout 387ms data 311 MiB received objects 422,423 refs 1 branch · 1,012 tags files 4,856 files · 48.0 MiB in the work tree ``` ## See also [grit init](https://grit-scm.com/docs/init/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md), [grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit auth](https://grit-scm.com/docs/auth/index.md) # https://grit-scm.com/docs/checkout/index.md # grit checkout > Start work on a repository from a snapshot of its main branch, or of some of its paths, instead of a clone. ## Synopsis ```text grit checkout [] [-p|--path ]... [--into ] ``` ## Description `grit checkout` makes a working repository from a server's newest commit without downloading its history. It asks the server for a **snapshot**: the target branch's tree (the branch the server's `HEAD` names), cut down to the paths you give, in a single commit. It downloads that snapshot and builds a normal Git repository around it: `git` and `grit` work in it as usual. - With no `--path`, the snapshot is the whole tree. - With `--path ` (repeatable), it is everything under each path, plus the files directly in every directory above one, the top level included — the same files Git's cone-mode sparse checkout would have. - With a `` name, it is that [slice](https://grit-scm.com/docs/slice/index.md)'s paths (plus any `--path`), and the directory defaults to the slice's name. Download and materialization honor Ctrl+C (and `SIGTERM` / `SIGHUP` on Unix) with `error: operation cancelled` and exit code **130**; a checkout directory grit created for this run is removed when materialization fails or is cancelled. The new repository's history is one commit, `Snapshot of : `, which stands for the real commit on the server. It is at `origin/` (which `origin/HEAD` names), and you are on a new **work branch** on top of it, named for your `user.email` and two random words (like `alice/amber-brook`). The server picks the final name: it numbers it (`alice/amber-brook-2`) when it already has that branch or has given the name to another checkout, and never gives a name out twice, even across restarts. There is no local copy of the target branch. `origin` is the repository URL, set up so that plain `git` and `grit` commands stay with the checkout's snapshots: ```text [remote "origin"] url = http://127.0.0.1:8080/demo.git fetch = +refs/checkouts//target:refs/remotes/origin/main push = +refs/heads/*:refs/checkouts//out/heads/* tagOpt = --no-tags ``` A plain `git fetch` or `grit fetch` brings only the checkout's own snapshots into `origin/main`, never the real history, other branches or tags. A plain `git push` or `grit push` sends your branches to the check-in area that [`grit checkin`](https://grit-scm.com/docs/checkin/index.md) grafts from, never onto the server's real branches. `grit checkin` and `grit pull` themselves always talk to the server the checkout was made from, even if you point `origin` somewhere else. What makes the repository a checkout is a small record in its git directory (`grit-checkout.json`): the server, the checkout's id, its target branch, its paths and its snapshots, and the tips of branches it checked in that were since [integrated](https://grit-scm.com/docs/integrate/index.md) into its target branch, whose commits refreshes leave out. Every worktree of the checkout (`git worktree add`) shares it, so checking in and refreshing work from any of them. Snapshots are made the same way every time, so everyone who checks out the same paths at the same commit gets the same snapshot commit, and the server makes its download once. The download resumes: if a checkout is interrupted, run the same command again and it picks up where it stopped (partial downloads are kept in `$XDG_CACHE_HOME/grit/checkouts`, `~/.cache/grit/checkouts` by default). The download has the same display as [`grit clone`](https://grit-scm.com/docs/clone/index.md)'s bundle download. Snapshot checkouts need a server that offers them, such as [`grit serve`](https://grit-scm.com/docs/serve/index.md). They are served at their own endpoint, `/.grit/checkouts/`, separate from Git's. When a server doesn't have it (a plain Git server, or a repository you can't read), `grit checkout` stops with an error and makes nothing: ```text error: https://example.com/demo.git offers no grit checkout (no https://example.com/.grit/checkouts/demo endpoint); it may be a plain Git server, or the repository may not exist ``` Sign in to the server first with [`grit auth `](https://grit-scm.com/docs/auth/index.md). Work comes back with [`grit checkin`](https://grit-scm.com/docs/checkin/index.md), which rebuilds your branches on the server's real history. [`grit integrate `](https://grit-scm.com/docs/integrate/index.md) merges one into the target branch, and [`grit pull`](https://grit-scm.com/docs/pull/index.md) refreshes the checkout: the server makes a snapshot of the newest commit of the branch the checkout was made from (even if the server's `HEAD` has since moved to another branch) on top of your last one, `grit pull` fetches just the changes in your paths and rebases the current branch onto it. Commits already in the target drop out. A rebase that conflicts stops for you to resolve, then `grit rebase --continue`; other branches still on an older snapshot are named (see [`grit pull`](https://grit-scm.com/docs/pull/index.md#in-a-snapshot-checkout)). `grit pull ` shows you a branch on the server as your checkout sees it and brings your branch onto it, so checkouts of different paths can work on one branch (see [`grit pull`](https://grit-scm.com/docs/pull/index.md#a-server-branch-in-a-snapshot-checkout)). To switch branches, use [`grit switch`](https://grit-scm.com/docs/switch/index.md) (also `grit co`). Out of Git habit, `grit checkout ` with no URL (nothing with `://`) and no other arguments does the same as `grit switch `, hints included. ## Options | Option | Description | | --- | --- | | `` | The repository, such as `http://127.0.0.1:8080/demo.git`. | | `` | A [slice](https://grit-scm.com/docs/slice/index.md) on the server whose paths to check out. | | `-p`, `--path ` | Check out only this path (a directory or file), plus the files in the directories above it. Repeatable. | | `--into ` | Directory to check out into. Defaults to the repository's name. It must not exist or must be empty. | ## Examples Check out one directory of a repository served by `grit serve`: ```console $ grit checkout http://127.0.0.1:8080/demo.git --path src/deep ✓ Checked out /home/alice/demo on alice/birch-pebble in 117ms paths src/deep files 4 files, 293 KiB as a 294 KiB download history one commit, fd590c7, standing for main at 5a80f18 Commit on alice/birch-pebble as usual; origin/main is the snapshot. $ cd demo && git log --oneline --all fd590c7 Snapshot of 5a80f18e14a3: Add src and docs ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/checkout/schemas/checkout/v1.json/index.md) | Field | Type | Meaning | | ----- | ---- | ------- | | `url` | string | The repository URL, configured as `origin` (with the fetch and push refspecs above), with any `user:password@` removed. | | `path` | string | Directory the checkout was made in. | | `branch` | string | The server's target branch the snapshot was taken from. | | `work` | string | The new branch checked out for your work. | | `base` | string | The real commit of the target branch the snapshot stands for. | | `snapshot` | string | The snapshot commit, the checkout's only commit. | | `paths` | array of strings | The paths checked out; empty for the whole tree. | | `files` | integer | Files in the snapshot. | | `bytes` | integer | Bytes of those files. | | `download_bytes` | integer | Size of the download. | | `resumed_from` | integer | Bytes an earlier, interrupted checkout had already downloaded. | | `id` | string | The server's id for the checkout. | | `seconds` | number | Wall-clock seconds. | ```json { "url": "http://127.0.0.1:8080/demo.git", "path": "demo", "branch": "main", "work": "alice/amber-elm", "base": "5a80f18e14a38d1fddfb042e0b7724901ae7b30f", "snapshot": "ebf573ce69beba70f4dfe136c515dc6e2a1899f7", "paths": [], "files": 5, "bytes": 300010, "download_bytes": 300744, "resumed_from": 0, "id": "a093149cf50483d816cc", "seconds": 0.13 } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v1](https://grit-scm.com/docs/checkout/schemas/checkout/v1.json/index.md) ```markdown ## Checkout complete - **path**: `demo` - **work branch**: `alice/birch-pebble` - **url**: `http://127.0.0.1:8080/demo.git` - **target**: `main` at `5a80f18e14a38d1fddfb042e0b7724901ae7b30f` - **snapshot**: `fd590c7ae90eb06479c29d9640d83e72504483c1` - **paths**: `src/deep` - **files**: 4 (300010 bytes) - **download**: 300744 bytes (resumed at 0) ``` ## Exit status | Code | Meaning | | --- | --- | | `0` | The checkout was made. | | `1` | The server offers no snapshot checkouts for the repository, has no such slice, refused the request (for example a path it doesn't have), the destination is not empty, or the download failed. | ## See also - [`grit serve`](https://grit-scm.com/docs/serve/index.md) — serves snapshot checkouts. - [`grit checkin`](https://grit-scm.com/docs/checkin/index.md), [`grit integrate`](https://grit-scm.com/docs/integrate/index.md), [`grit slice`](https://grit-scm.com/docs/slice/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) — working in a checkout. - [`grit clone`](https://grit-scm.com/docs/clone/index.md) — a full copy with history. # https://grit-scm.com/docs/status/index.md # grit status > Show where you are and what's changed. This is what plain grit runs. ## Synopsis ```text grit grit status grit st ``` ## Description The status screen is your home base. It shows, from top to bottom: - **Where you are.** The current branch and how it compares with its target branch: ahead and behind counts, followed by ahead commits (up to ten). A branch with no commits says `no commits yet`, and a detached HEAD shows the commit it's on (short id follows `core.abbrev` and always resolves). - **Staged** changes, which are ready to commit. - **Changed (not staged)** files, which have been modified since they were last staged. - **Untracked** files, which `grit` isn't tracking yet. - **A hint** with the next command to run. Each change has a label: `new`, `modified`, `deleted`, `renamed`, `copied`, `type changed` or `conflict`. `type changed` (`type_changed` in `--json`, Git's `T`) means the path switched between a regular file, a symlink and a submodule; a permission-only change such as `chmod +x` is `modified`. **Submodules:** grit records gitlinks in the index but does not fetch nested repositories ([`grit clone`](https://grit-scm.com/docs/clone/index.md) leaves an empty directory and prints a note). An **uninitialized** submodule directory (no embedded `.git`) is ignored the same way Git ignores it: stray files you create inside that placeholder are not listed as modified or untracked, and `grit commit` agrees with a clean `git status`. A **checked-out** submodule with its own `.git` directory is compared by its HEAD commit and inner worktree dirtiness. Short status uses lowercase `m` when the recorded gitlink commit still matches the checkout but tracked content inside the submodule is dirty; uppercase `M` means the submodule HEAD moved. Git's `diff.ignoreSubmodules`, `submodule..ignore`, and the `ignore` key in `.gitmodules` apply to unstaged gitlink reporting the same way they do in Git (`none`, `untracked`, `dirty`, `all`; per-submodule settings override the global default). Staged gitlink updates (index commit differs from `HEAD`) stay visible even when ignore is `all`. In default untracked listing, a directory that contains an embedded repository (with or without sibling untracked files) is reported once as `?? parent/` (Git collapses the nested checkout the same way). With `--untracked all`, grit lists the embedded repository directory and any sibling files under the parent, but never files inside the nested checkout. A tracked file that grit cannot open to compare its content (another program holds it open without sharing, or it has no read permission) is listed as `modified`, like Git does, and the rest of the status is reported as usual. When a **directory** on the path cannot be opened (for example `chmod 000` on a parent of a tracked file or an untracked tree), grit prints a `warning:` on stderr naming the path, skips that subtree, and continues — the rest of status is unchanged and exit status stays `0`. With `--json`, those warnings appear in the `warnings` array alongside the normal status fields. Commands that need the file's bytes, such as `grit add` of that path or a patch from `grit diff`, still fail with [`worktree_path_io`](https://grit-scm.com/docs/exit-codes/index.md), and `grit switch` refuses a branch that would change it. **Index refresh:** after stat data in the work tree no longer matches `.git/index`, grit re-verifies content and normally writes the refreshed stat cache back to the index (like `git status`). If another command updates the index after status loaded it (for example a concurrent commit), grit skips the write and keeps the on-disk index that command wrote. Use [`--no-optional-locks`](https://grit-scm.com/docs/global-options/index.md) or `GIT_OPTIONAL_LOCKS=0` when a background status must not touch the index file; grit still refreshes stat data in memory so the report matches a full run. Library callers set [`StatusOptions::write_index`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/status/struct.StatusOptions.html#structfield.write_index) to `false` for the same read-only behavior without changing the process environment. During a paused merge or grit rebase, human output also lists **Conflicts** grouped by kind (`both modified`, `both added`, …). In `--json`, each conflict is `{ "path", "kind" }` and `operation.next_steps` lists the ordered `grit` commands while an operation is paused (for example `grit diff` then `grit add .` with conflicts, or `grit merge --continue` / `grit rebase --continue` once conflicts are resolved). Use `operation.alternatives` for cancel paths such as `grit merge --abort` or `grit rebase --abort` (not part of the ordered sequence). Grit rebase sessions are detected via `.git/rebase-merge/grit-plan`. A rebase that `git` started (`.git/rebase-merge/` or `.git/rebase-apply/` without grit's plan) is recognised too. The header names the branch being rebased (`Rebasing topic onto 1a2b3c4`), JSON `branch` reports that branch, and `operation` is `rebase-interactive` (Git's default merge backend) or `rebase` (`git rebase --apply`). Its `next_steps` end with `git rebase --continue`, because only git can resume its own todo list. `grit rebase --abort` is listed in `alternatives` and cancels it. ### Conflict kinds Every grit command that reports conflicts (`status`, `merge`, `pick`, `revert`, `rebase` and `pull`) names each conflicted path with the same `kind`. The kind says which sides still have the path: "us" is the side you were on when the operation started (`HEAD`), "them" is the side being brought in (the merged branch, the picked or reverted commit, or the commit a rebase is replaying). So a conflict reads the same in an operation's output and in `grit status` afterwards, and matches the unmerged XY code of `git status --porcelain=v2`: | `kind` | Human label | Git XY | Meaning | | ------ | ----------- | ------ | ------- | | `both_modified` | both modified | `UU` | Both sides changed the file. | | `both_added` | both added | `AA` | Both sides added the path with different content. | | `both_deleted` | both deleted | `DD` | Both sides removed the path. | | `added_by_us` | added by us | `AU` | Only our side has the path. | | `added_by_them` | added by them | `UA` | Only their side has the path. | | `deleted_by_us` | deleted by us | `DU` | We deleted the path and they changed it. | | `deleted_by_them` | deleted by them | `UD` | We changed the path and they deleted it. | | `rename_rename` | — | — | Both sides renamed one file to different names (`merge`, `pick`, `revert`, `rebase` and `pull` only; `status` shows the three paths as `both_deleted`, `added_by_us` and `added_by_them`). | | `directory_rename_moved` | moved with its directory | — | A file one side added to a directory the other side renamed was moved into the new directory; confirm the location (operations only; `status` shows the path as `added_by_us` or `added_by_them`). See [directory renames](https://grit-scm.com/docs/merge/index.md#directory-renames). | | `directory_rename_split` | directory split up | — | A directory was spread over several directories with no clear destination, so files added to it stayed put. The path is the directory; nothing is unmerged (operations only). | | `directory_rename_blocked` | directory move blocked | — | Files were not moved into a renamed directory because their destination is taken. The path is the destination; nothing is unmerged (operations only). | ### Interrupted rebases and history edits A `grit rebase` or `grit history` edit that is killed after moving branches but before the files are updated leaves a recovery journal in `.git/grit/rewrite-apply/`. With optional locks enabled (the default), `grit status` finishes that work before it reports anything, and says what it did in one line above the usual screen. With `--no-optional-locks` / `GIT_OPTIONAL_LOCKS=0`, recovery is deferred and the outcome stays **Pending** until a status run that may write the index: - **Finished the checkout.** The branches had already moved, so status puts back the files the interrupted checkout was writing and checks out the rewritten commit again. The rebase stands. Unrelated local edits are kept. - **Rolled back.** When that checkout cannot finish (or for an interrupted `history fixup` or `absorb`), branches, index and files go back to where they were before the command. Status still succeeds. - **Pending.** Another process holds `.git/index.lock`, so nothing is touched yet. When grit wrote a pid sidecar for that lock (default for grit-owned locks) and the recorded process has exited, the next status removes the stale lock and recovers. When no sidecar exists (for example `core.lockfilePid=false` or a foreign Git lock), the message notes the lock may be stale; run status again after the holder exits, or remove the lock only when nothing else is using the repository. `--json` reports the outcome in `interrupted_rewrite`. The line and the field appear only on the run that finished or rolled back the work, and on every run while it is pending. ```console $ grit status Finished the checkout of an interrupted rebase or history edit; HEAD stays on the rewritten commits. On feat · 1 ahead of master 4f2a9c1 you just now feat Nothing to commit — working tree clean. ``` Paths are shown relative to the directory you run `grit` from. Valid UTF-8 file names print as-is in human and `--markdown` output (unlike Git’s default `core.quotepath=true`, which octal-escapes non-ASCII bytes). Names that contain C0 control characters (including ESC and BEL) are still C-quoted so a malicious repository cannot inject terminal escape sequences. Set `core.quotepath=true` in config if you want Git-style octal escaping for all non-ASCII bytes. `--json` path fields are always unquoted UTF-8 strings (JSON escapes controls as `\uXXXX`). ### GitButler workspaces [GitButler](https://gitbutler.com) applies several branches at once by checking out `gitbutler/workspace`, topped by a merge of the applied branches that it maintains itself (its message says `GitButler Workspace Commit`). That commit is GitButler's bookkeeping, so on such a workspace `grit status` lists the applied branches instead of the commits ahead, and leaves the workspace commit out of `commits` and `ahead`. The next-step hint suggests `but commit`, because [`grit commit`](https://grit-scm.com/docs/commit/index.md) refuses to commit there. ```console $ grit status On GitButler workspace · 2 branches applied · 3 behind origin/main login-form 4f2a9c1 qzvtyxkl Ada Lovelace 2 hours ago Validate the login form api-retries 9b3e0d2 mrnwkpst Ada Lovelace 1 day ago Retry failed API calls Nothing to commit — working tree clean. ``` `--json` describes the workspace in `gitbutler_workspace`. ### The target branch The target is the branch your work is compared against in the header line (`target`, `ahead`, and `behind` in JSON). It uses the first of these that exists: 1. the branch named in the `target.branch` config setting 2. `origin/master` 3. `origin/main` 4. `master` 5. `main` To compare against something else, set it for the repository: ```console $ grit config target.branch origin/develop ``` When the current branch has a configured upstream (`branch..remote` and `branch..merge`) that differs from the target, human output adds a second line (`↑n ↓m origin/topic`) and JSON includes an `upstream` object with the same counts relative to that tracking ref. When upstream and target resolve to the same ref, `upstream` is `null`. On Unix, explicit path operands must be valid UTF-8. An operand containing invalid UTF-8 bytes is rejected before the command runs, with exit status **2** and no changes to the repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout, and `--markdown` writes `**Error:**` on stdout. The argument is never replaced with a similar Unicode filename. Without a path filter, status still reports non-UTF-8 filenames using reversible `grit+pathhex:` encoding in JSON path fields, including untracked paths discovered via the index UNTR cache walk. ## Options | Flag | Description | | ---- | ----------- | | `--untracked ` | How untracked paths are listed: `normal` (default) shows untracked files and collapses wholly untracked directories to a single directory entry; `all` lists every untracked file; `no` omits untracked paths. When the flag is omitted, `status.showUntrackedFiles` from config is used (Git-compatible; defaults to `normal`). | | `--no-ahead-behind` | Skip ahead/behind rev-list walks; JSON sets `ahead`, `behind`, and upstream counts to `null`. Also skipped when `status.aheadBehind=false` in config. | | `PATH`… | Limit the report to paths matching these pathspecs (after `--`). Uses the same pathspec rules as [`grit add`](https://grit-scm.com/docs/add/index.md). | | `--pathspec-from-file ` | Read pathspecs from a file (`-` for stdin), in addition to any `PATH` arguments. | | `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated (requires `--pathspec-from-file`). | | `--ignored` | List ignored paths (traditional mode; same `!!` set as `git status --ignored --porcelain`). | | `-s`, `--short` | Compact one-line-per-path output for humans only (two-letter staged/unstaged codes; JSON unchanged). | From a subdirectory, short status uses cwd-relative paths; untracked directories keep a trailing slash (for example `?? ./` inside an untracked folder, or `?? ../other/` for a sibling directory). Rename detection is on by default (Git’s `status.renames` / `diff.renames`; disable with `status.renames=false`). Human output shows renames as `old → new`; `--json` adds `old_path` on rename and copy entries. ### How changes are detected Like Git, `grit status` compares each tracked file's size and timestamps with what the index recorded, and reads a file only when they differ. A clean tree costs one file-system lookup per tracked file, whatever the file sizes or `core.filemode`. Files written in the same second as the index (right after `git clone`, a commit or a checkout) cannot be trusted by timestamp alone: status reads them once and saves the refreshed index, so later runs skip them. Like `git status`, it may therefore rewrite `.git/index`; only the cached file information changes, never what is staged. A changed size alone counts as a change only when nothing converts the file on the way into the repository. When a line-ending setting (`core.autocrlf`, `text`, `eol`), a clean filter, `working-tree-encoding` or `ident` applies, status reads the file and decides by content. So a file rewritten with only different line endings, which cleans to the staged content, is clean, and its index entry is refreshed. `git status` may show such a file as ` M` until its index is refreshed, while `git diff` already shows nothing. Mode changes the checkout cannot express are not reported: with `core.filemode=false` the executable bit is ignored, and with `core.symlinks=false` a symlink checked out as a plain file holding its target is compared by content, so it shows up only when the target text changes. See also the [global options](https://grit-scm.com/docs/global-options/index.md). ## Examples A branch with work in progress: ```console $ grit On feature · 2 ahead of origin/main cf18394 ada 2 hours ago Say hi 9a1c2e0 ada 3 hours ago Add a greeting test Staged + new notes.md Changed (not staged) ~ modified main.rs Untracked ? untracked scratch.txt → grit add to stage · grit merge --continue to finish ``` Everything committed and pushed: ```console $ grit st On main · even with origin/main Nothing to commit — working tree clean. ``` Behind the target after a fetch: ```console $ grit status On main · 1 behind origin/main Nothing to commit — working tree clean. → grit pull to update from origin/main ``` On a local branch with no remote, when you are behind another local branch: ```console $ grit status On old · 1 behind main Nothing to commit — working tree clean. → grit merge main ``` Diverged from the target: ```console $ grit status On main · 1 ahead, 1 behind origin/main abc1234 you 1 hour ago Local work Nothing to commit — working tree clean. ``` Merge in progress with a conflict: ```console $ grit status On main · merging — resolve conflicts Staged ! conflict f Conflicts both modified (1) f → grit diff → grit add . ``` A rebase that `git` started, stopped on a conflict: ```console $ grit status Rebasing topic onto 3f1c2a9 Staged ! conflict f.txt Conflicts both modified (1) f.txt → grit diff · grit add . · git rebase --continue or grit rebase --abort ``` Check from a script whether the working tree is clean: ```console $ grit status --json --filter .clean true ``` List every untracked file (for staging scripts and agents): ```console $ grit status --untracked all --json --filter .untracked [ "docs/a.txt", "docs/b.txt", "plain.txt", "src/main.rs" ] ``` With the default `normal` mode, the same tree collapses directories: ```console $ grit status --json --filter .untracked [ "docs/", "plain.txt", "src/" ] ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/status/schemas/status/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `branch` | string or null | Current branch, or `null` when HEAD is detached. While a rebase is in progress (grit's or git's), the branch being rebased; `null` when the rebase started on a detached HEAD. | | `detached` | boolean | Whether HEAD is detached. | | `head` | string or null | Full id of the current commit, or `null` before the first commit. | | `target` | string or null | Target branch, or `null` when none was found. | | `ahead` | number or null | Commits on the branch that the target does not have; `null` when ahead/behind counts were skipped. | | `behind` | number or null | Commits on the target that the branch does not have; `null` when counts were skipped. | | `upstream` | object or null | When upstream tracking differs from `target`: `{ "ref", "ahead", "behind" }` (counts may be `null` when skipped). Always present; `null` when there is no separate upstream. | | `commits` | array | Newest of those commits, up to ten, each using the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape (including `change_id` and `change_id_stored`). | | `staged` | array | Staged changes with `path`, `status`, and optional `old_path` (renames/copies). | | `unstaged` | array | Unstaged changes with `path`, `status`, optional `old_path` (renames/copies), and optional `submodule` (`new_commits`, `modified`, `untracked`) on gitlink worktree changes. | | `untracked` | array | Untracked paths (raw UTF-8; JSON escapes control characters). With default `--untracked normal`, wholly untracked directories appear once (often with a trailing `/`); with `--untracked all`, every file path is listed. | | `embedded_repositories` | array | Untracked nested repositories that would be recorded as gitlinks if staged. Omitted when empty. Human and `--markdown` output print a one-line **note** on stderr for each path. A symlink (including one pointing at a repository directory) is an ordinary `120000` entry and is not listed here. | | `clean` | boolean | `true` when there is nothing to commit and nothing untracked. | | `merging` | boolean | **Deprecated.** Prefer `operation`. `true` when a merge is in progress (`MERGE_HEAD` exists). | | `in_progress` | array | **Deprecated.** Prefer `operation`. Stable operation ids while work is paused (for example `merge`, `rebase`). Omitted when empty. | | `conflicts` | array | Unmerged paths. Each item is `{ "path": "", "kind": "" }`, with a [conflict kind](#conflict-kinds). Omitted when empty. | | `operation` | object or null | Primary paused operation: `{ "kind", "next_steps", "alternatives" }`. `next_steps` is the ordered sequence; `alternatives` lists mutually exclusive options (for example `grit merge --abort`). Steps are `grit` commands, except `git rebase --continue` for a rebase that git started. Omitted when no operation is in progress. | | `ignored` | array | Ignored paths when `--ignored` was passed; omitted otherwise. | | `stash_count` | number | Entries on the stash reflog (`0` when empty). | | `interrupted_rewrite` | string | Recovery of a rebase or history edit that was killed after moving refs: `finished_checkout` (the rewrite stands), `rolled_back` (it was undone) or `pending` (another process holds `.git/index.lock`). Omitted when nothing was pending. | | `gitbutler_workspace` | object | Only on a [GitButler workspace](#gitbutler-workspaces): `commit` (the workspace commit, which `head` names and `commits` and `ahead` leave out) and `heads`, the merged branch tips in the workspace's parent order, each with `commit`, `branches` (local branches pointing there, sorted; empty when none), `subject` and `ahead` (commits not on `target`, or `null` when counts were skipped). Omitted otherwise. | | `warnings` | array | Non-fatal worktree access problems while scanning. Each item is `{ "kind", "message" }` (for example `worktree_access_failed` when a directory could not be opened). Omitted when empty. | | `worktree_case_collisions` | array | On case-insensitive volumes: tracked path groups that share one on-disk file and block staging (`[{ "paths": ["Readme.TXT", "readme.txt"] }, …]`). Omitted when empty. Human output prints the collision warning and suggests a case-sensitive volume or `grit reset --hard` instead of `grit add`. | | `shared` | object | Only on a [shared](https://grit-scm.com/docs/share/index.md) branch: `remote` (where the other members' heads were fetched from) and `heads`, the other members' heads, each with `user`, `tip`, `relation` to your branch (`same`, `ahead`, `behind`, `diverged` or `unknown`), and for a head that diverged from yours `divergence`: `scenario` (a stable code such as `amended_both_conflicting`; see [Divergence scenarios](https://grit-scm.com/docs/share/index.md#divergence-scenarios)), `summary`, `needs_decision`, `base`, `changes` (each commit's `change`, `subject`, and what `you` and `them` did to it), `conflicts` and `also`. Human output lists them under the branch line (`shared with bob, carol`); `--markdown` as a table. Omitted otherwise. | Example: ```json { "branch": "main", "detached": false, "head": "83352a61f6715ec3f0a297c6d6150725154fb833", "target": "main", "ahead": 0, "behind": 0, "upstream": null, "commits": [], "staged": [ { "path": "staged.txt", "status": "added" } ], "unstaged": [ { "path": "tracked.txt", "status": "modified" } ], "untracked": [ "untracked.txt" ], "clean": false, "merging": false, "stash_count": 0 } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/status/schemas/status/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for headed sections that mirror the status screen: ```text On **`feature`** · **2** ahead of `origin/main` - `cf18394` Say hi (ada, 1 hour ago) Staged - **new** `notes.md` Changed (not staged) - **modified** `main.rs` Untracked - `scratch.txt` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit shortlog](https://grit-scm.com/docs/shortlog/index.md), [grit diff](https://grit-scm.com/docs/diff/index.md), [grit add](https://grit-scm.com/docs/add/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md) # https://grit-scm.com/docs/config/index.md # grit config > Read, set, list or remove configuration values. ## Synopsis ```text grit config [] grit config [] grit config [] --unset grit config [] --unset-all grit config [] --add grit config [] --all grit config [] --list [] grit config [] --rename-section OLD --rename-section-new NEW grit config [] --remove-section NAME ``` `` is one of `--global`, `--local`, `--system`, `--worktree`, or `-f ` (mutually exclusive). ## Description Reads and writes Git configuration. `grit` uses the same config files as Git: the repository's `.git/config`, and your per-user `~/.gitconfig`. Settings you've made with Git apply to `grit`, and the other way around. With just a key, `grit config` prints its value. By default, reads use the full config cascade (system, global, local, then command-line overrides), with later layers winning. Writes go to the repository's local config (`.git/config`). Use `--global` or `-f` to read or write a different file instead. `--local` limits reads to the repository config only (writes already target that file). Keys are written as `section.name`, for example `user.email`. Path strings in human, `--json`, and `--markdown` output (the `file` field on reads and list entries) use forward slashes and no Windows `\\?\` verbatim prefix, matching other grit commands. ### Settings grit uses | Key | Used for | | --- | --- | | `user.name`, `user.email` | The author and committer of new commits. | | `target.branch` | The branch [`grit status`](https://grit-scm.com/docs/status/index.md) and [`grit shortlog`](https://grit-scm.com/docs/shortlog/index.md) compare against. | | `branch..remote` | Which remote [`grit push`](https://grit-scm.com/docs/push/index.md), [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) use for a branch. Defaults to `origin`. | | `branch..merge` | Which remote branch a branch pushes to and pulls from. Defaults to the same name. | | `credential.helper` | Where HTTPS credentials are stored and looked up. See [`grit auth`](https://grit-scm.com/docs/auth/index.md). | | `grit.githubClientId` | The GitHub OAuth app [`grit auth`](https://grit-scm.com/docs/auth/index.md) signs in with. | | `grit.changeIds` | When true (default), [`grit commit`](https://grit-scm.com/docs/commit/index.md) adds a `change-id` header to new commits and stores derived ids on amends when the old tip had none. | | `grit.testing.changeId` | Test-only: `content-hash` makes change ids deterministic from commit bytes; any other value is used verbatim. | | `receive.denyNonFastForwards` | Refuse pushes that would discard commits. Enforced on the remote for [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md), smart HTTP, and local-path [`grit push`](https://grit-scm.com/docs/push/index.md). | | `receive.denyDeletes` | Refuse pushes that delete branches or tags. Same enforcement as `receive.denyNonFastForwards`. | | `receive.denyCurrentBranch` | `refuse` (default) rejects pushes to the checked-out branch. `ignore` / `false` allow the ref to move without updating the worktree. `warn` allows the update and may warn. `updateInstead` updates the worktree via the `push-to-checkout` hook or grit's built-in deploy (same checks as Git). Enforced by [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md), smart HTTP, and local-path [`grit push`](https://grit-scm.com/docs/push/index.md). | | `receive.denyDeleteCurrent` | Refuse pushes that delete the branch `HEAD` points at, bare repository or not. On by default; same enforcement as the other `receive.deny*` keys. | | `receive.fsckObjects`, `transfer.fsckObjects` | Refuse pushes that contain malformed commits, trees or tags. Tune single checks with `receive.fsck.` and `receive.fsck.skipList`. Enforced by [`grit receive-pack`](https://grit-scm.com/docs/receive-pack/index.md) and smart HTTP; local-path [`grit push`](https://grit-scm.com/docs/push/index.md) does not check objects. | ## Options | Option | Description | | --- | --- | | `` | The setting to read, set or remove. | | `` | The value to set. Omit it to read the current value. | | `--global` | Use your per-user config instead of the repository's. | | `--local` | Read or write only this repository's config file. Default for writes; optional for reads. | | `--system` | Read or write the system config file (`GIT_CONFIG_SYSTEM` or `/etc/gitconfig`). | | `--worktree` | Read or write `config.worktree` (requires `extensions.worktreeConfig` in the common config). | | `-f`, `--file ` | Read or write only the given config file (no repository required). | | `-l`, `--list` | List settings as `key=value`. Optional `` limits to canonical keys with that prefix. | | `--all` | Print every value for a multi-valued key (load order). | | `--add` | Append a value without replacing existing entries. | | `--unset` | Remove the last matching value for a key. | | `--unset-all` | Remove every value for a key. | | `--type bool\|int\|path` | Parse or canonicalize values like `git config --type`. | | `--default ` | When reading, use this value if the key is unset (before `--type` coercion). | | `--rename-section OLD` | Rename a section; requires `--rename-section-new NEW`. | | `--rename-section-new NEW` | New section name for `--rename-section`. | | `--remove-section NAME` | Delete a section and all of its keys. | | `--dry-run` | On writes, report what would change without modifying the config file. | ### Exit codes | Situation | Code | | --- | --- | | Success | `0` | | `get` when the key is not set | `1` (human mode prints nothing; `--json` still prints a `get` object with `"value": null`) | | Other errors (invalid key, not in a repository for `--local`, …) | `1` with an error message | Reading or removing a key that is not set in the chosen scope is an error for `--unset`; `get` treats a missing key as exit `1` without treating it as a command failure in `--json` mode. ## Examples Set your identity for every repository: ```console $ grit config --global user.name "Ada Lovelace" $ grit config --global user.email ada@example.com ``` Read a value: ```console $ grit config user.email ada@example.com ``` Use a different email address in one repository: ```console $ grit config user.email ada@work.example ``` Read only the repository file (ignore global overrides for keys set locally): ```console $ grit config --local user.email ada@work.example ``` Edit a standalone config file: ```console $ grit config -f ~/.gitconfig.user user.email ada@personal.example ``` List everything: ```console $ grit config --list user.name=Ada Lovelace user.email=ada@example.com core.repositoryformatversion=0 core.bare=false remote.origin.url=https://github.com/ada/project.git remote.origin.fetch=+refs/heads/*:refs/remotes/origin/* ``` Remove a setting: ```console $ grit config --unset target.branch ``` ## JSON output Schema: [v2](https://grit-scm.com/docs/config/schemas/config/v2.json/index.md) · [v1](https://grit-scm.com/docs/config/schemas/config/v1.json/index.md) Pass `--json` for stable, scripting-friendly output. The object's `action` field says what happened: | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | `get`, `get_all`, `set`, `add`, `unset`, `unset_all`, `list`, `rename_section`, or `remove_section`. | | `key` | string | Configuration key for `get`, `set`, or `unset`. | | `value` | string or `null` | Value for `get` or `set`. `null` when `get` did not find the key (exit `1`). | | `scope` | string or `null` | For `get`, which layer won (`system`, `global`, `local`, `worktree`, `command`). | | `file` | string or `null` | For `get`, source path when file-backed. | | `line` | integer or `null` | For `get`, one-based line number in `file`. | | `entries` | array | For `list`, each entry with `key`, optional `value`, `scope`, and optional `file`. | | `values` | array | For `get_all`, each `{ value, scope, file?, line? }`. | | `dry_run` | boolean | Present on write actions when `--dry-run` was used. | | `preview` | string | Human summary of the pending change when `dry_run` is true. | | `removed` | integer | For `unset_all`, number of values removed. | | `old_name` | string | For `rename_section`, the previous section name. | | `new_name` | string | For `rename_section`, the new section name. | | `section` | string | For `remove_section`, the section that was removed. | Reading a value: ```json { "action": "get", "key": "user.name", "value": "Ada Lovelace", "scope": "global", "file": "/home/ada/.gitconfig", "line": 2 } ``` Missing key: ```json { "action": "get", "key": "missing.key", "value": null, "scope": null, "file": null, "line": null } ``` Listing values: ```json { "action": "list", "entries": [ { "key": "user.name", "value": "Ada Lovelace", "scope": "global", "file": "/home/ada/.gitconfig" } ] } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v2](https://grit-scm.com/docs/config/schemas/config/v2.json/index.md) · [v1](https://grit-scm.com/docs/config/schemas/config/v1.json/index.md) For `get`, markdown includes the value (when set) plus scope, file, and line. See the JSON output section for the stable field contract. ```text | Key | Value | | --- | --- | | `core.repositoryformatversion` | 0 | | `core.filemode` | true | | `core.bare` | false | | `core.logallrefupdates` | true | | `user.email` | snap@example.com | | `gc.auto` | 0 | | `maintenance.auto` | false | | `grit.testing.changeid` | content-hash | ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit auth](https://grit-scm.com/docs/auth/index.md), [grit status](https://grit-scm.com/docs/status/index.md) # https://grit-scm.com/docs/add/index.md # grit add > Stage changes. With no paths, stages everything. ## Synopsis ```text grit add [-u | --update] [--dry-run] [--hunks ] [--lines ] [-U | --unified ] [--patch-file ] [--executable | --non-executable] [--pathspec-from-file ] [--pathspec-file-nul] [...] ``` ## Description Stages changes so they show up under **Staged** in [`grit status`](https://grit-scm.com/docs/status/index.md). Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). With no paths, `grit add` stages everything `grit status` reports: modified files, deleted files and untracked files. A tracked file replaced by a directory, or a tracked directory replaced by a file, is staged the way Git does it: the old path as a deletion and the new files as additions. With paths, it stages only those files, or everything under those directories. Paths are relative to your current directory, so from inside `src/`, `grit add main.rs` stages `src/main.rs`. Paths like `../README.md` and absolute paths inside the repository work too. Attribute pathspecs such as `:(attr:myattr)` stage every matching path under the same `.gitattributes` rules as [`grit diff`](https://grit-scm.com/docs/diff/index.md) and [`grit status`](https://grit-scm.com/docs/status/index.md). A path that matches nothing is an error, and nothing is staged. A path that crosses a symlinked directory (for example `link/file` when `link` is a symlink) is an error: nothing is staged. Naming a path that exists but is excluded by `.gitignore`, `.git/info/exclude`, or `core.excludesfile` is also an error: nothing is staged and the command lists the ignored paths (pathless `grit add` still skips ignored files silently, like Git). With `core.ignorecase=true`, ignore patterns match without regard to case (see [`grit ignore`](https://grit-scm.com/docs/add/ignore.md/index.md)). On a case-folding work tree (typical macOS and Windows volumes), `grit add` keeps the spelling already recorded in the index and stores new paths under those directory names; rename a path's case only with [`grit mv`](https://grit-scm.com/docs/add/mv.md/index.md). Explicitly staging an **unmerged** path fails while Git-style conflict markers remain in the worktree file (the same rule as [`grit commit`](https://grit-scm.com/docs/commit/index.md) auto-staging); remove the markers or use a resolved file, then run `grit add` again. When a broad pathspec (for example `grit add .` after a merge) matches both resolved and still-marked unmerged files, Grit stages every path it can and exits with status **1**, naming each remaining conflict (`path: conflict markers remain; not staged`). Git may stage marker-bearing files in the same situation; Grit refuses to record conflict markers in the index. Files with a `filter=` attribute (Git LFS, for example) are staged through the driver's clean filter, which runs through `sh` the way Git runs it. On Windows that is the `sh` bundled with Git for Windows, so you don't need it on `PATH`. If the driver sets `filter..required=true` and the filter fails or cannot be started, `grit add` fails, says why, and stages nothing. It never stores the unfiltered file. When an optional filter fails, the file is staged unfiltered, as Git does. Files of at least `core.bigFileThreshold` bytes (512 MiB unless configured; `k`, `m` and `g` suffixes work) are hashed and compressed as a stream straight into their own pack, as Git does, so staging a multi-gigabyte file takes a few megabytes of memory. This applies to [`grit commit`](https://grit-scm.com/docs/commit/index.md) auto-staging and to the re-hash `grit status` does after a big file's timestamp changes, too. A file that needs a clean filter, `working-tree-encoding` or line-ending conversion is read into memory whatever its size. On filesystems where Grit sets `core.filemode=false` (typical on Windows), every new file is staged as non-executable (`100644`) even when it is a script. Use `--executable` on the paths you ship as runnable scripts so the index and commits record mode `100755`. Use `--non-executable` to clear an explicit executable bit in the index. These flags require at least one path argument. [`grit commit`](https://grit-scm.com/docs/commit/index.md) stages every change before it records a commit, so you don't need `grit add` to commit. It's useful for starting to track a new file and checking what will be committed. Copying or cloning another Git repository into your tree (a directory that contains its own `.git`) is recorded as a **gitlink** (mode `160000`), not as ordinary files. Clones of your repository get an empty directory at that path. When `grit add` newly records such a path, human and `--markdown` output print a **warning** on stderr; `--json` includes `embedded_gitlinks` (omitted when empty). Remove `/.git` and stage again if you meant to vendor the files inside. A symlink (including one aimed at a repository directory) is staged as mode `120000` and does not trigger this warning. Touching a tracked file's timestamp without changing its bytes or mode is not a stage: `grit add` refreshes the index stat cache silently (same as Git) and reports nothing to stage. A directory that contains an embedded git repository (for example after `git init` inside the tree, or `cargo new` in a subdirectory) is staged as a **gitlink** (mode `160000`) when that nested repository has at least one commit checked out on its current branch. When the nested repository has **no commits yet**, `grit add` refuses with `embedded_repo_without_commit`, leaves the index unchanged, and does not record the path as a regular file. On Unix, explicit path operands must be valid UTF-8. An operand containing invalid UTF-8 bytes is rejected before the command runs, with exit status **2** and no changes to the repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout, and `--markdown` writes `**Error:**` on stdout. The argument is never replaced with a similar Unicode filename. On an interactive terminal (human output, not `--json` or `--markdown`), a live **Staging** line on stderr counts the files hashed into the index; nothing is drawn when stderr is not a TTY. ## Options | Option | Description | | --- | --- | | `...` | Files or directories to stage. Omit to stage every change. | | `-u`, `--update` | Stage tracked changes only (modified and deleted paths). Untracked files are left alone. With no paths, applies to the whole tree. | | `--dry-run` | List paths that would be staged without updating the index or writing objects. | | `--hunks` | Stage only the listed hunk ids from `grit diff --json` (`hunks[].id`). Comma-separated ids; pass the flag again to add more. Optional `-- paths` narrow the diff scan. Cannot be combined with `--patch-file`, `-u` / `--update`, or `-N` / `--intent-to-add`. | | `--lines` | Stage only new-side line ranges from `grit diff --json` (`lines[].new`). Use `path:start-end` or `path:line` (1-based, inclusive); comma-separate or repeat the flag. Mix with `--hunks`. Same restrictions as `--hunks`. | | `-U`, `--unified` | With `--hunks` only: unified context lines for hunk boundaries (same meaning as `grit diff -U`; default 3 when omitted). Use the same value as the diff that produced the ids. | | `--patch-file` | Apply a unified diff to the index only (like `git apply --cached`). Use `-` for stdin. Cannot be combined with `--hunks`, paths, `-u` / `--update`, or `-N` / `--intent-to-add`. | | `-N`, `--intent-to-add` | Record intent-to-add entries (empty blob, extended flag) instead of hashing content. | | `-f`, `--force` | Stage ignored paths when named explicitly (instead of erroring with pathspec ignored). | | `--pathspec-from-file` | Read additional pathspecs from a file, or `-` for stdin (same rules as Git). | | `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. | | `--executable` | Stage listed regular files with mode `100755` in the index (requires at least one path). | | `--non-executable` | Stage listed regular files with mode `100644` in the index (requires at least one path). | ## Examples Stage everything: ```console $ grit add Staged 3 changes. ``` Stage one file and a directory: ```console $ grit add README.md src/ Staged 2 changes. ``` Apply a patch to the index (worktree files stay as-is until you edit them): ```console $ grit add --patch-file changes.diff Staged 1 change. ``` Stage selected hunks by stable id (from `grit diff --json`): ```console $ grit diff --unstaged --json -- f.txt | jq -r '.files[0].hunks[0].id' a1b2c3d4e5f6 $ grit add --hunks a1b2c3d4e5f6 -- f.txt Staged 1 change. ``` Stage a line range within one hunk: ```console $ grit add --lines f.txt:10-15 -- f.txt Staged 1 change. ``` ## JSON output Schema: [v2](https://grit-scm.com/docs/add/schemas/add/v2.json/index.md) · [v1](https://grit-scm.com/docs/add/schemas/add/v1.json/index.md) Pass `--json` for stable, scripting-friendly output. | Field | Type | Meaning | | ----- | ---- | ------- | | `added` | array | Newly staged paths. | | `modified` | array | Staged modifications. | | `removed` | array | Staged deletions. | | `intent_to_add` | array | Paths recorded with intent-to-add. | | `dry_run` | boolean | Whether the index was left unchanged. | | `count` | number | Total paths touched. | | `staged` | number | Same as `count` for successful staging. | | `staged_hunks` | object | Path → hunk ids when `--hunks` staged something (empty object when unused). | | `staged_lines` | object | Path → line ranges when `--lines` staged something (empty object when unused). | | `embedded_gitlinks` | array | Nested repositories newly recorded as gitlinks. Omitted when empty. | | `worktree_case_collisions` | array | Case-insensitive path groups that block staging (`[{ "paths": [...] }, …]`). Omitted when empty. | ```json { "added": ["src/new.rs"], "modified": ["README.md"], "removed": [], "intent_to_add": [], "dry_run": false, "count": 2, "staged": 2, "staged_hunks": {}, "staged_lines": {}, "embedded_gitlinks": ["vendor-hello"] } ``` When `--hunks` or `--lines` staged something, `staged_hunks` or `staged_lines` maps path → ids or ranges; otherwise those fields are empty objects. Grit computes blob object ids with the same plain SHA-1 digests as Git. SHAttered test vectors (for example blobs in the `git/git` history) stage and commit normally; grit does not reject them during ingestion. ## Markdown output Schema: [v2](https://grit-scm.com/docs/add/schemas/add/v2.json/index.md) · [v1](https://grit-scm.com/docs/add/schemas/add/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for an `Add` heading and how many paths were staged: ```text - Staged **1** change ``` When there is nothing to stage and you ran `grit add` with no paths: ```text Nothing to stage — working tree clean. ``` On a case-insensitive volume, when tracked paths collide (for example `Readme.TXT` and `readme.txt` sharing one file), `grit add` with no paths does **not** print “working tree clean”. Human and `--markdown` output show the same path-collision warning as [`grit switch`](https://grit-scm.com/docs/add/switch.md/index.md) and a hint to use a case-sensitive volume or [`grit reset --hard`](https://grit-scm.com/docs/add/reset.md/index.md). `--json` includes `worktree_case_collisions` (`[{ "paths": [...] }, …]`) when any group blocks staging. ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | `grit add` reads and writes the index while holding `.git/index.lock`, so parallel `grit add` (or `git add`) runs in one repository never undo each other: every run that exits `0` has its paths in the index. A run that cannot get the lock within `core.filesRefLockTimeout` (default 100 ms; `-1` waits forever) exits `1` with an `index.lock` error and stages nothing, so a script can simply retry it. `grit rm` follows the same rule. With `--json`, a held index lock returns `kind: "lock_held"` and `lock.path`. When a PID sidecar exists, `lock.holder.pid` identifies the recorded process and `lock.holder.running` reports whether it was running when checked. Grit leaves both files alone. Retry after the owner finishes, or remove a stale lock after checking that no writer is running. ```json {"error":"another process holds /work/repo/.git/index.lock; if none is running, remove the stale lock and retry","kind":"lock_held","lock":{"path":"/work/repo/.git/index.lock"}} ``` See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit status](https://grit-scm.com/docs/status/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md) # https://grit-scm.com/docs/commit/index.md # grit commit > Stage every change and record a new commit. ## Synopsis ```text grit commit [-a] grit commit [-a] -m grit commit --staged -m grit commit -m -- […] grit commit -F grit commit --author "Name " grit commit --no-verify -m grit commit --dry-run -m grit commit -q -m grit commit --allow-empty -m grit commit --amend [-m ] grit commit --hunks -m [-- …] grit commit --patch-file -m ``` ## Description By default, `grit commit` **auto-stages** every change in the working tree (modified, deleted and untracked files) and records a new commit on the current branch. When `status.showUntrackedFiles` is `no` (or a Git boolean false synonym such as `false` or `0`), auto-staging matches `git commit -a`: only tracked modifications and deletions are staged, and untracked paths hidden from [`grit status`](https://grit-scm.com/docs/commit/status.md/index.md) are not added. `normal`, `all`, and the default when the key is unset still auto-stage untracked files. `-a` / `--all` follows the same rule. Auto-staging refuses an embedded git repository that has no commit checked out (same rule as [`grit add`](https://grit-scm.com/docs/commit/add.md/index.md)); the commit is not created and the index is left unchanged. When auto-staging newly records a nested repository as a gitlink, grit prints the same **warning** as [`grit add`](https://grit-scm.com/docs/commit/add.md/index.md) on stderr (human and `--markdown`); `--json` includes `embedded_gitlinks` for paths introduced in that staging pass only (not when the gitlink was already in the index). Paths it cannot access because a directory is unreadable are left as-is in the index (with a `warning:` on stderr, same as [`grit status`](https://grit-scm.com/docs/commit/status.md/index.md)); other staged changes still commit. With `core.ignorecase=true` on a case-folding volume, auto-staging keeps indexed path spellings (same as [`grit add`](https://grit-scm.com/docs/commit/add.md/index.md)) and does not rewrite either spelling of a case-colliding path when the shared on-disk file already matches one of the indexed blobs (including directory-name collisions such as `Docs/` vs `docs/`); use [`grit mv`](https://grit-scm.com/docs/commit/mv.md/index.md) to change a path's case on purpose. On a [GitButler workspace](https://grit-scm.com/docs/status/index.md#gitbutler-workspaces), `grit commit` refuses (exit **1**, `kind: "gitbutler_workspace"`) and changes nothing, because GitButler rewrites the `gitbutler/workspace` branch and would lose the commit. Commit with `but commit`, or switch to a branch first. Use **`--staged`** to commit the index as-is without auto-staging (Git’s `git commit` without `-a`). Use **`-a` / `--all`** to force auto-staging even when `commit.autoStage=false`. Use **trailing paths** (`grit commit -m msg -- a b`) or **`--pathspec-from-file`** to commit only those paths from the worktree while leaving other staged changes in the index (Git’s `git commit --only --` paths). Partial path commits are refused while a merge, cherry-pick, or revert is in progress. Use **`--hunks`** with stable ids from [`grit diff --json`](https://grit-scm.com/docs/diff/index.md) to stage and commit only selected unstaged hunks in one step (like `git apply --cached` on those hunks, then commit). Optional **`-- paths`** narrow the diff scan the same way as [`grit add --hunks`](https://grit-scm.com/docs/add/index.md). Use **`--patch-file`** to apply a unified diff to the index and commit the result (`-` reads stdin). These modes do not auto-stage the rest of the worktree (same effective scope as **`--staged`**). They cannot be combined with `-a` / `--all`, **`--staged`**, or path-only commits. **`--lines`** follows the same rules as `grit add --lines` when that flag is available. The message can be given as an argument, with `-m`, or with `-F` / `--message-file` (`-` reads stdin). Messages may start with `-` when quoted on the shell (for example `grit commit -m "-fix typo"`) or passed via `--message=-fix typo`. A positional message that starts with `-` must contain whitespace (`grit commit "-fix typo"`): a single hyphen-leading word such as `-q`, `--bogus` or `--opt=value` is treated as an unknown flag and rejected with exit status `2` before anything is staged or committed, so a misspelled or unsupported flag never becomes the commit message. Pass such a message with `-m` (`grit commit -m --bogus`). Message text is normalized with Git-style stripspace before hooks run (leading/trailing blank lines collapse; a trailing newline is added). A message with several lines is recorded as is after normalization; its first line is the subject that [`grit log`](https://grit-scm.com/docs/log/index.md) shows. A normal commit needs a message: without one, `grit commit` stops with an error and does not change the index or working tree. You cannot combine `-m`, a positional message, and `--message-file`. Use **`--dry-run`** to preview what would be committed: path list, parents, and author, without writing objects, updating refs, running hooks, or changing the index on disk. The preview includes executable-bit-only changes the same way the commit does, and lists modified or deleted files whose names are not valid UTF-8 under the same stored paths as the commit's `files`. Dry-run returns the same errors as a real commit for nothing-to-commit and unmerged index. A commit either completes or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while the index is being updated or files are being checked out stops the commit with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the command started, no `.git/index.lock` is left behind, and the same commit can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. Auto-staging may leave unreachable loose blobs in the object database if you interrupt mid-write; they are harmless. In the rare case that a path cannot be put back during checkout rollback, the error has kind `checkout_incomplete` and lists those paths in `paths`. With `--amend`, `grit commit` replaces the **tip** commit on the current branch instead of adding a new one. It does not reword or squash older commits; positional arguments are always the commit message, not a revision (for example `grit commit --amend HEAD~1` records the message `HEAD~1`, it does not amend that commit). The new commit keeps the previous tip's parents and author; the committer and commit time come from your identity and `GIT_COMMITTER_DATE` as usual. If you omit the message while amending, the previous commit message is reused. Amending with no staged changes is allowed when the tree is unchanged (Git-compatible). You cannot amend on a branch that has no commits yet. The author and committer come from `user.name` and `user.email` (see [`grit config`](https://grit-scm.com/docs/config/index.md)), or from `GIT_AUTHOR_NAME` / `GIT_AUTHOR_EMAIL` and `GIT_COMMITTER_NAME` / `GIT_COMMITTER_EMAIL`. Use `--author "Name "` (or a bare email) to override the author for one commit; the committer line still comes from your committer identity. If none of those are set and no repo or global `user.email` is configured, `grit commit` fails with an identity error instead of inventing an address (the same sources Git uses before it refuses with “unable to auto-detect email address”). Set identity once with: ```console $ grit config --global user.name "Your Name" $ grit config --global user.email "you@example.com" ``` To set the recorded time, use the `GIT_AUTHOR_DATE` and `GIT_COMMITTER_DATE` environment variables, or pass `--date` for the author timestamp on this commit (Git date formats, RFC 3339, `@epoch`, and the same loose strings Git accepts). On amend, the author line is taken from the commit being replaced unless you pass `--author` or `--reset-author`. Repeat `--trailer key=value` (or `key: value`) to append trailers the same way `git interpret-trailers` would. `-s` / `--signoff` adds a `Signed-off-by` line for the committer. `--reset-author` sets the author to the committer with a fresh author date (also when amending). `-C` / `--reuse-message ` reuses that commit's message and author; it is a copy and gets a new change id. `-S` / `--gpg-sign` and `--no-gpg-sign` override `commit.gpgsign` for one commit. When `commit.gpgsign` is true (or `commit.gpgSign`), `grit commit` signs the new commit object the same way Git does: OpenPGP and X.509 via your configured `gpg`/`gpgsm` program, or SSH via `ssh-keygen -Y sign` when `gpg.format` is `ssh`. Signing uses `user.signingkey` and the same `gpg.*` settings Git reads. [`grit merge`](https://grit-scm.com/docs/merge/index.md) and [`grit pick`](https://grit-scm.com/docs/pick/index.md) honor the same policy when they create commits. `grit commit` fails when there's nothing to commit (except when amending with an unchanged tree, or when you pass `--allow-empty`), when no message is provided (for a normal commit), and when the index still has **unmerged** paths after staging (for example when a merge conflict is not fully resolved in the working tree). With **`commit.autoStage=false`** or **`--staged`**, an empty index while the work tree still has changes is **`nothing staged to commit`** (not “working tree clean”): human output names how many files are unstaged or untracked and suggests `grit add` or `grit commit -- `. With **`--json`**, `kind` is `nothing_staged` (dirty work tree, nothing staged) or `nothing_to_commit` (genuinely clean). On a case-insensitive volume, when tracked paths such as `Readme.TXT` and `readme.txt` share one on-disk file and cannot be staged, commit fails with **`kind` `worktree_case_collision`** (library [`CommitError::WorktreeCaseCollision`](https://grit-scm.com/docs/library/index.md)) instead of `nothing_staged` or `nothing_to_commit`; human and `--markdown` output name the colliding paths and suggest a case-sensitive volume or [`grit reset --hard`](https://grit-scm.com/docs/commit/reset.md/index.md)—not `grit add`. Auto-staging does **not** treat a conflicted file as resolved while Git-style conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) remain in the worktree copy — edit the file to remove them, then run `grit commit` again. The same check applies when a file's conflict stages were dropped without editing it (for example by `git restore --staged` after a merge, pick, revert, rebase or `stash pop`): the commit fails with `kind` `unmerged_paths`, names the file, and leaves the index, `HEAD` and any operation state untouched, so `--abort` still works. Marker text that is already in the committed version of the file (for example an example in documentation) is not refused, but any new conflict block next to it is. Validation failures such as a missing message or empty message leave the index and working tree unchanged. When auto-staging finds changes that cancel out against `HEAD` (for example a new file that was staged and then deleted, or a staged edit that was reverted in the working tree), `grit commit` still records the staged index before reporting nothing to commit, so the index matches `HEAD` and `git status` is clean afterward; `--dry-run` never writes the index. On a **detached HEAD** (for example after [`grit switch --detach`](https://grit-scm.com/docs/switch/index.md)), `grit commit` records a new commit and moves `HEAD` to it without updating any branch — the same as `git commit` in that state. Use [`grit switch -c `](https://grit-scm.com/docs/switch/index.md) afterward to name the branch if you want to keep the work. With `--json`, a detached-HEAD commit reports `"branch": null` and `"detached": true`. A failed commit (missing message, nothing to commit) does not advance `HEAD` or stage your working tree on detached HEAD, the same as on a branch. Auto-staging records the modes Git would. With `core.symlinks=false` (common on Windows, where Git and Grit check symlinks out as plain files holding the link target), a symlink stays a symlink (`120000`): an untouched link is not part of the commit, and editing the file stages the new link target. With `core.filemode=false`, a tracked file keeps the executable bit the index already has. Symlinks to files, directories and missing paths are staged as link-target bytes, without clean filters or line-ending conversion. `--dry-run` uses the same comparison in serial and parallel scans: an unchanged tree returns `nothing_to_commit` under `--json`, and retargeted links appear in the preview just as they will in the commit. Preview leaves the index, refs and stored objects unchanged. With `--allow-empty`, grit records a new commit whose tree matches the parent even when the working tree is clean (staging still runs first, the same as any other commit). Use this to mark a point in history (for example to trigger CI) without changing files. The resulting commit is valid for Git the same way as `git commit --allow-empty`. When a merge is in progress (`MERGE_HEAD` is present) and every conflict is resolved in the index, `grit commit` records a **merge commit** with two parents (your branch tip and the merged tip) and clears merge state the same way Git does after `git commit`. When a cherry-pick or revert is paused (`CHERRY_PICK_HEAD` or `REVERT_HEAD`) and conflicts are resolved, `grit commit` finishes the current step the same way `git commit` does during `git cherry-pick`: it keeps the picked commit’s **author** and **author date** (revert keeps the committer as author), uses `MERGE_MSG` when you omit `-m`, clears replay state, and writes a reflog entry `commit (cherry-pick): …` for picks. Auto-staging applies as usual; you do not need `grit pick --continue` after a resolving commit unless more steps remain in a multi-commit sequence. During a **rebase conflict stop** (grit-owned `.git/rebase-merge/` with `grit-plan`), a resolving `grit commit` records the replayed pick on the detached replay parent: it keeps that commit’s **author**, **change id**, and `MERGE_MSG` when you omit `-m`, and leaves the rebase session in place so `grit rebase --continue` replays only the remaining commits. `pre-commit`, `prepare-commit-msg` and `commit-msg` hooks run, in that order, before the commit object is written when they are installed (config `hook.*` entries or scripts under the hooks directory). `prepare-commit-msg` gets `.git/COMMIT_EDITMSG` and where the message came from: `message` for `-m`, `-F` or the argument, `commit ` when `--amend` or a reused message keeps a commit's message, `merge` when finishing a merge with its `MERGE_MSG`, and `squash` after `grit merge --squash`. Both message hooks may edit the file, and the commit records what they leave. Pass `--no-verify` to skip `pre-commit` and `commit-msg`; `prepare-commit-msg` and `post-commit` still run, matching Git. A `pre-commit`, `prepare-commit-msg` or `commit-msg` hook that exits non-zero or cannot be started aborts the commit, and the error names the hook and its exit status (or the OS error). The index and working tree stay as they were before the attempt (including a deliberate staged/unstaged split on the same file and untracked paths not yet in the index). In human mode the hook's output appears on stderr as it runs, followed by the error. With `--json` the failure is a structured error with `kind: "hook_failed"` and a `hook` object carrying `name`, `status`, and the hook's captured `stdout` and `stderr`; `--markdown` prints the error followed by the captured output in `text` blocks. `post-commit` never changes the result: the commit is already written, so a non-zero exit is ignored, and a hook that cannot be started prints a warning on stderr (`hook_not_run`). With `--amend`, grit then runs `post-rewrite amend` with ` ` on stdin, as Git does (library callers can skip it with `CommitRequest::post_rewrite`); like `post-commit`, its outcome never changes the result. Dry-run skips all hooks. See [`grit hooks`](https://grit-scm.com/docs/commit/hooks.md/index.md). After a successful commit (not `--dry-run`), grit checks `gc.auto` and `gc.autoPackLimit` like `git commit` does and, once loose objects or packs pile up, starts background maintenance with one stderr line in human mode. See [Automatic maintenance](https://grit-scm.com/docs/commit/gc.md/index.md#automatic-maintenance). For a `pre-commit` hook that prints a line on each stream and exits 1, `grit commit --json` prints (exit status 1): ```json { "error": "hook pre-commit failed with exit status 1", "kind": "hook_failed", "hook": { "name": "pre-commit", "status": 1, "stdout": "stdout from hook\n", "stderr": "lint failed: bad stuff\n" } } ``` ### Change ids Every commit `grit commit` creates gets a `change-id` header (reverse-hex by default) that stays with the same logical change across amends. Commits created without the header still have a deterministic id derived from the commit object id (Jujutsu-compatible); amending such a commit stores that derived value. Set `grit.changeIds=false` to omit the header (Git byte-identical commits for tests or importers that reject extra headers). See [Change ids](https://grit-scm.com/docs/library/change-ids/index.md) for policy, testing knobs, and library APIs. On an interactive terminal (human output, not `--json`, `--markdown` or `-q`), a live **Staging** line on stderr counts the files auto-staged before the commit; nothing is drawn when stderr is not a TTY. ## Options | Option | Description | | --- | --- | | `` | The commit message. A single hyphen-leading word is rejected as an unknown flag; use `-m` for it. | | `-q`, `--quiet` | Print nothing on success in human mode. `--json` and `--markdown` output is unchanged; errors still go to stderr. | | `-m`, `--message ` | The commit message, as an option (repeatable; each `-m` starts a new paragraph separated by a blank line, like Git). Do not combine with `-F` / `--message-file` or a positional message. Optional with `--amend` (keeps the previous message when omitted). | | `-F`, `--message-file ` | Read the commit message from a file, or from stdin when the path is `-`. | | `--author ` | Author for this commit (`Name ` or bare email). Committer unchanged. | | `--no-verify` | Skip `pre-commit` and `commit-msg` hooks (`prepare-commit-msg` still runs). | | `--dry-run` | Preview the commit; no objects, refs, hooks, or on-disk index changes. | | `-a`, `--all` | Stage every change first, then commit. Conflicts with `--staged` and path arguments. | | `--staged` | Commit only what is already in the index (no auto-stage). Conflicts with `-a` and path arguments. | | `--hunks` | Commit only listed hunk ids from `grit diff --json` (comma-separated, repeatable). Optional `-- paths` narrow the diff scan. Conflicts with `--patch-file`, `--lines`, `-a`, and `--staged`. | | `--patch-file` | Apply a unified diff to the index, then commit (`-` for stdin). Conflicts with `--hunks`, `--lines`, `-a`, and `--staged`. | | `--lines` | Commit only line ranges from the unstaged diff (same format as [`grit add --lines`](https://grit-scm.com/docs/add/index.md)). Mix with `--hunks`. Optional `-- paths`. Conflicts with `--patch-file`, `-a`, and `--staged`. | | `--pathspec-from-file`, `--pathspec-file-nul` | Same as on [`grit add`](https://grit-scm.com/docs/add/index.md): read pathspecs from a file; combine with trailing `PATH` arguments. | | `--amend` | Replace the tip commit on the current branch. | | `--allow-empty` | Record a commit even when staged content matches the parent tree (empty tree change). | | `--dry-run` | Stage in memory and list the files the commit would change, without writing objects, the index or refs, or running hooks. | | `-F`, `--message-file ` | Read the commit message from a file; use `-` for stdin (same body rules as `-m`). | | `--author ` | Override the author line (`Name `); committer identity is unchanged unless you also set `GIT_COMMITTER_*`. | | `--no-verify` | Skip `pre-commit` and `commit-msg` hooks; `prepare-commit-msg` and `post-commit` still run on a real commit. | ## Examples Commit everything: ```console $ grit commit "Add the greeting" [main 217c6f9] Add the greeting 2 changes committed ``` Preview before committing: ```console $ grit commit --dry-run -m "Add the greeting" Would commit 2 files M README A src/main.rs ``` The same, written the way you'd write it for `git`: ```console $ grit commit -am "Add the greeting" ``` A longer message with a body: ```console $ grit commit -m "Add the greeting Prints hi on startup so we know the binary runs." ``` Amend the latest commit after fixing staged files: ```console $ grit commit --amend -m "Add the greeting (fixed typo)" ``` Record an empty commit on a clean tree: ```console $ grit commit --allow-empty -m "Trigger CI" [main a1b2c3d] Trigger CI 0 changes committed ``` Commit only staged paths when another file is staged but should not be in this commit: ```console $ grit add baz $ grit commit -m "file only" -- file ``` Commit the index without auto-staging (with `commit.autoStage=true`, or always with `--staged`): ```console $ grit add a.txt $ grit commit --staged -m "index only" ``` ## JSON output Schema: [v2](https://grit-scm.com/docs/commit/schemas/commit/v2.json/index.md) · [v1](https://grit-scm.com/docs/commit/schemas/commit/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `oid` | string or omitted | Full commit object id; omitted when `dry_run` is true | | `branch` | string or null | Short name of the branch the commit advanced (e.g. `main`); `null` on a detached `HEAD` | | `detached` | boolean | `true` when the commit was made on a detached `HEAD` (only `HEAD` moved) | | `subject` | string | First line of the commit message | | `changes` | number | Path changes vs the parent commit tree | | `amended` | boolean | `true` when `--amend` was used | | `dry_run` | boolean | `true` when `--dry-run` was used | | `scope` | string | `auto_stage`, `staged`, `paths`, or `patch` — how the index was prepared | | `dry_run` | boolean | `true` when `--dry-run` was passed | | `files` | array | Path-level changes (`path`, `status`, optional `old_path` for renames). Each `path` uses the same stored encoding as [`grit status`](https://grit-scm.com/docs/commit/status.md/index.md) JSON (UTF-8 when valid, else `grit+pathhex:`). | | `change_id` | string or null | Stored `change-id` header on the new commit, or null when absent or dry-run (see [Change ids](https://grit-scm.com/docs/library/change-ids/index.md)) | | `parents` | array of strings | Parent commit OIDs that would be stored | | `author` | object | `name`, `email`, and `date` (RFC 3339, same shape as [`grit log`](https://grit-scm.com/docs/log/index.md) / [`grit show`](https://grit-scm.com/docs/show/index.md)) | | `hooks_run` | array of strings | Hook names that ran, in order (`pre-commit`, `prepare-commit-msg`, `commit-msg`, `post-commit`, and `post-rewrite` after `--amend`); empty on dry-run | | `embedded_gitlinks` | array | Nested repositories newly recorded as gitlinks during auto-staging for this commit. Omitted when empty. | Example: ```json { "oid": "92501f188ae0815af09a0cef6e121eddda4113cf", "branch": "main", "detached": false, "subject": "second", "changes": 1, "amended": false, "dry_run": false, "scope": "auto_stage", "files": [{ "path": "b.txt", "status": "M" }], "change_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", "parents": ["abc123…"], "author": { "name": "Your Name", "email": "you@example.com", "date": "2023-11-14T22:13:20Z" }, "hooks_run": ["pre-commit", "post-commit"] } ``` Human output includes a `hooks:` line only when at least one hook ran. Preview a commit without writing (message required): ```console $ grit commit --dry-run -m "preview" ``` Read the message from stdin (agents): ```console $ printf '%s\n' "Subject line" "" "Body." | grit commit --staged -F - ``` ## Markdown output Schema: [v2](https://grit-scm.com/docs/commit/schemas/commit/v2.json/index.md) · [v1](https://grit-scm.com/docs/commit/schemas/commit/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Commit` heading, branch and commit summary, and change count: ```text - **`main`** · `9244cbd` — third - **3** changes committed ``` With `--amend`, the first bullet notes the amended branch tip: ```text - Amended **`main`** at `2fb4e89` — third (amended) - **3** changes committed ``` With `--dry-run`, output lists the paths that would be committed instead of a new OID. ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | An unknown flag is a usage error even when it lands where the positional message goes; nothing is staged or committed: ```console $ grit commit --bogus error: unexpected argument '--bogus' found tip: to use '--bogus' as text, pass it with '-m --bogus' Usage: grit commit [OPTIONS] [MESSAGE] [-- ...] For more information, try '--help'. ``` See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. When another process holds `.git/index.lock`, `grit commit` exits `1` with `kind` `lock_held` under `--json`. `lock.path` names the lock file, and `lock.holder` gives its owning process and whether it still runs when `core.lockfilePid` recorded one; the message says whether the lock looks live or stale. Every scope checks the lock before it creates the commit, so on this error no commit was recorded and `HEAD`, the branch, the reflog and the index are unchanged. It is safe to retry once the other process finishes. Path commits (`-- paths`), `--hunks` and `--patch-file` take the lock before writing anything at all; auto-staging may leave an unreferenced blob behind for a later `git gc` to prune. Ordinary commands never remove a foreign lock; interrupted rewrite recovery may remove a stale grit index lock when its pid sidecar shows the holder exited. ```console $ grit commit -m "fix" -- f1.txt error: another process holds /work/repo/.git/index.lock; if none is running, remove the stale lock and retry $ grit commit -m "fix" --json -- f1.txt {"error":"another process holds /work/repo/.git/index.lock; if none is running, remove the stale lock and retry","kind":"lock_held","lock":{"path":"/work/repo/.git/index.lock"}} ``` Several `grit commit` processes can run in one checkout at once, for example parallel jobs each committing their own `-- paths`. The index lock serializes them: each one either records a commit with its own message and only its own paths, or fails with `lock_held` and changes nothing. The message always comes from `-m`, `-F` or the positional argument; `.git/COMMIT_EDITMSG` is read back only after a `prepare-commit-msg` or `commit-msg` hook ran, so one process never records another's message. A commit is built on the `HEAD` it read first: if another tool moves the branch before the commit lands, `grit commit` fails with `ref 'refs/heads/' did not match expected state` (exit `1`) instead of recording a commit that would undo the other change. ## See also [grit add](https://grit-scm.com/docs/add/index.md), [grit status](https://grit-scm.com/docs/status/index.md), [grit log](https://grit-scm.com/docs/log/index.md), [grit config](https://grit-scm.com/docs/config/index.md) # https://grit-scm.com/docs/diff/index.md # grit diff > Show uncommitted, staged, commit, or range changes. ## Synopsis ```text grit diff [--staged] [--unstaged] [--against ] [ []] [--pathspec-from-file ] [--pathspec-file-nul] [-- …] grit diff [--staged] [--unstaged] [--against ] [..] [--pathspec-from-file ] [--pathspec-file-nul] [-- …] grit diff --no-index ``` ## Description With no argument, shows every uncommitted change: the working tree and index together, compared with the last commit (`HEAD`). Pass `--staged` to compare only the index to `HEAD` (staged changes). Pass `--unstaged` to compare only the working tree to the index (changes not yet staged). Pass `--against ` to compare the working tree to another ref’s tree instead of `HEAD` (useful for “what changed since `main`?” while keeping a single commit argument as “show this commit’s patch”). Untracked paths are not diff entries—they appear only in [`grit status`](https://grit-scm.com/docs/diff/status.md/index.md). When a tracked path lives under a worktree directory grit cannot read (for example permission denied), grit warns with the path and continues with the rest of the diff; pathspecs limit the scan so unreadable directories outside the selection are not touched. Symlinks are compared using the bytes of their link targets, including links to directories and missing paths. Clean filters and line-ending conversion do not apply to link targets. Serial and parallel scans produce the same changes, including on large worktrees; an unchanged symlink does not make a clean tree dirty. With `core.symlinks=false`, regular files checked out as symlink placeholders retain the link mode recorded in the index. With one commit, shows the change that commit introduced (its first parent’s tree against its own tree). Commit, range, **staged**, and **unstaged** diffs detect renames by default (Git `-M50`): a move with small edits appears as one `renamed` file instead of a full delete and add. With two commits, or a two-dot range such as `A..B`, shows the tree diff between those commits with the same rename detection. A three-dot range `A...B` diffs from the merge base of `A` and `B` to `B`. When many add/delete candidates remain after exact and basename pairing, inexact rename detection may be skipped because of `diff.renameLimit`; grit then prints a one-line notice on **stderr** with the candidate counts, the configured limit, and a suggested limit to retry with (`grit -c diff.renameLimit=`). JSON and Markdown output are unchanged. Pass one or more paths after `--` (or as trailing arguments when unambiguous) to limit any diff form to those paths—the same pathspec rules as [`grit log`](https://grit-scm.com/docs/diff/log.md/index.md). For commit and tree diffs, that limit is applied before rename detection, so a pathspec that matches only one side of a move is reported as an add or delete, same as Git. Pathspec magic works as in Git, including attribute selection from `.gitattributes`: `grit diff -- ':(attr:diff=rust)'` limits the diff to files with `diff=rust`, and `':(exclude,attr:-diff)'` drops files marked `-diff`. A single positional argument that is neither a revision nor a range is still treated as a worktree path for unstaged changes (`grit diff a.txt`). If paths after `--` or entries from `--pathspec-from-file` are supplied, an unknown revision is reported as a revision error. With **two** positional arguments, both are revisions (tree diff); a path limit requires `--` (for example `grit diff HEAD~1 HEAD -- f`) or the `commit known-path` form when the second token names a file in the repo (`grit diff HEAD f`). Each file starts with its path (UTF-8 names print literally; C-quoted only when the name contains control characters, unless `core.quotepath=true`), and each hunk with its position. Lines have two number columns, the line number before and after the change. In a terminal, removed lines are red, added lines are green, and the words that changed within a line are highlighted when the diff touches at most 64 changed files; larger tree and commit-range diffs stay line-level for throughput. When the output isn't a terminal, or `NO_COLOR` is set, lines are marked with `-` and `+` instead. `--json` and `--markdown` use line-level hunks only (no word-level `emphasis` segments) so large commit-range diffs stay fast. Tree and commit diffs that change 16 or more files honor the global `--threads` flag and `index.threads` when loading blobs and computing line diffs; smaller ones run on one thread, which is faster than starting workers. Three lines of unchanged context are shown around each change. Binary files print `Binary file differs` when the blob changed (mode-only binary changes show mode lines only). `` can be anything that names a commit: a full or short commit id, a branch or tag name, or an expression like `HEAD~2`. In a shallow clone, a commit listed in `.git/shallow` is diffed like a root (against the empty tree), even when its object still names a parent that was not fetched. ## Options | Option | Description | | --- | --- | | `-p`, `--patch` | Full patch (the default). Mutually exclusive with the other format flags below. | | `--stat` | Per-file change counts with `+`/`-` bars and a summary line (like `git diff --stat`). Mutually exclusive with the other format flags below. | | `--numstat` | Machine-readable `insertionsdeletionspath` lines (`--` for binary). | | `--shortstat` | Only the summary line (`N files changed, …`). | | `--name-only` | Changed paths, one per line. | | `--name-status` | Status letter and path(s) per line (`M`, `A`, `R100oldnew`, …). | | `--patch-text` | Git-apply-compatible unified patch on stdout (`git diff --binary` shape): `index` lines carry abbreviated preimage and postimage blob ids (including unstaged worktree content, hashed at render time), and binary files appear as `GIT binary patch` sections so `git apply --index` reproduces them. Human output only; not combinable with `--json` or `--markdown`. | | `-M`, `--find-renames[=]` | Detect renames (default similarity 50). Long form requires `=` when a threshold is given. | | `--no-renames` | Do not detect renames. | | `--diff-algorithm ` | Line diff algorithm (`myers`, `minimal`, `patience`, `histogram`). | | `--diff-filter ` | Limit to change types (`A` added, `D` deleted, `M` modified, `R` renamed, …). | | `-w`, `--ignore-all-space` | Ignore whitespace when comparing lines. | | `-b`, `--ignore-space-change` | Ignore changes in the amount of whitespace. | | `--ignore-blank-lines` | Ignore changes whose lines are all blank. | | `-U`, `--unified ` | Lines of context around each hunk when the output is a patch (bare `-U` means 3). | | `-M`, `--find-renames[=]` | Detect renames; optional similarity threshold (`50` default, or `50%`). Attached `-M30` is accepted. | | `--no-renames` | Do not detect renames (show separate delete and add entries). | | `--diff-algorithm ` | Line diff algorithm (`myers`, `patience`, `histogram`, …); overrides `diff.algorithm`. | | `--diff-filter ` | Limit output to change types (`A` added, `D` deleted, `M` modified, `R` renamed, …). | | `-w`, `--ignore-all-space` | Ignore whitespace when comparing lines. | | `-b`, `--ignore-space-change` | Ignore changes in the amount of whitespace. | | `--ignore-blank-lines` | Ignore changes whose lines are all blank. | | `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries (Git `-W`). | | `-p`, `--patch` | Unified patch output (default when no other format flag is set). | | `--exit-code` | Exit with status **1** when there are changes (for scripts); **0** when clean. | | `--quiet` | Print nothing; implies `--exit-code`. | | `--staged`, `-S` | Staged changes only (index vs `HEAD`). Cannot be combined with `--unstaged`, commit arguments, or `--against`. Optional path limits after `--` are allowed. | | `--unstaged` | Unstaged changes only (worktree vs index). Cannot be combined with `--staged`, commit arguments, or `--against`. Optional path limits after `--` are allowed. | | `--against ` | Compare the worktree to ``’s tree instead of `HEAD`. No commit arguments. Optional path limits after `--` are allowed. | | `--no-index` | Compare two filesystem paths without a repository: two files, two directories (recursive), or a file and a directory (compared with `directory/`, as Git does). Takes exactly two paths and cannot be combined with `--staged`, `--unstaged`, `--against` or commits. Exits 1 when they differ, as with `--exit-code`. | | `--exit-code` | Exit with status 1 when there are changes and 0 when there are none; errors exit 2. | | `--quiet` | Print nothing and exit as with `--exit-code`. | | `` | One commit (that commit’s patch), two commits (tree diff), or a range `A..B` / `A...B`. Omit for uncommitted changes. | | `--pathspec-from-file ` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. | | `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. | | `…` | After `--`, limit the diff to these paths (all forms above, including `--staged`). | ## Examples What have I changed since the last commit? ```console $ grit diff main.rs @@ -1 +1 @@ 1 │ - fn main() {} 1 │ + fn main() { 2 │ + println!("hi"); 3 │ + } ``` What is staged but not yet committed? ```console $ grit diff --staged ``` What changed in the working tree since the last `grit add`? ```console $ grit diff --unstaged ``` What changed between two commits? ```console $ grit diff HEAD~1 HEAD $ grit diff HEAD~1..HEAD ``` Only one file between two branches: ```console $ grit diff main feature -- README.md ``` What does my worktree look like compared to `main`? ```console $ grit diff --against main ``` What did the commit before the last one change? ```console $ grit diff HEAD~1 ``` List the files changed by a commit: ```console $ grit diff v0.1 --json --filter '.files[].path' [ "README.md", "main.rs" ] ``` Write the staged changes, binary files included, as a patch `git apply` can replay elsewhere: ```console $ grit diff --staged --patch-text diff --git a/b.bin b/b.bin new file mode 100644 index 0000000000000000000000000000000000000000..eaf36c1daccfdf325514461cd1a2ffbc139b5464 GIT binary patch literal 4 Lc${NkWMT#Y01f~L literal 0 Hc$@ ../change.patch $ cd ../other && git apply --index ../change.patch ``` Compare two files or directories that aren't in a repository: ```console $ grit diff --no-index ./old ./new ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/diff/schemas/diff/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `changed` | boolean | Whether any selected change exists (matches `--exit-code` / `--quiet`). | | `files` | array | Changed files (see nested fields below). | | `totals` | object | Present for `--stat`, `--numstat`, and `--shortstat`: `files_changed`, `insertions`, `deletions`. | | `changed` | boolean | Whether any change was selected; the same answer `--exit-code` gives as an exit status. | Each `files[]` entry includes `path`, `status`, `binary`, optional `old_path` (renames), optional `similarity` (0–100 on renames/copies), optional `combined_status` (per-parent combined letters such as `MM` or `DD` on merge `--cc` / `--name-status` output; omitted on ordinary two-tree diffs), optional `stat` (`{ "insertions", "deletions" }` when line counts were computed; omitted when `binary` is true), optional `old_size` / `new_size` (byte lengths on each side when `binary` is true, matching `--stat`’s `Bin old -> new bytes` line), optional `old_mode` / `new_mode`, optional `old_encoding_lossy` / `new_encoding_lossy`, and `hunks` only for the default patch format. Nested fields include `files[].status` (`added`, `modified`, `deleted`, `renamed`, and so on; `type_changed`, Git's raw `T`, when a path switches between a regular file, a symlink and a submodule, reported the same way for unstaged, staged, worktree-vs-commit and commit-to-commit diffs, while a permission-only change stays `modified`), optional `files[].old_path` when `status` is `renamed`, `hunks[].old_start` / `new_start` / `old_lines` / `new_lines`, optional `hunks[].id` (twelve lowercase hex characters; present on `--staged` and `--unstaged` patch JSON for stable hunk selection), optional `hunks[].index` (0-based hunk index within the file; same scopes as `id`), optional `hunks[].context` (the `@@` function-name suffix from the path's `diff` driver, or the enclosing definition when `-W` / `--function-context` is set), `hunks[].lines[].kind` (`context`, `add`, or `del`), line numbers on `old` and `new`, a compact `text` string per line (or `segments` with optional `emphasis` only when intra-line word highlights are present), and `no_newline_at_eof` when that side lacks a trailing newline (Git’s `\ No newline at end of file`). JSON is written in compact form (no pretty-printing). When `files[].binary` is true, `hunks` is always an empty array — blob bytes are never included in JSON (use human or `--markdown` output for the “Binary file differs” note). For unstaged and other worktree-sourced sides, line text is normalized to repository form (`.gitattributes` / `core.autocrlf`) before diffing, so trailing `\r` from CRLF checkouts does not appear in line `text`. Commit and staged diffs compare stored blobs and may still show carriage returns when the on-disk object bytes differ. When file bytes are not valid UTF-8 and the file is treated as text, `old_encoding_lossy` or `new_encoding_lossy` is true and non-UTF-8 bytes appear as U+FFFD in text fields. Unstaged gitlinks honor Git's submodule ignore settings (`diff.ignoreSubmodules`, `submodule..ignore`, `.gitmodules` `ignore`); `--staged` omits gitlinks only when ignore is `all` (index-vs-`HEAD` OID compare). Example: ```json { "changed": true, "files": [ { "path": "staged.txt", "status": "added", "new_mode": "100644", "binary": false, "hunks": [ { "old_start": 0, "new_start": 1, "old_lines": 0, "new_lines": 1, "lines": [ { "kind": "add", "new": 1, "text": "staged contents" } ] } ] }, { "path": "tracked.txt", "status": "modified", "old_mode": "100644", "new_mode": "100644", "binary": false, "hunks": [ { "old_start": 1, "new_start": 1, "old_lines": 1, "new_lines": 1, "lines": [ { "kind": "del", "old": 1, "text": "tracked v2" }, { "kind": "add", "new": 1, "text": "tracked modified" } ] } ] } ] } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/diff/schemas/diff/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for one section per changed file: a level-2 heading, then metadata lines (`**status:**`, and `**old_mode:**` / `**new_mode:**` when the git mode changed), then a `diff`-fenced unified patch when there are text hunks (binary files note `Binary file differs.` when content changed). Mode-only or rename-only changes omit the fence when the patch would be empty. ```text ## main.rs **status:** modified ``` When there are text hunks, a unified patch follows in a `diff` code fence: ```diff @@ -1,1 +1,2 @@ fn main() { + println!("hello"); } ``` Mode-only changes list modes and omit an empty fence: ```text ## run.sh **status:** modified **old_mode:** `100644` **new_mode:** `100755` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | No changes selected, or success without `--exit-code` / `--quiet`. | | `1` | Changes exist when `--exit-code` or `--quiet` is set ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or diff error while `--exit-code` / `--quiet` is set ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for the full table. ## See also [grit status](https://grit-scm.com/docs/status/index.md), [grit show](https://grit-scm.com/docs/show/index.md), [grit log](https://grit-scm.com/docs/log/index.md) # https://grit-scm.com/docs/restore/index.md # grit restore > Restore working tree and/or index paths from HEAD, the index, or another revision. ## Synopsis ```text grit restore [--staged] [--worktree] [--hunks ] [--lines ] [--dry-run] [--source=] [--ours|--theirs|--merge] [--conflict=merge|diff3|zdiff3] [--pathspec-from-file ] [--pathspec-file-nul] -- … ``` ## Description Discards local changes for tracked paths you name. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). By default, `grit restore` resets the **working tree** to match the **index** (the same idea as unstaging worktree edits while keeping the index as-is). - `--staged` resets the **index** from `HEAD` (or from `--source` when you pass it). On an unborn branch, staged paths are removed from the index. - `--worktree` resets the **working tree**. When you omit both flags, only the worktree is restored. - `--hunks` and `--lines` reverse-apply only the selected diff hunks instead of whole files. Unstaged ids come from `grit diff --unstaged --json`; with `--staged`, ids come from `grit diff --staged --json`. Line ranges use new-side line numbers from `grit diff --json` (`lines[].new`), same as `grit add --lines`. Cannot be combined with `--source`, `--ours`, `--theirs`, or `--merge`. A worktree hunk restore rewrites `.git/index` only when it updates a path's cached stat data, which it checks once the selected ids cover every remaining hunk of a file; while the file still differs from the index (or when `--lines` brought it back), the index file is left as it was, like `git apply -R`, and the next `grit status` re-reads the file. - `--dry-run` with `--hunks` or `--lines` validates selection and reports paths without writing the worktree or index. - `--source=` reads content from a commit or tree instead of the usual default (`HEAD` for `--staged`, the index for the worktree). - Paths that are missing in the source are removed from the target. Untracked files are never touched. - Index entries with the skip-worktree bit (for example after `git update-index --skip-worktree`) are left out of restore, the same as Git: `grit restore .` does not rewrite them or clear the flag. - During a merge conflict, `--ours` and `--theirs` write index stage 2 or 3 into the worktree (filters and line endings apply) and leave the index unmerged. `--merge` rebuilds conflict markers from stages 1–3; `--conflict` picks the marker style and implies `--merge`. These options cannot be combined with `--staged` or `--source`. - A plain worktree restore (no `--staged`, no `--source`) refuses paths that are still unmerged, for example after a conflicted `grit merge` or `grit stash pop`: there is no single index version to restore. It fails before writing anything, even when other matched paths could be restored (`grit restore .` included), and tells you to pick `--ours`, `--theirs` or `--merge`. Exclude the conflicted path (`-- . ':!f.txt'`) to restore the rest. `--staged` on its own refuses unmerged paths the same way (Git would drop the conflict stages and leave the markers in the file, and grit's auto-staging commit would then record them); to resolve, edit out the markers and `grit add` the file. `--staged --worktree` resets both the index and the file to `HEAD`, and `--source` without `--staged` writes only the worktree and leaves the conflict stages in place. ## Options | Option | Description | | --- | --- | | `…` | One or more pathspecs (required for full-file restore unless `--pathspec-from-file` is set). Optional with `--hunks` / `--lines` to narrow the diff scan. Attribute pathspecs such as `:(attr:myattr)` use the same `.gitattributes` stack as [`grit log`](https://grit-scm.com/docs/restore/log.md/index.md). | | `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). | | `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. | | `-S`, `--staged` | Restore the index (or unstage selected hunks with `--hunks` / `--lines`). | | `-W`, `--worktree` | Restore the working tree (default when `--staged` is absent). | | `--hunks` | Discard or unstage only the listed hunk ids (comma-separated, repeatable). | | `--lines` | Discard or unstage only new-side line ranges (`path:start-end`, repeatable). Mix with `--hunks`. | | `--dry-run` | With `--hunks` or `--lines`, report paths that would change without writing. | | `-s`, `--source` | Commit or tree to restore from. | | `--ours` | Unmerged paths only: check out our side (stage 2) in the worktree. | | `--theirs` | Unmerged paths only: check out their side (stage 3) in the worktree. | | `--merge` | Unmerged paths only: recreate conflict markers in the worktree (default style from `merge.conflictStyle`). | | `--conflict` | With `--merge`: `merge`, `diff3`, or `zdiff3` marker style. | ## Examples Discard unstaged edits to a file (worktree ← index): ```console $ grit restore README.md Restored README.md ``` Unstage a file (index ← HEAD): ```console $ grit restore --staged README.md Restored README.md ``` Discard one unstaged hunk by id: ```console $ grit diff --unstaged --json -- f.txt | jq -r '.files[0].hunks[0].id' a1b2c3d4e5f6 $ grit restore --hunks a1b2c3d4e5f6 -- f.txt Restored f.txt ``` Restore the working tree from the previous commit: ```console $ grit restore --source=HEAD~1 -- README.md Restored README.md ``` During a merge, inspect one side or bring conflict markers back: ```console $ grit restore --ours -- README.md Restored README.md $ grit restore --merge --conflict=diff3 -- README.md Restored README.md ``` A plain or `--staged` restore on a conflicted path names the options that work: ```console $ grit restore README.md error: path 'README.md' is unmerged hint: take one side with `grit restore --ours README.md` or `grit restore --theirs README.md`, bring the conflict markers back with `grit restore --merge README.md`, or edit out the markers and run `grit add README.md` ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/restore/schemas/restore/v1.json/index.md) Pass `--json` for scripting: | Field | Type | Meaning | | ----- | ---- | ------- | | `restored` | array of strings | Paths created or updated (non-UTF-8 names use reversible `grit+pathhex:` encoding, same as [`grit status`](https://grit-scm.com/docs/restore/status.md/index.md)). | | `removed` | array of strings | Paths removed because the source had no entry (same encoding as `restored`). | | `path_collisions` | array of strings | On a case-insensitive work tree, index paths that share one dentry (informational; same shape as `grit switch` / `grit clone`). Omitted when empty. | | `restored_hunks` | object | When `--hunks` was used: map of path → hunk id strings. | | `restored_lines` | object | When `--lines` was used: map of path → range strings (`start` or `start-end`). | | `dry_run` | boolean | True when `--dry-run` was passed with hunk/line selection. | Example: ```json { "restored": ["README.md"], "removed": [], "restored_hunks": {}, "restored_lines": {}, "dry_run": false } ``` When a plain or `--staged` restore refuses an unmerged path, stdout with `--json` is a single error object with `kind` `unmerged_paths`, a `paths` array of the unmerged paths and a `hint` naming the `grit restore --ours` / `--theirs` / `--merge` commands and `grit add`. See the [error schema](https://grit-scm.com/docs/restore/schemas/error/v1.json/index.md). ## Markdown output Schema: [v1](https://grit-scm.com/docs/restore/schemas/restore/v1.json/index.md) Pass `--markdown` for agent-friendly bullet lists of restored and removed paths. ```text ## Restore ### Restored - `tracked.txt` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)), including a plain or `--staged` restore of an unmerged path. | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. When another process holds `.git/index.lock`, `grit restore` fails with exit `1` (`kind` `lock_held` under `--json`) before restoring any path, so the worktree and index are unchanged. ## See also [grit add](https://grit-scm.com/docs/add/index.md), [grit status](https://grit-scm.com/docs/status/index.md) # https://grit-scm.com/docs/rm/index.md # grit rm > Remove tracked paths from the working tree and index. ## Synopsis ```text grit rm [--cached] [-f|--force] [--dry-run] [--ignore-unmatch] [--pathspec-from-file ] [--pathspec-file-nul] ... ``` ## Description Removes tracked files or directories from the index and, by default, from the working tree. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). With `--cached`, the file stays on disk as an untracked file but is removed from the index. Grit refuses to remove a path when doing so would lose content that is stored nowhere else, unless you pass `--force`. The rules match Git's safety rules for `git rm`: | The path has… | `grit rm` | `grit rm --cached` | | --- | --- | --- | | No changes since `HEAD` | removed | removed | | Local modifications (the file differs from the index) | refused | removed, file kept | | Staged changes (the index differs from `HEAD`, or there is no commit yet) | refused | removed, file kept | | Staged content that differs from both `HEAD` and the file | refused | refused | | A file already deleted from the working tree | removed | removed | So the usual way to stop tracking an accidentally committed file (`.env`, build output) works even after you edited it: `grit rm --cached .env` keeps your copy on disk and stages the deletion. When a path is refused, nothing is changed; the error lists each refused path with its reason and suggests `--cached` only when it would help. Directory pathspecs remove every tracked file under that directory; trailing slashes on a directory path (or a path that names an existing directory) imply recursive removal. Attribute pathspecs such as `:(attr:myattr)` use the same `.gitattributes` stack as [`grit log`](https://grit-scm.com/docs/rm/log.md/index.md) (including with `--cached`). `--dry-run` runs the same checks and lists paths that would be removed without writing the index or work tree. `--ignore-unmatch` treats non-matching pathspecs as success with an empty result (like `git rm --ignore-unmatch`). ## Options | Option | Description | | --- | --- | | `...` | Files or directories to remove (required unless `--pathspec-from-file` is set). | | `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). | | `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. | | `--cached` | Remove from the index only; keep the working tree copy. | | `-f`, `--force` | Remove even when the safety rules above would refuse the path. | | `--dry-run` | Preview removals without changing the index or work tree. | | `--ignore-unmatch` | Do not error when a pathspec matches nothing. | ## Examples Remove a tracked file: ```console $ grit rm old.txt Removed old.txt. ``` Preview removal: ```console $ grit rm --dry-run old.txt Would remove old.txt. ``` Keep the file on disk but stop tracking it: ```console $ grit rm --cached config.local Removed config.local. ``` A file with unsaved content is refused: ```console $ grit rm notes.txt error: not removed, these files have content that would be lost: notes.txt (local modifications) (use --cached to stop tracking them and keep the files, or --force to remove them anyway) ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/rm/schemas/rm/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `removed` | array of strings | Repository-relative paths removed from the index (and work tree unless `--cached`), or that would be removed when `--dry-run` is set. | | `dry_run` | boolean | `true` when `--dry-run` was passed. | Example: ```json { "dry_run": false, "removed": ["old.txt"] } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/rm/schemas/rm/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output: ```text - **Removed**: - `old.txt` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)), including a refusal by the safety rules; with `--json` the refusal is an `{"error": "..."}` object listing the refused paths. | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit add](https://grit-scm.com/docs/add/index.md), [grit mv](https://grit-scm.com/docs/mv/index.md), [grit status](https://grit-scm.com/docs/status/index.md) # https://grit-scm.com/docs/mv/index.md # grit mv > Rename or move tracked paths. ## Synopsis ```text grit mv [-f|--force] [--dry-run] ... ``` ## Description Renames or moves tracked paths in the working tree and index, preserving object ids and cached stat data. Pathnames in human and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). The last argument is the destination; earlier arguments are sources. When the destination is an existing directory, each source is moved into that directory under its original base name. A trailing slash on the destination (`docs/` or `docs//`) is accepted and means the same as naming the directory without the slash. Moving a directory renames the whole tree of tracked files. Multiple sources are validated together before anything moves; the index is updated once. Grit refuses untracked sources, overwriting an existing destination without `--force`, and moving a directory into one of its own subdirectories. On case-insensitive volumes with `core.ignorecase=true`, case-only renames succeed: the worktree spelling updates and the index tracks the destination path. That includes renaming a tracked directory to a case-only spelling (for example `Dir` to `dir`), which updates every indexed path under that tree (for example `Dir/x.txt` becomes `dir/x.txt`). Single-file case-only renames behave like `git mv`; upstream Git still fails directory case-only renames on APFS. When a move leaves a source directory empty, grit leaves that directory on disk (same as `git mv`). ## Options | Option | Description | | --- | --- | | `...` | One or more tracked paths to move. | | `` | Final path or existing directory (last argument). | | `-f`, `--force` | Replace an existing file at the destination. | | `--dry-run` | List planned renames without changing the index or work tree. | ## Examples Rename a file: ```console $ grit mv draft.txt final.txt Renamed draft.txt -> final.txt. ``` Move into a directory: ```console $ grit mv report.txt docs/ Renamed report.txt -> docs/report.txt. ``` ## JSON output Live `--json` output follows schema [v2](https://grit-scm.com/docs/mv/schemas/mv/v2.json/index.md). The frozen [v1](https://grit-scm.com/docs/mv/schemas/mv/v1.json/index.md) schema documents the legacy `{from, to}` shape. Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `moves` | array of `{from, to}` | Each rename performed or previewed. | | `dry_run` | boolean | `true` when `--dry-run` was passed. | Example: ```json { "dry_run": false, "moves": [ { "from": "draft.txt", "to": "final.txt" } ] } ``` ## Markdown output Schema: [v2](https://grit-scm.com/docs/mv/schemas/mv/v2.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output: ```text - **moves**: - `draft.txt` → `final.txt` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit add](https://grit-scm.com/docs/add/index.md), [grit rm](https://grit-scm.com/docs/rm/index.md), [grit status](https://grit-scm.com/docs/status/index.md) # https://grit-scm.com/docs/stash/index.md # grit stash > Save and restore shelved work. ## Synopsis ```text grit stash [-m ] [-u] [-- path…] grit stash push [-m ] [-u] [-S] [-k] [--hunks ] [--lines ] [--dry-run] [--pathspec-from-file ] [--pathspec-file-nul] [-- path…] grit stash list grit stash show [|] [--stat] [-p] [-u] grit stash apply [|] [--index] grit stash pop [|] [--index] grit stash branch [|] grit stash drop [] grit stash clear [--force] [--dry-run] ``` ## Description Shelve uncommitted changes and restore them later. With no subcommand, `grit stash` saves local changes (same as `grit stash push`), resets the working tree and index to `HEAD`, and records a stash entry compatible with Git's `refs/stash` format. Skip-worktree paths are not stashed or reset on push, and the bit stays set through pop, matching Git. Unreadable worktree directories produce a warning naming the path; stash still saves readable changes and does not treat files under those directories as deleted. Like Git, dirty content inside a checked-out submodule whose gitlink commit is unchanged does not count as a local change to save (push reports that there is nothing to stash); a submodule whose HEAD moved away from the recorded gitlink is still stashed. Like Git, stash never signs the commits it records, even when `commit.gpgsign` is true, so a configured signing program is not run on push. Pass `--` followed by pathspecs (or `--pathspec-from-file`) on push to stash only matching paths; other staged and unstaged changes stay in place. The stash commit still records the full index on its index parent; the working-tree parent and optional untracked parent are limited to those paths, matching `git stash push -- `. Attribute pathspecs such as `:(attr:myattr)` use the same `.gitattributes` stack as [`grit log`](https://grit-scm.com/docs/stash/log.md/index.md). Stash indices follow Git: `0` is the newest entry. You can pass an integer or `stash@{n}`. An all-decimal token is always an index (never a short object id). Any other revision resolves to a stash commit id: `apply` and `branch` accept dangling stash commits (for example after `drop`), and `pop` accepts a commit id only while that commit is still on the stack. `grit stash pop` applies the entry and removes it when there are no conflicts. When applying would leave merge conflicts, the stash entry is kept and the command exits non-zero; conflicting paths are listed. There is no merge to continue: edit the files, mark them resolved with `grit add `, then remove the kept entry with `grit stash drop` (or pick a side with `grit restore --ours|--theirs `). `grit stash apply` stops the same way but never drops the entry. `apply` and `pop` preserve the exact tracked filename bytes, including literal names beginning with `grit+pathhex:` and non-UTF-8 names on Unix. If a stashed change would overwrite local edits to that file, the operation fails before changing files and keeps the stash. Conflict paths use reversible `grit+pathhex:` encoding when needed; Rust callers can recover the original bytes with `repo_relpath::storage_bytes`. When a stash was created with `-u` / `--include-untracked`, `apply` and `pop` refuse to write stashed untracked files onto a path that already exists on disk (visible untracked, ignored, or tracked content you added after stashing). The command exits non-zero, the stash entry is kept, and your existing file bytes are unchanged. On an interactive terminal (human output, not `--json` or `--markdown`), push shows a live **Staging** line while it hashes local changes and a **Checkout** line while it resets them, and apply and pop show a **Checkout** line; nothing is drawn when stderr is not a TTY. Push, apply, and pop either complete or change nothing. A pop or apply that includes untracked files finishes restoring every path (tracked and untracked) before it writes the index or drops the stash entry; if an object cannot be read (for example because background repack moved it while the command was running), the worktree and index are rolled back and the stash entry stays. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while the index or work tree is being updated stops the command with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were, no `.git/index.lock` is left behind, and the same stash command can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. Staging may leave unreachable loose blobs if you interrupt mid-write; they are harmless. ## Options | Option | Description | | --- | --- | | `-m`, `--message` | Message stored on the stash reflog (push / bare `grit stash`). | | `-u`, `--include-untracked` | Include untracked files in the stash (not with `--hunks` / `--lines` or `--staged`). | | `-S`, `--staged` | Stash only index changes vs `HEAD`; unstaged edits on other paths remain (not with `-u`, `--hunks`, or `--lines`). | | `-k`, `--keep-index` | Stash tracked changes but leave the index and worktree matching staged content afterward. | | `--hunks` | Stash only listed unstaged hunk ids from `grit diff --unstaged --json`. | | `--lines` | Stash only unstaged line ranges (`path:start-end`, same as `grit add --lines`). | | `--dry-run` | Preview what would be stashed; no objects, refs, index, or worktree updates. | | `-n`, `--limit` | Cap path lists in `--dry-run` preview output. | | `…` | Limit what is stashed (after `--`); with `--staged`, only matching index changes are saved and reset. | | `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same rules as Git). | | `--pathspec-file-nul` | With `--pathspec-from-file`, entries are NUL-separated instead of line-based. | | `--index` | On `apply` / `pop`, restore the stashed index as well as the worktree. Changes that were unstaged when you stashed come back unstaged, including when nothing was staged at all. | | `` | Stash index for `show`, `apply`, `pop`, or `drop` (default `0`). | | `--stat` | Show a diffstat in `grit stash show` (default when `-p` is not set). | | `-p`, `--patch` | Show the full patch in `grit stash show` instead of a diffstat. | | `-u`, `--include-untracked` | On `show`, include untracked files from the stash U parent (same as `git stash show -u`). | | `push` | Save changes explicitly (same flags as bare `grit stash`). | | `list` | List stash entries. | | `show` | Show a diffstat or patch for one entry. | | `apply` | Apply an entry without removing it. | | `pop` | Apply an entry and drop it when clean. | | `drop` | Remove an entry without applying it. | | `branch` | Create a branch at the stash base commit, check it out, apply with `--index` (staged changes come back staged, unstaged ones unstaged), and drop the entry on success. | | `clear` | Remove every stash entry. Requires `--force`; without it the command exits non-zero and reports how many entries would be cleared. `--dry-run` reports the count without deleting. | ## Examples Save work in progress: ```console $ grit stash -m "wip feature" Saved working directory and index state On main: wip feature a1b2c3d ``` List entries: ```console $ grit stash list stash@{0} a1b2c3d: On main: wip feature ``` Show the newest stash as a diffstat: ```console $ grit stash show f.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) ``` Human and `--markdown` diffstat output C-quotes C0 control characters in path names (including ESC, tab, and newline), the same as [`grit status`](https://grit-scm.com/docs/stash/status.md/index.md) and other diffstat commands; `--json` `stat.files[].path` values stay raw UTF-8 strings (JSON escapes controls as `\uXXXX`). Pop the newest entry: ```console $ grit stash pop Dropped stash@{0} (applied) ``` When pop leaves conflicts: ```console $ grit stash pop Stash pop left conflicts in: f.txt The stash entry was kept. → resolve conflicts, grit add , then grit stash drop $ echo resolved > f.txt $ grit add f.txt Staged f.txt $ grit stash drop Dropped stash@{0} ``` When pop would overwrite an existing path from a `-u` stash: ```console $ grit stash pop stash untracked restore blocked: 'notes.txt' already exists on disk ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/stash/schemas/stash/v1.json/index.md) · [stash.push v1](https://grit-scm.com/docs/stash/schemas/stash.push/v1.json/index.md) · [stash.list v2](https://grit-scm.com/docs/stash/schemas/stash.list/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.list/v1.json/index.md) · [stash.show v1](https://grit-scm.com/docs/stash/schemas/stash.show/v1.json/index.md) · [stash.apply v2](https://grit-scm.com/docs/stash/schemas/stash.apply/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.apply/v1.json/index.md) · [stash.pop v1](https://grit-scm.com/docs/stash/schemas/stash.pop/v1.json/index.md) · [stash.drop v2](https://grit-scm.com/docs/stash/schemas/stash.drop/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.drop/v1.json/index.md) · [stash.branch v2](https://grit-scm.com/docs/stash/schemas/stash.branch/v2.json/index.md), [v1](https://grit-scm.com/docs/stash/schemas/stash.branch/v1.json/index.md) · [stash.clear v1](https://grit-scm.com/docs/stash/schemas/stash.clear/v1.json/index.md) Pass `--json` for stable, scripting-friendly output. ### `grit stash` / `grit stash push` When something was stashed: ```json { "oid": "6e513d5cd6ab8d618238e22d7ca55d942b55964a", "message": "On main: wip feature", "mode": "all" } ``` Partial stash (`--hunks` / `--lines`) also includes `stashed_hunks` and `stashed_lines` maps (same shape as `grit add --json`). `--dry-run` preview (no `oid`): ```json { "dry_run": true, "mode": "staged_only", "paths": ["staged_new.txt"], "untracked": [] } ``` When there was nothing to save: ```json { "stashed": false } ``` | Field | Type | Meaning | | ----- | ---- | ------- | | `oid` | string | Full object id of the stash commit (success object only). | | `message` | string | Reflog message (for `-m`, `On : …`; otherwise Git-style `WIP on …`). | | `mode` | string | `all`, `staged_only`, or `keep_index`. Omitted when `all`. | | `dry_run` | boolean | Always `true` on the preview object; omitted on successful save (`false`). | | `paths` | array of strings | Tracked paths that would be stashed (`--dry-run` preview only). | | `untracked` | array of strings | Untracked paths in a dry-run preview when `-u` is set. | | `stashed_hunks` | object | Map of repository-relative path → hunk id strings stashed (partial `--hunks` only; same shape as `grit add --json`). Omitted when empty. | | `stashed_lines` | object | Map of path → line range labels stashed (partial `--lines` only). Omitted when empty. | | `paths` | array of strings | Resolved pathspecs when push was limited with `-- path…` or `--pathspec-from-file`. Omitted when empty. | | `stashed` | boolean | Present and `false` only on the empty-worktree result. | ### `grit stash list` ```json { "action": "list", "entries": [ { "index": 0, "oid": "6e513d5cd6ab8d618238e22d7ca55d942b55964a", "message": "On main: second" } ] } ``` | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | Always `"list"`. | | `entries` | array | Stash entries, newest first. | | `entries[].index` | number | Index matching `stash@{index}`. | | `entries[].oid` | string | Full stash commit id. | | `entries[].message` | string | Reflog message. | ### `grit stash show` Diffstat (default): ```json { "index": 0, "include_untracked": true, "stat": { "files_changed": 1, "insertions": 1, "deletions": 1, "files": [ { "path": "f.txt", "status": "modified", "insertions": 1, "deletions": 1, "binary": false } ] } } ``` With `--patch`, a `patch` object with the same shape as [`grit diff`](https://grit-scm.com/docs/diff/index.md) is included instead of `stat`. | Field | Type | Meaning | | ----- | ---- | ------- | | `index` | number | Stash index shown. | | `include_untracked` | boolean | Whether `-u` / `--include-untracked` was used (omitted when false). | | `stat` | object | Diffstat summary (when `-p` is not set). | | `patch` | object | Full diff outcome (when `-p` is set). | ### `grit stash branch` ```json { "branch": "from-stash", "base": "a1b2c3d4e5f6789012345678901234567890abcd", "oid": "d78432c4772cb8509513bca138a60d13e5ad50fd", "index": 0, "conflicts": false } ``` When `conflicts` is true, `conflict_paths` lists paths with unmerged index entries. | Field | Type | Meaning | | ----- | ---- | ------- | | `branch` | string | Branch created and checked out. | | `base` | string | Stash base commit (parent 1 of the W commit). | | `oid` | string | Stash W commit that was applied. | | `index` | number | Stash index when the commit was on the stack (omitted for an off-stack commit id). | | `conflicts` | boolean | Whether merge conflicts remain after apply. | | `conflict_paths` | array of strings | Conflicted paths when `conflicts` is true. | ### `grit stash clear` Without `--force` (preview only): ```json { "cleared": 2, "dry_run": true } ``` After `grit stash clear --force`: ```json { "cleared": 2, "dry_run": false } ``` | Field | Type | Meaning | | ----- | ---- | ------- | | `cleared` | number | Stash reflog entries removed or that would be removed. | | `dry_run` | boolean | True when nothing was deleted (`--force` missing or `--dry-run`). | ### `grit stash apply` / `grit stash pop` ```json { "oid": "d78432c4772cb8509513bca138a60d13e5ad50fd", "index": 0, "conflicts": false, "index_restored": false, "dropped": true } ``` When `conflicts` is true, `conflict_paths` lists paths with unmerged index entries. On a clean apply or pop the field is omitted. Pop adds `dropped` (whether the entry was removed): | Field | Type | Meaning | | ----- | ---- | ------- | | `oid` | string | Stash W commit id (always set on apply). | | `index` | number | Stash index when the selector was on the stack (omitted for a bare commit id). | | `conflicts` | boolean | Whether merge conflicts remain. | | `index_restored` | boolean | Whether `--index` was used. | | `conflict_paths` | array of strings | Paths with unmerged index entries when `conflicts` is true. | | `dropped` | boolean | (`pop` only) Whether the stash entry was removed. | ### `grit stash drop` ```json { "index": 0, "oid": "d78432c4772cb8509513bca138a60d13e5ad50fd" } ``` | Field | Type | Meaning | | ----- | ---- | ------- | | `index` | number | Stash index removed. | | `oid` | string | Full hex id of the dropped stash W commit (for recovery with `grit stash apply `). | ## Markdown output Schema: [v1](https://grit-scm.com/docs/stash/schemas/stash/v1.json/index.md) With `--markdown`, list/apply/pop/drop use bullet lists; `show` renders the diffstat or patch like other diff commands. ```text ## Stash - Saved **On main: wip** · `690b7a6` ``` A conflicted pop lists the paths and the next steps: ```text ## Stash pop - **stash@{0}** · stopped with conflicts (entry kept) - `f.txt` → resolve conflicts, `grit add PATH`, then `grit stash drop` ``` When the stash is empty, `pop` (and `apply` with no entries) reports a plain message instead of stash ref syntax: ```console $ grit stash pop error: no stash entries hint: save local changes with `grit stash push` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. With `--json`, typed stash failures use the shared [error schema](https://grit-scm.com/docs/stash/schemas/error/v1.json/index.md). Common `kind` values include `stash_not_found` when `apply`, `pop`, `drop`, or `show` names an index with no entry (for example `pop` on an empty stack), `not_a_repository` when the command needs a repository, and `lock_held` when another process holds `.git/index.lock` before any stash write. Human messages name the missing index (`stash@{n}`) or say `no stash entries` when the stack is empty. Apply and pop that would overwrite local tracked edits or clobber an on-disk untracked file exit **1** without changing the stash entry; `--json` still carries the error string (no separate `kind` yet for those cases). When another process holds `.git/index.lock`, `grit stash`, `stash push`, `apply`, `pop` and `branch` fail with exit `1` (`kind` `lock_held` under `--json`) before writing anything: no stash commit or `refs/stash` entry is created, and the worktree and index are unchanged. Retry once the other process finishes. If a push fails after `refs/stash` was updated (for example an I/O error while resetting the worktree), the entry stays on the stash so the saved changes are never only a dangling object. ## See also [grit status](https://grit-scm.com/docs/status/index.md), [grit restore](https://grit-scm.com/docs/restore/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md) # https://grit-scm.com/docs/log/index.md # grit log > Show commits, newest first: the whole history in the pager on a terminal, a page at a time for scripts and agents. ## Synopsis ```text grit log […] [-n ] [--cursor ] [--no-pager] [-p] [--stat | --numstat | --shortstat | --name-only | --name-status] [-U] [--oneline] [--decorate] [--graph] [--graph-ascii] [--graph-unicode] [--group-by author] [--count] [--skip ] [--since|--after ] [--until|--before ] [--first-parent] [--follow] [--merges | --no-merges] [--reverse] [--author ] [--committer ] [--grep ] [-S ] [-G ] [--pickaxe-regex] [-i] [--all-match] [--invert-grep] [-F] [--no-mailmap] [--all] [--branches[=]] [--tags[=]] [--remotes[=]] [--pathspec-from-file ] [--pathspec-file-nul] [-- …] ``` ## Description Lists commits reachable from the selected revisions (default `HEAD`), newest first. Each line shows the short commit id, the change id, the author, when the commit was made and its subject (the first line of its message). Short ids follow `core.abbrev` (Git’s auto length from the number of packed objects when unset) and extend when needed so they always resolve with `grit show` or `grit log `. The author is the commit's author name when present, otherwise the part of their email address before the `@`. How much it shows depends on who is reading: - **On a terminal**, `grit log` shows the whole history, one line per commit, through the pager, and cuts every row to the terminal width so nothing wraps. Each row ends at the right edge with the lines the commit added and removed (`+12 -3`, against its first parent; merges and commits that change no lines show none). History is walked a batch at a time, so the first screen appears at once, and the walk stops when you quit the pager. `--no-pager` writes straight to the terminal. `-n` still limits the listing. - **For scripts and agents** (`--json`, `--markdown`, or output piped or redirected), it shows a page of twenty commits (or `-n`). When there is more history, the last line gives the command for the next page, `→ more: grit log --cursor=` (in Markdown, ``More history: run `grit log --cursor=` ``), and `--json` puts the same token in `next`. The pager is `GRIT_PAGER`, then the `core.pager` config, then `PAGER`, then `less`; an empty value or `cat` turns paging off. As in Git, `LESS=FRX` and `LV=-c` are set unless you set them, so a history that fits on one screen prints and exits. When the pager executable is missing or the shell cannot start it, grit prints a short note on stderr and writes the log straight to the terminal instead. On a [GitButler workspace](https://grit-scm.com/docs/status/index.md#gitbutler-workspaces), `grit log` with no revision starts from the applied branches instead of `HEAD`, so GitButler's workspace commit is not listed. Naming a revision (`grit log HEAD`) walks exactly that. In a shallow clone, commits listed in `.git/shallow` are treated as roots for `-p` and `--stat`: their patch is against the empty tree, the same as [`grit show`](https://grit-scm.com/docs/show/index.md). Revision selection matches [`grit revs`](https://grit-scm.com/docs/revs/index.md): plain tips, `A..B`, `A...B`, `^tip`, and the same ref-set flags (`--all`, `--branches`, and so on). With no revision arguments, `--branches`, `--tags`, and `--remotes` (and optional globs) replace the usual default start at `HEAD`; they do not add `HEAD` on top. If the selection matches no refs, the log is empty (exit 0), like `git log`. Path operands after `--` limit to commits that touch those paths (same cwd rules as [`grit diff`](https://grit-scm.com/docs/diff/index.md)). Attribute pathspecs such as `:(attr:myattr)` use the repository's current `.gitattributes` stack, like diff and status; they do not read historical attribute files from each commit's tree. Long-form magic pathspecs (`:(...)`) can appear as trailing operands without `--` (they are not treated as revision names). When a path filter matches no commits on a repository that already has history, human output is blank (not "No commits yet."). Path filters use the same author/date output as the default log, not the bare oid list from `grit revs`. Without `-n`, every matching commit is listed when paths are set (not capped at a page). The continuation token is short and local to the repository (`lw1.s.` plus eight characters, stored under `.git/grit/log-walk/`; in a read-only repository it is the longer self-contained `lw1.` form instead); it encodes the revision selection, so the next page needs only `--cursor=`. Path filters, commit filters (`--author`, `--grep`, …), pickaxe filters (`-S`, `-G`), `--reverse`, `--first-parent`, merge filters, `--skip`, and a one-shot `-n` without `--cursor` do not emit a continuation cursor; when such a listing stops early, the hint is ``→ more: rerun with a larger `-n` ``. Pickaxe filters match Git's `-S` and `-G`: `-S` keeps commits where the number of occurrences of a string changed in the diff against the first parent (literal string unless `--pickaxe-regex`); `-G` keeps commits where added or removed lines match a BRE. `-i` applies to both. Binary files are skipped for `-G` (not for `-S`). `-S` and `-G` cannot be combined. As in Git, the diff is limited to the path operands first, then deleted and added files are paired as renames (`diff.renames`, `diff.renameLimit`), and only then is each file tested. A rename whose old and new file hold the same number of matches (`-S`), or whose diff changes no matching line (`-G`), is not listed. A file moved into the path operands from outside them counts as added, so `grit log -S needle -- new/path` still lists the move. With `diff.renames=false` every rename is a deletion plus an addition. Merges are skipped, except under `--first-parent`, where they are diffed against their first parent. Author, committer, and message filters match [`grit revs`](https://grit-scm.com/docs/revs/index.md): patterns use Git's default POSIX BRE rules unless `-F` / `--fixed-strings` is set; multiple `--author` or `--committer` patterns OR together; multiple `--grep` patterns OR together unless `--all-match`; `--invert-grep` negates only the grep group; `-i` applies to all. When `log.mailmap` is unset or true (and `--no-mailmap` is not passed), `.mailmap` is applied before matching author or committer (same sources as Git). Invalid patterns exit **129** with `kind: "invalid_pattern"` in `--json` output. Diff detail flags (same family as [`grit diff`](https://grit-scm.com/docs/diff/index.md)) append output under each commit line: `-p` / `--patch` (unified patch), `--stat`, `--numstat`, `--shortstat`, `--name-only`, or `--name-status`. Only one format at a time. `-U` sets unified context lines for patches (default from `diff.context`). With `--stat`, each commit is also summarized in JSON under `stat` (legacy shape matching [`grit show`](https://grit-scm.com/docs/show/index.md)). By default, merge commits include no diff in any detail mode (same as `git log` without `-m`, `-c`, or `--cc`); there is no grit flag for a first-parent or combined merge diff yet. Path operands limit both which commits appear and the paths included in each patch. With `--graph`, human output draws a commit graph in the left margin (Unicode box-drawing by default, or ASCII `*|` with `--graph-ascii`). `--graph-unicode` is accepted as an alias for the default Unicode graph and implies `--graph`. Graph mode uses topological ordering like Git's `log --graph`, including with path and author/committer/grep filters (filtered commits are skipped while keeping lane connectivity). `--json` rejects `--graph` (exit **1**, `kind: "incompatible_flags"`) because graph columns are human-only; `--markdown` lists commits without graph columns and includes a note that `--graph` is human-only. `--graph` cannot be combined with diff format flags, `--group-by`, or `--cursor`. ## Options | Option | Description | | --- | --- | | `…` | Tips and ranges to walk (default `HEAD`). | | `-n`, `--limit ` | Stop after `N` commits (on a terminal too). On the default walk, this is the page size when continuing with `--cursor`. With path filters, caps how many matching commits are returned; omit it to list all matches. A one-shot `-n` without `--cursor` and without paths lists `N` commits with no `next` cursor. `--max-count` is Git’s well-known alias. Git’s `-1` / `-3` shorthand (for example `grit log -1` or `grit log --graph --oneline -3`) is accepted as `-n`. | | `--cursor ` | Continue a paged walk using the token from the `→ more` line or `next` from `--json` (short `lw1.s.` tokens are stored under `.git/grit/log-walk/`; long `lw1.` base64 tokens still work). An empty value is ignored. The cursor encodes the original revision selection, date cutoffs, and walk queue—when resuming, pass `--cursor=` alone (optional `-n` for page size). Revision operands, date filters, and ref-set flags are rejected when continuing. Cannot be combined with path operands. | | `--before ` | Alias for `--until` (date cutoff on committer date). | | `--skip ` | Skip `N` commits after ordering (cursor walks do not support `--skip`). | | `--since`, `--after ` | Exclude commits older than this date (committer date). Accepts Git approxidate strings (for example `2024-01-01`, `1 week ago`, `yesterday`) as well as ISO/RFC forms. | | `--until`, `--before ` | Exclude commits newer than this date. | | `--first-parent` | Follow only the first parent at merges (disables cursor paging). | | `--follow` | With exactly one literal file path after `--`, include commits before a rename of that file (Git `log --follow`). Still walks when the path no longer exists at the start commit. | | `--merges` | Only merge commits (conflicts with `--no-merges`; disables cursor paging). | | `--no-merges` | Exclude merge commits (conflicts with `--merges`; disables cursor paging). | | `--reverse` | Print the selected window oldest-first. `-n`, `--skip`, and date filters choose the window (newest `N` commits after skip); `--reverse` only flips that window (disables cursor paging). | | `--all` | Include every ref tip. | | `--branches[=]` | Branch tips, optionally filtered by glob under `refs/heads/`. | | `--tags[=]` | Tag tips, optionally filtered by glob under `refs/tags/`. | | `--remotes[=]` | Remote-tracking tips, optionally filtered by glob under `refs/remotes/`. | | `-p`, `--patch` | Unified patch under each commit (merge commits omit the patch). | | `--patch-text` | Git-apply-compatible unified patch per commit (`git diff --binary` shape). Honors trailing pathspecs. Paged walks print the `→ more` continuation after the final patch. Merge commits omit the patch body (same as `-p`). Human output only; not combinable with `--json` or `--markdown`. | | `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries (same as [`grit diff`](https://grit-scm.com/docs/log/diff.md/index.md)). | | `--stat` | Per-file change bars and totals under each commit. The JSON `stat` summary uses the same path selection and counts as `files` and `totals`; it does not compute patch hunks. | | `--numstat` | Tab-separated insertion/deletion/path lines per commit. | | `--shortstat` | One summary line per commit. | | `--name-only` | Changed paths only, one per line per commit. | | `--name-status` | Status letter and path(s) per line per commit. | | `-U`, `--unified ` | Context lines for `-p` (Git `-U`). | | `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries when `-p` is set. | | `--oneline` | One line per commit: collision-aware short oid and subject (`--json` unchanged). With `--decorate`, refs appear in parentheses after the oid. | | `--graph` | Draw a commit graph beside each commit in human output only (implies topological order; Unicode lanes by default). | | `--no-pager` | On a terminal, write straight to it instead of through the pager. | | `--graph-ascii` | Use ASCII `*|` lane characters in `--graph` output instead of Unicode. | | `--graph-unicode` | Same as `--graph` with Unicode lanes (default); implies `--graph`. Conflicts with `--graph-ascii`. | | `--decorate` | Show branch/tag/`HEAD` labels on each commit in human and Markdown output (refs are always in `--json`). | | `--group-by author` | Aggregate by author (mailmap-aware, sorted like `git shortlog -sne`). Uses the rev walk for the full selection (no cursor paging). | | `--count` | With `--group-by`, omit per-commit lists in `--json` (counts and author names only). | | `--author ` | Only commits whose author matches (repeatable; OR). | | `--committer ` | Only commits whose committer matches (repeatable; OR). | | `--grep ` | Only commits whose message matches (repeatable; OR unless `--all-match`). | | `-S ` | Only commits where this string's occurrence count changed in the tree diff vs the first parent. | | `-G ` | Only commits where added/removed lines match this BRE (binary files skipped). | | `--pickaxe-regex` | Treat `-S` as a BRE instead of a literal string (not valid with `-G`). | | `-i`, `--regexp-ignore-case` | Case-insensitive patterns for author, committer, grep, and pickaxe. | | `--all-match` | Every `--grep` pattern must match. | | `--invert-grep` | Exclude commits that match the grep group. | | `-F`, `--fixed-strings` | Literal string patterns (no regex). | | `--no-mailmap` | Do not apply `.mailmap` for author/committer matching. | | `--pathspec-from-file ` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. | | `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. | | `…` | After `--`, limit to commits that touch these paths (cwd-relative under the work tree, like `grit diff`; all matches unless `-n` is set). | ## Examples Browse the whole history on a terminal (in the pager): ```console $ grit log b52cca6 wuwxlkvx Ada Lovelace 2 minutes ago Handle empty input +9 -3 5fbefea nrntqslp Ada Lovelace 1 hour ago Add a greeting test +24 -0 ... 2efcc2d krnxwkpm Ada Lovelace 3 days ago Start the project +41 -0 ``` From a script or an agent, the same command shows a page and how to get the next one: ```console $ grit log | cat b52cca6 wuwxlkvx Ada Lovelace 2 minutes ago Handle empty input 5fbefea nrntqslp Ada Lovelace 1 hour ago Add a greeting test ... → more: grit log --cursor=lw1.s.a1b2c3d4 ``` Show the next page: ```console $ grit log --cursor=lw1.s.a1b2c3d4 ``` See which files each recent commit touched: ```console $ grit log --stat b52cca6 ada 2 minutes ago Handle empty input src/parse.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) 5fbefea ada 1 hour ago Add a greeting test ... ``` Get the subjects of the last twenty commits: ```console $ grit log --json --filter '.commits[].subject' ``` Show the five newest commits: ```console $ grit log -n 5 ``` History of one file: ```console $ grit log -- src/lib.rs ``` Commits on a range: ```console $ grit log -n 20 main..feature ``` Authors and dates: ```console $ grit log --author=ada --since='2 weeks ago' -n 20 ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/log/schemas/log/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `commits` | array | Up to twenty commits by default, or up to `-n` when set, newest first. Each entry uses the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape (`oid`, `parents`, `author`, `committer`, `subject`, `message`, `refs`, `change_id`, `change_id_stored`, optional `relative_date`). Defaults to `[]` when omitted (for example with `--group-by author`, which fills `groups` instead). | | `commits[].files` | array | With any diff detail flag: same [`FileDiff`](https://grit-scm.com/docs/log/schemas/diff/v1.json/index.md) objects as [`grit diff`](https://grit-scm.com/docs/diff/index.md) (including `stat` sub-objects for `--stat` / `--numstat`). | | `commits[].totals` | object | With `--stat`, `--numstat`, `--shortstat`, or `-p`: `files_changed`, `insertions`, `deletions` (for `-p`, summed from patch hunks). Omitted with `--name-only` and `--name-status`. | | `commits[].stat` | object | Only with `--stat`: duplicate summary in the legacy [`grit show`](https://grit-scm.com/docs/show/index.md) `stat` shape (`files`, `files_changed`, …). | | `groups` | array | With `--group-by author`: `{name, email, count, commits?}` sorted like `git shortlog -sne`. `commits` holds full [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) rows unless `--count` is set. | | `next` | string or null | Opaque continuation cursor (prefix `lw1.`) to pass to `--cursor` for the next page, or `null` when there is no more history or when the walk does not support paging (paths, `--reverse`, `--group-by`, and similar). | | `truncated` | boolean | **Required.** `true` when more commits matched the query than returned in this page (`-n` or the default page size). | Combining `--json` with `--graph` fails with exit **1** and `{"error":"…","kind":"incompatible_flags"}` on stdout (same message as human mode). Example: ```json { "commits": [ { "oid": "83352a61f6715ec3f0a297c6d6150725154fb833", "parents": [ "062ca6e74f5603f4d09063c0f46cd07d8c96e019" ], "author": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "committer": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "subject": "second", "message": "second", "refs": [ { "name": "HEAD", "kind": "head" }, { "name": "main", "kind": "branch" } ], "relative_date": "[TIME_AGO]", "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk", "change_id_stored": true }, { "oid": "062ca6e74f5603f4d09063c0f46cd07d8c96e019", "parents": [], "author": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "committer": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "subject": "first", "message": "first", "refs": [ { "name": "feature", "kind": "branch" } ], "relative_date": "[TIME_AGO]", "change_id": "prkwwuwrytvxrwozplzrxmvozwutplkq", "change_id_stored": true } ], "next": null, "truncated": false } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/log/schemas/log/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a bullet list of commits (short oid, subject, author, relative date): ```text - `b52cca6` Handle empty input (Ada Lovelace, 2 minutes ago) - `5fbefea` Add a greeting test (Ada Lovelace, 1 hour ago) More history: run `grit log --cursor=lw1.s.a1b2c3d4` ``` When the current branch has no commits yet (for example right after [`grit init`](https://grit-scm.com/docs/log/init.md/index.md)): ```console $ grit log error: no commits yet on branch main — make one with `grit commit "message"` hint: make one with `grit commit "message"` ``` Structured `--json` failures use `kind` `branch_no_commits` (see [Exit codes](https://grit-scm.com/docs/exit-codes/index.md)). ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit revs](https://grit-scm.com/docs/revs/index.md), [grit shortlog](https://grit-scm.com/docs/shortlog/index.md), [grit show](https://grit-scm.com/docs/show/index.md) # https://grit-scm.com/docs/blame/index.md # grit blame > Show who last modified each line of a file. ## Synopsis ```text grit blame [] [--rev ] [--contents ] [-L RANGE] [--first-parent] [--group] [-w] [-M] [-C]... [--ignore-rev ]... [--ignore-revs-file ]... [--] ``` ## Description Walks history for one file and prints each line with the commit that last modified it, the author, when that commit was made, and the line number in the blamed file. Human and `--markdown` output use collision-aware short commit ids (`core.abbrev`); `--json` always includes full oids. The file operand uses Git pathspec cwd rules (same as [`grit diff`](https://grit-scm.com/docs/diff/index.md)): from a subdirectory, a bare name like `f.txt` refers to that path under your current directory. Paths returned by `grit status --json` can be passed directly as the file operand, including reversible `grit+pathhex:` strings for non-UTF-8 filenames. These encoded paths are repository-relative, even when invoked from a subdirectory. Blame decodes one storage layer and compares exact filename bytes, so raw invalid-byte names, valid Unicode names, and literal names beginning with `grit+pathhex:` remain distinct. JSON `original_path` values (both lines and grouped hunks) use the same reversible encoding, including rename and copy origins. In Rust, use `repo_relpath::storage_bytes` to recover the original bytes; use `storage_string` when supplying raw names that begin with the reserved prefix. ### Uncommitted changes Without a revision, blame reads the file from the working tree, so line numbers match what is on disk (and in your editor). The file is cleaned the way `grit add` would store it (line-ending conversion, clean filters; a symlink blames its target path), then blamed as if it were a commit on top of `HEAD`: lines that match `HEAD` keep their history, and lines that exist only in the working tree are reported as **not committed**. They show the null commit `0000000` and the author `Not Committed Yet`, and every later line keeps its working-tree line number. During an unfinished merge, the commits in `MERGE_HEAD` are parents too, so lines brought in by the merge are blamed on the incoming branch. With `--first-parent` only `HEAD` is a parent, so those lines are not committed (as in Git). A file that is staged but not yet committed is entirely not committed; a file that is neither committed nor staged is an error. When the working tree matches `HEAD`, blame is the same as `--rev HEAD`. Nothing is written to the object database. Passing a revision (`` or `--rev`, including `HEAD`) blames that commit's file and ignores the working tree. `--contents ` blames the given file's content instead (`-` reads standard input), on top of the revision or `HEAD`; this is how an editor can blame an unsaved buffer. Those uncommitted lines show the author `External file (--contents)`. In a bare repository, blame without `--contents` uses `HEAD`. `-L` ranges (numbers, `/regex/`, `:funcname`) are resolved against the same text that is blamed, so `-L /pattern/` finds the line where it sits in the working tree or `--contents` buffer. For a literal root filename such as `grit+pathhex:6162`, `./grit+pathhex:6162` also works; ordinary operands (including `../` from a subdirectory) are normalized before the result is escaped for storage lookup. Blame visits commits newest first (by committer date) and keeps one entry per commit that still owns lines. When a merge hands lines to several parents and those branches meet again at an older commit, their lines join that commit's entry, so a commit is normally diffed against its parents once, however many merge paths reach it (a commit whose timestamp is older than one of its descendants can be visited again when clocks were skewed). File versions that no queued commit needs are dropped once more than 64 are cached, and parent/child line maps are cached only when `--ignore-rev` or `-C` can ask for the same pair twice. On git.git's `Makefile` (4.1k lines touched across thousands of merges) that is about 1.2 s and 335 MB peak RSS on a 4-core Linux VM, against about 1.0 s and 290 MB for system `git blame`. Each parent step attributes lines the way `git blame` places hunks: the diff sees the files as Git hands them to xdiff (with the common tail dropped in 1 KiB blocks), counts how often each line occurs across all of that, and slides inserted or deleted blocks into the unchanged ends exactly as Git's compaction and indent heuristic do. Lines still being tracked that fall in an unchanged prefix or suffix beyond the reach of such a slide (past the first unchanged line whose text appears nowhere in the edited region) are mapped to the parent without running a diff, and only a window around the edit is diffed; when every remaining line is outside that reach, the step skips diffing entirely. With `-L`, that often avoids almost all diffs on large files whose recent edits are far from the requested range (for example tail-only churn). Stretches of history where the file does not change are skipped by reading only each commit's header and the tree entries on the file's path (unchanged subdirectories are not re-read), and parsed tree data is released once its entry is found. Earlier full-file measurements showed: blaming `README.md` in git.git (22.5k first-parent commits) takes about 0.37 s and 290 MB peak RSS, against about 0.29 s and 245 MB for system `git blame`. On this repository, blaming `grit-lib/src/pack.rs` (~4.6k lines, ~90 commits) completes in a few seconds on a release build; system `git blame` on the same path is still faster on some very large real-world files, and parity work continues. With `-L`, packed history is read with positioned reads of individual indexed entries. Ranged blame retains up to 32 pack readers per object directory, with eight 16 KiB compressed windows per reader. Evicting an inactive reader closes its file and releases its windows; active reads keep their original file handle until completion. It uses private delta-base caches capped at 16 MiB per object directory, including alternates, and leaves the repository's shared caches and configuration untouched. Pack residency therefore follows the entries being read rather than every pack page touched during the walk. Memory also includes pack indexes, visited commit/path metadata, and complete blobs and delta chains needed to compare the requested lines; a three-line result does not imply that only three lines of source data are decoded. See the [ranged blame measurements](https://grit-scm.com/docs/benchmarks/index.md#ranged-blame-pack-residency). When a commit renamed or moved the file (including rename-and-edit in the same commit), blame follows the predecessor path using rename detection with Git's default similarity threshold (50%, like `git blame` with `-M`). This behavior is independent of `diff.renames` (system Git blame still follows renames when that diff setting is off). Git's `diff.renameLimit` and `status.renameLimit` cap how many rename pairings diff/status consider; they do not change blame's similarity percentage. On Unix, explicit file operands must be valid UTF-8. An operand containing invalid UTF-8 bytes is rejected before the command runs, with exit status **2** and no changes to the repository. Human output reports the usage error on stderr; `--json` writes an error object with `kind: "usage"` on stdout, and `--markdown` writes `**Error:**` on stdout. The argument is never replaced with a similar Unicode filename. Adding or removing the final newline attributes the last line to the commit that changed it. With `-w` / `--ignore-all-space`, newline-only changes are ignored along with other whitespace-only changes. Line content in the output excludes LF in either mode. Lines attributed to a commit with no effective parents (a repository root or a shallow boundary in `.git/shallow`) are prefixed with `^` in human output, the same marker Git uses. `--json` sets `"boundary": true` on those lines. ### Benchmarking Measured on 2026-10-26 on a 4-core Linux VM with system Git 2.55.0 and release builds. The baseline is `origin/main` at `5d557d222cbe621d4d3bd41f7ecf1ab7d71c477b`. These are the existing deep-history and large-tail blame fixtures used by `grit-bench`. Each cell shows median wall time in milliseconds / peak RSS in KiB. Nine fresh-process measurements are interleaved across Git, baseline grit, and fixed grit after two warmups. Executable files and repository data are warmed equally before measurement; stdout is discarded. Git uses `blame --porcelain`, grit uses `blame`, and peak RSS comes from `/usr/bin/time -v`. | Scenario | System Git (ms / KiB) | Baseline grit (ms / KiB) | Fixed grit (ms / KiB) | | --- | ---: | ---: | ---: | | 2,000 commits, full file | 12.31 / 7,296 | 21.53 / 16,780 | 21.02 / 16,860 | | 5,000 lines / 150 commits, full file | 53.37 / 7,736 | 41.21 / 29,872 | 37.13 / 29,832 | | 5,000 lines / 150 commits, `-L 100,120` | 52.33 / 7,736 | 31.02 / 28,252 | 26.90 / 27,708 | Wall time improves by about 2–13% against the baseline. Peak RSS is effectively flat for deep history (+80 KiB, within observed run variation), and falls by 40 KiB for full-file tail churn and 544 KiB for the range. The unchanged-prefix/suffix shortcut remains enabled. #### Rename metadata regression Measured on 2026-10-27 on a 4-core Linux x86_64 VM with system Git 2.55.0 and Rust 1.99.0 release builds. Baseline grit is `origin/main` at `80dc322f7c2fafae948c30b9e6de159f884504e0`. Nine measurements are interleaved across Git, baseline grit, and the fix after two warmups, with builds and tests stopped. Each cell shows median wall milliseconds / peak RSS KiB; wall time uses a monotonic subprocess timer and RSS comes from `/usr/bin/time -v`. Output is discarded. The real-history case is `--rev 7e34d8174d -L 1,3 --json git-gui/git-gui.sh` in git/git (Git uses `--line-porcelain`). The tail cases use the existing 5,000-line / 150-commit fixture with `grit blame` versus `git blame --porcelain`, and `-L 100,120` for the range. | Scenario | System Git (ms / KiB) | Baseline grit (ms / KiB) | Fixed grit (ms / KiB) | | --- | ---: | ---: | ---: | | git/git git-gui, lines 1–3 | 191.81 / 83,372 | 527.11 / 335,004 | 527.43 / 334,968 | | Large-tail full file | 70.37 / 6,252 | 52.35 / 26,828 | 51.61 / 26,760 | | Large-tail lines 100–120 | 69.89 / 6,304 | 42.44 / 25,128 | 42.33 / 25,188 | The source-path fix retains the unchanged-prefix/suffix shortcut. Median wall time changes by at most 1.5%; the largest peak RSS increase is 60 KiB against baseline in this run. ### Benchmarking encoded paths Measured on a 4-core Linux x86_64 VM with system Git 2.55.0 and Rust 1.99.0, using `dist` builds of main (`5a715a522`) and this fix. Each cell reports median **wall milliseconds / peak RSS KiB** from ten measured invocations after two warmups, interleaving Git, main, and the fix on an idle VM. RSS comes from `/usr/bin/time -v`; stdout is discarded. Grit uses `blame --json`; Git uses `blame --line-porcelain`. Ranges use `-L 1,200`. The packed fixture has 201 commits and two identical 4,096-line files, one UTF-8 path and one raw-byte directory/filename, with Git-written changed-path Bloom filters. The real-repository case blames `grit-lib/src/blame.rs` at the baseline revision, whose file history has 76 changes. | Scenario | System Git | Main | Fix | | --- | ---: | ---: | ---: | | Packed UTF-8, full file | 73.9 / 30,226 | 101.7 / 75,230 | 102.7 / 75,262 | | Packed UTF-8, lines 1–200 | 56.5 / 30,174 | 71.1 / 68,962 | 71.9 / 68,810 | | Packed encoded path, full file | 74.5 / 30,266 | Path error | 101.7 / 75,290 | | Packed encoded path, lines 1–200 | 56.1 / 30,196 | Path error | 70.7 / 69,194 | | Grit repository, UTF-8, full file | 97.6 / 40,774 | 92.8 / 68,084 | 92.2 / 68,010 | | Grit repository, UTF-8, lines 1–200 | 63.5 / 39,864 | 72.9 / 64,658 | 72.2 / 64,672 | UTF-8 timings remain within 1.2% of the baseline in this run, with no material RSS increase. Encoded paths now complete both full-file and ranged blame; main's path errors provide no comparable successful-operation timing. ## Options | Option | Description | | --- | --- | | `` | Optional revision before `--` (same values as `--rev`). Without a revision the working-tree file is blamed on top of `HEAD`. | | `--rev ` | Blame the file as committed at this revision, ignoring the working tree. Cannot be combined with a positional ``. | | `--contents ` | Blame this file's content (`-` for standard input) instead of the working tree, on top of the revision (default `HEAD`). Lines not in the revision are reported as not committed. | | `-L RANGE` | Limit output with a Git-style line range in the final file (see below). Blame stops once every line in the range is attributed. | | `--lines` | Same as `-L` (long form). | | `--first-parent` | At merge commits, follow only the first parent when attributing lines. Default matches Git blame: all parents are considered. | | `--group` | With `--json` only: emit grouped `hunks[]` instead of per-line `lines[]` (smaller on large files). Human and `--markdown` output stay per line. | | `--ignore-rev ` | Treat this commit as transparent while walking history (repeatable). Unknown revisions are an error. | | `--ignore-revs-file ` | Read full-length commit oids to ignore, one per line (`#` comments, blank lines skipped). Repeatable; `""` clears entries loaded from config or earlier files. Missing files are an error. Relative paths are resolved from the repository root. Config `blame.ignoreRevsFile` (multi-valued) is applied before CLI files. | | `-w`, `--ignore-all-space` | Ignore whitespace when comparing lines between revisions (same rules as [`grit diff -w`](https://grit-scm.com/docs/diff/index.md)). Whitespace-only edits do not move blame to a newer commit. | | `-M`, `--move-detection` | Detect lines moved within the same file (`git blame -M`). Relocated blocks are blamed on the commit that originally wrote them when the move scores above Git's default threshold. | | `-C`, `--copy-detection` | Detect lines copied from other files (repeat up to three times for deeper search, matching `git blame -C` / `-C -C` / `-C -C -C`). A fourth `-C` is rejected with exit code 2. Using `-C` also enables move detection, matching Git (`-C` implies `-M`). | Human output prefixes ignored lines with `?` and lines that cannot be blamed past an ignored commit with `*` (same markers Git uses when `blame.markIgnoredLines` / `blame.markUnblamableLines` are enabled). ## Examples Blame a file as it is in the working tree: ```console $ grit blame src/lib.rs 0000000 (Not Committed Yet just now 1) // edited a1b2c3d (ada 2 days ago 2) use std::io; f4e5d6c (bob 1 week ago 3) fn main() { ``` Blame the committed file, or an unsaved editor buffer piped on standard input: ```console $ grit blame --rev HEAD src/lib.rs $ cat buffer.rs | grit blame --contents - src/lib.rs ``` Blame an older revision and a slice of lines: ```console $ grit blame v1.0 -- README.md $ grit blame --rev=v1.0 -L 10,25 README.md $ grit blame -L 10,+20 src/lib.rs $ grit blame -L '/fn main/' src/main.rs $ grit blame -L ':my_function' src/lib.rs ``` Scripting with JSON: ```console $ grit blame --json story.txt ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/blame/schemas/blame/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `file` | string | Work-tree path that was blamed (repository-relative after cwd resolution). | | `rev` | string | Full commit oid of the start revision (the `HEAD` commit unless a revision was given, also when blaming the working tree or `--contents`). | | `lines` | array | One record per line (after any `-L` filter), in final-line order. | | `lines[].commit` | string | Full commit oid for the line; all zeros for a line that is not committed. | | `lines[].original_line` | number | 1-based line number in the originating commit. | | `lines[].original_path` | string | Reversibly stored path in the originating commit, preserving filename bytes through renames and copies. | | `lines[].final_line` | number | 1-based line number in the blamed file (the working tree or `--contents` when those are blamed). | | `lines[].content` | string | Line text (lossy UTF-8 when `encoding_lossy` is true). | | `lines[].encoding_lossy` | boolean | Present and `true` when the line bytes were not valid UTF-8 and `content` used lossy decoding. Raw bytes are not included in JSON; use [`grit_lib::blame::BlameAttributedLine::content_bytes`](https://docs.rs/grit-lib/latest/grit_lib/blame/struct.BlameAttributedLine.html#structfield.content_bytes) from the library when you need them. | | `lines[].ignored` | boolean | Present and `true` when the line was attributed through an ignored revision. | | `lines[].unblamable` | boolean | Present and `true` when the line was added in an ignored revision and cannot be blamed further back. | | `lines[].boundary` | boolean | Present and `true` when the attributed commit has no effective parents (root or shallow boundary). Human output prefixes the line with `^`. | | `lines[].not_committed` | boolean | Present and `true` when the line exists only in the working tree or `--contents` buffer. `commit` is then all zeros and `original_line` equals `final_line`. | | `commits` | object | Map of commit oid → metadata for every line. | | `commits..author` | object | Author with `name`, `email`, and `date` (RFC 3339 — same shape as [`grit show`](https://grit-scm.com/docs/show/index.md)). Author date is only here, not repeated on each line or hunk. | | `commits..summary` | string | First line of the commit message. | Lines that are not committed share the all-zeros entry in `commits`: its author is `Not Committed Yet` (or `External file (--contents)`) with email `not.committed.yet`, dated when the command ran, and its summary repeats that label. ### Grouped JSON (`--json --group`) Same top-level `file`, `rev`, and `commits` map. Replaces `lines[]` with `hunks[]` (omit `lines`): | Field | Type | Meaning | | ----- | ---- | ------- | | `hunks[].commit` | string | Full commit oid for every line in the hunk. | | `hunks[].original_path` | string | Reversibly stored originating path for the hunk (same encoding as status). | | `hunks[].original_start` | number | 1-based first line in the originating commit. | | `hunks[].final_start` | number | 1-based first line in the blamed revision. | | `hunks[].count` | number | Number of consecutive final lines in the hunk. | | `hunks[].ignored` | boolean | Present and `true` when the hunk passed through an ignored revision. | | `hunks[].unblamable` | boolean | Present and `true` when blame could not continue past an ignored revision. | | `hunks[].not_committed` | boolean | Present and `true` when the hunk's lines are not committed (`commit` is all zeros). | | `hunks[].lines` | array of strings | Line text for each row in the hunk (same order as final lines). | | `hunks[].line_encoding_lossy` | array of boolean | Present when any line in the hunk was decoded lossily; parallel to `lines`, one flag per row. Omitted when every line is valid UTF-8. | Every `original_path` names the file in its reported `commit`, even when a line range crosses rename-and-edit commits or subtree imports. After decoding the filename bytes, read that commit's file at `original_line` (or `original_start` for a hunk). The path can differ from both the requested path and intermediate names in history. Hunk boundaries match `git blame --porcelain` group headers (` `). Prefer `--group` for agents and scripts on large files. Example: ```json { "file": "story.txt", "rev": "92501f188ae0815af09a0cef6e121eddda4113cf", "lines": [ { "commit": "919c45f33de5e5c0bd05f8ffb089f697f4644976", "original_line": 1, "original_path": "story.txt", "final_line": 1, "content": "alpha ONE" } ], "commits": { "919c45f33de5e5c0bd05f8ffb089f697f4644976": { "author": { "name": "Blame Test", "email": "blame@example.com", "date": "2024-03-09T12:26:40Z" }, "summary": "edit first line" } } } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v1](https://grit-scm.com/docs/blame/schemas/blame/v1.json/index.md) Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract. ```text ## Blame: `tracked.txt` Revision `83352a61f6715ec3f0a297c6d6150725154fb833` | Line | Mark | Commit | Author | Date | Original | Content | | ---: | :---: | --- | --- | --- | ---: | --- | | 1 | | `0000000` | Not Committed Yet | [TIME_AGO] | 1 | tracked modified | ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also - [`grit log`](https://grit-scm.com/docs/blame/log.md/index.md) — commit history - [`grit show`](https://grit-scm.com/docs/blame/show.md/index.md) — one commit's message and file stats # https://grit-scm.com/docs/reflog/index.md # grit reflog > Show, delete, or expire reflog entries. ## Synopsis ```text grit reflog [REF] [-n N] [--since DATE] [--until DATE] [--grep PAT] grit reflog list [-n N] grit reflog delete ... grit reflog expire [--all] [--expire ] [--expire-unreachable ] [--dry-run] ``` ## Description Inspect and maintain reference logs. With no subcommand, lists entries for `REF` (default `HEAD`) in newest-first order. Each line shows the selector (`REF@{n}`), the `new_oid` after the update, a relative date, and the log message. Filters apply to the reflog entry identity timestamp (not the commit date). Scanning stops once `-n` matches are collected, so large logs are not fully materialized. `delete` removes explicit entries without rewriting the branch tip. In `ref@{n}`, `n` is a nonnegative integer: `0` selects the newest entry, `1` the next older entry. Date selectors and bare indices are not accepted by `delete`. `list` prints every ref that currently has a reflog file (sorted), bounded by `-n` / `--limit`. `expire` applies Git-compatible `gc.reflogExpire*` rules (same layering as `grit gc`), using explicit `--expire` / `--expire-unreachable` values when given and merged config otherwise. An entry older than the unreachable cutoff is dropped when its old or new commit is not reachable from the ref's tip (from any ref for `HEAD`), with annotated tags peeled as current Git does; when the tip does not name a commit, every such entry is dropped. The check walks commits only: history down to the `--expire` cutoff first, and the rest once, only if an entry names an older commit. It never reads trees or fetches missing objects in a partial clone. Refs expired in one run share the commits already read, so expiring many branches with old entries costs little more than one. With `--dry-run`, `expire` reports per-ref prune counts without rewriting any log file. A branch literally named `list` is ambiguous with the `list` subcommand; use the full ref (`refs/heads/list`) when showing that branch's entries. ## Options | Option | Description | | --- | --- | | `REF` | Ref to list (default `HEAD`). Branch short names are accepted (`main` → `refs/heads/main`). | | `-n`, `--max-count` | Show at most `N` matching entries (newest first). Alias: `--limit`. | | `--since`, `--after` | Exclude entries older than this date (Git `--since`). | | `--until`, `--before` | Exclude entries newer than this date (Git `--until`). | | `--grep` | Keep entries whose message contains this substring (case-sensitive). | | `list` | List refs that have a reflog (`-n` / `--limit` bounds the list). | | `delete` | Remove one or more `ref@{n}` selectors. | | `expire` | Drop old reflog entries using gc expiry rules. | | `--all` | On `expire`, walk every ref under `refs/`, not only refs that already have log files. | | `--expire` | Reachable expiry time (`now`, `never`, `2.weeks.ago`, Unix time, …). | | `--expire-unreachable` | Unreachable expiry time (same syntax as Git). | | `--dry-run` | On `expire`, preview pruning without writing reflog files. | ## Examples Show the last three `HEAD` reflog entries: ```console $ grit reflog HEAD -n 3 HEAD@{0} b5ea30de417ac84c09b8cfc0acf5f2c39efc611f 2 minutes ago commit: second HEAD@{1} 72934dedd47ecaf7e340fd6c5ef46620187fb317 1 hour ago commit: first ``` Entries since yesterday whose message mentions `checkout`: ```console $ grit reflog --since=yesterday --grep=checkout -n 20 --json ``` Delete one entry: ```console $ grit reflog delete main@{1} Deleted main@{1} ``` Expire using gc defaults: ```console $ grit reflog expire Pruned 0 reflog entries ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/reflog/schemas/reflog/v1.json/index.md) (show entries), [list v1](https://grit-scm.com/docs/reflog/schemas/reflog.list/v1.json/index.md), [delete v1](https://grit-scm.com/docs/reflog/schemas/reflog.delete/v1.json/index.md), [expire v1](https://grit-scm.com/docs/reflog/schemas/reflog.expire/v1.json/index.md) List (`grit reflog [REF]`): | Field | Type | Meaning | | --- | --- | --- | | `ref` | string | Ref that was listed. | | `truncated` | boolean | `true` when listing stopped before the oldest entry (typically because of `-n`). | | `entries` | array | Newest-first entries. | | `entries[].index` | integer | Newest-first index in the full reflog (`0` is latest). | | `entries[].oid` | string | Hex object id stored as `new_oid` for that entry (v1 alias of `new_oid`). | | `entries[].old_oid` | string | Previous object id before the update. | | `entries[].new_oid` | string | Object id after the update (same as `oid`). | | `entries[].date` | string | Reflog committer time in RFC 3339 (original offset preserved). | | `entries[].relative_date` | string | Human-relative time from the entry identity. | | `entries[].committer` | object | `name`, `email`, and `date` (same shape as `log` / `blame`). | | `entries[].message` | string | Reflog message (may be empty). | | `entries[].action` | string (optional) | Best-effort prefix before the first `": "` in the message. | ```json { "ref": "HEAD", "truncated": false, "entries": [ { "index": 0, "oid": "b5ea30de417ac84c09b8cfc0acf5f2c39efc611f", "old_oid": "72934dedd47ecaf7e340fd6c5ef46620187fb317", "new_oid": "b5ea30de417ac84c09b8cfc0acf5f2c39efc611f", "date": "2026-10-23T18:15:00Z", "relative_date": "2 minutes ago", "committer": { "name": "Example User", "email": "user@example.com", "date": "2026-10-23T18:15:00Z" }, "message": "commit: second", "action": "commit" } ] } ``` Delete (`grit reflog delete …`): | Field | Type | Meaning | | --- | --- | --- | | `deleted` | array of strings | Selectors that were removed. | List refs (`grit reflog list`): | Field | Type | Meaning | | --- | --- | --- | | `refs` | array | Sorted ref names that have a log. | | `refs[].ref` | string | Full ref name (for example `refs/heads/main`). | ```json { "refs": [ { "ref": "HEAD" }, { "ref": "refs/heads/main" } ] } ``` Expire (`grit reflog expire`): | Field | Type | Meaning | | --- | --- | --- | | `entries_pruned` | integer | Reflog lines removed (or that would be removed with `--dry-run`). | | `dry_run` | boolean | `true` when `--dry-run` was passed (default `false`). | | `refs` | array | Per-ref prune counts. | | `refs[].ref` | string | Ref that was processed. | | `refs[].pruned` | integer | Entries pruned on that ref. | ```json { "entries_pruned": 0, "dry_run": false, "refs": [] } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v1](https://grit-scm.com/docs/reflog/schemas/reflog/v1.json/index.md) (show entries); subcommands use [list v1](https://grit-scm.com/docs/reflog/schemas/reflog.list/v1.json/index.md), [delete v1](https://grit-scm.com/docs/reflog/schemas/reflog.delete/v1.json/index.md), and [expire v1](https://grit-scm.com/docs/reflog/schemas/reflog.expire/v1.json/index.md). List mode emits a bullet per entry with `REF@{n}`, abbreviated oid, **absolute** `date`, and message (human mode keeps relative dates). Delete and expire print short confirmation lines. ```text - HEAD@{0} 83352a6 2023-11-14T22:13:20Z commit: second - HEAD@{1} 062ca6e 2023-11-14T22:13:20Z commit (initial): first ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit log](https://grit-scm.com/docs/reflog/log.md/index.md), [grit gc](https://grit-scm.com/docs/reflog/gc.md/index.md) # https://grit-scm.com/docs/shortlog/index.md # grit shortlog > List the commits on this branch that aren't on the target branch yet. ## Synopsis ```text grit shortlog [-n COUNT] [--behind] [--stat | --name-only] [--target REF] grit sl [-n COUNT] [--behind] [--stat | --name-only] [--target REF] grit ahead [-n COUNT] [--behind] [--stat | --name-only] [--target REF] ``` ## Description Shows the current branch, its target branch, and every commit on the current branch that the target doesn't have, newest first. It's the list of what you would be proposing if you opened a pull request now. The target branch is found the same way as for [`grit status`](https://grit-scm.com/docs/status/index.md#the-target-branch): the `target.branch` setting, then `origin/master`, `origin/main`, `master` and `main`. Use `--target ` to compare against any ref or revision instead (branch, remote-tracking ref, tag, or commit id). `grit ahead` is an alias for the same command — grit's shortlog means commits ahead of a target, not Git's author-grouped `shortlog -sne`. Unlike `grit status`, which shows at most ten commits, `grit shortlog` lists up to `-n` / `--max-count` commits (default **100**). Full ahead and behind **counts** are always exact even when the lists are truncated. When no target branch can be discovered, the result is an empty list. An explicit `--target` that cannot be resolved is an error. With `--behind`, also lists commits that are on the target but not on this branch yet (the commits you would pick up by fast-forwarding or merging the target). For author commit counts over an arbitrary revision range (Git's `shortlog -sne` shape), use [`grit log --group-by author`](https://grit-scm.com/docs/shortlog/log.md/index.md#options) instead — `grit shortlog` means commits ahead of the target branch, not author grouping. ## Options | Flag | Meaning | | ---- | ------- | | `--target ` | Ref or revision to compare against instead of the discovered target branch. | | `-n`, `--max-count` | Maximum commits to list on each side (default 100). Counts stay exact when the list is truncated. | | `--behind` | Also list commits on the target that are not on this branch (`behind` / `behind_commits` in JSON). | | `--stat` | Per-commit diffstat (same shape as [`grit log --stat`](https://grit-scm.com/docs/shortlog/log.md/index.md)). | | `--name-only` | Per-commit changed paths (same shape as [`grit log --name-only`](https://grit-scm.com/docs/shortlog/log.md/index.md)). | Only `--stat` and `--name-only` are supported for per-commit diffs; use [`grit log`](https://grit-scm.com/docs/shortlog/log.md/index.md) for patch and other formats. Global options: [global options](https://grit-scm.com/docs/global-options/index.md). ## Examples ```console $ grit shortlog On feature Ahead of origin/main by 2 commits cf18394 ada 2 hours ago Say hi 9a1c2e0 ada 3 hours ago Add a greeting test ``` List at most one ahead commit and show how far behind the target you are: ```console $ grit sl -n 1 --behind --json --filter '{ahead, behind, truncated, behind_truncated, commits: .commits|length, behind_commits: .behind_commits|length}' ``` Per-commit stats for the ahead list: ```console $ grit shortlog --stat ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/shortlog/schemas/shortlog/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `branch` | string | Current branch name. | | `target` | string or null | Target branch used for comparison, or `null` when none was found. | | `ahead` | number | How many commits are on the branch but not on the target. | | `behind` | number or null | How many commits are on the target but not on the branch; `null` when no target was found. | | `commits` | array | Ahead commits, newest first, each using the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape plus optional `stat` / `files` when `--stat` / `--name-only` is set. | | `truncated` | boolean | `true` when `ahead` exceeds the number of commits listed. | | `behind_commits` | array or null | Behind commits when `--behind` is set; same commit object shape as `commits`. | | `behind_truncated` | boolean or null | `true` when `behind` exceeds `behind_commits` length; only with `--behind`. | | `next` | null | Reserved for future paging; always `null` today. | Example: ```json { "branch": "main", "target": "main", "ahead": 2, "behind": 0, "commits": [], "truncated": false, "next": null } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/shortlog/schemas/shortlog/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a branch summary and commit bullets: ```text # Branch `feature` Ahead of `main` by **2** commits. - `cf18394` Say hi (ada, 1 hour ago) - `9a1c2e0` Add a greeting test (ada, 2 hours ago) ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for the shared rules and structured `--json` `kind` values. ## See also [grit status](https://grit-scm.com/docs/status/index.md), [grit log](https://grit-scm.com/docs/log/index.md), [grit config](https://grit-scm.com/docs/config/index.md) # https://grit-scm.com/docs/revs/index.md # grit revs > List or count commits matching revision ranges. ## Synopsis ```text grit revs ... [-n ] [--count] [--left-right] [--cherry-mark] [--skip ] [--since|--after ] [--until|--before ] [--first-parent] [--follow] [--merges | --no-merges] [--reverse] [--author ] [--committer ] [--grep ] [-S ] [-G ] [--pickaxe-regex] [-i] [--all-match] [--invert-grep] [-F] [--no-mailmap] [--all] [--branches[=]] [--tags[=]] [--remotes[=]] [--pathspec-from-file ] [--pathspec-file-nul] [-- ...] ``` ## Description Walks commits reachable from one or more revision ranges and prints each commit’s full object id and subject (first line of the message), one commit per line. Ranges use the same syntax as Git’s `rev-list`: plain tips, `A..B`, symmetric difference `A...B`, and `^tip` exclusions. With no revision arguments, `--branches`, `--tags`, and `--remotes` (and optional globs) select only those ref tips—they replace the implicit `HEAD` default, they do not union with it, and if nothing matches the count is `0` with exit **0** (like `git rev-list`). Use `--count` to print only the number of reachable commits (no subject lines). With `--left-right` and exactly one `A...B` range, `--count` prints left and right counts (same as `git rev-list --left-right --count`). Without `--count`, `--left-right` lists the range with a `<` (left) or `>` (right) prefix on each commit. ### Reviewing a rewritten branch `--cherry-mark` compares the two sides of one `A...B` range by [patch-ID](https://grit-scm.com/docs/patch-id/index.md), the way `git rev-list --left-right --cherry-mark` does. Run it on the version you reviewed and the version that was force-pushed (`old...new`) to see which commits are the same change and which are new: - `=` marks a commit whose patch-ID also appears on the other side. When exactly one commit on each side has that patch-ID, the line names its counterpart and says whether the commit message changed, so a reworded commit stands out from an untouched one. - `<` and `>` mark commits found only on the left or right side: dropped, added, or edited commits, and commits that came in with the new base. When several commits on one side share a patch-ID, they are all marked equivalent without being paired. Matching uses the stable patch-ID (path-limited when paths follow `--`). Only the diff counts: a commit whose content changed is a new commit on its side, and no content interdiff is shown. `--cherry-mark` and `--left-right` need exactly one `A...B` range and exit **1** otherwise, even with `-n 0`; `--cherry-mark` cannot be combined with `--count`. When a commit-graph file is present, the walk takes parents and commit dates from it instead of reading commit objects. Unfiltered counts use that graph linkage, and listings read each listed commit once to render its row. `A..B` and `A...B` counts walk the range once: the excluded side is marked down to where it meets the included side, and the walk stops there instead of building ancestor sets for the shared history. `--since`, `--until`, `--merges`, `--no-merges` and `--first-parent` only decide which of those commits are counted, so counting a range costs about the same as listing it. With a commit-graph, generation numbers let the walk stop as soon as the included side is resolved, so a small range stays bounded even in a repository with a deep history. As in Git, `--first-parent` follows first parents from the included tips only; everything an excluded tip reaches through any parent stays excluded. Path arguments after `--` limit history to commits that touched those paths. Operands use Git pathspec cwd rules (same as [`grit diff`](https://grit-scm.com/docs/diff/index.md)): from a subdirectory, `.` limits to that directory, and bare filenames are relative to the current directory, not the repository root. Attribute pathspecs such as `:(attr:myattr)` use the repository's current `.gitattributes` stack (work tree, index, `info/attributes`, and macros), the same way as [`grit diff`](https://grit-scm.com/docs/diff/index.md); they do not read historical trees' attribute files. Author, committer, message, and pickaxe filters use the same rules as [`grit log`](https://grit-scm.com/docs/log/index.md) (`-S`, `-G`, `--pickaxe-regex`, and the same `-i` / `-F` / mailmap behavior). Invalid patterns exit **129** with `kind: "invalid_pattern"` in `--json` output. ## Options | Option | Description | | --- | --- | | `…` | One or more revision ranges (required unless a ref-set flag such as `--all` is used). | | `-n`, `--limit ` | Stop after `N` commits (listing mode only). `--max-count` is Git’s well-known alias. | | `--count` | Print only the commit count (or left/right counts with `--left-right`). | | `--left-right` | With one `A...B` range, mark each listed commit as left (`<`) or right (`>`); with `--count`, print `{left, right}` instead of a single total. | | `--cherry-mark` | With one `A...B` range, pair the two sides by patch-ID: `=` marks equivalent commits, `<` / `>` the rest (implies `--left-right`; conflicts with `--count`). | | `--skip ` | Skip `N` commits after ordering. | | `--since`, `--after ` | Exclude commits older than this date (committer date). | | `--until`, `--before ` | Exclude commits newer than this date. | | `--first-parent` | Follow first parents only at merges. | | `--follow` | With exactly one literal file path after `--`, walk history across renames (Git `log --follow`). Still walks when the path no longer exists at the start commit. | | `--merges` | Only merge commits (conflicts with `--no-merges`). | | `--no-merges` | Exclude merge commits (conflicts with `--merges`). | | `--reverse` | Print the selected window oldest-first. `-n` and `--skip` choose the window (newest `N` commits after skip); `--reverse` only flips that window. | | `--all` | Include every ref tip. | | `--branches[=]` | Branch tips, optionally filtered by glob. | | `--tags[=]` | Tag tips, optionally filtered by glob. | | `--remotes[=]` | Remote-tracking tips, optionally filtered by glob. | | `--author ` | Only commits whose author matches (repeatable; OR). | | `--committer ` | Only commits whose committer matches (repeatable; OR). | | `--grep ` | Only commits whose message matches (repeatable; OR unless `--all-match`). | | `-i`, `--regexp-ignore-case` | Case-insensitive patterns. | | `--all-match` | Every `--grep` pattern must match. | | `--invert-grep` | Exclude commits that match the grep group. | | `-F`, `--fixed-strings` | Literal string patterns. | | `--no-mailmap` | Do not apply `.mailmap` for author/committer matching. | | `--pathspec-from-file ` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. | | `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. | | `-- …` | Limit to commits touching these paths (cwd-relative under the work tree, like `grit diff`). | ## Examples List commits on the current branch: ```console $ grit revs HEAD 92501f188ae0815af09a0cef6e121eddda4113cf second 919c45f33de5e5c0bd05f8ffb089f697f4644976 initial ``` Count reachable commits: ```console $ grit revs --count HEAD 2 ``` Left/right counts on a symmetric range: ```console $ grit revs --count --left-right main...feature 3 5 ``` What changed in a force-pushed branch since review (`old-feature` is the reviewed version; the branch was rebased onto a new `main` commit, `c3` was reworded and `c4` was added): ```console $ grit revs --cherry-mark old-feature...feature = 09d5318d2c9bb2881fd2b503861aadf43737463e c3 (message changed, pairs with 05075c9436c1) > 42f209db819ee73ae750d5d33a85a4a972c75c36 c4 edits f1 = 05075c9436c17c49302513b5960c332ecfcdbae4 c3 reworded (message changed, pairs with 09d5318d2c9b) = 9000bf12a1499df8fc46332773bfd822e31dbcbd c2 (pairs with a41d2d81bcbe) = 8d35e4e808b5b12bdd0910e7fbc0eaad0804d1d4 c1 (pairs with e778fe04f497) > 4c78873b7c8588803452c16634f5b36ae4164264 m = a41d2d81bcbea60b67ac7f6c530d71bea889b628 c2 (pairs with 9000bf12a149) = e778fe04f49705176ea24d7fa28182952a835187 c1 (pairs with 8d35e4e808b5) ``` Commits on one branch but not another: ```console $ grit revs main..feature ``` Count commits mentioning an issue id on a range: ```console $ grit revs --count --grep=JIRA-123 main.. ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/revs/schemas/revs/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `commits` | array | Commits in walk order. Each entry uses the shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) shape, plus the side fields below with `--left-right` or `--cherry-mark`. Empty when `--count` is set. | | `commits[].side` | string or omitted | `left` or `right`: which side of the `A...B` range the commit is on. Only with `--left-right` or `--cherry-mark`. | | `commits[].equivalent` | boolean or omitted | With `--cherry-mark`: `true` when a commit on the other side has the same patch-ID. | | `commits[].equivalent_to` | string or omitted | With `--cherry-mark`, when exactly one commit on each side shares the patch-ID: the other side's commit. | | `commits[].message_changed` | boolean or omitted | Present with `equivalent_to`: `true` when the two commit messages differ. | | `count` | number or null | Total reachable commits when `--count` is set without `--left-right`; otherwise `null`. | | `left_right` | object or omitted | When `--count` and `--left-right` are set: `left` and `right` commit counts for the symmetric range. | | `truncated` | boolean | `true` when more commits matched than returned (`-n`). | | `next` | null | Reserved for future paging; always `null` today. | Example (listing): ```json { "commits": [ { "oid": "83352a61f6715ec3f0a297c6d6150725154fb833", "parents": [ "062ca6e74f5603f4d09063c0f46cd07d8c96e019" ], "author": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "committer": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "subject": "second", "message": "second", "refs": [ { "name": "HEAD", "kind": "head" }, { "name": "main", "kind": "branch" } ], "relative_date": "[TIME_AGO]", "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk", "change_id_stored": true }, { "oid": "062ca6e74f5603f4d09063c0f46cd07d8c96e019", "parents": [], "author": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "committer": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "subject": "first", "message": "first", "refs": [ { "name": "feature", "kind": "branch" } ], "relative_date": "[TIME_AGO]", "change_id": "prkwwuwrytvxrwozplzrxmvozwutplkq", "change_id_stored": true } ], "count": null, "truncated": false, "next": null } ``` Example (`--cherry-mark -n 1 old-feature...feature`): ```json { "commits": [ { "oid": "09d5318d2c9bb2881fd2b503861aadf43737463e", "parents": [ "a41d2d81bcbea60b67ac7f6c530d71bea889b628" ], "author": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "committer": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "subject": "c3", "message": "c3", "refs": [ { "name": "old-feature", "kind": "branch" } ], "relative_date": "[TIME_AGO]", "change_id": "sntxlnlnxkouurtynzpmvokryyvmmqwv", "change_id_stored": false, "side": "left", "equivalent": true, "equivalent_to": "05075c9436c17c49302513b5960c332ecfcdbae4", "message_changed": true } ], "count": null, "truncated": true, "next": null } ``` Example (`--count`): ```json { "commits": [], "count": 2, "truncated": false, "next": null } ``` Example (`--count --left-right`): ```json { "commits": [], "count": null, "truncated": false, "next": null, "left_right": { "left": 3, "right": 5 } } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/revs/schemas/revs/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a heading and bullet list of oid/subject pairs, or a bold count when `--count` is used. ```text # Commits - `83352a61f6715ec3f0a297c6d6150725154fb833` second - `062ca6e74f5603f4d09063c0f46cd07d8c96e019` first ``` With `--left-right` or `--cherry-mark`, each bullet starts with the side in bold, and equivalent pairs carry a note: ```text # Commits - **left, equivalent** `09d5318d2c9bb2881fd2b503861aadf43737463e` c3 _(message changed, pairs with 05075c9436c1)_ - **right** `42f209db819ee73ae750d5d33a85a4a972c75c36` c4 edits f1 - **right, equivalent** `05075c9436c17c49302513b5960c332ecfcdbae4` c3 reworded _(message changed, pairs with 09d5318d2c9b)_ ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit log](https://grit-scm.com/docs/log/index.md), [grit merge-base](https://grit-scm.com/docs/merge-base/index.md), [grit patch-id](https://grit-scm.com/docs/patch-id/index.md), [grit shortlog](https://grit-scm.com/docs/shortlog/index.md) # https://grit-scm.com/docs/show/index.md # grit show > Show a commit, tag or branch, and the change it introduced. ## Synopsis ```text grit show […] [--diff-merges first-parent|combined] [--stat | --numstat | --shortstat | --name-only | --name-status] [-U[n]] [-W] [--pathspec-from-file ] [--pathspec-file-nul] [-- …] ``` ## Description Shows a commit's id, author, date and full message, followed by the change that commit introduced (delta-style patch by default, like `grit diff `). With no argument, it shows the current commit. `` can be a commit id (full or short), an expression like `HEAD~2`, a branch or a tag. For a branch or tag, the first line names it. For an annotated tag, the tag's own author, date and message come before the commit it points at. **Merge commits** default to **combined** parent diffs (`--diff-merges=combined`, like `git show --cc`). Use `--diff-merges=first-parent` for a diff against the first parent only. Pass several `` values to show more than one commit (human and markdown output are concatenated). With `--json`, multiple objects are wrapped as `{ "objects": [ … ] }`; a single object keeps the usual top-level shape. `revision:path` specs (same resolution as [`grit cat`](https://grit-scm.com/docs/show/cat.md/index.md)) show blob contents or list tree entries without commit metadata. Use `--stat` (or other diff format flags below) instead of the default patch. Limit output to paths with `-- …` after the commit arguments. In a shallow clone, a commit listed in `.git/shallow` is diffed like a root (against the empty tree), even when its object still names a missing parent. ## Options | Option | Description | | --- | --- | | `…` | Commits, branches, tags, or `rev:path` specs. Defaults to `HEAD`. | | `--diff-merges` | `combined` (default) or `first-parent` for merge commits. | | `-p`, `--patch` | Full patch (the default). | | `--patch-text` | Git-apply-compatible unified patch on stdout (`git diff --binary` shape): branch or tag metadata (when present), commit metadata, then `diff --git` / `index` / hunks. Preserves this order when stdout is piped or redirected. Honors trailing pathspecs. Merge commits omit the patch unless `--diff-merges=first-parent`. Human output only; not combinable with `--json` or `--markdown`. | | `-W`, `--function-context` | Expand patch hunks to enclosing function boundaries (same as [`grit diff`](https://grit-scm.com/docs/show/diff.md/index.md)). | | `--stat` | Summary with change bars per file instead of a full patch. | | `--numstat` | Machine-readable `insertionsdeletionspath` lines. | | `--shortstat` | Only the summary line (`N files changed, …`). | | `--name-only` | Changed paths, one per line. | | `--name-status` | Status letter and path(s) per line. | | `-p`, `--patch` | Unified patch (default when no other format flag is set). | | `-U`, `--unified ` | Lines of context around each change in patch mode (bare `-U` means 3). | | `-W`, `--function-context` | Expand hunks to enclosing function boundaries (patch mode). | | `-p`, `--patch` | Unified patch output (default when no other format flag is set). | | `--pathspec-from-file ` | Read pathspecs from a file (`-` for stdin), in addition to argv paths after `--`. | | `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. | | `-- …` | Limit the diff to these paths (pathspecs). | ## Examples Show the latest commit with patch (default): ```console $ grit show branch feature commit cf18394a62c3f845bd9c44927a5a55e014b2a99d change yrwyvtvk Author: Ada Lovelace Date: 2026-10-07 10:00:00 +0000 Say hi ## main.rs **status:** modified - 1 1 + 1 2 context line - old line + new line ``` Show only the diffstat (previous default style): ```console $ grit show HEAD --stat ``` Show one file from a commit: ```console $ grit show HEAD~1 -- README.md ``` Show what a tag points at: ```console $ grit show v0.1 ``` Get the subject of a commit: ```console $ grit show HEAD~1 --json --filter .commit.subject "Start the project" ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/show/schemas/show/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `objects` | array | When more than one `` is requested: each element is a commit show object or a `rev:path` blob/tree object (below). | | `warnings` | array | Non-fatal diagnostics emitted while resolving the object; omitted when empty. | | `kind` | string | For a commit, branch, tag, or annotated tag: `commit`, `branch`, `tag`, or `annotated_tag`. For `rev:path`: `blob` or `tree`. | | `ref_name` | string | Branch or tag name when you named a ref; omitted for a raw commit id. | | `tag` | object | For an annotated tag: `name`, `tagger`, and `message`. | | `commit` | object | Shared [`CommitJson`](https://grit-scm.com/docs/README.md/index.md#commit-json-object-commitjson) row: `oid`, parents, author, committer, subject, message, ref decorations, `change_id`, and `change_id_stored`. | | `files` | array | Per-file diff rows (same shape as [`grit diff`](https://grit-scm.com/docs/show/diff.md/index.md) `--json`), including optional `combined_status` (`MM`, `DD`, …) on combined merge name-status output. | | `totals` | object | Aggregate line counts when a stat-style format is selected; omitted for patch-only output unless the library computed totals. | | `stat` | object | Summary diffstat with `files`, `files_changed`, `insertions`, and `deletions` (always present on commit shows). | | `spec` | string | For `rev:path`: the object spec you passed (for example `HEAD:README.md`). | | `path` | string | For `rev:path`: repository-relative path after the first revision colon. | | `oid` | string | For `rev:path`: object id of the blob or tree. | | `size` | integer | For `rev:path`: uncompressed object size in bytes. | | `text` | string | For a text blob at `rev:path`; omitted for binary blobs. | | `data_base64` | string | For a binary blob at `rev:path`; standard base64 of raw bytes. | | `binary` | boolean | For `rev:path` blobs: true when `data_base64` is used instead of `text`. | | `entries` | array | For `rev:path` trees: `mode`, `type`, `oid`, and `path` per entry. | Combined merge hunks may attach a `parents` array on each patch line in `files[].hunks[].lines[]`. Example: ```json { "kind": "branch", "ref_name": "main", "commit": { "oid": "83352a61f6715ec3f0a297c6d6150725154fb833", "parents": [ "062ca6e74f5603f4d09063c0f46cd07d8c96e019" ], "author": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "committer": { "name": "Test", "email": "test@example.com", "date": "2023-11-14T22:13:20Z" }, "subject": "second", "message": "second", "refs": [ { "name": "HEAD", "kind": "head" }, { "name": "main", "kind": "branch" } ], "relative_date": "[TIME_AGO]", "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk", "change_id_stored": true }, "files": [ { "path": "second.txt", "status": "added", "new_mode": "100644", "binary": false, "hunks": [ { "old_start": 0, "new_start": 1, "old_lines": 0, "new_lines": 1, "lines": [ { "kind": "add", "new": 1, "text": "second file" } ] } ] }, { "path": "tracked.txt", "status": "modified", "old_mode": "100644", "new_mode": "100644", "binary": false, "hunks": [ { "old_start": 1, "new_start": 1, "old_lines": 1, "new_lines": 1, "lines": [ { "kind": "del", "old": 1, "text": "tracked v1" }, { "kind": "add", "new": 1, "text": "tracked v2" } ] } ] } ], "stat": { "files": [ { "path": "second.txt", "status": "added", "insertions": 1, "deletions": 0, "binary": false }, { "path": "tracked.txt", "status": "modified", "insertions": 1, "deletions": 1, "binary": false } ], "files_changed": 2, "insertions": 2, "deletions": 1 } } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/show/schemas/show/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for headings, commit metadata, the message body in a length-adaptive `text` fence (so commit text cannot forge grit headings or tables), and fenced `diff` blocks per file (or a diffstat table with `--stat`): ```text # Commit `b52cca6` **Oid:** `92501f188ae0815af09a0cef6e121eddda4113cf` **Change:** `yrwyvtvk` **Author:** Ada Lovelace **Date:** 2026-10-07T14:54:02Z ## second ~~~diff @@ -1,1 +1,2 @@ line +added ~~~ ``` With no commits on the current branch yet, default `HEAD` fails with `branch_no_commits`: ```console $ grit show error: no commits yet on branch main — make one with `grit commit "message"` hint: make one with `grit commit "message"` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also - [`grit diff`](https://grit-scm.com/docs/show/diff.md/index.md) — compare commits, ranges, or the working tree without commit metadata. - [`grit log`](https://grit-scm.com/docs/show/log.md/index.md) — list recent commits. # https://grit-scm.com/docs/merge-base/index.md # grit merge-base > Find common ancestors or test whether one commit is an ancestor of another. ## Synopsis ```text grit merge-base [--all] [--is-ancestor] ``` ## Description Finds merge bases between two commits, or checks reachability. With no flags, prints one minimal merge base (same default as Git). `--all` lists every minimal base (needed for criss-cross histories). `--is-ancestor` exits `0` when `A` is an ancestor of `B`, `1` when it is not, and prints nothing in human mode. ## Options | Option | Description | | --- | --- | | ``, `` | Two commits or refs to compare. | | `--all` | List all minimal merge bases. | | `--is-ancestor` | Exit status only: ancestor test (`A` vs `B`). | ## Examples Default merge base: ```console $ grit merge-base main feature 919c45f33de5e5c0bd05f8ffb089f697f4644976 ``` All merge bases: ```console $ grit merge-base --all topic-a topic-b ``` Ancestor check (exit code 0): ```console $ grit merge-base --is-ancestor HEAD~1 HEAD $ echo $? 0 ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/merge-base/schemas/merge-base/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `merge_bases` | array of strings | Hex object ids of merge bases (empty when `--is-ancestor` is set). | | `is_ancestor` | boolean or null | `true` or `false` with `--is-ancestor`; otherwise `null`. | Example: ```json { "merge_bases": ["919c45f33de5e5c0bd05f8ffb089f697f4644976"], "is_ancestor": null } ``` Example (`--is-ancestor`): ```json { "merge_bases": [], "is_ancestor": true } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/merge-base/schemas/merge-base/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a short heading and bullet list of merge bases, or a sentence for `--is-ancestor`. ```text # Merge bases - `062ca6e74f5603f4d09063c0f46cd07d8c96e019` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success, or `--is-ancestor` when the first commit is an ancestor of the second. | | `1` | `--is-ancestor` when not an ancestor, or other failure. | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit revs](https://grit-scm.com/docs/revs/index.md), [grit log](https://grit-scm.com/docs/log/index.md), [grit diff](https://grit-scm.com/docs/diff/index.md) # https://grit-scm.com/docs/notes/index.md # grit notes > List, show, add, and remove Git notes on commits. ## Synopsis ```text grit notes [--ref REF] grit notes list [--ref REF] grit notes show [--ref REF] grit notes add (-m | -F / --message-file ) [--force] [--dry-run] [--ref REF] grit notes remove ... [--dry-run] [--ref REF] ``` ## Description Git **notes** are extra blob objects attached to commits via a notes ref (default `refs/notes/commits`, or `core.notesRef` / `GIT_NOTES_REF`). They do not change history; they add metadata Git and other tools can read with `git notes`. With no subcommand, `grit notes` lists every note under the selected ref. `show` prints one note body to stdout (like `git notes show`). `add` writes a new note commit; without `--force`, adding when a note already exists fails. `remove` drops notes from the given revisions in a single notes commit when multiple revs are passed. Notes update commits use your configured `user.name` / `user.email` (and optional `GIT_*` overrides), with the committer date taken from the process clock passed into the library — the same identity rules as [`grit commit`](https://grit-scm.com/docs/notes/commit.md/index.md). ## Options | Option | Description | | --- | --- | | `--ref` | Notes namespace (`commits`, `refs/notes/commits`, …). Overrides `core.notesRef` / `GIT_NOTES_REF`. | | `-n`, `--limit ` | List at most `N` notes (`truncated` in JSON when more exist). | | `-m`, `--message` | Note text for `add` (conflicts with `--message-file`). | | `-F`, `--message-file` | Read note text from a file, or `-` for stdin (conflicts with `-m`). | | `--force` | Replace an existing note on `add`. | | `--dry-run` | Preview `add` or `remove` without writing objects, refs, or reflogs. | Subcommands: `list`, `show`, `add`, `remove`. ## Examples ```console $ grit notes add HEAD -m 'Reviewed by Alex' Added note for abc1234 $ grit notes show HEAD Reviewed by Alex $ grit notes abc1234567890abcdef1234567890abcdef123456 Reviewed by Alex $ grit notes remove HEAD~1 HEAD Removed note for def5678 $ grit notes list --ref refs/notes/review No notes yet. ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/notes/schemas/notes/v1.json/index.md) (subcommands also have `notes.list`, `notes.show`, `notes.add`, and `notes.remove` schemas). Pass `--json` for stable output. The top-level `action` field is `list`, `show`, `add`, or `remove`. | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | `list`, `show`, `add`, or `remove`. | | `notes_ref` | string | Ref that was read or updated. | | `notes` | array | For `list`: `object`, `blob`, and `body` for each note. | | `truncated` | boolean | For `list`: `true` when more notes exist than returned (`-n`). | | `object` | string | For `show` / `add`: annotated commit id (full hex). | | `body` | string | For `show`: note text. | | `replaced` | boolean | For `add`: whether a note was overwritten. | | `dry_run` | boolean | For `add` / `remove`: `true` when nothing was written. | | `notes_ref_old` | string or null | For `add` / `remove` dry-run: notes ref tip before the operation. | | `notes_ref_new` | string or null | For `add` / `remove` dry-run: predicted notes ref tip after the operation. For `remove` with several revisions, this is the single notes commit the real run writes; `null` when no listed revision has a note. | | `note_blob` | string or null | For `add` dry-run: blob id that would store the note bytes. | | `objects` | array | For `remove`: ids whose notes were removed (or would be, with `--dry-run`), in argument order. Revisions without a note and repeats are left out. | Listing: ```json { "action": "list", "notes_ref": "refs/notes/commits", "notes": [ { "object": "abc1234567890abcdef1234567890abcdef123456", "blob": "d719f2387b35d9751843418fe3b613e61d7fd2d0", "body": "Reviewed by Alex\n" } ] } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v1](https://grit-scm.com/docs/notes/schemas/notes/v1.json/index.md) List actions render a heading with the notes ref and one bullet per note (short object id and body preview). Show wraps the note body in a fenced `text` block. Add and remove print a short confirmation line per action; with `--dry-run` it starts with "Would" (for example ``Would remove notes on `refs/notes/commits`:``). ```text ## Notes (`refs/notes/commits`) - _(no notes)_ ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [Library: Notes](https://grit-scm.com/docs/library/notes/index.md), [`grit show`](https://grit-scm.com/docs/notes/show.md/index.md) # https://grit-scm.com/docs/describe/index.md # grit describe > Nearest reachable tag, exact commit distance, and abbreviated id for a revision. ## Synopsis ```text grit describe [REV] [--tags] [--match GLOB] [--first-parent] [--abbrev N] ``` ## Description Finds the nearest tag reachable from `REV` (default `HEAD`) and reports the exact number of commits in the range from the tag’s peeled commit to `REV`. Output uses the long form `tag-distance-gabbrev` (including `-0-` when `REV` is exactly the tag commit). By default only annotated tags are considered; `--tags` includes lightweight tags. The distance is the exact `peeled..REV` count (what `grit revs --count` reports), which can differ from Git’s lazy `git describe` depth and from which tag Git picks when many tags are reachable. ## Options | Option | Description | | --- | --- | | `REV` | Commit or ref to describe (default `HEAD`). | | `--tags` | Include lightweight tags (default: annotated only). | | `--match GLOB` | Only consider tags whose short name matches `GLOB`. | | `--first-parent` | Count distance along first-parent chains only. | | `--abbrev N` | Minimum abbreviated commit id length (default follows `core.abbrev`, extending on collision like Git). | ## Examples ```console $ grit describe --tags v1.2.0-3-g4a1b2c3 ``` With `--json`: ```console $ grit describe --tags --json ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/describe/schemas/describe/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `tag` | string | Full `refs/tags/…` name. | | `tag_short` | string | Short tag name. | | `tag_oid` | string | Object id at the tag ref. | | `peeled` | string | Peeled commit oid. | | `distance` | integer | Exact commits in `peeled..commit`. | | `commit` | string | Described commit oid. | | `abbrev` | string | Abbreviated commit oid. | | `long_format` | string | `tag-distance-gabbrev` line. | Example: ```json { "tag": "refs/tags/v1.2.0", "tag_short": "v1.2.0", "tag_oid": "a1b2c3d4e5f6789012345678901234567890abcd", "peeled": "1111111111111111111111111111111111111111", "distance": 3, "commit": "2222222222222222222222222222222222222222", "abbrev": "2222222", "long_format": "v1.2.0-3-g2222222" } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/describe/schemas/describe/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a short heading and bullet list of the tag, distance, and abbrev. ```text # Describe - **Tag:** `v1.2.0` - **Distance:** 3 - **Commit:** `2222222` - **Long:** `v1.2.0-3-g2222222` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success. | | `1` | No reachable tag, or other failure. | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also - [`revs`](https://grit-scm.com/docs/describe/revs.md/index.md) — count commits in a range. - [`tag`](https://grit-scm.com/docs/describe/tag.md/index.md) — list or create tags. # https://grit-scm.com/docs/rebase/index.md # grit rebase > Replay local commits onto a new base; recover from conflicts and exec commands that leave edits. ## Synopsis ```text grit rebase [] grit rebase [--onto ] [] grit rebase --continue | --abort | --skip grit history rebase [] grit rebase|history rebase … [--check] [-X ours|theirs] [--dry-run] [--exec ]… [--fork-point] [--no-fork-point] [--update-refs=(branches|head)] [--empty=(drop|keep|abort)] [--keep-committer] [--no-verify] ``` ## Description `grit rebase` replays commits reachable from `HEAD` but not from `` onto `` (or onto `--onto` when set). It uses the same history engine as [`grit history`](https://grit-scm.com/docs/rebase/history.md/index.md). When every commit replays cleanly, grit writes new commit objects and updates refs in one batch. During checkout or replay, Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Partial ref moves and the worktree are rolled back, and no stale `.git/index.lock` is left behind. A second interrupt exits immediately without cleanup. Before it replays anything, grit runs the `pre-rebase` hook with the upstream as you typed it (`pre-rebase main`), or the configured upstream's full ref name (`pre-rebase refs/remotes/origin/main`) when you omitted it, as Git does. It runs once there is something to replay and before any commit is replayed, so a refusal comes before a replay conflict on every path (`-X` and `--exec` included): not when the branch is already up to date, and not for `--check`, `--dry-run`, `--continue`, `--skip` or `--abort`. When the hook exits non-zero, the rebase stops with exit **1** and a `hook_failed` error, and nothing changes. `--no-verify` skips it. ```console $ grit rebase main error: hook pre-rebase failed with exit status 1 $ grit rebase main --no-verify Rebased 1 commit(s) commit 9c1f2d3 → 4e5a6b7 (feature work) refs/heads/feature 9c1f2d3 → 4e5a6b7 ``` When the rebase moves the branch, grit runs the `post-checkout` hook with Git's arguments, ` 1`: Git checks out the onto commit before replaying, and the hook names that commit even though grit applies the rebase in one step. This also happens when a rebase stops on conflicts. When the rebase finishes, grit runs `post-rewrite rebase` with one ` ` line per replayed commit on stdin, oldest first. Dropped commits, commits already upstream, and fast-forwards are not listed, so a fast-forward rebase runs only `post-checkout`. Unlike Git, grit does not run `post-commit` for each replayed commit. Hook exit statuses never change the result. See [`grit hooks`](https://grit-scm.com/docs/rebase/hooks.md/index.md). When `notes.rewriteRef` is configured, grit copies notes from each replayed commit to its replacement (same rules as Git's `git notes copy --for-rewrite`) before `post-rewrite` runs. See the [notes library guide](https://grit-scm.com/docs/library/notes.md/index.md). A commit whose patch is already upstream (for example one you cherry-picked from the upstream branch) is skipped, as `git rebase` skips it. The commits before and after it are still replayed in order on top of the new base, and a branch that pointed at the skipped commit moves to the replayed commit before it, or to the new base when nothing came before. In the output and the `rewritten` JSON rows, the skipped commit maps to the upstream commit that carries its patch. When `` is omitted, grit uses `@{upstream}` of the current branch. If no upstream is configured, the command fails with a hint to run [`grit branch -u`](https://grit-scm.com/docs/rebase/branch.md/index.md). On a **detached `HEAD`**, an explicit `` is required (same as `git rebase`); omitting it fails with `cannot rebase detached HEAD without an upstream argument`. With implicit upstream on a branch, grit uses the upstream tracking ref's reflog to find where your branch forked (`rebase.forkPoint`, default true), matching `git rebase` with `--fork-point`. An explicit `` uses the merge base unless you pass `--fork-point`; `--no-fork-point` disables reflog fork detection even for implicit upstream. When replay stops on conflicts, grit writes Git-compatible `.git/rebase-merge/` state (including `grit-plan`), leaves conflict markers in the worktree, and exits **1**. As with [`grit pick`](https://grit-scm.com/docs/rebase/pick.md/index.md) (and `git rebase`), the incoming `>>>>>>>` marker names the commit being replayed as ` ()`, so each stop shows which commit it came from; the current side is `HEAD`. The branch tip recorded in `orig-head` is unchanged until you `--continue`, `--skip`, or `--abort`. While stopped (and after `--abort` re-attaches the branch), grit appends `HEAD` reflog entries for each detach and reattach so `HEAD@{0}` always matches the current `HEAD` and `HEAD@{n}` recovery stays consistent. Resume with the same conflict model as [`grit pick`](https://grit-scm.com/docs/rebase/pick.md/index.md) and [`grit revert`](https://grit-scm.com/docs/rebase/revert.md/index.md): inspect (`grit diff`), resolve, then either stage and `grit rebase --continue` (`grit add` + `--continue`) or record the resolution with [`grit commit`](https://grit-scm.com/docs/rebase/commit.md/index.md) (auto-staging applies) and run `grit rebase --continue` to replay only the remaining commits. Use `--skip` / `--abort` to drop the stopped pick or restore `orig-head` (the checked-out branch, or detached `HEAD` when the rebase started detached). [`grit pull --rebase`](https://grit-scm.com/docs/rebase/pull.md/index.md) stops the same way. When the replayed range contains merge commits (the default, unlike `git pull --rebase`), grit keeps merge topology like `git rebase --rebase-merges`: the first-parent chain from your branch tip is replayed onto the new base; a side branch that forked at the rebase boundary is replayed onto the new base, while one that forked inside the range follows its rewritten parent until mapping moves it, and resolving a conflict on a merge commit with `--continue` keeps every parent (the current `HEAD` as the first parent, mapped originals for the rest). Merged-in files and refs on side branches are not dropped silently. Stopping resets the index and worktree to the replayed commits, so grit only stops when that loses nothing. If replay would conflict while you have staged or unstaged changes, or an untracked file sits where the stop would check out a path, the rebase refuses (`kind: dirty_worktree`, or the untracked-overwrite error) and nothing changes; commit or stash first. A rebase that replays cleanly still carries local changes along, like a branch switch. The conflict stop state is complete enough for `git` to take over: `git rebase --continue`, `--skip` and `--abort` all work on a rebase grit started (grit writes `author-script`, `stopped-sha` and the current pick in `done`, as git does). With the default `--update-refs=branches`, Git's todo lists only the rebased branch's own commits so `git rebase --continue` finishes that branch; stacked-branch updates happen when you resume with `grit rebase --continue`. A rebase that replays commits records the branch's pre-rebase tip in `ORIG_HEAD`, as `git rebase` does. That includes `-X ours|theirs`, `--exec` (including when the branch is already based on the upstream and only the commands run), a rebase that stops on conflicts, and an `--exec` stop (`exec_dirty` or a replay conflict after an amending command); an `--exec` command that fails rolls everything back and leaves `ORIG_HEAD` alone. It stays there after the rebase finishes, `--continue`, `--skip` or `--abort`, so `grit reset --hard ORIG_HEAD` undoes a finished rebase. When there is nothing to replay and no `--exec`, `--check` and `--dry-run`, `ORIG_HEAD` is left alone. When grit records history for [`grit history undo`](https://grit-scm.com/docs/rebase/history.md/index.md), finishing a conflict stop with `--continue` or `--skip` writes `.git/grit/history-last` from the reattached branch (pre-rebase tip to final tip), the same shape as a rebase that never stopped. A rebase that `git` started (`.git/rebase-merge/` or `.git/rebase-apply/` without `grit-plan`) blocks `grit rebase ` and [`grit switch`](https://grit-scm.com/docs/rebase/switch.md/index.md). `grit rebase --abort` cancels it: `HEAD` is re-attached to the rebased branch at `orig-head`, the index and worktree are reset, git's state directory is removed, and unresolved rerere records for the abandoned conflict (`MERGE_RR`) are cleared, as `git rebase --abort` does. When git recorded an autostash, grit leaves the rebase alone and asks you to run `git rebase --abort`. `grit rebase --continue` and `--skip` refuse with a pointer to `git rebase --continue` / `--skip`, since only git can resume its own todo list. `--check` predicts success or conflicts without touching refs, the index, or the worktree (exit **1** when conflicts are predicted, like [`grit merge --check`](https://grit-scm.com/docs/rebase/merge.md/index.md)). It does not start a rebase session. `-X ours` and `-X theirs` auto-resolve replay conflicts the way `git rebase -X` does. During replay, **ours** is the onto (upstream) side and **theirs** is the commit being replayed — the opposite of everyday merge wording where “ours” is your checked-out branch. A conflict that `-X` cannot resolve (for example a file deleted on one side and modified on the other) stops the rebase like any other conflict, and `--continue` keeps replaying with the same `-X` side. `--dry-run` still uses the stateless planner only: it lists ref updates without starting a session and without writing objects for a real rebase. When there is nothing to replay and no `--exec` commands, human output is `Already up to date` and `--json` sets `result` to `completed` with `rewritten` as `[]`. With `--exec`, grit still runs the commands at every commit in the rebase range even when the branch is already based on the upstream (the usual `git rebase -x` idiom for testing each commit). Human output is `Exec commands ran; branch is unchanged`, `--json` includes an `exec` array, and `rewritten` stays empty when no commit OIDs changed. A failing command still rolls back and returns the command's exit code. Shared rewrite flags match [`grit history`](https://grit-scm.com/docs/rebase/history.md/index.md): `--dry-run`, `--update-refs`, `--empty`, and `--keep-committer`. With the default `--update-refs branches`, stacked branches move with the rebase: a branch on one of the replayed commits, or on a commit built on top of them, ends up on its replayed copy. Another branch at the same commit as the checked-out branch is not moved, so a `backup` branch created right before the rebase still points at the original commits: ```console $ grit branch backup $ grit rebase main Rebased 2 commit(s) commit cc10d19 → 931f74a (X) commit 874d334 → 8489106 (Y) refs/heads/feature 874d334 → 8489106 $ grit log --oneline backup 874d334 Y cc10d19 X 70709d8 base ``` ### Exec commands that amend or add commits An `--exec` command may rewrite the commit it runs at, the way it can with `git rebase --exec`. When it exits zero with a detached `HEAD` that amends the replay commit, or adds new commits on top of it, grit keeps the result: later commits are replayed onto the new `HEAD`, later commands see its tree, and the branch ends up on the rewritten history. The common "format every commit" loop works as expected: ```console $ grit rebase main --exec 'cargo fmt && git commit -qa --amend --no-edit' Rebased 2 commit(s) commit d9b09e2 → 4ec1aa7 (one) commit 3fe1bb2 → 0c24bc2 (two) refs/heads/feature 3fe1bb2 → 0c24bc2 ``` `git commit --amend` keeps the commit's change id. A command that leaves `HEAD` anywhere else (switching branches, resetting the commit away) fails the rebase: grit restores `HEAD`, the index, and the worktree without moving refs, and the commits the command made stay in the object database. If the first replayed commit conflicts before any `--exec` command runs, grit stops the same way as a plain rebase: conflict markers, `rebase-merge/grit-plan`, and the branch ref left at its pre-rebase tip. If a later commit no longer applies on top of an amended one, replay stops with `result: "conflicts"` and conflict markers, like any rebase conflict, without undoing the commits already rewritten. Resolve and stage the paths, then run `grit rebase --continue` (the exec commands run at the resolved commit), or use `--skip` to drop that commit (its exec commands still run, at the current `HEAD`, as with Git), or `--abort` to restore the original branch. Resuming keeps the options the rebase started with, such as `--empty keep`; there is no need to repeat them. ### Successful exec commands that leave edits After **every** successful `--exec` command, grit reloads the index and checks tracked staged and unstaged changes against the resulting `HEAD` (the replay commit, or the commit the command amended it into). If anything changed, replay stops immediately with exit **1** and `result: "exec_dirty"`. The edits and index stay exactly as the command left them, `HEAD` remains detached at that commit, and the original branch refs remain unchanged. Later exec commands do not run. Save the edits before continuing: ```bash grit stash push -m "exec edits" grit rebase --continue grit stash pop ``` `--continue` resumes after the successful command, so it does not repeat the edit. `--skip` skips any remaining exec commands at that commit and keeps the already replayed commit. Both require a clean index and worktree at the recorded replay HEAD. If you move HEAD or create a commit while stopped, save new commits on a branch, then abort and restart. `--abort` explicitly discards exec edits and restores the original HEAD, index, and tracked files; save any edits you want first. Exec stops use grit's `rebase-merge/grit-exec` recovery record. Resume these with grit. Commands exiting nonzero retain their existing rollback behavior and command exit code. If grit is interrupted (Ctrl-C or `kill`) while an `--exec` command is running, the recovery record is kept at the detached replay commit. `grit status` reports the interrupted rebase and suggests `--continue` or `--abort`; `--abort` restores the branch tip, index, and worktree from before the rebase started. Starting a second rebase while one is already paused: ```console $ grit rebase main error: cannot rebase while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort` ``` ### When the branch moves during a stop Something else may move the rebased branch while the rebase is stopped: a commit from another worktree, `git branch -f`, `git update-ref`, or checking the branch out and amending it. The saved plan no longer applies then, so `--continue` and `--skip` refuse with exit **1** and change nothing: ```console $ grit rebase --continue error: refs/heads/feature moved to 045e4cc while the rebase was stopped, so it cannot be continued or skipped; run `grit rebase --abort` to restore refs/heads/feature to b37ca7f (the moved tip stays in its reflog) ``` `--abort` always works: it resets the branch to its pre-rebase tip (`orig-head`), clears the rebase state, and reports the tip it overwrote, which stays reachable as `@{1}` (logged as `rebase (abort)`). This holds for conflict stops and exec stops alike: ```console $ grit rebase --abort Rebase aborted. refs/heads/feature was moved during the rebase; reset 045e4cc → b37ca7f (the moved tip stays in its reflog) ``` In `--json`, the overwritten branch appears in `refs` as `{ref, old, new}`, with `old` the moved tip and `new` the restored one. An abort of an unmoved branch has no `refs`. ## Options | Option | Description | | --- | --- | | `` | Exclude commits reachable from this revision (default: `@{upstream}`). | | `--onto` | Replay onto this revision instead of ``. | | `--continue` | Finish the current conflict resolution (including a replay conflict after an amending exec), or resume exec after saving its edits. | | `--abort` | Cancel the rebase and restore the branch or detached `HEAD` to `orig-head`, even if something moved it during the stop (the overwritten tip is reported). Also cancels a rebase that `git` started. | | `--skip` | Skip a conflicted commit, or remaining exec commands at an exec stop (save edits first). | | `--dry-run` | List ref updates without moving refs (no session). | | `--update-refs` | `branches` (default: the checked-out branch and every stacked branch on or above the replayed commits, but not other branches at the `HEAD` commit) or `head`. | | `--empty` | `drop` (default), `keep`, or `abort` when a replay would become empty. | | `--keep-committer` | Preserve committer ident and timestamp on replayed commits. | | `--exec` | After each replayed commit is checked out, run `CMD` via `sh -c` in the worktree (repeatable; runs in order at every commit). Requires a clean index and worktree. Incompatible with `--dry-run`, `--check`, and `-X`. Command output goes to stderr. On nonzero command exit, grit restores `HEAD`, the index, and the worktree without moving refs; exit code is the command's exit code. A successful command may amend the replayed commit or add commits on top of it; later commits are replayed onto the result. A successful command that leaves tracked edits stops with `exec_dirty` and preserves them for recovery. | | `--check` | Predict success or conflicts without changing refs, index, or worktree (conflicts with `--dry-run`). | | `--fork-point` | Use the upstream reflog to find where the branch forked (on by default when `` is omitted). | | `--no-fork-point` | Use the merge base with `` instead of the reflog fork point. | | `-X ours\|theirs` | Auto-resolve replay conflicts in favor of the onto side (`ours`) or replayed commits (`theirs`). | | `--no-verify` | Skip the `pre-rebase` hook. | ## Examples ```console $ grit rebase --onto release/v2 origin/main --dry-run Dry run — refs would change: commit abc1234 → def5678 (feature work) refs/heads/feature abc1234 → def5678 ``` ```console $ grit rebase origin/main CONFLICT (both_modified): docs/guide.md Rebase stopped on conflicts; fix them and run `grit rebase --continue`, or `grit rebase --abort` / `grit rebase --skip`. $ grit add docs/guide.md $ grit rebase --continue Rebased 3 commit(s) ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/rebase/schemas/rebase/v1.json/index.md) Pass `--json` on `grit rebase` or `grit history rebase`: | Field | Type | Meaning | | --- | --- | --- | | `result` | string | `completed`, `conflicts`, `exec_dirty`, or `aborted`. | | `operation` | string | `rebase` when present. | | `rewritten` | array | `{old,new,change_id,subject}` per replayed commit when `result` is `completed`. | | `refs` | array | `{ref,old,new}` for each ref that moved. For `aborted`, each branch the abort reset after something else moved it during the stop (`old` is the overwritten tip, `new` the restored `orig-head`); omitted when nothing was overwritten. | | `head` | object or null | `{old,new}` for the completed invocation's `HEAD` OID change; `null` when unchanged. Dry runs show the planned change; conflict and abort outcomes use `null`. | | `dry_run` | boolean | Whether refs were left unchanged. | | `exec` | array | Captured invocations during this call, on completion or an exec stop: `{commit, command, exit_code}` per invocation (full hex `commit`). | | `commit` | string | Source commit for `conflicts`; `HEAD` after the command (the replay commit or its amended replacement) for `exec_dirty`. | | `command` | string | Successful command that left edits, for `exec_dirty`. | | `paths` | array of strings | Changed tracked paths at an exec stop. | | `conflicts` | array | `{path,kind,summary?}` when `result` is `conflicts`; `kind` is a [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds). | | `rerere` | array | Rerere events when `rerere.enabled` is active at a conflict stop (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. | | `next_steps` | array | Ordered `grit` commands after a stop. | | `alternatives` | array | `grit rebase --abort` and `grit rebase --skip` when paused. | For completed results, `head.old` is the OID immediately before this command and `head.new` is the final OID. On `--continue` and `--skip`, this compares the stopped, detached `HEAD` with the completed branch tip after reattachment. `refs` and `rewritten` still describe the whole rebase, so their old OIDs can differ from `head.old`. Skipping the final conflicting commit can reattach `HEAD` without changing its OID; then `head` is `null`. After resolving a conflict (with `grit add` or `grit commit`), `grit rebase --continue --json` reports: ```json { "result": "completed", "operation": "rebase", "rewritten": [ { "old": "420bacbf7a90d30965b669336667fc144be897c1", "new": "77fc7445860c1cc5a111ddd9bc9e0be97884522c", "change_id": "rwlqysmxxrwkltttnnqttmptqznozqul", "subject": "feature" } ], "refs": [ { "ref": "refs/heads/feature", "name": "refs/heads/feature", "old": "420bacbf7a90d30965b669336667fc144be897c1", "new": "77fc7445860c1cc5a111ddd9bc9e0be97884522c" } ], "head": { "old": "8f302b0a5bc73aecb1c2f23b8a00953c7c64ed6c", "new": "77fc7445860c1cc5a111ddd9bc9e0be97884522c" } } ``` With `--check` when already up to date: ```json { "operation": "rebase", "result": "up_to_date", "check": true } ``` With `--check --json`, stdout is a result object instead of a stop/resume payload: Schema: [rebase.check v1](https://grit-scm.com/docs/rebase/schemas/rebase.check/v1.json/index.md) | Field | Type | Meaning | | --- | --- | --- | | `operation` | string | Always `rebase`. | | `result` | string | `up_to_date`, `clean`, or `conflicts`. | | `check` | boolean | Always `true`. | | `commits` | array of strings | Replacement commit OIDs when `result` is `clean`. | | `conflicts` | array | `{path, kind}` entries when `result` is `conflicts`, with the [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds) the replay would leave. | | `commit` | string | Original commit OID when `result` is `conflicts`. | | `refs` | array of strings | Present when the conflicting commit is only on other branches that `--update-refs branches` would move: their full names. Rebasing with `--update-refs head` leaves them alone. | Exit code is **0** for `up_to_date` and `clean`, **1** for `conflicts`. ## Markdown output Schema: [v1](https://grit-scm.com/docs/rebase/schemas/rebase/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `## Rebase` heading (or `## History rebase` for the alias). On conflict or exec stops, lists paths, the stopped commit, and `next_steps` / `alternatives` like pick and revert. ```text ## Rebase check - Already up to date ``` On a branch with no commits yet, rebase onto any upstream fails with `branch_no_commits` and a hint to make the first commit (see [`grit log`](https://grit-scm.com/docs/rebase/log.md/index.md)). ## Exit status | Code | Meaning | | ---: | --- | | `0` | Rebase completed, `--check` predicts success, or `--dry-run`. | | `1` | Conflicts, successful exec with tracked edits, `pre-rebase` refused (`kind: hook_failed`), or other failure. | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | | *varies* | `--exec` command failure ([`custom`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also - [`grit history`](https://grit-scm.com/docs/rebase/history.md/index.md) — other rewrite helpers (`reword`, `drop`, `squash`, …) - [`grit status`](https://grit-scm.com/docs/rebase/status.md/index.md) — `operation` hints while a grit rebase is paused - [`grit pull --rebase`](https://grit-scm.com/docs/rebase/pull.md/index.md) — fetch then rebase onto the remote tip - [`grit push --force-with-lease`](https://grit-scm.com/docs/rebase/push.md/index.md) — publish rewritten history safely # https://grit-scm.com/docs/history/index.md # grit history > Stateless history rewrite helpers (reword, and more over time). ## Synopsis ```text grit history drop grit history move (--before | --after ) grit history reword (-m | -F / --message-file | --author ) grit history reword --author [-m ] grit history drop|move|reword|fixup|squash|absorb|rebase … [--dry-run] [--update-refs=(branches|head)] [--empty=(drop|keep|abort)] [--keep-committer] grit history fixup [-m | -F / --message-file] [--hunks ] [--lines ] [-- …] grit history squash … [-m | -F / --message-file | --combine] grit history absorb [--base ] grit history rebase [] [--onto ] grit history split -m [--rest-message ] -- … grit history undo [--dry-run] ``` ## Description `grit history` groups **stateless** rewrite operations: grit plans how commits and refs should change, writes new commit objects into the object database, then applies ref updates in one atomic batch. There is no sequencer state file and no hooks run during planning. Once a rewrite is applied, grit runs `post-checkout` (` 1`) when `HEAD`'s tree changed, then `post-rewrite rebase` with an ` ` line per rewritten commit on stdin (dropped commits are left out), as Git does after `rebase -i`. `--dry-run` and `history undo` run no hooks. Rewrites preserve stable [change ids](https://grit-scm.com/docs/change-ids/index.md) on surviving logical changes and store derived ids when the source commit had no header. With `notes.rewriteRef` set, notes on rewritten commits are copied to the new objects before `post-rewrite` (see [notes](https://grit-scm.com/docs/library/notes.md/index.md)). Shared behavior for every subcommand: - **Interrupts** — while a rewrite is applying (checkout or ref updates), Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Partial work is rolled back and no stale `.git/index.lock` remains. A second interrupt terminates grit without that cleanup. - **Conflicts abort** — if replaying a descendant would conflict, nothing is applied (planned objects may already exist in the ODB from planning). The error names the commit that could not be replayed. When that commit is only on another branch that `--update-refs branches` would move (a branch built on top of the edited commit), the error also names that branch and hints at `--update-refs head`, which rewrites only the current branch and leaves the others where they are. - **`--dry-run`** — print which refs would move; refs, the index, and the worktree stay unchanged. New commit objects are still written during planning, matching Git’s `git history --dry-run` model. Commit signing is skipped during dry-run planning (no `gpg` / `ssh-keygen` invocation); a full run signs replacement commits when [`commit.gpgsign`](https://grit-scm.com/docs/commit/index.md) is enabled, like [`grit commit`](https://grit-scm.com/docs/commit/index.md). - **`--update-refs`** — `branches` (default) updates every local branch whose tip descends from the edited commit, except other branches at the same commit as `HEAD` (a `backup` branch made before the edit keeps the old history); `head` updates only the commit `HEAD` points at. ### `drop` Remove one commit from history and replay its descendants onto that commit’s first parent. The dropped commit’s tree changes are omitted; descendant commits are replayed with three-way merges like other history rewrites. You cannot drop a **root** commit (no parent) or a **merge** commit itself. Descendant **merge** commits are replayed: mapped parents are updated and the merge tree is recomputed (first-parent transplant when side branches are unchanged, otherwise a fresh merge of the mapped parents). ### `move` Reorder one commit on the **first-parent chain** of `HEAD` (no merge commits in the affected range). Grit replays the segment in the new order with the same cherry-pick semantics as other history helpers; branches pointing at commits in the segment move to the rewritten tips. Provide exactly one of `--before` or `--after` naming another commit on that chain. Moving a commit to its current position is an error. ### `reword` Replace one commit’s message and/or author and replay descendants onto the rewritten history. On the edited commit, tree and parents stay the same; only the message and/or author line change. Committer identity and time come from your configured committer and `GIT_COMMITTER_DATE`, like [`grit commit`](https://grit-scm.com/docs/history/commit.md/index.md). Provide at least one of `-m` / `--message`, `--message-file` (use `-` to read from stdin), or `--author`. The author value uses the same `Name ` / bare-email rules as [`grit commit --author`](https://grit-scm.com/docs/history/commit.md/index.md); when you omit a date, grit keeps the edited commit’s author timestamp. Grit does not open an editor. Descendant **merge** commits are replayed the same way as for [`drop`](#drop): parents are remapped and the merge tree is updated to match the rewritten first-parent chain. ### `fixup` Fold **staged** changes into an earlier commit on the first-parent chain of `HEAD`, then replay descendants onto the rewritten history. Grit three-way merges staged edits into the target commit’s tree; descendant commits are replayed like other history rewrites. If the merge would make the target empty, grit aborts unless `--empty keep` or `--empty drop` is set (same shared `--empty` flag as other history subcommands). Provide exactly one of `-m` / `--message` or `--message-file` when you want an explicit fixup message; otherwise grit uses the staged diff to build the amended commit. ### `absorb` Assign **staged** hunks into the commits that last touched overlapping lines (between `--base` and `HEAD`), then replay descendants in **one** rewrite. Grit uses blame line mapping to find candidate commits and checks that each hunk commutes with commits after its target. Assigned hunks are folded into target commits via the same three-way merge as [`fixup`](#fixup); unassigned hunks stay staged. `--base` is exclusive: commits at and before the base are not considered. When omitted, grit hides other local branch tips (except a second branch name at the checked-out tip, such as a backup or review branch parked at `HEAD`), applies an upstream fork-point when configured, and caps the stack at ten commits. When a hunk’s introducing commit is excluded because of another local tip, `--json` and human output report `hidden_by_ref` with the ref name and suggest `--base`. ### `rebase` Replay commits on the current branch onto `` (or `--onto`), matching [`grit rebase`](https://grit-scm.com/docs/history/rebase.md/index.md) including `--continue`, `--abort`, and `--skip`. Prefer the top-level command for everyday use; `grit history rebase` shares the same handler and JSON shape. `--exec` commands may [amend or add commits](https://grit-scm.com/docs/history/rebase.md/index.md#exec-commands-that-amend-or-add-commits) at each replayed commit; later commits are replayed onto the result. Successful `--exec` commands that leave tracked edits stop with `exec_dirty`, preserve the index and worktree, and use the same [exec recovery](https://grit-scm.com/docs/history/rebase.md/index.md#successful-exec-commands-that-leave-edits) workflow. ### `undo` Restore branch tips (and the worktree when `HEAD`'s tree changed) from the last successful history rewrite that moved refs. Grit records each apply in `.git/grit/history-last` (ignored by `git fsck --strict`); `undo` inverts that plan when every recorded ref is still at its post-rewrite tip. A second `undo` redoes the rewrite. Recorded applies always write reflog entries for moved refs (even when `core.logAllRefUpdates=false`) so the pre-rewrite tips stay reachable until undo or reflog expiry. `fixup` and `absorb` consume staged (or `--hunks` / `--lines` selected) edits. Undoing one puts those edits back: each consumed path gets the index entry and work tree file it had before the command, so a staged fixup comes back staged, unstaged edits on the same path come back unstaged, and a `--hunks` fixup leaves the selected hunks unstaged again. A staged submodule pointer comes back staged too; the submodule's own checkout is never touched. The saved state lives next to the record in `.git/grit/history-last-work` (also ignored by `git fsck`), and the next recorded rewrite replaces it. A second `undo` returns to the post-fixup state. Undo refuses to run when one of those paths changed after the command, because putting the edit back would overwrite the newer change. ```console $ git add a.txt $ grit history fixup HEAD~2 Fixed up 3 commit(s) commit 6904103 → 32a5464 (c1) commit 8b9fec5 → 384d455 (c2) commit 16a0857 → 46f21c2 (c3) refs/heads/main 16a0857 → 46f21c2 $ grit history undo Undid last history rewrite refs/heads/main 46f21c2 → 16a0857 restored a.txt (index and work tree) $ git status --short M a.txt ``` A record written by an older grit has no saved state. Undoing a `fixup` or `absorb` from such a record still moves the refs, and prints the commit that still holds the folded edits (`unrestored_edits` in `--json`), so you can recover them from it. There is nothing to undo when no record exists, when a listed ref moved, or when local changes would be overwritten by the checkout. ### `squash` Fold every commit in a **connected** revision range into the **oldest** commit in that range, then replay descendants onto the new history. The squashed commit keeps the oldest commit's author and parents; its tree matches the range tip. By default the squashed commit keeps the oldest commit's message (including `amend!` handling inside the range). Use `-m` / `--message-file` for an explicit message, or `--combine` for an autosquash-style combined message from every commit in the range. The range uses the same revision syntax as `git rev-list` (for example `HEAD~3..HEAD` or full OIDs `abc..def`). With `--update-refs head`, grit may fold at `HEAD` without replaying when the range ends at the current tip and the message mode allows it. ### `split` Peel changes that match pathspecs out of one commit into a **new parent commit**, then leave the target commit’s tree unchanged and replay descendants. The new parent’s tree is the target’s first parent plus only the selected paths; the target commit keeps its author and tree (and its message unless `--rest-message` is set). Provide `-m` / `--message-file` for the new parent commit and one or more paths after `--` (or `--pathspec-from-file`). Grit errors when the pathspec matches nothing or every change in the commit. ## Options | Option | Description | | --- | --- | | `` | Commit to drop, move, or reword (revision spec). | | `--before` | Place `` immediately before this revision (`move` only). | | `--after` | Place `` immediately after this revision (`move` only). | | `-m`, `--message` | New commit message (conflicts with `--message-file`). | | `-F`, `--message-file` | Read the new message from a file, or `-` for stdin. | | `--author` | Replacement author ident (`Name ` or bare email). | | `--dry-run` | List ref updates without moving refs. | | `--update-refs` | `branches` (default) or `head`. | | `--empty` | `drop` (default), `keep`, or `abort` when a replay would become empty. | | `--keep-committer` | Preserve committer ident and timestamp on replayed commits. | ### `split` options | Option | Description | | --- | --- | | `` | Commit to split (revision spec). | | `-m`, `--message` | Message for the new parent commit (conflicts with `--message-file`). | | `-F`, `--message-file` | Read the new parent message from a file, or `-` for stdin. | | `--rest-message` | Replace the remaining commit’s message after the split. | | `PATH`… | Pathspecs after `--` limiting which changes move into the new parent (required). | | `--pathspec-from-file` | Read pathspecs from a file, or `-` for stdin (same as other commands). | | `--pathspec-file-nul` | `--pathspec-from-file` entries are NUL-separated. | | `--dry-run` | List ref updates without moving refs. | | `--update-refs` | `branches` (default) or `head`. | | `--empty` | When a replayed commit would not change the tree: `drop` (default), `keep`, or `abort`. | | `--keep-committer` | Keep each replayed commit’s original committer line instead of your configured committer. | ## Examples ### `squash` options | Option | Description | | --- | --- | | `…` | One or more revision specs defining the commits to fold (required). | | `-m`, `--message` | Message for the squashed commit (conflicts with `--message-file` and `--combine`). | | `-F`, `--message-file` | Read the squashed commit message from a file, or `-` for stdin. | | `--combine` | Combine messages from every commit in the range. | | `--dry-run` | List ref updates without moving refs. | | `--update-refs` | `branches` (default) or `head`. | ### `absorb` options | Option | Description | | --- | --- | | `--base` | Oldest commit boundary (exclusive) for absorb targets. | | `--dry-run` | List assignments and ref updates without moving refs. | | `--update-refs` | `branches` (default) or `head`. | Move a commit before its parent on a linear branch: ```console $ grit history move HEAD~1 --before HEAD~3 Rewrote 3 commit(s) commit a1b2c3d → d4e5f60 refs/heads/main f6a7b89 → c0ffee0 ``` Reword the parent of `HEAD` on a linear branch: ```console $ grit history reword HEAD~1 -m " clearer subject line " Rewrote 2 commit(s) commit a1b2c3d → d4e5f60 refs/heads/main d4e5f60 → f6a7b89 ``` Change only the author on an older commit (message and author date unchanged): ```console $ grit history reword HEAD~2 --author "Ada Lovelace " --json {"operation":"reword","rewritten":[…],"refs":[…],"head":{…},"dry_run":false} ``` Preview ref movements without updating branches: ```console $ grit history reword HEAD~1 -m "new message" --dry-run Dry run — refs would change: commit a1b2c3d → d4e5f60 refs/heads/main f6a7b89 → c0ffee0 ``` Fix up the parent of `HEAD` using staged edits: ```console $ grit add file.txt $ grit history fixup HEAD~1 Fixed up 2 commit(s) commit a1b2c3d → d4e5f60 refs/heads/main f6a7b89 → c0ffee0 ``` Fold only selected **unstaged** hunks (same ids and `--lines` syntax as [`grit add`](https://grit-scm.com/docs/history/add.md/index.md)) without staging the whole file first: ```console $ grit diff --unstaged --json -- file.txt # copy hunks[].id $ grit history fixup HEAD~1 --hunks abcdef012345 -- file.txt Fixed up 2 commit(s) commit a1b2c3d → d4e5f60 refs/heads/main f6a7b89 → c0ffee0 ``` Unknown or stale hunk ids exit **2** (same as `grit add --hunks`). Hunk ids and `--lines` ranges are resolved against the same index→worktree diff as [`grit diff --unstaged --json`](https://grit-scm.com/docs/history/diff.md/index.md). Other unstaged hunks on the same paths stay in the worktree; pre-staged edits on those paths are preserved after apply, including when the selected hunk changes line count. Absorb staged fixes on a linear branch: ```console $ grit add file.txt $ grit history absorb Absorbed 1 hunk(s) into 2 commit(s) file.txt @@ -2,0 +3 @@ → a1b2c3d touch line 4 ``` Preview hunk → commit assignment without changing refs or the index: ```console $ grit add file.txt $ grit history absorb --dry-run Dry run — absorb would change 2 commit(s) file.txt @@ -2,0 +3 @@ → a1b2c3d touch line 4 other.txt @@ -1,0 +2 @@ — no_candidate commit a1b2c3d → d4e5f60 refs/heads/main f6a7b89 → c0ffee0 ``` Split one file out of the parent of `HEAD`: ```console $ grit history split HEAD~1 -m "add foo only" -- foo Split 2 commit(s) commit a1b2c3d → d4e5f60 refs/heads/main f6a7b89 → c0ffee0 ``` ## JSON output Schemas: [drop v1](https://grit-scm.com/docs/history/schemas/history.drop/v1.json/index.md), [move v1](https://grit-scm.com/docs/history/schemas/history.move/v1.json/index.md), [reword v1](https://grit-scm.com/docs/history/schemas/history.reword/v1.json/index.md), [fixup v1](https://grit-scm.com/docs/history/schemas/history.fixup/v1.json/index.md), [squash v1](https://grit-scm.com/docs/history/schemas/history.squash/v1.json/index.md), [absorb v1](https://grit-scm.com/docs/history/schemas/history.absorb/v1.json/index.md), [undo v1](https://grit-scm.com/docs/history/schemas/history.undo/v1.json/index.md), [rebase v1](https://grit-scm.com/docs/history/schemas/history.rebase/v1.json/index.md), [split v1](https://grit-scm.com/docs/history/schemas/history.split/v1.json/index.md) Pass `--json` on `grit history drop`, `grit history move`, `grit history reword`, `grit history fixup`, `grit history squash`, `grit history split`, `grit history absorb`, or `grit history undo`: | Field | Type | Meaning | | ----- | ---- | ------- | | `operation` | string | `"drop"`, `"move"`, `"reword"`, `"fixup"`, `"squash"`, `"split"`, `"absorb"`, `"undo"`, or `"rebase"`. | | `result` | string | `rebase` only: `completed`, `conflicts`, `exec_dirty`, or `aborted`. | | `rewritten` | array | `{old,new,change_id,subject}` full hex OIDs, stored change id (`null` when dropped or absent), and the first line of the replacement commit message (or the original when dropped). | | `refs` | array | `{ref,old,new}` for each ref that would move or moved. `name` duplicates `ref` and is deprecated; it will be removed in a future release. | | `head` | object or null | `{old,new}` when `HEAD`'s commit OID changes; `null` when unchanged. | | `dry_run` | boolean | `true` when `--dry-run` was set. | | `commit` | string | `rebase` when paused: source commit for `conflicts`, or `HEAD` after the command for `exec_dirty` (full hex). | | `conflicts` | array | `rebase` when `result` is `conflicts`: `{path,kind,summary?}`. | | `rerere` | array | `rebase` when `rerere.enabled` is active at a conflict stop (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. | | `next_steps` | array | `rebase` when paused: ordered follow-up `grit` commands. | | `alternatives` | array | `rebase` when paused: `grit rebase --abort` and `grit rebase --skip`. | For `rebase` with `--exec`, the object also includes: | Field | Type | Meaning | | ----- | ---- | ------- | | `exec` | array | `{commit,command,exit_code}` per successful `--exec` invocation through completion or a dirty stop (full hex `commit`). | | `command` | string or null | Successful command that left tracked edits when `result` is `exec_dirty`. | | `paths` | array | Changed tracked paths preserved when `result` is `exec_dirty`. | For `absorb`, the object also includes: | Field | Type | Meaning | | ----- | ---- | ------- | | `assignments` | array | `{path,hunk_range,commit,subject}` for hunks assigned to historical commits. | | `unassigned` | array | `{path,hunk_range,reason,detail?}` for hunks left staged (`reason` is a stable code; `detail` explains `hidden_by_ref`). | | `excluded_refs` | array | `{ref,commit}` for local branch tips hidden from the stack (always present; empty when none apply). | For `undo`, the object also includes: | Field | Type | Meaning | | ----- | ---- | ------- | | `restored_paths` | array | Paths whose index entry and work tree file were put back (or would be, with `--dry-run`) because the undone `fixup` or `absorb` had consumed their edits. Omitted when empty. | | `unrestored_edits` | string | Full hex OID of the commit that still holds edits an undone `fixup` or `absorb` folded in, when the record had no saved state to restore. Omitted otherwise. | For `rebase`, use the [`grit rebase`](https://grit-scm.com/docs/history/rebase.md/index.md) JSON table (`result`, `commit`, `conflicts`, `next_steps`, `alternatives`, plus `rewritten` / `refs` / `head` when `result` is `completed`). Example: ```json { "operation": "reword", "rewritten": [ { "old": "6e513d5cd6ab8d618238e22d7ca55d942b55964a", "new": "1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d", "change_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", "subject": "Reworded subject" } ], "refs": [ { "ref": "refs/heads/main", "name": "refs/heads/main", "old": "9f8e7d6c5b4a392817061524334352637281910", "new": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567" } ], "head": { "old": "9f8e7d6c5b4a392817061524334352637281910", "new": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567" }, "dry_run": false } ``` History rewrite commands other than `rebase` report planning conflicts as structured errors (`kind: "conflict"`) with `conflicts` (paths) and `commit` (the commit that could not be replayed). When that commit is only on other branches the rewrite would move, `refs` lists them and `hint` suggests `--update-refs head`. `grit history rebase` uses the same stop/resume JSON as [`grit rebase`](https://grit-scm.com/docs/history/rebase.md/index.md) (`result: "conflicts"`, exit **1**). Here `other` was built on `topic` and edits the line that `c2` added, so dropping `c2` from `topic` cannot move `other`: ```console $ grit history drop topic~1 error: history drop has conflicts moving refs/heads/other onto the new history: commit 78d765c o1 a.txt Nothing was changed. grit can't resolve conflicts yet. hint: pass --update-refs head to rewrite only the current branch and leave the others as they are $ grit history drop topic~1 --json {"commit":"78d765caa49114094c4779be2dc3e505979ba6c4","conflicts":["a.txt"],"error":"history drop has conflicts","hint":"pass --update-refs head to rewrite only the current branch and leave the others as they are","kind":"conflict","refs":["refs/heads/other"]} $ grit history drop topic~1 --update-refs head Dropped 1 commit, replayed 2 descendant commit(s) commit e8de07f → (dropped) (c2) commit a8a77a4 → 844233b (c3) refs/heads/topic a8a77a4 → 844233b ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/history/schemas/history.reword/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a heading such as `History squash` or `History reword` (matching `operation`), plus rewritten commits, ref updates, and optional `HEAD` movement. ```text ## History drop - Dry run (refs unchanged) - commit `e813550` → (dropped) — two - commit `ac49499` → `5973cf5` — three - change id `nlwnxqt` - `refs/heads/main` `ac49499` → `5973cf5` - HEAD `ac49499` → `5973cf5` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [Library guide: History rewrite](https://grit-scm.com/docs/library/history.md/index.md), [`grit log`](https://grit-scm.com/docs/history/log.md/index.md), [`grit pick`](https://grit-scm.com/docs/history/pick.md/index.md) # https://grit-scm.com/docs/branch/index.md # grit branch > List branches, or create, delete, rename, or configure one. ## Synopsis ```text grit branch [--list ]... [-r | -a] [--merged [REV]] [--no-merged [REV]] [--contains [REV]] [--sort name|version|date] [--reverse] [-n ] [--show-current] grit branch [] grit branch -d grit branch -D grit branch -m [] grit branch -M grit branch -u [] grit branch --unset-upstream [] grit branch [--dry-run] … ``` ## Description With no arguments, lists your local branches and marks the current one with `*`. When a branch has a configured upstream, the line includes a short marker such as `[origin/main: ahead 2, behind 1]` or `[gone]` when the tracking ref is missing. Use `-r` / `--remotes` for remote-tracking branches (`origin/main`, …) and `-a` / `--all` for both (remote names use the `remotes/origin/main` form, like `git branch -a`). `--list`, `--merged`, `--no-merged`, `--contains`, `--sort`, `--reverse`, and `-n` / `--limit` follow Git’s branch listing filters (`--max-count` is an alias). `--show-current` prints only the current branch name. With `--json` or `--markdown`, list output includes `full_ref`, commit `subject` and `date`, upstream details, and linked `worktree` paths when present. Plain human list stays names plus upstream markers. Path strings in human, `--json`, and `--markdown` output use forward slashes and no Windows `\\?\` verbatim prefix (same spelling as [`grit worktree`](https://grit-scm.com/docs/branch/worktree.md/index.md)), so scripts can compare `branches[].worktree` with `worktrees[].path`. With a name, creates `refs/heads/` at `` or at `HEAD`. It does not switch to the new branch; use [`grit switch -c`](https://grit-scm.com/docs/switch/index.md) to create and switch in one step. Branch names follow the same rules as `git check-ref-format --branch`. Invalid names fail before anything is written under `.git/refs`. With `-d`, deletes a branch when its tip is reachable from the current branch's upstream (if configured) or from `HEAD`. With `-D` or `--force-delete`, deletes even when commits would otherwise be lost. You cannot delete the branch you are on, or a branch checked out in another linked worktree. With `-m` / `--move`, renames a branch (one argument renames the current branch). `-M` is the same as `-m --force`, replacing an existing `refs/heads/` when needed. With `-u` / `--set-upstream-to`, writes `branch..remote` and `branch..merge` from a local or remote-tracking branch. With `--unset-upstream`, removes those keys. Use `--dry-run` on any mutation to preview the JSON outcome without changing refs, config, or reflogs. ## Options | Option | Description | | --- | --- | | `` | Branch to create, delete, rename, or configure. Omit to list. | | `` | Commit to start from when creating (`rev-parse` syntax). Defaults to `HEAD`. | | `-f`, `--force` | On create or rename, replace an existing branch tip (refuses when that branch is checked out in a worktree). | | `-t`, `--track` | When creating, always configure upstream from `` when possible. | | `--no-track` | When creating, never configure upstream. | | `-u`, `--set-upstream-to` | Set upstream for `` or the current branch when `` is omitted. | | `--unset-upstream` | Clear upstream for `` or the current branch. | | `-m`, `--move` | Rename: `-m ` or `-m `. | | `-M` | Force rename: `-M ` (current branch) or `-M `. | | `-d`, `--delete` | Delete the branch when it is fully merged. | | `-D`, `--force-delete` | Delete even when not fully merged. | | `--list ` | Include only branches whose short name matches `GLOB` (repeatable). | | `-r`, `--remotes` | List remote-tracking branches (list mode). | | `-a`, `--all` | List local and remote-tracking branches (list mode). | | `--merged [REV]` | Branches merged into `REV` (default `HEAD`). | | `--no-merged [REV]` | Branches not merged into `REV` (default `HEAD`). | | `--contains [REV]` | Branches whose tip contains `REV` (default `HEAD`). | | `--sort name\|version\|date` | Sort key (default name). | | `--reverse` | Reverse sort order. | | `-n`, `--limit ` | Limit the number of branches listed (`--max-count` alias). | | `--show-current` | Print only the current branch name (nothing when detached). | | `--dry-run` | Preview without writing refs, config, or reflogs. | `--force` does not delete branches. Use `--force-delete` (or `-D`) instead; passing `--force` with `--delete` is a usage error. ## Examples ```console $ grit branch feature * main [origin/main: ahead 1, behind 0] $ grit branch --list 'feat*' --sort date -n 5 feature-old * feature $ grit branch --show-current main $ grit branch experiment Created branch experiment at a1b2c3d $ grit branch topic main~1 Created branch topic at 9f8e7d6 $ grit branch -d experiment Deleted branch experiment (was cf18394). $ grit branch -m topic renamed Renamed branch topic to renamed $ grit branch -u origin/main renamed Set upstream of renamed to origin/main ``` While a rebase is paused and `HEAD` is detached, renaming the branch being rebased is refused: ```console $ grit branch -m renamed error: cannot rename the branch while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort` ``` Deleting a branch with unmerged work: ```console $ grit branch -d spike error: the branch 'spike' is not fully merged into 'main' If you are sure you want to delete it, run 'grit branch --force-delete spike' $ grit branch -D spike Deleted branch spike (was a7020c2). ``` A branch name cannot also be a directory of other branches. Creating `rel` while `rel/1.0` exists (loose or packed, or with only its reflog left under `.git/logs/`) names the branch in the way, and `grit switch -c rel` refuses the same way: ```console $ grit branch rel error: cannot lock ref 'refs/heads/rel': 'refs/heads/rel/1.0' exists; cannot create 'refs/heads/rel' ``` ## JSON output List results include `truncated: true` when `-n` / `--limit` caps the branch list and more branches matched. With `--contains` and name ordering (including `--reverse`), the limit bounds matching rows: grit checks tips in name order and stops after the extra match needed to detect truncation. Earlier nonmatching branches do not consume the limit. Graft-defined ancestry, including cycles, has the same ordered matches and truncation as an unlimited query. Schema: [v1](https://grit-scm.com/docs/branch/schemas/branch/v1.json/index.md) Pass `--json` for stable, scripting-friendly output. The object's `action` field says what happened: | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | `list`, `create`, `delete`, `rename`, `set_upstream`, or `unset_upstream`. | | `current` | string or null | For `list`, the current branch, or `null` when detached. | | `branches` | array | For `list`, each branch (see below). | | `truncated` | boolean | For `list`: `true` when more branches matched than returned (`-n` / `--limit`). | | `branches[].name` | string | Short name (`main`, `origin/main`, `remotes/origin/main` with `-a`, …). | | `branches[].current` | boolean | Whether this is the checked-out local branch. | | `branches[].is_remote` | boolean | True for remote-tracking refs. | | `branches[].full_ref` | string | Full ref (`refs/heads/…`, `refs/remotes/…`). | | `branches[].oid` | string | Tip object id (full hex). | | `branches[].short_oid` | string | Abbreviated tip id (seven hex digits when possible). | | `branches[].subject` | string or null | Tip commit subject (`--json` / `--markdown` list). | | `branches[].date` | string or null | Tip committer time (RFC 3339). | | `branches[].upstream` | object or omitted | `ref`, optional `remote`, `gone`, `ahead`, `behind`. | | `branches[].worktree` | string or null | Linked worktree path when checked out elsewhere. | | `name` | string | For `create` or `delete`, the branch name. | | `oid` | string | For `create` or `delete`, full tip id. For `rename`, tip before rename when present. | | `short_oid` | string | Abbreviated tip id (seven hex digits when possible). | | `upstream` | string or null | For `create`, the branch's upstream display name afterwards: the one tracking configures, or the one already configured when `--force` resets an existing branch (`--dry-run` reports what the live create would). For `set_upstream`, the upstream display name (for example `origin/main`). | | `old` | string | For `rename`, previous short name. | | `new` | string | For `rename`, new short name. | | `replaced` | string or null | For `rename` with `--force`, previous tip of `new` when overwritten. | | `branch` | string | For `set_upstream` / `unset_upstream`, the branch that was updated. | | `dry_run` | boolean | Present and `true` when the operation was preview-only. | Listing branches: ```json { "action": "list", "current": "main", "branches": [ { "name": "feature", "current": false, "is_remote": false, "full_ref": "refs/heads/feature", "oid": "a1b2c3d4e5f6789012345678901234567890abcd", "short_oid": "a1b2c3d", "subject": "Add feature", "date": "2023-11-14T22:13:20Z", "upstream": { "ref": "origin/feature", "remote": "origin", "gone": false, "ahead": 0, "behind": 2 } }, { "name": "main", "current": true, "is_remote": false, "full_ref": "refs/heads/main", "oid": "b2c3d4e5f6789012345678901234567890abcde1", "short_oid": "b2c3d4e", "subject": "Initial commit", "date": "2023-11-14T22:13:20Z" } ] } ``` Remote-tracking list: ```json { "action": "list", "current": "main", "branches": [ { "name": "origin/main", "current": false, "is_remote": true, "oid": "b2c3d4e5f6789012345678901234567890abcde1", "short_oid": "b2c3d4e" } ] } ``` Creating a branch: ```json { "action": "create", "name": "experiment", "oid": "a1b2c3d4e5f6789012345678901234567890abcd", "short_oid": "a1b2c3d" } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v1](https://grit-scm.com/docs/branch/schemas/branch/v1.json/index.md) Markdown lists branches in a table with upstream and worktree columns when present. Table cells escape `|` and internal newlines so commit subjects and paths stay on one row. See the JSON output section for the stable field contract. ```text ## Branches | Branch | Current | OID | Subject | Upstream | Worktree | | --- | --- | --- | --- | --- | --- | | `feature` | | `062ca6e` | first | | | | `main` | yes | `83352a6` | second | | [REPO] | ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success, including `--dry-run` previews. | | `1` | Branch not found, not fully merged, checked out elsewhere, invalid start point (`branch_invalid_start_point`), or other operational failure. | | `2` | Usage error (missing arguments, incompatible flags). | On failure with `--json`, stdout includes `error` and a stable `kind`. See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit switch](https://grit-scm.com/docs/switch/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md) # https://grit-scm.com/docs/switch/index.md # grit switch > Switch to another branch, remote branch, or detached commit. ## Synopsis ```text grit switch grit switch - grit switch @{-1} grit switch -c [] grit switch --detach grit switch [--dry-run] … ``` `grit co` does the same thing, and so does `grit checkout `; `grit checkout ` makes a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md) from a server instead. ## Description Switches to a local branch, creates a branch from a remote-tracking ref or start point, or checks out a commit in detached `HEAD` mode. Updates tracked files in the working tree to match the destination. Local edits are allowed when they only touch paths that are the same on both sides of the switch, or when a changed path already matches the destination tree in the index. Grit still refuses when your changes would conflict with files that differ between branches, or when an untracked file would be overwritten. After a [`clone --no-checkout`](https://grit-scm.com/docs/clone/index.md), the first switch creates the index and materializes the entire destination tree. This works with clones created by grit or system Git, including switching to the current branch, detaching at `HEAD`, or creating a branch at a commit with the same tree. The previous `HEAD` is still used for reflogs and hooks. Untracked files at destination paths block the switch. An existing empty index continues to represent staged deletions and receives the normal local-change protection. Use `--dry-run` to run the same overwrite checks and report how many paths would change without updating `HEAD`, the index, the worktree, or reflogs. Agents can preflight a switch with `--json --dry-run` before mutating the tree. On the first switch after `clone --no-checkout`, the dry-run count includes every path to materialize, including files unchanged between the old and new commits. A switch either completes or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out stops the switch with `error: operation cancelled`; `HEAD`, the index and the work tree are left exactly as they were, so `grit status` stays clean, no `.git/index.lock` is left behind and the same switch can simply be run again. If cancellation is already requested before the switch starts (or is observed while the plan is being built), grit returns cancelled without deleting work-tree paths. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` or closing the console window skips rollback. In the rare case that a path cannot be put back (for example a directory that became read-only), the error has kind `checkout_incomplete` and lists those paths in `paths`; `HEAD` and the index still did not move. Switching is refused while a merge, rebase, pick, revert or `am` is paused, whether grit or `git` started it: those operations finish by committing onto the current `HEAD`, so moving it would land their result on the wrong branch. When grit knows how the operation finishes or is cancelled (merge, rebase, pick, revert), the error names those commands. `--dry-run` is refused too. A bisect does not block a switch. A local branch can only be checked out in one worktree at a time (including linked worktrees created with `git worktree add`). Switching to a branch that is already checked out elsewhere fails. With `-c`, creates the branch at the current commit (or at `` when you pass one), then switches to it. When `` is a remote-tracking branch (for example `origin/main`), grit configures upstream tracking the same way as [`grit branch --track`](https://grit-scm.com/docs/branch/index.md) and `git switch -c`, unless you pass `--no-track` or `branch.autoSetupMerge` is `false`/`simple`. When `` names a remote-tracking branch (for example `origin/feature`), Grit creates `feature` at the same commit and switches to it if no local branch exists yet. It also records upstream tracking in the repository config (`branch.feature.remote` and `branch.feature.merge`), the same keys `git switch` writes, so `grit status`, `grit pull`, and `grit push` use the matching remote branch. `--detach` checks out `` without moving a branch tip. Use another branch or `grit switch ` to reattach. In a sparse checkout (`git sparse-checkout`), only paths inside the sparse patterns are written to the worktree. Paths outside them are recorded in the index with the skip-worktree bit, the same as `git switch`. The same applies to [`grit merge`](https://grit-scm.com/docs/merge/index.md), [`grit pull`](https://grit-scm.com/docs/pull/index.md) and [`grit reset`](https://grit-scm.com/docs/reset/index.md). After a real switch (not `--dry-run`), grit runs the `post-checkout` hook with the previous `HEAD` commit, the new one, and `1`, as Git does. The old id is all zeros when switching away from a branch with no commits. The hook also runs when you switch to the branch or commit you are already on. Its exit status never changes the result; a hook that cannot be started prints a `hook_not_run` warning. See [`grit hooks`](https://grit-scm.com/docs/hooks/index.md). Leaving a detached `HEAD` that carries commits of its own (made with `grit commit` after `--detach`) would leave those commits on no branch, recoverable only through `grit reflog` until garbage collection removes them. Grit still switches, but warns on stderr with the commits it leaves behind (newest first, up to 20) and a `grit branch ` command that keeps them. A commit counts as left behind when no ref, the stash, another worktree's `HEAD`, or the switch destination reaches it, so `grit switch -c ` from the detached commit leaves nothing behind. Without a commit-graph the check ends by commit date like Git's `rev-list`, so heavy clock skew can make the count wrong (see [grit reset](https://grit-scm.com/docs/reset/index.md)). `--dry-run` reports the same list without switching. Leaving a branch never warns: the branch still holds its commits. Updating the working tree uses parallel checkout when the change set is large enough; tune [`checkout.workers`](https://grit-scm.com/docs/library/parallelism.md/index.md) and `checkout.thresholdForParallelism`. On non-Windows hosts, global [`--threads`](https://grit-scm.com/docs/global-options.md/index.md) can cap checkout workers for this run; on **Windows**, checkout stays serial until `checkout.workers` is set in config (see [parallelism](https://grit-scm.com/docs/library/parallelism.md/index.md)). ## Options | Option | Description | | --- | --- | | `` | Local branch to switch to, remote-tracking name to DWIM, or new branch name with `-c`. | | `-`, `@{-1}` | Switch to the previous branch (from the `HEAD` reflog); fails when there is no prior checkout entry. | | `` | With `-c`, commit to create the branch from (defaults to `HEAD`). | | `-c`, `--create` | Create the branch first, then switch to it. Fails if the branch already exists. | | `-t`, `--track` | With `-c`, always configure upstream from the start point. | | `--no-track` | With `-c`, do not configure upstream. | | `--detach` | Check out a commit in detached `HEAD` mode instead of switching a branch. | | `--dry-run` | Run overwrite checks and report how many paths would change; do not update refs, the index, or the worktree. | ## Examples ```console $ grit switch -c feature Created and switched to branch feature $ grit switch main Switched to branch main hooks: post-checkout $ grit switch - Switched to branch feature $ grit switch -c work origin/main Created and switched to branch work tracking origin/main $ grit switch -c br2 origin/br2 Created and switched to branch br2 tracking origin/br2 $ grit switch --detach HEAD~1 HEAD detached at a1b2c3d $ grit switch other --dry-run Would switch to other (3 path(s) would change) ``` When you leave a detached `HEAD` with commits no branch holds: ```console $ grit switch main Switched to branch main Warning: 1 commit left behind, not on any branch: 85ffcb0 work done on detached HEAD Keep it on a branch with: grit branch 85ffcb090615556eb238400c577de383ca034213 ``` When local changes would conflict with the destination branch: ```console $ grit switch other error: you have uncommitted changes — commit them before switching notes.txt hint: commit them with `grit commit`, or set them aside with `grit stash`, then try again ``` When `grit switch -` has no previous branch to return to (for example right after `grit init`): ```console $ grit switch - error: there is no previous branch to go back to ``` When no branch has that name: ```console $ grit switch nonexistent error: no branch named 'nonexistent' hint: `grit branch` lists your branches; create this one with `grit switch -c nonexistent` ``` While a rebase that `git` started is stopped on a conflict: ```console $ grit switch main error: cannot switch branches while an interactive rebase is in progress; finish it with `git rebase --continue` or cancel it with `grit rebase --abort` ``` When an untracked file would be overwritten: ```console $ grit switch other error: untracked file 'new.txt' would be overwritten — move or remove it first new.txt hint: move or remove those files, then try again ``` ## JSON output Schema: [v2](https://grit-scm.com/docs/switch/schemas/switch/v2.json/index.md) · [v1](https://grit-scm.com/docs/switch/schemas/switch/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `branch` | string or null | Short branch name `HEAD` is on after the switch; `null` when detached. | | `created` | boolean | `true` when `-c` or remote DWIM created the branch. | | `upstream` | string or null | When `-c` configured upstream tracking, the remote branch name (for example `origin/main`); omitted when none was set. | | `detached` | boolean | `true` when `HEAD` is detached after the switch (`branch` is `null`). | | `commit` | string or null | Full hex oid when `detached` is true; omitted when attached. | | `dry_run` | boolean | `true` when `--dry-run` was used (omitted when false). | | `changed_paths` | integer or null | With `--dry-run`, count of paths that would differ after checkout. | | `hooks_run` | array of strings | Hooks that ran after the switch (`post-checkout` when installed); empty on `--dry-run`. | | `stranded_commits` | array | Commits only the previous detached `HEAD` reached, newest first, at most 20. Each has `oid`, `change_id` and `subject`. Omitted when nothing is left behind. | | `stranded_total` | integer | Advisory count of commits left behind (may exceed the length of `stranded_commits`). Without a commit-graph, severe clock skew can make this inaccurate; it never controls the switch. Omitted when zero. | | `stranded_truncated` | boolean | `true` when `stranded_commits` was capped (omitted when false). | | `path_collisions` | array of strings | Index paths that collided during checkout when tracked paths share one on-disk file (case or Unicode normalization). Omitted when empty. | When `core.ignorecase` or `core.precomposeunicode` is set and the destination tree contains paths that collide on this filesystem (different ASCII case or NFC/NFD spellings mapping to one file), grit prints a **warning** on **stderr** in human mode listing every colliding index path, the same message as [`grit clone`](https://grit-scm.com/docs/clone/index.md). Only one path from each group exists on disk; status and diff treat index rows whose blob does not match the shared dentry as modified. Example (branch switch): ```json { "branch": "feature", "created": true, "detached": false, "hooks_run": ["post-checkout"] } ``` Example (`--dry-run`): ```json { "branch": "other", "created": false, "detached": false, "dry_run": true, "changed_paths": 3, "hooks_run": [] } ``` Example (detached): ```json { "branch": null, "created": false, "detached": true, "commit": "a1b2c3d4e5f6789012345678901234567890abcd", "hooks_run": [] } ``` Example (leaving a detached `HEAD` with one commit of its own): ```json { "branch": "main", "created": false, "detached": false, "hooks_run": [], "stranded_commits": [ { "oid": "85ffcb090615556eb238400c577de383ca034213", "change_id": "zrmsknstkznuqxynsolvwoovmolrxwum", "subject": "work done on detached HEAD" } ], "stranded_total": 1 } ``` On overwrite refusal with `--json`, stdout is a single object with `kind` `would_overwrite` and `would_overwrite.reason` (`local_changes` or `untracked`) plus a sorted `paths` array, and a `hint`, for example `{"error":"you have uncommitted changes — commit them before switching","hint":"…","kind":"would_overwrite","would_overwrite":{"paths":["notes.txt"],"reason":"local_changes"}}`. See the [error schema](https://grit-scm.com/docs/switch/schemas/error/v1.json/index.md). A branch that does not exist is `kind` `branch_not_found` with a `hint`. With `--create`, an existing name is `kind` `branch_already_exists`, an invalid name is `branch_invalid_name`, and an empty repository with no start point is `branch_no_commits`. A start point that does not resolve is `revision_not_found`; one that resolves to a non-commit object is a plain error string with no dedicated `kind`. While a merge, rebase, pick or revert is paused, the refusal is `{"error": "interactive rebase in progress", "kind": "operation_in_progress"}` (the `error` names the paused operation). ## Markdown output Schema: [v2](https://grit-scm.com/docs/switch/schemas/switch/v2.json/index.md) · [v1](https://grit-scm.com/docs/switch/schemas/switch/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Switch` heading and one summary line, plus a `- Hooks:` line when a hook ran: ```text - Switched to **`feature`** ``` Creating a branch: ```text - Created and switched to **`topic`** ``` Dry run: ```text - Would switch to **`other`** (3 path(s) would change) ``` Detached HEAD: ```text - HEAD detached at `9244cbd` ``` Leaving commits behind adds a warning block after the summary line: ```text - Switched to **`main`** > **Warning:** 1 commit left behind, not on any branch: - `85ffcb0` work done on detached HEAD Keep it with `grit branch 85ffcb090615556eb238400c577de383ca034213`. ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. When another process holds `.git/index.lock`, a switch that would update the worktree fails with exit `1` (`kind` `lock_held` under `--json`) before touching anything: the worktree, index, `HEAD` and branches are unchanged. `--dry-run` never takes the lock. ## See also [grit branch](https://grit-scm.com/docs/branch/index.md), [grit reset](https://grit-scm.com/docs/reset/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md), [grit status](https://grit-scm.com/docs/status/index.md) Sparse indexes keep unchanged excluded directory trees compact during checkout. Only affected directories or directories present outside the sparse cone need individual index rows. Performance and scaling methodology are documented in [Benchmarks](https://grit-scm.com/docs/benchmarks.md/index.md). Unmerged indexes use the full worktree guard checks. # https://grit-scm.com/docs/merge/index.md # grit merge > Merge another branch, tag or commit into the current one. ## Synopsis ```text grit merge grit merge --check grit merge --dry-run grit merge --continue [-m ] grit merge --abort grit merge [--ff-only | --no-ff] [--squash | --no-commit] [-X ours|theirs] [--conflict diff3|zdiff3|merge] [--allow-unrelated-histories] [--no-verify] [-m | -F / --message-file ] ``` ## Description Brings the commits from `` into the current branch. Pathnames in human, stderr conflict lines, and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). - If the current branch already has everything, nothing changes. - If the current branch has no commits of its own since they diverged, it's moved forward to `` (a fast-forward). No new commit is made. - Otherwise both sides are merged. When there are no overlapping edits, a merge commit is recorded with the message `Merge `, using `` as you typed it. That commit gets a new `change-id` header like [`grit commit`](https://grit-scm.com/docs/commit/index.md). When `commit.gpgsign` is enabled, that merge commit is signed like [`grit commit`](https://grit-scm.com/docs/commit/index.md). - When the same lines were changed on both sides, `grit merge` stops with conflicts: it updates the index and working tree, writes conflict markers around each conflicting hunk, records merge-in-progress state (`MERGE_HEAD`, `ORIG_HEAD`, `MERGE_MSG`), and leaves the branch ref unchanged. When `rerere.enabled` is true (or `.git/rr-cache/` already exists), grit replays resolutions Git recorded in `.git/rr-cache/` and records new preimages and postimages in Git's format on conflict stops and when you `--continue` or [`grit commit`](https://grit-scm.com/docs/commit/index.md) after resolving. Replayed files stay unstaged unless `rerere.autoupdate` is set; `--abort` drops unresolved rerere state like Git. Fix conflicts, then run `grit merge --continue` to create the two-parent merge commit (message from `MERGE_MSG` with comment lines stripped, or `-m` to override). When `commit.autoStage` is true (the default), `--continue` stages resolved paths from the work tree the same way [`grit commit`](https://grit-scm.com/docs/commit/index.md) does, so you do not need `grit add` after editing away conflict markers. With `commit.autoStage=false`, stage resolved paths with `grit add` before `--continue`. [`grit commit`](https://grit-scm.com/docs/commit/index.md) can also finish a resolved merge. Run `grit merge --abort` to discard the in-progress merge and restore the pre-merge branch, index, and working tree. - After a merge with `--no-commit` (when supported), run `grit merge --continue` to record the merge commit without re-running the three-way merge. Before a clean merge records its commit, grit runs the same hooks as Git, in Git's order: `pre-merge-commit` (no arguments), then `prepare-commit-msg .git/MERGE_MSG merge` and `commit-msg .git/MERGE_MSG`, which see `MERGE_HEAD` and may rewrite the message (the commit records what they leave). Files a `pre-merge-commit` hook stages go into the merge commit. When one of them exits non-zero, the merge stops with exit **1** and a `hook_failed` error (as for [`grit commit`](https://grit-scm.com/docs/commit/index.md)): the merged files stay in the work tree and index, `MERGE_HEAD`, `ORIG_HEAD` and `MERGE_MSG` are recorded, and the branch does not move. Finish with `grit merge --continue` (which runs `pre-commit` like `grit commit`, as Git does) or cancel with `grit merge --abort`; edits a [`grit pull --autostash`](https://grit-scm.com/docs/pull/index.md) stashed come back either way. `--no-verify` skips `pre-merge-commit` and `commit-msg`; `prepare-commit-msg` and `post-merge` still run. None of these run for a fast-forward, `--squash`, `--no-commit`, conflicts, `--check` or `--dry-run`. ```console $ grit merge topic -m 'WIP merge' pre-merge-commit: blocked error: hook pre-merge-commit failed with exit status 1 hint: the merge is still in progress: run `grit merge --continue` to commit it, or `grit merge --abort` to cancel $ grit merge --abort Merge aborted. ``` A merge either completes, stops for conflicts, or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out during a fast-forward or three-way merge stops the merge with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the merge started (no `MERGE_HEAD`), no `.git/index.lock` is left behind, and the same merge can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. In the rare case that a path cannot be put back during checkout rollback, the error has kind `checkout_incomplete` and lists those paths in `paths`. With `--json` the error carries the hook's output and the same `hint`: ```json { "error": "hook pre-merge-commit failed with exit status 1", "hint": "the merge is still in progress: run `grit merge --continue` to commit it, or `grit merge --abort` to cancel", "hook": { "name": "pre-merge-commit", "status": 1, "stderr": "pre-merge-commit: blocked\n", "stdout": "" }, "kind": "hook_failed" } ``` After a fast-forward or a merge commit, grit runs the `post-merge` hook with `0`; after `--squash` it passes `1`, as Git does. The hook does not run when the branch is already up to date, when the merge stops on conflicts, with `--no-commit`, or for `--check` and `--dry-run`. `grit merge --continue` runs `post-commit` like [`grit commit`](https://grit-scm.com/docs/commit/index.md), not `post-merge` (Git behaves the same). The hook's exit status never changes the result. See [`grit hooks`](https://grit-scm.com/docs/hooks/index.md). Every merge records the commit the branch was on in `ORIG_HEAD`, as `git merge` does: an up-to-date merge, a fast-forward, a merge commit, `--squash`, `--no-commit`, a merge that stops on conflicts, and a `--ff-only` merge refused because it cannot fast-forward. It replaces any earlier value and stays after the merge finishes, `--continue` or `--abort`, so `grit reset --hard ORIG_HEAD` undoes a merge you regret. `--check` and `--dry-run` leave it alone. `` can be any branch, tag or commit: a local branch, a remote-tracking branch such as `origin/main`, a tag such as `v1.2` (annotated tags merge the commit they point at), a full or abbreviated commit id, or a revision expression such as `topic~2`, `origin/main^` or `ORIG_HEAD`. A name is looked up as a local branch first, then a remote-tracking branch, then a tag, then as a revision. Ranges (`a..b`, `a...b`) and trees or blobs are refused. Literal braces are allowed in ref names: `grit merge 'foo{bar'` merges that branch, while `grit merge 'foo{bar...main'` refuses the range without moving HEAD. Dots within selectors, such as `main^{/release..candidate}`, remain part of a single revision. On a criss-cross history the two branches have several merge bases (`grit merge-base --all` lists them). grit then merges those bases into one virtual base first and merges the two branches against it, like Git, so `grit merge` and `grit merge --check` give the same answer whichever base comes first. When the two sides resolved the same old conflict in different ways, the merge stops with a conflict instead of silently keeping one resolution. In that case the base version (stage 1 in the index, the `|||||||` section with `--conflict diff3`) holds the bases' own conflict, with markers labelled `Temporary merge branch 1` and `Temporary merge branch 2`. `-X ours|theirs` applies only to the final merge, not to the merge of the bases. Local edits are allowed when they only touch paths the merge does not change, or when a changed path already matches the post-merge tree in the index (same scoped rule as [`grit switch`](https://grit-scm.com/docs/switch/index.md)). Grit refuses when your changes would be overwritten by files the merge updates, when an untracked file would be replaced by a path the merge would check out, or on a branch with no commits; the branch (or detached `HEAD`) and file are left unchanged. With a **detached `HEAD`**, grit merges into `HEAD` like Git: a fast-forward or merge commit moves only `HEAD` (branch tips such as `main` stay put). `--check` and `--dry-run` work the same way and leave `HEAD`, the index, and merge state untouched. ### Merge modes - **`--ff-only`** — Refuse when a fast-forward is not possible (histories diverged). Nothing changes. Exit code **128** (same as Git's `merge --ff-only`). - **`--no-ff`** — Always record a merge commit with two parents when a real merge is needed, even if a fast-forward was possible. - **`--squash`** — Apply the merged tree to the index and worktree, write a Git-compatible `SQUASH_MSG`, and do not update the branch ref or write `MERGE_HEAD`. Finish with [`grit commit`](https://grit-scm.com/docs/commit/index.md) (which uses `SQUASH_MSG` as the default message when you omit `-m`). - **`--no-commit`** — Perform the merge but stop before committing: writes `MERGE_HEAD`, `ORIG_HEAD`, and `MERGE_MSG` (and `MERGE_MODE` when `--no-ff` applies). Finish with [`grit commit`](https://grit-scm.com/docs/commit/index.md) or `grit merge --continue` (when implemented). `-m` / `-F` / `--message-file` override the default merge commit message and the text stored in `MERGE_MSG` on conflicts or `--no-commit`. **`-X ours|theirs`** — When both sides edited the same region, prefer the current branch (`ours`) or the branch being merged (`theirs`) instead of leaving conflict markers. Matches Git's merge strategy options (union is not exposed). `--check` and `--dry-run` honor the same option when predicting the outcome. **`--conflict diff3|zdiff3|merge`** — Conflict marker style in the worktree. When omitted, grit reads `merge.conflictStyle` (default `merge`). Textual merges during a three-way tree merge use the histogram diff algorithm, matching Git's merge-ort strategy (distinct from `git merge-file`, which uses Myers). **`--allow-unrelated-histories`** — Merge branches that share no commits, using the empty tree as the merge base (Git-compatible). Without this flag, grit refuses unrelated histories. On an interactive terminal (human output, not `--json` or `--markdown`), a live **Checkout** line on stderr counts the files the merge writes, and `--continue` shows a **Staging** line while it auto-stages; nothing is drawn when stderr is not a TTY. ### Directory renames When one branch moved every file out of a directory (renaming `a/` to `b/`) and the other branch added a file inside the old directory, the new file most likely belongs in `b/`. Grit detects this the way Git does: the directory must be gone on the renaming side, and its destination is the directory that received the most of its files. The `merge.directoryRenames` config decides what happens: - **`conflict`** (default, as in Git) — The file is moved to `b/` and left unmerged so you can confirm the location. It's in the work tree at the new path; stage it there (or move it back) and run `grit merge --continue`. - **`true`** — The file is moved to `b/` and the merge is clean. - **`false`** — The file stays in `a/`. Any other value is an error. With `conflict` or `true`, two cases still stop the merge without moving anything, and leave nothing unmerged: a directory whose files went to several directories with no clear winner (`directory_rename_split`), and a new file whose destination already exists on the branch that added it, or would be shared with another new file (`directory_rename_blocked`). When only the base or the renaming branch has a file at the destination, the moved file is merged with it there, as Git does; that can stop with an ordinary conflict at the new path, such as `deleted_by_us` when the renaming branch deleted that file. Review the placement, then run `grit merge --continue`. [`grit pick`](https://grit-scm.com/docs/pick/index.md), [`grit revert`](https://grit-scm.com/docs/revert/index.md), [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) and [`grit pull`](https://grit-scm.com/docs/pull/index.md) follow the same setting. ```console $ grit merge theirs CONFLICT (directory_rename_moved): a/new was added to a directory the other side renamed, so it now sits at b/new; stage it there or move it back Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`. $ grit add b/new $ grit merge --continue Merged theirs into the current branch (06e1c12) ``` ## Options | Option | Description | | --- | --- | | `` | The branch, tag or commit to merge into the current one. | | `--check` | Predict whether the merge would succeed without changing refs, the index, or the working tree. Exit **0** when it would fast-forward, already be up to date, or merge cleanly; exit **1** when it would conflict. Uses the same `-X ours\|theirs` as the merge it predicts. Other failures use the usual error exit. | | `--dry-run` | Report the planned merge outcome (up to date, fast-forward, merge commit with parents, or conflicts) without changing refs, the index, or the working tree. Exit **0** unless the merge would be refused (for example `--ff-only` when a fast-forward is not possible, exit **128**). Conflicts are reported in the JSON but do not fail the command. Mutually exclusive with `--check`. | | `--continue` | Finish an in-progress merge after conflicts are resolved (or after `--no-commit`). Auto-stages resolved paths when `commit.autoStage` is true (default). Conflicts with ``, `--check`, and `--abort`. | | `-m`, `--message` | Commit message for `--continue` only (overrides `MERGE_MSG`). | | `--abort` | Cancel an in-progress merge and restore the state recorded in `ORIG_HEAD`. | | `--ff-only` | Refuse when a fast-forward is not possible (exit code 128). Mutually exclusive with `--no-ff`. | | `--no-ff` | Create a merge commit even when a fast-forward is possible. Mutually exclusive with `--ff-only`. | | `--squash` | Squash merged commits into the index; write `SQUASH_MSG` (no `MERGE_HEAD`). Mutually exclusive with `--no-commit`. | | `--no-commit` | Apply the merge but do not commit yet (Git-compatible merge state). Mutually exclusive with `--squash`. | | `-m`, `--message` | Merge commit / `MERGE_MSG` message (conflicts with `--message-file`). | | `-F`, `--message-file` | Read the message from a path, or `-` for stdin (conflicts with `-m`). | | `-X ours\|theirs` | Prefer one side on overlapping edits (same as Git `-X`). | | `--conflict` | Marker style: `merge`, `diff3`, or `zdiff3`. | | `--allow-unrelated-histories` | Merge with no common ancestor (empty-tree base). | | `--no-verify` | Skip the `pre-merge-commit` and `commit-msg` hooks (`prepare-commit-msg` and `post-merge` still run). Not with `--continue`, `--abort`, `--check` or `--dry-run`. | ## Examples ```console $ grit switch old $ grit merge main Fast-forwarded old → cf18394 (main) $ grit merge origin/main Merged origin/main into the current branch (acd1d4b) $ grit merge --no-ff topic Merged topic into the current branch (1a2b3c4) $ grit merge v1.2 Merged v1.2 into the current branch (15d4bf9) $ grit merge a79778433f24ac0955d38d912c13644b0920de68 Merged a79778433f24ac0955d38d912c13644b0920de68 into the current branch (e3ca27d) $ grit merge --squash topic Squash merge applied from topic — run `grit commit` to record the squashed commit $ grit merge --no-commit topic Merge from topic applied — run `grit commit` to finish, or `grit merge --abort` to cancel ``` When both branches change the same lines: ```console $ grit merge topic CONFLICT (both_modified): README.md Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`. ``` When one branch deleted a file and the other modified it, grit leaves the modified side's content in the work tree (like Git) so you can run `grit add ` to keep it or `grit rm ` to accept the deletion: ```console $ grit merge feat CONFLICT (deleted_by_us): f deleted on the current branch and modified in feat; feat's version is in the work tree Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`. ``` When one branch deleted a file and the other renamed it, grit reports the same `deleted_by_us` conflict at the **new** path (the rename target), with unmerged stages in the index and the renamed side's content in the work tree. `grit merge --check` exits **1** for this case, as it does for modify/delete. When both branches renamed the same file to different names, grit cannot pick a name, so it stops (like Git) and keeps both names in the work tree. Each one holds the merged content. The old name stays unmerged in the index next to the two new names. To keep one name, remove the old name and the other new name with `grit rm`, then run `grit merge --continue`. `grit merge --check` exits **1** for this case. ```console $ grit merge topic CONFLICT (rename_rename): a renamed to b on the current branch and to c in topic; both names are in the work tree CONFLICT (rename_rename): b CONFLICT (rename_rename): c Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`. $ grit rm a c Removed 2 paths. $ grit merge --continue Merged topic into the current branch (b3e1fe8) ``` When the branches put two different files at the same path (each renamed a different file to it, or one renamed a file onto a path the other added), grit reports a `both_added` conflict at that path, like Git. Both versions stay in the index and the work-tree file shows them between conflict markers; a renamed file already carries the other branch's edits to it. The old names are gone, so nothing is lost until you resolve the path. ```console $ grit merge topic CONFLICT (both_added): c Automatic merge failed; fix conflicts and run `grit merge --continue`, or run `grit merge --abort`. ``` After resolving markers (staging is optional when `commit.autoStage` is true): ```console $ grit merge --continue Merged topic into the current branch (acd1d4b) ``` To cancel: ```console $ grit merge --abort Merge aborted. ``` When nothing has that name: ```console $ grit merge nonexist error: no branch, tag or commit named 'nonexist' ``` While a rebase is paused, starting another merge is refused (same wording as [`grit switch`](https://grit-scm.com/docs/switch/index.md)): ```console $ grit merge main error: cannot merge while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort` ``` When `--continue` runs while conflict markers are still in a file: ```console $ grit merge --continue error: you still have unmerged paths: notes.txt hint: resolve the conflict markers in notes.txt, then run `grit merge --continue` (or `grit merge --abort` to start over) ``` When local edits on a path the merge would update would be overwritten: ```console $ grit merge feature error: local changes would be overwritten by merge a.txt ``` When an untracked file would be overwritten: ```console $ grit merge feature error: untracked file 'notes.txt' would be overwritten — move or remove it first ``` When `--ff-only` cannot fast-forward: ```console $ grit merge --ff-only topic Cannot fast-forward topic — histories have diverged (use merge without --ff-only) ``` (Exit code 128.) ## JSON output Schema: [v2](https://grit-scm.com/docs/merge/schemas/merge/v2.json/index.md) · [v1](https://grit-scm.com/docs/merge/schemas/merge/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `result` | string | `up_to_date`, `fast_forward`, `clean` (`--check` only), `merged`, `squashed`, `stopped`, `conflicts`, `refused_not_ff`, or `aborted`. | | `check` | boolean | `true` when this outcome is from `--check` (nothing was merged). Omitted for real merges. | | `dry_run` | boolean | `true` when this outcome is from `--dry-run` (nothing was merged). Omitted for real merges. | | `branch` | string | The branch, tag or commit that was merged in, exactly as given on the command line. | | `updated_branch` | string or null | After a fast-forward, the current branch whose tip moved. Omitted when it matches `branch`. | | `oid` | string or null | Resulting commit after a real merge or fast-forward; for `--check` with `result: clean`, the predicted merge tree OID (the id `git merge-tree --write-tree` prints; `--check` does not store that tree, so it is not in the object database). Omitted for `--dry-run` when a new merge commit would be created. | | `parents` | array or null | For `--dry-run` with `result: merged`, the two parent commit ids of the merge commit that would be recorded. | | `change_id` | string or null | Stored `change-id` on `oid` when present (merge commit or fast-forward tip). | | `conflicts` | array or null | When `result` is `conflicts`, each item has `path`, a [conflict `kind`](https://grit-scm.com/docs/status/index.md#conflict-kinds) (the same names `grit status` uses, plus `rename_rename` and the `directory_rename_*` kinds), and optional `summary` text for `deleted_by_us`, `deleted_by_them`, `rename_rename` and directory rename conflicts. A `rename_rename` conflict lists all three paths (the old name and both new names); the `summary` is on the old name's item. | | `rerere` | array | When rerere is active on `conflicts` or after a successful `merged` from `--continue`, each item has `path` and `kind`: `resolved_from_previous`, `staged_from_previous`, `recorded_preimage`, or `recorded_resolution`. Omitted when empty. | | `next_steps` | array or null | Ordered follow-up commands when `result` is `conflicts` (for example `grit diff`, `grit add .`), or suggested commands when `result` is `squashed` or `stopped`. | | `alternatives` | array or null | Mutually exclusive options such as `grit merge --abort` (not part of the ordered sequence). | Example: ```json { "result": "up_to_date", "branch": "main" } ``` Dry-run prediction with `--check` (exit code 0): ```json { "result": "clean", "check": true, "branch": "topic", "oid": "4b825dc642cb6eb9a06054e089d91b5929f0d0a" } ``` Squash merge: ```json { "result": "squashed", "branch": "topic", "next_steps": [ "grit commit", "Review SQUASH_MSG or pass -m / --message-file" ] } ``` When the merge stops on conflicts (exit code 1), stdout is still a single JSON object: ```json { "result": "conflicts", "branch": "topic", "conflicts": [ { "path": "src/lib.rs", "kind": "both_modified" } ], "next_steps": ["grit diff", "grit add ."], "alternatives": ["grit merge --abort"] } ``` When `` names nothing, the command exits **1** with `{"error":"no branch, tag or commit named 'nonexist'","kind":"revision_not_found"}` on stdout (see [`revision_not_found`](https://grit-scm.com/docs/exit-codes/index.md)). When `--continue` finds unresolved conflicts, it exits **1** with `kind` `unmerged_paths`, the files in `paths` and the next step in `hint` (with `commit.autoStage=false`, files that are resolved but not staged get a `grit add` hint instead), for example `{"error":"you still have unmerged paths: notes.txt","hint":"…","kind":"unmerged_paths","paths":["notes.txt"]}`. On overwrite refusal with `--json`, stdout is a single object with `kind` `would_overwrite` and `would_overwrite.reason` (`local_changes` or `untracked`) plus a sorted `paths` array, and a `hint` — the same shape as [`grit switch`](https://grit-scm.com/docs/switch/index.md). For example `{"error":"local changes would be overwritten by merge","hint":"…","kind":"would_overwrite","would_overwrite":{"paths":["a.txt"],"reason":"local_changes"}}`. See the [error schema](https://grit-scm.com/docs/merge/schemas/error/v1.json/index.md). ## Markdown output Schema: [v2](https://grit-scm.com/docs/merge/schemas/merge/v2.json/index.md) · [v1](https://grit-scm.com/docs/merge/schemas/merge/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Merge` heading and a result summary. Fast-forward: ```text - Fast-forwarded **`main`** → `9244cbd` ``` When the merge stops on conflicts (exit code 1), stdout still carries structured Markdown with conflict paths and next steps: ```text - Merge **`side`** stopped with conflicts - `f.txt` → fix conflicts, then `grit merge --continue`, or `grit merge --abort` ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Merge completed, `--check` predicts success, or `--dry-run` preview. | | `1` | Conflicts (`result: conflicts`), `` names nothing (`kind: revision_not_found`), a hook refused the merge commit (`kind: hook_failed`), or other failure ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | | `128` | `--ff-only` when not fast-forward ([`refused_not_ff`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit pull](https://grit-scm.com/docs/pull/index.md), [grit pick](https://grit-scm.com/docs/pick/index.md), [grit branch](https://grit-scm.com/docs/branch/index.md) # https://grit-scm.com/docs/reset/index.md # grit reset > Move the branch tip and optionally reset the index or worktree. ## Synopsis ```text grit reset [] grit reset --soft [] grit reset --mixed [] grit reset --hard [] grit reset --keep [] grit reset --dry-run [] ``` ## Description Moves the current branch (or detached `HEAD`) to ``, which defaults to `HEAD`. Use this to uncommit while keeping changes (`--soft`), drop commits from the tip but keep your files in the worktree (`--mixed`, the default), discard local changes entirely (`--hard`), or move the tip while merging index and worktree updates toward the target but keeping unrelated local edits (`--keep`). `--soft` updates the branch ref only: staged and unstaged files stay as they are. That is the usual way to “uncommit” the last commit while keeping everything staged. `--mixed` moves the tip and resets the index to match ``; the worktree is not touched. `--hard` moves the tip, resets the index, and updates tracked files in the worktree to match ``. Untracked files are left alone. Paths that were unmerged when the reset started and are absent from `` are removed from the worktree (including files another side introduced during a conflict). Intent-to-add paths stay on disk as untracked files, as in Git. In a blobless clone, `--hard` batches missing blobs needed to materialize or repair tracked paths into one promisor fetch. This includes `reset --hard HEAD` after `clone --blobs none --no-checkout`, and unchanged paths missing from the worktree when resetting to another commit. Repeated blob ids are requested once; sparse-excluded paths and submodule gitlinks do not download blob content. The usual partial-clone lazy-fetch opt-outs still apply. In a sparse checkout (`git sparse-checkout`), `--hard` and `--mixed` keep paths outside the sparse patterns out of the worktree: their index entries keep the skip-worktree bit, the same as `git reset`. User skip-worktree entries (for example `git update-index --skip-worktree`) are preserved on `--mixed` and `--hard` as well; hard reset refuses when the target tree would change such a path and your worktree edit differs from the index. Hard reset handles tracked directories replaced by files or symlinks, including directories with materialized files outside the sparse patterns. Files reached through a symlinked parent are left untouched. `--keep` moves the tip and updates paths that differ between the current commit and ``, but refuses when a path that would change also has local staged or unstaged edits. Unrelated local changes (files that do not differ between the commits) are preserved. `--dry-run` reports what would happen — including paths that `--hard` would discard or `--keep` would refuse on — without moving refs, the index, or the worktree. A successful reset (any mode except `--dry-run`) ends an in-progress merge, cherry-pick, or revert the same way Git's `reset` does: operation sentinel files such as `MERGE_HEAD` and `CHERRY_PICK_HEAD` are removed. A reset that moves the tip checks that the branch (or detached `HEAD`) still names the commit the reset started from, so a concurrent update is reported instead of overwritten. The move is appended to the branch's and `HEAD`'s reflogs where `core.logAllRefUpdates` asks for one or the reflog already exists, as Git does. Every successful reset, in any mode and also to the commit `HEAD` is already on, records the commit `HEAD` was on before it in `ORIG_HEAD` (as `git reset` does, with no reflog), replacing any earlier value. `grit reset ORIG_HEAD` with the same mode undoes the reset, and `grit reset --hard ORIG_HEAD` is the usual way to undo a merge, rebase or pull, which record `ORIG_HEAD` too. `--dry-run` and a refused reset leave `ORIG_HEAD` alone. When resetting backward, grit lists commits that would leave the branch (not reachable from `` or any other ref, including branches, tags, remotes, stash, and other worktrees). After a successful reset, human output reports how many commits are no longer on the branch, the previous tip (abbreviated), and how to recover with the same mode you used — for example `grit reset --hard ` after a hard reset, or `grit reset ` after the default mixed reset (also recorded in `ORIG_HEAD`, and in the reflog when reflogs are enabled). With `--dry-run`, the same count uses future tense (“would leave …”) because nothing has moved yet. The check usually stays near the commits being left behind, so undoing the last commit stays fast on deep repositories; annotated tags are peeled from `packed-refs` when it records their targets, and without a commit-graph the tip commits of hundreds of refs are read in parallel, headers only. Refs recorded in `packed-refs` (on a clone, usually every tag) are not read at all when every commit being left behind is dated more than a day after the file was last written: such a ref named a commit that already existed then, so it cannot reach them. Otherwise, and in repositories with grafts, replace refs or a shallow boundary, those refs are read as above. With a commit-graph the count is exact. Without one, the walk ends by commit date like Git's `git rev-list --not `, so under heavy clock skew (a ref that reaches a commit through history dated more than a day before it, or a commit dated more than a day ahead of when it was made) the count can be wrong. `` is any revision Grit understands: branch name, `HEAD~1`, full or abbreviated commit id, and so on. ## Options | Option | Description | | --- | --- | | `` | Commit to reset to. Defaults to `HEAD`. | | `--soft` | Move the branch tip only. | | `--mixed` | Move the tip and reset the index (default when no mode flag is given). | | `--hard` | Move the tip, reset the index, and update the worktree. | | `--keep` | Move the tip and update differing paths; refuse when local edits block a tree change. | | `--dry-run` | Preview the reset without changing refs, index, or worktree. | | `-n`, `--limit` | Cap the `orphaned_commits` list in `--json` output (default 20). | ## Examples Uncommit the last commit but keep changes staged: ```console $ grit reset --soft HEAD~1 Reset refs/heads/main to a1b2c3d (soft) Warning: 1 commit is no longer on refs/heads/main (was d4e5f6a). Recover it with `grit reset --soft d4e5f6a` (recorded in ORIG_HEAD and, when reflogs are on, the reflog). ``` Hard reset two commits back, then follow the recovery hint to restore the branch and worktree: ```console $ grit reset --hard HEAD~2 Reset refs/heads/main to a1b2c3d (hard) Warning: 2 commits are no longer on refs/heads/main (was f6a7b8c). Recover them with `grit reset --hard f6a7b8c` (recorded in ORIG_HEAD and, when reflogs are on, the reflog). $ grit reset --hard f6a7b8c Reset refs/heads/main to f6a7b8c (hard) ``` Move the tip back one commit and unstage, keeping file contents: ```console $ grit reset HEAD~1 Reset main to a1b2c3d (mixed) ``` Preview a hard reset without discarding work: ```console $ grit reset --dry-run --hard HEAD~1 Would reset main to a1b2c3d (hard) Would discard local changes in: tracked.txt ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/reset/schemas/reset/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `mode` | string | `soft`, `mixed`, `hard`, or `keep`. | | `target` | string | Full hex oid of the commit `HEAD` will point at (or would, when `dry_run` is true). | | `previous` | string | Full hex oid before the reset. | | `ref` | string | Branch ref updated, or `HEAD` when detached. | | `dry_run` | boolean | True when nothing was written. | | `would_overwrite` | string[] | With `--dry-run --hard`: tracked paths whose local edits would be discarded. | | `would_block` | string[] | With `--dry-run --keep`: paths that would make the reset refuse. | | `orphaned_commits` | object[] | Sample of commits that would leave the branch (`oid`, `change_id`, `subject`). | | `orphaned_total` | number | Advisory unreachable count (may exceed `orphaned_commits.length`). Without a commit-graph, severe clock skew can make this inaccurate; it never controls the reset. | | `orphaned_truncated` | boolean | True when `-n`/`--limit` capped the orphan list. | Example: ```json { "mode": "soft", "target": "062ca6e74f5603f4d09063c0f46cd07d8c96e019", "previous": "83352a61f6715ec3f0a297c6d6150725154fb833", "ref": "refs/heads/main", "dry_run": false, "would_overwrite": [], "would_block": [], "orphaned_commits": [ { "oid": "83352a61f6715ec3f0a297c6d6150725154fb833", "change_id": "xzyqzyyzswyupvtlsovyzultryuqzlvk", "subject": "second" } ], "orphaned_total": 1, "orphaned_truncated": false } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/reset/schemas/reset/v1.json/index.md) Pass `--markdown` for agent-friendly output: a short heading plus bullet list of ref, mode, target, previous, dry-run, and orphan summary. ```text ## Reset - **ref:** `refs/heads/main` - **mode:** `soft` - **target:** `062ca6e74f5603f4d09063c0f46cd07d8c96e019` - **previous:** `83352a61f6715ec3f0a297c6d6150725154fb833` - **dry_run:** `false` - **orphaned_total:** `1` (truncated: `false`) - **recovery:** `grit reset --soft 83352a61f6715ec3f0a297c6d6150725154fb833` restores it (also recorded in ORIG_HEAD; reflog when enabled) ``` Resetting to default `HEAD` on an unborn branch reports `branch_no_commits` (same message as [`grit log`](https://grit-scm.com/docs/reset/log.md/index.md)) instead of an opaque revision error. ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. When another process holds `.git/index.lock`, `--hard`, `--keep` and the default mixed reset fail with exit `1` (`kind` `lock_held` under `--json`) before touching anything: `HEAD`, the branch, the index and the worktree are unchanged. Retry once the other process finishes. ## See also [grit switch](https://grit-scm.com/docs/switch/index.md), [grit restore](https://grit-scm.com/docs/restore/index.md), [grit commit](https://grit-scm.com/docs/commit/index.md) Sparse indexes keep unchanged excluded directory trees compact during checkout. Only affected directories or directories present outside the sparse cone need individual index rows. Performance and scaling methodology are documented in [Benchmarks](https://grit-scm.com/docs/benchmarks.md/index.md). Hard reset reapplies the sparse definition: tracked files that appeared outside the cone are removed again. `sparse.expectFilesOutsideOfPatterns=true` preserves outside files whose index entries still have skip-worktree set. Keep-reset uses the full worktree guard checks for unmerged indexes. # https://grit-scm.com/docs/pick/index.md # grit pick > Cherry-pick one or more commits onto the current branch. ## Synopsis ```text grit pick [ | ]... grit pick --check [ | ]... grit pick --continue | --abort | --skip ``` ## Description Replays commits from another branch (or arbitrary revisions) onto the current branch, like `git cherry-pick`. Each new commit keeps the original **author** and message (unless you pass `--message` / `--message-file` for a single commit), gets a fresh **`change-id`**, and records a normal reflog entry. Textual merges use the histogram diff algorithm, matching Git merge-ort (same as [`grit merge`](https://grit-scm.com/docs/merge/index.md)). Positional arguments are applied **oldest first**. Each argument is either: - a single commit (`feature`, `abc1234`, `HEAD~2`), or - a two-dot range `A..B` (commits reachable from `B` but not from `A`, same as `git log A..B`). `grit pick` stops — leaving Git-compatible sequencer state — when: - a step has **merge conflicts** (conflict markers in the worktree, `CHERRY_PICK_HEAD`, `MERGE_MSG`, `.git/sequencer/`) - a step would be **empty** and `--empty stop` (default) - the worktree is **dirty**, or the branch has **no commits** (detached `HEAD` is allowed, like `git cherry-pick`) - a commit is a **merge** without `--mainline` (not yet exposed on the CLI) Resolve conflicts, then either run [`grit commit`](https://grit-scm.com/docs/commit/index.md) (auto-stages the worktree and finishes the step, keeping the picked author) or stage with [`grit add`](https://grit-scm.com/docs/add/index.md) and run `grit pick --continue`. Use `grit pick --skip` to drop the current step, or `grit pick --abort` to cancel. If the branch tip moved because you already committed the resolution, `--abort` clears replay state without moving the branch (Git warns and exits 0 in the same situation). Pick either completes a step, stops for conflicts or an empty commit, or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out stops the pick with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the pick started (no `CHERRY_PICK_HEAD`), no `.git/index.lock` is left behind, and the same pick can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. ## Options | Option | Description | | --- | --- | | ``… | Commits or ranges to replay (oldest first). | | `--continue` | Finish the paused pick after conflicts are resolved and staged. | | `--abort` | Cancel the in-progress pick and restore the branch tip and worktree (conflict-only files from the other side are removed). Uses `sequencer/head` when grit wrote a sequencer directory; otherwise resets the index and worktree to the current tip (including after a conflicting `git cherry-pick`). A stale `ORIG_HEAD` from an earlier operation is ignored. | | `--skip` | Skip the current todo step and continue with the rest; the worktree is reset to the saved tip, including removing conflict-only paths. | | `-x`, `--record-origin` | Append `(cherry picked from commit …)` to each new message. | | `--no-commit` | Apply the patch to the index and worktree without committing. | | `--empty` | When a step would not change the tree: `stop` (default), `keep` (empty commit), or `drop`. | | `-m`, `--message` | Replace the message (only with exactly one commit). | | `-F`, `--message-file` | Read the message from a file, or `-` for stdin (only with exactly one commit). | | `--mainline` | Parent number when replaying a merge commit (library support; CLI wiring pending). | | `--check` | Predict whether the pick would succeed without changing refs, the index, or the worktree. Exit **0** when every step would apply cleanly; exit **1** when a step would conflict or stop as empty (with `--empty stop`), including rename/delete conflicts at the new path (same as [`grit merge`](https://grit-scm.com/docs/pick/merge.md/index.md)). Conflicts with `--continue`, `--abort`, `--skip`, and `--dry-run`. | | `--dry-run` | Print the commits that would be replayed without changing refs or the worktree. Conflicts with `--check`. | | `-X ours\|theirs` | Auto-resolve replay conflicts: keep the current branch side (`ours`) or the picked change (`theirs`). | | `--conflict merge\|diff3\|zdiff3` | Conflict marker style when a step stops with conflicts (default from `merge.conflictStyle`). | ## Examples Pick the latest commit on a topic branch: ```console $ grit pick feature Picked cf18394 → 4be20a1 Say hi ``` Pick a range of commits: ```console $ grit pick main..feature Picked a1b2c3d → d4e5f6a First change Picked b2c3d4e → e5f6a7b Second change ``` While a rebase is paused, `grit pick` refuses (it does not treat conflict markers as a dirty worktree): ```console $ grit pick main error: cannot pick while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort` ``` Conflict, then continue: ```console $ grit pick topic~1..topic CONFLICT (both_modified): shared.txt → grit restore --ours shared.txt (or edit markers) → grit add shared.txt → grit pick --continue Picked … → … Resolved topic change ``` ## JSON output Schema: [v2](https://grit-scm.com/docs/pick/schemas/pick/v2.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `result` | string | `picked`, `clean`, `conflicts`, `empty`, `aborted`, or `skipped`. | | `oid` | string or null | Predicted final tree oid when `result` is `clean` (`--check` only). | | `check` | boolean | True when `--check` was used (nothing was picked). | | `commits` | array | Each picked or attempted step: `source`, `oid`, `change_id`, `subject`. | | `dropped` | array | Source commit oids skipped as empty (`--empty drop`). | | `conflicts` | array or null | Conflicted paths when `result` is `conflicts`, each `{path, kind}` with a [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds). | | `rerere` | array | Rerere events when `rerere.enabled` is active and the pick stops on conflicts (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. | | `next_steps` | array or null | Suggested commands when stopped (`conflicts` or `empty`). | | `alternatives` | array or null | `grit pick --abort` / `--skip` when a sequence is paused. | | `dry_run` | boolean or null | `true` when `--dry-run` was set (no refs or objects were updated). | Example (success): ```json { "result": "picked", "commits": [ { "source": "6e513d5cd6ab8d618238e22d7ca55d942b55964a", "oid": "a1b2c3d4e5f6789012345678901234567890abcd", "change_id": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", "subject": "Say hi" } ], "dropped": [] } ``` On conflicts, exit code is **1** with `result: "conflicts"` and the same conflict shape as [`grit merge`](https://grit-scm.com/docs/merge/index.md). ## Markdown output Schema: [v2](https://grit-scm.com/docs/pick/schemas/pick/v2.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Pick` heading, one bullet per replayed commit, and conflict next steps when stopped. ```text ## Pick - `d5d832b` → `d5d832b` — pick me ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Pick completed or `--check` predicts a clean replay. | | `1` | Conflicts, empty commit, or other failure. | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit merge](https://grit-scm.com/docs/merge/index.md), [grit revert](https://grit-scm.com/docs/revert/index.md), [grit log](https://grit-scm.com/docs/log/index.md) # https://grit-scm.com/docs/revert/index.md # grit revert > Undo commits with new inverse commits. ## Synopsis ```text grit revert [...] grit revert --check [...] grit revert --continue | --abort | --skip ``` ## Description Creates new commits on the current branch that undo the changes introduced by each listed commit. Reverts run **newest first** within a revision range, matching `git revert`. Each revert commit uses the standard `Revert "…"` subject and a `This reverts commit .` body (unless you pass `-m` / `--message-file` for a single commit), and gets a new `change-id`. `` can be a full or short commit id, a branch name, a range such as `v1.0..main`, or several commits in one invocation. When a step would conflict, grit stops with conflict markers in the worktree and unmerged index entries — the same model as [`grit pick`](https://grit-scm.com/docs/pick/index.md) and [`grit merge`](https://grit-scm.com/docs/merge/index.md). Resolve conflicts, then either run [`grit commit`](https://grit-scm.com/docs/commit/index.md) (auto-stages and finishes the step) or stage with [`grit add`](https://grit-scm.com/docs/add/index.md) and run `grit revert --continue`. Use `--abort` to restore the branch to its pre-revert state when the tip has not moved; if you already committed the resolution, `--abort` only clears revert state. Use `--skip` to drop the current step and continue with any remaining commits. Merge commits require `--mainline ` (1-based parent number, long option only) so grit knows which parent line to replay. Revert either completes a step, stops for conflicts or an empty commit, or changes nothing. Pressing Ctrl+C, or sending `SIGTERM` or `SIGHUP` on Unix, while files are being checked out stops the revert with `error: operation cancelled`; `HEAD`, the index and the work tree are left as they were before the revert started (no `REVERT_HEAD`), no `.git/index.lock` is left behind, and the same revert can simply be run again. This works the same in a Windows console, where Ctrl+Break counts as Ctrl+C. A second interrupt terminates grit at once, without that cleanup; only `SIGKILL` skips rollback. ## Options | Option | Description | | --- | --- | | `…` | Commits or revision ranges to revert (required unless continuing). | | `--mainline ` | Parent number when reverting a merge commit. | | `--continue` | Finish a revert stopped on conflicts or an empty commit. | | `--abort` | Cancel the in-progress revert and restore the branch tip and worktree (conflict-only files from the other side are removed). Uses `sequencer/head` when grit wrote a sequencer directory; otherwise resets the index and worktree to the current tip (including after a conflicting `git revert`). A stale `ORIG_HEAD` from an earlier operation is ignored. | | `--skip` | Skip the current commit and continue with the rest of the sequence; the worktree is reset to the saved tip, including removing conflict-only paths. | | `--no-commit` | Apply the revert to the index only; do not create a commit yet. | | `--empty stop\|keep\|drop` | When a step would not change the tree: stop (default), record an empty commit, or skip the step. | | `-m`, `--message` | Replace the revert message (**single commit only**). | | `-F`, `--message-file` | Read the revert message from a file, or `-` for stdin (**single commit only**). | | `--check` | Predict whether the revert would succeed without changing refs, the index, or the worktree. Exit **0** when every step would apply cleanly; exit **1** when a step would conflict or stop as empty (with `--empty stop`). Conflicts with `--continue`, `--abort`, `--skip`, and `--dry-run`. | | `--dry-run` | List commits that would be reverted without changing refs or the worktree. Conflicts with `--check`. | | `-X ours\|theirs` | Auto-resolve replay conflicts: keep the current branch side (`ours`) or the reverted change (`theirs`). | | `--conflict merge\|diff3\|zdiff3` | Conflict marker style when a step stops with conflicts (default from `merge.conflictStyle`). | ## Examples Revert the previous commit: ```console $ grit revert HEAD~1 Reverted a1b2c3d → e4f5g6h Revert "Add feature" ``` Revert a merge (first parent as mainline): ```console $ grit merge feature $ grit revert --mainline 1 HEAD Reverted 9a1c2e0 → b2c3d4e Revert "Merge branch 'feature'" ``` Revert a range (newest commit in the range first): ```console $ grit revert release~5..release Reverted f1e2d3c → … Revert "Prepare release" Reverted a1b2c3d → … Revert "Bump version" ``` While a rebase is paused: ```console $ grit revert main error: cannot revert while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort` ``` When the revert conflicts: ```console $ grit revert feature CONFLICT (both_modified): f.txt Revert stopped on conflicts; fix them and run `grit revert --continue`, or `grit revert --abort` / `grit revert --skip`. ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/revert/schemas/revert/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `result` | string | `completed`, `clean`, `conflicts`, `aborted`, or `empty`. | | `source` | string or null | Source commit for the last revert created when `result` is `completed`. | | `oid` | string or null | New revert commit when `result` is `completed`, or the predicted final tree oid when `result` is `clean`. | | `subject` | string or null | Subject of the last revert commit when `result` is `completed`. | | `change_id` | string or null | Stored `change-id` on the last revert commit, or `null`. | | `commits` | array | Each revert commit created in this invocation (newest first). | | `dropped` | array | Source commits skipped as empty per `--empty drop`. | | `conflicts` | array or null | Conflicted paths when `result` is `conflicts`, each `{path, kind}` with a [conflict kind](https://grit-scm.com/docs/status/index.md#conflict-kinds). | | `rerere` | array | Rerere events when `rerere.enabled` is active and the revert stops on conflicts (`path`, `kind` as for [`grit merge`](https://grit-scm.com/docs/merge/index.md#json-output)). Omitted when empty. | | `next_steps` | array or null | Suggested follow-up commands when paused. | | `alternatives` | array or null | `--abort` / `--skip` when paused. | | `dry_run` | boolean or null | True when `--dry-run` was used. | | `check` | boolean | True when `--check` was used (nothing was reverted). | Example: ```json { "result": "completed", "source": "6e513d5cd6ab8d618238e22d7ca55d942b55964a", "oid": "a8f2c1d0e9b876543210abcdef0123456789abcd", "subject": "Revert \"Add feature\"", "commits": [ { "source": "6e513d5cd6ab8d618238e22d7ca55d942b55964a", "oid": "a8f2c1d0e9b876543210abcdef0123456789abcd", "subject": "Revert \"Add feature\"", "change_id": "zzzzzzzz" } ], "dropped": [] } ``` When `result` is `conflicts`, exit code is **1** and the object includes `conflicts`, `next_steps`, and `alternatives` (same shape as [`grit merge`](https://grit-scm.com/docs/merge/index.md) conflicts). ## Markdown output Schema: [v1](https://grit-scm.com/docs/revert/schemas/revert/v1.json/index.md) Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for a `Revert` heading and one bullet per reverted commit: ```text - `9244cbd` → `bbbca73` — Revert "third" ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Revert completed or `--check` predicts success. | | `1` | Conflicts, empty revert, or other failure. | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit pick](https://grit-scm.com/docs/pick/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md) # https://grit-scm.com/docs/tag/index.md # grit tag > List tags, or create or delete one (lightweight or annotated). ## Synopsis ```text grit tag grit tag -l [...] grit tag --sort version|date|name [--reverse] [--contains [REV]] [--points-at REV] [-n N] grit tag grit tag [] grit tag -m grit tag -F grit tag -s -m grit tag -s --tree-sha256 -m grit tag -f grit tag --dry-run grit tag -d grit tag --verify ... grit tag -v ... --no-signature ``` ## Description With no arguments, lists tag names sorted by **version** (`version:refname`). Use `-l` / `--list` with optional glob patterns (repeatable), `--sort version|date|name`, `--reverse`, `--contains [REV]` (defaults to `HEAD`), `--points-at ` (repeatable), and `-n` / `--limit` to cap the list. Plain human output reads names only and avoids loading annotated tag objects; `--json` and `--markdown` retain full annotation metadata. With a name and no `-m`/`-F`, creates a **lightweight** tag pointing at `HEAD` or the optional `` revision. With `-m` or `-F`, creates an **annotated** tag object with that message (comment lines starting with `#` are stripped, matching Git's default cleanup). Use `-s` / `--sign` (or `tag.gpgSign=true`) to cryptographically sign an annotated tag; signed tags verify with `git verify-tag` and system `git tag -v`. Annotated tag messages are stored as raw bytes (Git has no `encoding` header on tags). When listing with `--json` or `--markdown`, a message that is not valid UTF-8 is shown as a Unicode string with U+FFFD replacement characters, not as a corrupt object. Use `-f` / `--force` to replace an existing tag (lightweight or annotated). The previous ref target is reported in `--json` as `replaced`. Use `--dry-run` on create or delete to preview the outcome without changing refs. Use `--tree-sha256` on a signed tag to attach a [tree-sha256](https://grit-scm.com/docs/library/tree-sha256.md/index.md) content digest of the tagged commit's tree (implies signing). Repeat `--exclude-submodule ` to record excluded submodule paths in `tree-sha256-excluded` headers. Use `--verify` / `-v` on one or more **annotated** tag names to check the tag object's signature (OpenPGP or SSH, when present) and, when the tag carries a `tree-sha256` header, recompute that digest against the tagged commit's tree. Lightweight tags cannot be verified. Use `--no-signature` to skip signature checking while still validating `tree-sha256` when present. **Exit codes:** `grit tag --verify` exits **0** when every named tag passes and **1** when any tag fails verification or is not an annotated tag. Other `grit tag` modes use the default exit code (**0** on success). Tag names must be valid as `refs/tags/` under Git's ref-name rules (same checks as `git check-ref-format refs/tags/`). Invalid names are rejected before writing under `.git/refs`. Tags are local until you publish them with [`grit push --tags`](https://grit-scm.com/docs/push/index.md). Delete a remote tag with [`grit push --delete`](https://grit-scm.com/docs/push/index.md). ## Options | Option | Description | | --- | --- | | `` | The tag to create or delete. Omit to list tags. | | `` | Revision to tag (default `HEAD`). | | `-l`, `--list` | List tags matching `PATTERN` (repeatable). Omit `PATTERN` to list all. | | `--sort` | `version` (default), `date`, or `name`. | | `--reverse` | Reverse the sort order. | | `--contains` | Only tags whose peeled commit contains `REV` (default `HEAD`). | | `--points-at` | Only tags pointing at `REV` (repeatable). | | `-n`, `--limit` | Maximum number of tags to print. | | `-d`, `--delete` | Delete the tag locally. | | `-a`, `--annotate` | Git habit for an annotated tag; ignored when `-m` or `-F` is set (those already create an annotated tag). Without a message, grit errors instead of opening an editor. | | `-m`, `--message` | Annotated tag message (repeatable; paragraphs are separated by a blank line, like Git). | | `-F`, `--message-file` | Read the annotated tag message from a file (`-` reads stdin). | | `--file` | Hidden alias for `--message-file` (deprecated; emits a one-time warning). | | `-f`, `--force` | Replace an existing tag with the same name. | | `--dry-run` | Preview create or delete without updating refs. | | `-s`, `--sign` | Sign the tag object (implies annotated; honors `tag.gpgSign` when omitted). | | `--no-sign` | Do not sign, even when `tag.gpgSign` is true. | | `--signing-key` | Signing key id or path for this tag (overrides `user.signingkey`). | | `--tree-sha256` | Attach a tree-sha256 digest (implies `--sign`). | | `--exclude-submodule` | Submodule path glob excluded from the digest (repeatable). | | `-v`, `--verify` | Verify annotated tags (one or more names). | | `--no-signature` | With `--verify`, skip signature checks (digest still checked when present). | | `--object` | Hidden alias for `` (one release). | ## Examples ```console $ grit tag v0.1 -m 'First release' Created tag v0.1 $ grit tag v0.2 -s -m 'Signed release' Created tag v0.2 $ grit tag v0.1 main -f -m 'Repointed release' Created tag v0.1 $ grit tag v0.1 $ grit push --tags pushed --tags → origin refs/tags/v0.1 $ grit push --delete v0.1 deleted v0.1 from origin $ grit tag -d v0.1 Deleted tag v0.1 $ grit tag --verify v0.2 --no-signature tag v0.2 (92501f1…): ok target: abc1234… signature: not_checked (—) elapsed: 12 ms ``` ## JSON output Schema: [v2](https://grit-scm.com/docs/tag/schemas/tag/v2.json/index.md), [v1](https://grit-scm.com/docs/tag/schemas/tag/v1.json/index.md) Pass `--json` for stable, scripting-friendly output. The object's `action` field says what happened: | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | `list`, `create`, `delete`, or `verify`. | | `tags` | array | For `list`, each tag with `name`, `oid`, `kind`, `target_kind`, optional `peeled`, and optional `annotation` (`subject`, `message`, `tagger` with `name`, `email`, `date` in RFC 3339). | | `truncated` | boolean | For `list`: `true` when more tags matched than returned (`-n` / `--limit`). | | `name` | string | For `create` or `delete`, the tag name. | | `oid` | string | For `create`, full id the tag ref points at (tag object or commit). | | `kind` | string | For `create` or list entries: `lightweight` or `annotated`. | | `signed` | boolean | For `create`, whether the tag object was signed. | | `peeled` | string | Commit oid when the tag peels to a commit. | | `replaced` | string | For `create` with `--force`, oid the tag ref pointed at before replacement. | | `dry_run` | boolean | For `create` or `delete`, whether refs were left unchanged. | | `tree_sha256` | string | For `create` with `--tree-sha256`, hex digest recorded on the tag. | | `tree_sha256_excluded` | array | Submodule paths excluded from the digest (when `--exclude-submodule` is used). | | `tree_sha256_files` | integer | Blob count hashed for the tree-sha256 claim. | | `tree_sha256_submodules` | integer | Submodule trees included in the digest walk. | | `tree_sha256_hash_ms` | number | Wall time spent computing the tree-sha256 digest (milliseconds). | | `ok` | boolean | For `verify`, whether every tag passed. | For `action: verify`, each element of `tags` includes `name`, `oid`, `target`, `ok`, `signature` (with `verdict`, optional `signer`, `key`, `trust`), optional `tree_sha256` (`claimed`, `computed`, `match_digest`, `files`, `submodules`, `excluded`, `bogus_excluded`, `cycles`), `not_verifiable_submodules` (`path`, `reason`), and `elapsed.ms`. Listing tags: ```json { "action": "list", "tags": [ { "name": "v0.1", "oid": "92501f188ae0815af09a0cef6e121eddda4113cf", "kind": "annotated", "target_kind": "commit", "peeled": "abc1234567890abcdef1234567890abcdef123456", "annotation": { "subject": "First release", "message": "First release\n", "tagger": { "name": "Alex", "email": "alex@example.com", "date": "2023-11-14T22:13:20Z" } } } ] } ``` Creating an annotated tag: ```json { "action": "create", "name": "v0.1", "oid": "92501f188ae0815af09a0cef6e121eddda4113cf", "kind": "annotated", "signed": false, "dry_run": false, "peeled": "abc1234567890abcdef1234567890abcdef123456" } ``` Verifying tags: ```json { "action": "verify", "ok": true, "tags": [ { "name": "v0.2", "oid": "92501f188ae0815af09a0cef6e121eddda4113cf", "target": "abc1234567890abcdef1234567890abcdef123456", "ok": true, "signature": { "verdict": "good", "signer": "Release Bot ", "key": "ABCD1234", "trust": "fully" }, "tree_sha256": { "claimed": "a119881755f081b9f694f1f05eb31fa4771a108bc854d61fdd4d12482e2a14e2", "computed": "a119881755f081b9f694f1f05eb31fa4771a108bc854d61fdd4d12482e2a14e2", "match_digest": true, "files": 3, "submodules": 0, "excluded": [], "bogus_excluded": [], "cycles": [] }, "not_verifiable_submodules": [], "elapsed": { "ms": 12 } } ] } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v2](https://grit-scm.com/docs/tag/schemas/tag/v2.json/index.md), [v1](https://grit-scm.com/docs/tag/schemas/tag/v1.json/index.md) Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract. ```text No tags yet. ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success, or `--verify` when every tag passes. | | `1` | `--verify` when any tag fails or is not annotated. | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit push](https://grit-scm.com/docs/push/index.md) # https://grit-scm.com/docs/worktree/index.md # grit worktree > List, add, and remove linked worktrees for the same repository. ## Synopsis ```text grit worktree list grit worktree add [] grit worktree add -b [] grit worktree add -B [] grit worktree add --detach [] grit worktree add --lock [--reason ] [] grit worktree add --no-checkout [] grit worktree add --track [] grit worktree add -f [] grit worktree remove grit worktree remove -f grit worktree lock [--reason ] grit worktree unlock grit worktree move [-f] [--dry-run] grit worktree repair […] [--dry-run] grit worktree prune ``` ## Description Git linked worktrees share one object database but have separate working trees and `HEAD`. `grit worktree list` shows the main worktree first, then linked worktrees (same order as `git worktree list`). The current worktree is prefixed with `*` in human output. Detached checkouts are labeled `(detached HEAD)` in human output (same idea as `git worktree list`). When the repository was opened from a bare clone, the main row is shown as `(bare)` without `*` or a branch name — bare `HEAD` is not a checkout and does not block `grit worktree add` for that branch. Linked rows whose working tree directory is gone are marked `prunable`, matching `git worktree list --porcelain` reason text in JSON. Paths in human, `--json`, and `--markdown` output use normal absolute paths (no Windows `\\?\` verbatim prefix) with forward slashes, so scripts can pass them to `cd` or `grit worktree remove` unchanged. `grit worktree add` creates the admin directory under `.git/worktrees/`, writes the `gitdir` / `commondir` files, checks out the tree (unless `--no-checkout`), and registers the new worktree. After checkout it runs the `post-checkout` hook from the new worktree with a null old object id, the start commit, and flag `1`, as Git does (skipped for `--no-checkout` and orphan branches). With only a path, grit creates a new branch named after the directory basename at `HEAD`. With a `` that names an existing branch, that branch is checked out (it must not already be checked out elsewhere). Use `-b` to create a new branch at `` (default `HEAD`). Use `-B` to create or reset a branch to `` (writes a reflog entry when resetting). Use `--detach` for a detached HEAD at the resolved commit. Use `--lock` (optional `--reason`) to write the `locked` file before checkout finishes. Use `--no-checkout` to register `HEAD` without populating the working tree. Use `--track` when the start point is a remote-tracking branch to set `branch.*.remote` / `merge` like `git worktree add --track`. If `` is already registered but its directory was deleted manually, grit refuses the add (same as Git). Use `-f` / `--force` to replace the stale registration, or `grit worktree prune` / `grit worktree remove` to clear it first. While `grit worktree add` is checking out files, Ctrl+C (or `SIGTERM` / `SIGHUP` on Unix) stops with `error: operation cancelled` and exit code **130**. Grit removes the half-created worktree registration, rolls back a newly created branch, and leaves no stale `index.lock` in the linked admin directory. A second interrupt terminates grit immediately without that cleanup. `grit worktree remove` deletes the linked worktree's admin directory and, with `-f`, the working tree even when it has local changes. `grit worktree prune` removes admin directories for linked worktrees whose working tree is missing (skips locked worktrees). Use `--dry-run` to list what would be pruned without deleting registrations. `grit worktree lock` writes a `locked` file under the worktree admin directory (same on-disk format as `git worktree lock`). Locked worktrees are skipped by `prune` and refused by `remove` unless `-f`. `grit worktree unlock` removes that lock file. `grit worktree move` relocates a linked worktree and rewrites the worktree `.git` gitfile and admin `gitdir` file atomically (same on-disk layout as `git worktree move`). The main worktree cannot be moved. Locked worktrees require `-f` / `--force` (Git requires `-f` twice; grit uses one force flag). Populated submodules block the move, matching Git. `grit worktree repair` fixes broken `.git` / `gitdir` links after a manual directory move. With no paths, grit repairs every registered linked worktree from the open repository. ## Options ### `list` No flags. ### `add` | Option | Description | | --- | --- | | `` | Directory for the new working tree (must be missing or empty). | | `` | Commit or branch to check out (default `HEAD`). | | `-b`, `--branch` | Create and check out a new branch at ``. | | `-B` | Create or reset a branch to `` (refuses when that branch is checked out elsewhere). | | `--detach` | Detached HEAD at the resolved commit. | | `--lock` | Write the `locked` file before checkout completes. | | `--reason` | Reason stored in the lock file (requires `--lock`). | | `--no-checkout` | Register the worktree without checking out files. | | `--track` | Set upstream when `` is a remote-tracking branch. | | `-f`, `--force` | Replace a stale registration when the directory is missing. | ### `remove` | Option | Description | | --- | --- | | `` | Path to the linked worktree. | | `-f`, `--force` | Remove even when locked or dirty. | ### `lock` | Option | Description | | --- | --- | | `` | Path to the linked worktree. | | `--reason` | Optional reason stored in the lock file (shown by `git worktree list`). | ### `unlock` | Option | Description | | --- | --- | | `` | Path to the linked worktree. | ### `prune` | Option | Description | | --- | --- | | `--dry-run` | Report prunable worktrees without removing registrations. | ### `move` | Option | Description | | --- | --- | | `` | Path to the linked worktree to move. | | `` | Destination (must not exist; if it is an existing directory, the worktree basename is appended). | | `-f`, `--force` | Move even when the worktree is locked. | | `--dry-run` | Preview the move without renaming or rewriting link files. | ### `repair` | Option | Description | | --- | --- | | `[…]` | Linked worktree roots to repair (default: all linked worktrees). | | `--dry-run` | List repairs without writing files. | ## Examples ```console $ grit worktree add ../hotfix -b hotfix main Created worktree at /tmp/hotfix on branch hotfix $ grit worktree list /tmp/repo /tmp/hotfix [hotfix] $ grit worktree remove ../hotfix -f Removed worktree /tmp/hotfix $ grit worktree prune Pruned worktree /tmp/old-wt ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/worktree/schemas/worktree.list/v1.json/index.md) · [worktree.add v1](https://grit-scm.com/docs/worktree/schemas/worktree.add/v1.json/index.md) · [worktree.remove v1](https://grit-scm.com/docs/worktree/schemas/worktree.remove/v1.json/index.md) · [worktree.prune v2](https://grit-scm.com/docs/worktree/schemas/worktree.prune/v2.json/index.md) · [worktree.lock v1](https://grit-scm.com/docs/worktree/schemas/worktree.lock/v1.json/index.md) · [worktree.unlock v1](https://grit-scm.com/docs/worktree/schemas/worktree.unlock/v1.json/index.md) · [worktree.move v1](https://grit-scm.com/docs/worktree/schemas/worktree.move/v1.json/index.md) · [worktree.repair v1](https://grit-scm.com/docs/worktree/schemas/worktree.repair/v1.json/index.md) Pass `--json` on any subcommand. The top-level `action` is `list`, `add`, `remove`, `prune`, `lock`, `unlock`, `move`, or `repair`. List: ```json { "action": "list", "worktrees": [ { "path": "/tmp/repo", "head": "abc1234…", "branch": "main", "detached": false, "bare": false, "locked": false, "lock_reason": null, "prunable": false, "prunable_reason": null, "is_current": true } ] } ``` | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | `list`, `add`, `remove`, `prune`, `lock`, `unlock`, `move`, or `repair`. | | `worktrees` | array | For `list`, one object per worktree (fields below). | | `path` | string | For `add` / `remove` / `lock` / `unlock`, absolute path to the working tree. | | `from` | string | For `move`, previous worktree path. | | `to` | string | For `move`, new worktree path. | | `repairs` | array | For `repair`, objects with `path` and `kind` for each link rewritten. | | `head` | string | For `add`, current commit oid checked out in the new worktree. | | `branch` | string or null | For `add`, branch checked out when not detached. | | `locked` | boolean | For `add`, whether the worktree was created locked. | | `checked_out` | boolean | For `add`, whether files were checked out (`false` with `--no-checkout`). | | `dry_run` | boolean | For `prune`, whether registrations were left intact. | | `reason` | string or null | For `lock`, optional reason stored in the lock file. | | `pruned` | array | For `prune`, objects with `path` and `reason` for each pruned (or would-be pruned) worktree. | Each object in `worktrees` (list action) includes `path`, `head`, `branch`, `detached`, `bare`, `locked`, `lock_reason` (always present, `null` when absent), `prunable`, optional `prunable_reason`, and `is_current`. Add: ```json { "action": "add", "path": "/tmp/hotfix", "branch": "hotfix", "head": "abc1234…", "locked": false, "checked_out": true } ``` Remove: ```json { "action": "remove", "path": "/tmp/hotfix" } ``` Prune: ```json { "action": "prune", "dry_run": false, "pruned": [ { "path": "/tmp/old-wt", "reason": "gitdir file points to non-existent location" } ] } ``` Lock: ```json { "action": "lock", "path": "/tmp/hotfix", "reason": "maintenance" } ``` Unlock: ```json { "action": "unlock", "path": "/tmp/hotfix" } ``` Move: ```json { "action": "move", "from": "/tmp/linked", "to": "/tmp/moved", "dry_run": false } ``` Repair: ```json { "action": "repair", "repairs": [ { "path": "/tmp/moved", "kind": "gitdir_worktree_path" } ], "dry_run": false } ``` Repair `kind` values: `git_file_admin_dir`, `gitdir_worktree_path`, `git_file_path_style`, `gitdir_path_style`. ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for structured output. Schema: [worktree.list v1](https://grit-scm.com/docs/worktree/schemas/worktree.list/v1.json/index.md) · [worktree.add v1](https://grit-scm.com/docs/worktree/schemas/worktree.add/v1.json/index.md) · [worktree.remove v1](https://grit-scm.com/docs/worktree/schemas/worktree.remove/v1.json/index.md) · [worktree.prune v2](https://grit-scm.com/docs/worktree/schemas/worktree.prune/v2.json/index.md) · [worktree.lock v1](https://grit-scm.com/docs/worktree/schemas/worktree.lock/v1.json/index.md) · [worktree.unlock v1](https://grit-scm.com/docs/worktree/schemas/worktree.unlock/v1.json/index.md) · [worktree.move v1](https://grit-scm.com/docs/worktree/schemas/worktree.move/v1.json/index.md) · [worktree.repair v1](https://grit-scm.com/docs/worktree/schemas/worktree.repair/v1.json/index.md) List shows a table of path, branch, and HEAD: ```text | Path | Branch | HEAD | | --- | --- | --- | | /tmp/repo | `main` | `abc1234` | | /tmp/hotfix | `hotfix` | `abc1234` | ``` Add and remove use short headings with the path and branch (or detached HEAD) and commit oid. ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit switch](https://grit-scm.com/docs/switch/index.md), [grit branch](https://grit-scm.com/docs/branch/index.md) # https://grit-scm.com/docs/remote/index.md # grit remote > List remotes, add one, show one, set URLs, rename or remove one, or list refs on a remote. ## Synopsis ```text grit remote [-v] grit remote add [--fetch] grit remote set-url [--push] [--dry-run] grit remote remove [--dry-run] grit remote prune [--dry-run] grit remote set-head (--auto | | --delete) [--dry-run] grit remote show [--no-query] [-n N] grit remote rename [--dry-run] grit remote refs [--heads] [--tags] [--sort name|version] [--reverse] [-n N] […] ``` ## Description A remote is another copy of the repository that you fetch from and push to, usually on a server. With no arguments, `grit remote` lists your remotes and their URLs, sorted by name. Like `git remote`, the list includes a remote that has config but no URL, shown as `(no url)`. `grit remote add` adds a remote. It writes `remote..url` and the fetch refspec `+refs/heads/*:refs/remotes//*` to the repository's shared config, also when run from a linked worktree. It fails if a remote with that name is already configured, or if the name could not be used in a ref such as `refs/remotes//main` (for example names with spaces, `..` or `:`). With `--fetch` (long only; `-f` means force elsewhere in grit), it runs [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) for that remote immediately after adding it. [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) stores the remote's branches as remote-tracking branches named `/`, such as `origin/main`. [`grit clone`](https://grit-scm.com/docs/clone/index.md) adds a remote called `origin` for you. `grit remote prune` deletes stale remote-tracking refs for one remote without fetching: it lists refs on the remote, compares them to local tracking refs under that remote's fetch refspecs (same rules as `git fetch --prune`), and removes refs whose upstream branch is gone. `refs/remotes//HEAD` is never pruned. `--dry-run` lists refs that would be removed without deleting them. `grit remote set-head` updates or deletes the `refs/remotes//HEAD` symref. `--auto` queries the remote default branch and points HEAD at `refs/remotes//` when that tracking ref exists locally. A branch argument sets HEAD to that branch. `--delete` removes the symref. `--dry-run` reports the change without updating refs. `-v` / `--verbose` lists fetch and push URLs on separate lines (`name url (fetch)` and `name url (push)`), like `git remote -v`. With `--json`, each remote also includes `fetch_url` and `push_url` after `url.*.insteadOf` / `pushInsteadOf` rewrites, plus `refspecs`. `grit remote set-url` changes the fetch URL (`remote..url`) or, with `--push`, replaces every `remote..pushurl` with a single new push URL. It fails when the remote is not configured. `--dry-run` reports the change without writing config. `grit remote remove` deletes a configured remote: it removes the `remote.` section from the shared config, deletes every remote-tracking ref this remote's fetch refspecs map to (including `refs/remotes//HEAD`), and clears `branch..remote`, `branch..merge`, and matching `branch..pushRemote` / `remote.pushDefault` keys. Tracking refs that another remote's fetch refspec also maps to are kept. `--dry-run` reports what would change without writing config or refs. There is no `rm` alias. `grit remote show` summarizes one configured remote: fetch and push URLs, the remote `HEAD` branch, each remote branch classified as tracked, new, or stale (when the remote is queried), and local branches whose `branch..remote` points at this remote. By default it contacts the remote (same transports as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md)). With `--no-query`, branch rows come from local remote-tracking refs only and every branch is reported as tracked. `grit remote rename` renames a configured remote. When the remote uses the default fetch refspec into `refs/remotes//`, every remote-tracking ref is renamed in one transaction (reflogs preserved), then the config section is renamed, default fetch refspecs are updated, and `branch.*.remote`, `branch.*.pushRemote`, and `remote.pushDefault` entries that pointed at the old name are retargeted. Custom fetch refspecs that do not map into `refs/remotes//` are left unchanged. `--dry-run` reports counts without changing the repository. `grit remote refs` lists references on a configured remote name or a literal URL, scp-style `host:path` or path (same transports as [`grit clone`](https://grit-scm.com/docs/clone/index.md)), matching `git ls-remote` ordering. An argument that is none of these fails with `unknown remote`. SSH URLs use the same `GIT_SSH_COMMAND`, `GIT_SSH`, and `core.sshCommand` resolution as [`grit clone`](https://grit-scm.com/docs/clone/index.md) and [`grit fetch`](https://grit-scm.com/docs/fetch/index.md). Like fetch, listing uses `protocol.version` from config (default **2**): SSH sets `GIT_PROTOCOL=version=N` on the ssh child when `N > 0`, and adds `-o SendEnv=GIT_PROTOCOL` when the resolved program basename is `ssh` / `ssh.exe` (including a `GIT_SSH_COMMAND` line that starts with `ssh`), or when `GIT_SSH_VARIANT=ssh`. ## Options | Option | Description | | --- | --- | | `-v`, `--verbose` | With no subcommand, show fetch and push URLs (like `git remote -v`). | | `add ` | Add a remote called `` at ``. Fails if a remote with that name exists or the name is not valid in a ref. | | `--fetch` | With `add`, fetch from the new remote after writing config. | | `prune ` | Delete stale remote-tracking refs for ``. `--dry-run` previews without deleting. | | `set-head …` | Set or delete `refs/remotes//HEAD` (`--auto`, a branch name, or `--delete`). | | `--auto` | With `set-head`, follow the remote `HEAD` symref. | | `--delete` | With `set-head`, remove the local HEAD symref. | | `set-url ` | Set the fetch URL for ``. Use `--push` for `pushurl`. | | `--push` | With `set-url`, update push URL(s) instead of fetch. | | `remove ` | Remove remote `` and its tracking refs. `--dry-run` previews without writing. | | `show ` | Summarize `` (URLs, HEAD branch, remote branches, pull config). | | `--no-query` | With `show`, use local remote-tracking refs only; do not contact the remote. | | `--dry-run` | With `set-url`, `remove`, or `rename`, show the change without writing. | | `rename ` | Rename remote `` to ``. Fails when `` exists or is not a valid remote name. | | `refs ` | List refs on the remote (or URL). | | `--heads` | With `refs`, only `refs/heads/`. | | `--tags` | With `refs`, only `refs/tags/`. | | `--sort` | With `refs`, `name` (default) or `version` (`git ls-remote --sort=version:refname`). | | `--reverse` | With `refs`, reverse `--sort` order. | | `-n`, `--limit` | With `show` or `refs`, return at most `N` branch or ref lines after sorting. | | `…` | With `refs`, optional ref prefixes (same rules as `git ls-remote`). | ## Examples ```console $ grit remote add origin https://github.com/ada/project.git Added remote origin → https://github.com/ada/project.git $ grit remote origin https://github.com/ada/project.git $ grit remote -v origin https://github.com/ada/project.git (fetch) origin https://github.com/ada/project.git (push) $ grit remote set-url origin git@github.com:ada/project.git Set remote origin fetch URL to git@github.com:ada/project.git $ grit remote show origin * remote origin Fetch URL: https://github.com/ada/project.git Push URL: https://github.com/ada/project.git HEAD branch: main Remote branches: main tracked feature new Local branches configured for pull: main merges with remote main $ grit remote rename origin upstream Renamed remote origin → upstream (3 tracking refs updated) $ grit remote refs upstream a1b2c3d4e5f6789012345678901234567890abcd refs/heads/main ``` ## JSON output Schema: [v1](https://grit-scm.com/docs/remote/schemas/remote/v1.json/index.md) · [remote.add v1](https://grit-scm.com/docs/remote/schemas/remote.add/v1.json/index.md) · [remote.remove v1](https://grit-scm.com/docs/remote/schemas/remote.remove/v1.json/index.md) · [remote.show v1](https://grit-scm.com/docs/remote/schemas/remote.show/v1.json/index.md) · [remote.rename v1](https://grit-scm.com/docs/remote/schemas/remote.rename/v1.json/index.md) · [remote.refs v1](https://grit-scm.com/docs/remote/schemas/remote.refs/v1.json/index.md) (set-url uses the main remote schema) Pass `--json` for stable, scripting-friendly output: | Field | Type | Meaning | | ----- | ---- | ------- | | `action` | string | `list`, `add`, `set_url`, `remove`, `prune`, `set_head`, `show`, `rename`, or `refs`. | | `remotes` | array | For `list`, each remote with `name` and `url`; with `-v`, also `fetch_url`, `push_url`, and `refspecs`. | | `name` | string | For `add`, `set_url`, `remove`, or `show`, the remote name. | | `url` | string | For `add` or `set_url`, the remote URL or path. | | `fetched` | boolean | For `add`, whether a fetch ran after adding (`--fetch`). | | `refs_pruned` | array | For `prune`, full ref names deleted or that would be deleted. | | `target` | string or null | For `set_head`, new symref target, or null when deleted. | | `previous_target` | string or null | For `set_head`, symref target before the update, if any. | | `kind` | string | For `set_url`, `fetch` or `push`. | | `old_url` | string or null | For `set_url`, previous URL for that kind, if any. | | `refs_deleted` | array | For `remove`, deleted remote-tracking ref names. | | `branches_untracked` | array | For `remove`, local branch short names whose upstream keys were cleared. | | `dry_run` | boolean | For `set_url`, `remove`, or `rename`, whether changes were only reported. | | `fetch_url` | string | For `show`, fetch URL after config rewrite. | | `push_url` | string | For `show`, push URL (`pushurl` when set). | | `head_branch` | string or null | For `show`, remote default branch when known. | | `branches` | array | For `show`, each `{ name, state }` with `state` `tracked`, `new`, or `stale`. | | `pull` | array | For `show`, each `{ local, merges }` from `branch.*` config. | | `old` | string | For `rename`, the previous remote name. | | `new` | string | For `rename`, the new remote name. | | `refs_renamed` | number | For `rename`, remote-tracking refs renamed. | | `refspecs_updated` | array | For `rename`, fetch refspec strings rewritten for the new name. | | `branches_updated` | array | For `rename`, branch short names whose upstream remote was retargeted. | | `refs` | array | For `refs`, each entry with `name`, `oid`, optional `peeled`, optional `symref_target`. | Listing remotes: ```json { "action": "list", "remotes": [ { "name": "origin", "url": "https://github.com/ada/project.git" } ] } ``` Adding a remote: ```json { "action": "add", "name": "origin", "url": "https://github.com/ada/project.git", "fetched": false } ``` Showing a remote: ```json { "action": "show", "name": "origin", "fetch_url": "https://github.com/ada/project.git", "push_url": "https://github.com/ada/project.git", "head_branch": "main", "branches": [ { "name": "main", "state": "tracked" }, { "name": "feature", "state": "new" } ], "pull": [ { "local": "main", "merges": "refs/heads/main" } ] } ``` Pruning stale tracking refs: ```json { "action": "prune", "name": "origin", "refs_pruned": ["refs/remotes/origin/topic"], "dry_run": false } ``` Setting remote HEAD: ```json { "action": "set_head", "name": "origin", "target": "refs/remotes/origin/main", "previous_target": null, "dry_run": false } ``` Setting a URL: ```json { "action": "set_url", "name": "origin", "kind": "fetch", "old_url": "https://github.com/ada/old.git", "url": "https://github.com/ada/project.git", "dry_run": false } ``` Removing a remote: ```json { "action": "remove", "name": "origin", "refs_deleted": ["refs/remotes/origin/HEAD", "refs/remotes/origin/main"], "branches_untracked": ["main"], "dry_run": false } ``` Renaming a remote: ```json { "action": "rename", "old": "origin", "new": "upstream", "refs_renamed": 3, "refspecs_updated": ["+refs/heads/*:refs/remotes/upstream/*"], "branches_updated": ["main"], "dry_run": false } ``` Listing refs: ```json { "action": "refs", "refs": [ { "name": "refs/heads/main", "oid": "a1b2c3d4e5f6789012345678901234567890abcd", "peeled": null, "symref_target": null } ] } ``` ## Markdown output Schema: [v1](https://grit-scm.com/docs/remote/schemas/remote/v1.json/index.md) Pass `--markdown` for an agent-friendly Markdown table of refs (a “Remote refs” heading, then columns — not JSON). Example shape: ```text Remote refs | Ref | Object | Peeled | Symref target | | --- | --- | --- | --- | | `refs/heads/main` | `a1b2c3…` | — | — | | `refs/tags/v1` | `tagoid…` | `commitoid…` | — | ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | | `128` | `remote refs` could not reach or read the remote ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. ## See also [grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit push](https://grit-scm.com/docs/push/index.md), [grit clone](https://grit-scm.com/docs/clone/index.md) # https://grit-scm.com/docs/fetch/index.md # grit fetch > Download new commits, branches and tags from a remote. ## Synopsis ```text grit fetch [] […] [--all] [--depth N] [--deepen N] [--unshallow] [--tags] [--no-tags] [--prune] [--no-prune] [--dry-run] [-f] [-q] ``` ## Description Downloads objects and updates refs from a remote. Your working tree and current branch are unchanged; use [`grit merge`](https://grit-scm.com/docs/merge/index.md) or [`grit pull`](https://grit-scm.com/docs/pull/index.md) to integrate fetched commits. `` defaults to the current branch's remote (`branch..remote`, the remote `grit branch -u` and `grit push -u` record), and to `origin` when that is not set, when the branch tracks a local branch (`branch..remote = .`), or when `HEAD` is detached. It may be a configured remote name, a URL, an scp-style `host:path`, a filesystem path, or a [git bundle](https://git-scm.com/docs/git-bundle) file. Anything else fails with `unknown remote`. Each `` selects what to fetch (`main`, `refs/heads/x:refs/heads/y`, `+refs/…` to force). When no refspecs are given, configured `remote..fetch` refspecs apply (usually all heads into `refs/remotes//…`). When the source is a **literal path or URL** (not a configured remote), grit does not update `refs/remotes/origin/*` unless you pass refspecs with destinations. With no refspecs, grit fetches the bundle's `HEAD` into [`FETCH_HEAD`](https://git-scm.com/docs/git-fetch#_discussion) (matching Git's anonymous fetch). A bundle whose header lists no `HEAD` — typical of incremental range bundles — fails with a clear ref error instead of reporting "already up to date"; pass an explicit refspec (for example `main:refs/remotes/bundle/main` or `main` to update `FETCH_HEAD` only) to take a listed branch. Human output lists each local ref with its remote source and old → new oids. Pruned refs show `deleted`; rejected updates are listed and exit **1** (same as [`grit push`](https://grit-scm.com/docs/push/index.md) rejections). When a stale remote-tracking ref blocks another update (for example `origin/gone/x` still exists locally but the remote now has `gone`), grit still applies every ref it can and reports the blocked ref as rejected; the `reason` field suggests `grit fetch --prune` or `grit remote prune ` when pruning would remove the stale ref. With `core.ignorecase`, when the remote advertises two refs that differ only by case, grit stores the first and rejects the second as a loose ref; the `reason` mentions case and suggests `grit init --ref-format=reftable` if you need both spellings locally. When the fetch received objects, the ref list is followed by the same transfer summary [`grit clone`](https://grit-scm.com/docs/clone/index.md) prints: a `time` bar splitting the run into the network wait before the pack (**handshake**, **negotiate** and the server's **pack prep**, as described for [`grit clone`](https://grit-scm.com/docs/clone/index.md)), receiving, indexing, resolving deltas and finishing; the `data` received off the wire with its average and peak rate; and the `objects` received by type. Local `file://` and plain-path remotes use the same summary shape, with **Enumerating** (reachability walk) and **Copying** (link or pack the send set) instead of network **Receiving**. Nothing extra is printed when the fetch was already up to date. With `--all`, one summary after the last remote covers the whole run. On a terminal, stderr first shows `Fetching `, then one live progress line per phase with a throughput graph and, under it, an overall bar with a time-left estimate. Finished phases stay on screen as `✓` lines. When stderr is not a TTY, or with `--json`, `--markdown` or `-q`, no progress is drawn. By default grit follows tags, fetching every tag (lightweight or annotated) that points into the fetched history. That includes tags on commits, trees and blobs that arrive with the fetch, and tags on trees or blobs you already have. A tag on a commit you already have is followed only when the fetched refs reach that commit; Git also follows it when the commit is unreachable from them. In a partial clone, tag following never downloads missing objects. `--tags` fetches every remote tag, and `--no-tags` disables automatic tags. Tag following costs milliseconds even on large repositories. `remote..tagOpt` (`--tags` / `--no-tags`) applies when the CLI does not override it. Default tag following never updates a tag you already have locally, even when the remote retargets it — a plain `grit fetch` stays quiet and exits **0**, matching Git. To refresh moved release tags, use `grit fetch --tags` (reports a rejection until you accept the move) or `grit fetch --tags --force`. A refspec that names tags (`refs/tags/rel:refs/tags/rel2`, `refs/tags/*:refs/tags/*`) is honoured like any other refspec; a leading `+` or `--force` on the fetch forces the update (status `forced`). `--dry-run` negotiates and reports updates without writing refs, objects, or `FETCH_HEAD`. Human output ends with **Would fetch N update(s) from …** when anything would change, or **Already up to date with …** when nothing would. `--depth`, `--deepen`, and `--unshallow` match Git’s shallow fetch controls (mutually exclusive). `--depth` truncates history on the first shallow fetch; `--deepen` adds commits relative to an existing shallow clone; `--unshallow` fetches the rest and removes `.git/shallow`. `--unshallow` on a complete repository is a typed error. With default tag following, tags on newly fetched history (including annotated tags) arrive in that same operation; a second fetch is unnecessary. Following tags does not extend the requested branch depth. A shallow source can only supply its available history, so boundaries remain when the source is incomplete. A shallow fetch still offers the server the commits you have (the tips being deepened and your other branches and tags), over every protocol version, so only history the repository lacks is transferred. In a partial clone, a fetch takes part in the server's `promisor-remote` exchange (protocol v2) the way [`grit clone`](https://grit-scm.com/docs/clone/index.md#large-object-promisors) does: it accepts the advertised large-object promisors that `promisor.acceptFromServer` allows, tells the server so, and applies `promisor.storeFields`. A remote whose `partialclonefilter` is `auto` (a clone made with `--blobs auto`) picks its filter on every fetch from the accepted remotes' advertised `partialCloneFilter`. A fetch that is neither filtered nor from a promisor remote declines every promisor remote (`not_partial`), because it needs every object from the server; that includes an unfiltered fetch from a second, non-promisor remote of a partial clone, whose pack would otherwise be marked promisor although no promisor remote can give its objects back. The human output adds a `promisor` line per advertised remote, for example `promisor lop accepted · blob:limit=5k`, and `promisor stored partialCloneFilter for lop` for each stored field. `-q` / `--quiet` suppresses progress and human output (JSON and markdown are unchanged). Local fetches reuse the repository's ref store across tracking refs and tags. An up-to-date fetch skips object-copy preparation while still handling pruning, `FETCH_HEAD`, and the remote's default branch. See the [many-ref local fetch measurements](https://grit-scm.com/docs/benchmarks/index.md#local-fetch-with-many-refs). When `core.logAllRefUpdates` is enabled (grit's default for new repositories), each fetch that moves a remote-tracking branch writes a reflog entry on that ref (`fetch: fast-forward`, `fetch: forced-update`, or `fetch: storing head` for a newly stored tracking ref). [`grit pull`](https://grit-scm.com/docs/pull/index.md) uses the same mechanism with a `pull:` prefix. The initial clone fetch does not create branch tracking reflogs (Git matches this); only `refs/remotes//HEAD` gets `clone: from `. Pruning a stale tracking ref removes its reflog file. Tags are not logged unless a reflog already exists or logging is set to `always`. `--all` fetches every configured remote in config order. Remotes with `remote..skipFetchAll=true` are skipped. Each remote uses its own `remote..prune` and `remote..tagOpt` unless `--prune`, `--no-prune`, `--tags`, or `--no-tags` override on the command line. Failures on one remote do not stop the rest; the command exits **1** if any remote failed or any ref update was rejected. `--all` cannot be combined with `` or `` arguments. When a fetch is interrupted (`SIGINT`, `SIGTERM`, or `SIGHUP`, including Ctrl+C from a terminal), grit cancels the in-progress transfer, removes any partial pack temp file it was writing, and exits **130** without leaving `tmp_pack_*` or pack install staging directories behind. Stale temp files from a hard kill (`SIGKILL`) are removed later by [`grit gc`](https://grit-scm.com/docs/fetch/gc.md/index.md) once they are older than `gc.pruneExpire`, the same way `git gc` prunes `tmp_pack_*`. ## Options | Option | Description | | --- | --- | | `` | Remote name, URL, path, or bundle. Defaults to the current branch's remote, else `origin`. | | `…` | What to fetch; short names expand like Git (`main` → `refs/heads/main`). | | `--tags` | Fetch all tags from the remote. | | `--no-tags` | Do not fetch tags automatically. | | `--prune` | Remove stale remote-tracking refs. | | `--no-prune` | Do not prune, even when config enables it. | | `--dry-run` | Report updates without writing. | | `--all` | Fetch all configured remotes (see above). | | `--depth N` | Shallow fetch: keep at most N commits from each tip. | | `--deepen N` | Deepen a shallow clone by N commits (relative). | | `--unshallow` | Fetch full history and drop shallow boundaries. | | `-f`, `--force` | Force non-fast-forward branch updates and tag moves when combined with `--tags` or a forced refspec. Does not move existing tags on a default fetch. | | `-q`, `--quiet` | Suppress progress and human stdout/stderr. | ## Examples ```console $ grit fetch origin main refs/remotes/origin/main ← refs/heads/main a8e620a → b52cca6 Fetched 1 update from origin. $ grit fetch Already up to date with origin. $ grit fetch origin '+refs/heads/*:refs/remotes/origin/*' refs/remotes/origin/ag/bstr-migration ← refs/heads/ag/bstr-migration new → 4b88e08 refs/remotes/origin/ag/changelog ← refs/heads/ag/changelog new → f3146f8 … refs/remotes/origin/ag/snafu ← refs/heads/ag/snafu new → 7bf7ceb Fetched 15 updates from origin. time ···································█·▓▒· 1.4s · connect 1.3s █ receiving 0ms ▓ indexing 13ms ▒ resolving 22ms · finish 139ms data 201 KiB received objects 249 · 35 commits · 82 trees · 132 blobs $ grit fetch --prune refs/remotes/origin/gone1 a1b2c3d → deleted Fetched 1 update from origin. $ grit fetch --dry-run --prune refs/remotes/origin/gone1 a1b2c3d → deleted refs/remotes/origin/feature ← refs/heads/feature new → b52cca6 Would fetch 2 updates from origin. ``` On a terminal, with progress on stderr above the summary (here filling in a shallow clone, which moves no refs): ```console $ grit fetch --unshallow Fetching origin https://github.com/BurntSushi/ripgrep.git ✓ Receiving █████████████████████ 4.64 MiB 48.1 MiB/s 96ms ✓ Indexing █████████████████████ 13,715 objects 223.6k objects/s 61ms ✓ Resolving █████████████████████ 9,905 deltas 451.8k deltas/s 21ms Already up to date with origin. time ·····························███·▓▓▒···· 1.2s · handshake 259ms · negotiate 584ms · pack prep 61ms █ receiving 96ms ▓ indexing 61ms ▒ resolving 21ms · finish 138ms data 4.64 MiB received · 48.1 MiB/s avg · 48.1 MiB/s peak objects 13,868 · 2,302 commits · 6,319 trees · 4,977 blobs · 270 tags ``` The rates are left out when the pack arrived in a single read, too fast to time. A fetch pack can be *thin*: grit completes it with the delta bases it already has, so `objects` can be a little higher than the `Indexing` count. Fetch a pull request ref into a local branch: ```console $ grit fetch origin pull/123/head:pr-123 refs/heads/pr-123 ← refs/pull/123/head … → … Fetched 1 update from origin. ``` ## JSON output Pass `--json` for stable, scripting-friendly output. ### Single remote (default) Schema: [v1](https://grit-scm.com/docs/fetch/schemas/fetch/v1.json/index.md) | Field | Type | Meaning | | ----- | ---- | ------- | | `remote` | string | Remote that was fetched: its name, or the URL given with any `user:password@` removed. Human and Markdown output show the same value. | | `dry_run` | boolean | True when `--dry-run` was used. | | `rejected` | boolean | True when any update was rejected (exit 1). | | `updates` | array | Per-ref results. Each object has `ref`, `remote_ref`, `status` (`new`, `fast_forward`, `forced`, `pruned`, `rejected`, or `up_to_date`), `old_oid` and `new_oid` (full hex or `null`), and `reason` when `status` is `rejected`. | | `updated` | number | Count of refs that actually changed. Always **0** when `dry_run` is true (nothing is written); count pending changes by filtering `updates` where `status` is not `up_to_date`. | | `shallow` | object | When present: `added` and `removed` lists of full hex oids for new/removed `.git/shallow` boundaries. | | `promisor_remotes` | array | When the server advertised promisor remotes: `name`, `url` (credentials removed), `accepted`, `filter` (advertised `partialCloneFilter` or `null`) and `rejected` (`policy_none`, `unknown_remote`, `url_mismatch`, `field_missing`, `field_mismatch`, `not_partial`, or `null` when accepted). Tokens are never shown. | | `stored_fields` | array | When `promisor.storeFields` changed config: `remote` and `field` (`partialCloneFilter` or `token`), never the value. | | `promisor_warnings` | array | Promisor config or advertised values that were ignored: `code` is `unknown_accept_value` (`promisor.acceptFromServer` is not a known policy, so nothing is accepted), `unknown_field` (a `promisor.checkFields` / `promisor.storeFields` entry is not a known field), `invalid_advertised_value` (an advertised field was not stored because its value is invalid) or `unusable_auto_filter` (`--blobs auto` cannot use an accepted remote's filter, such as `tree:0`); `key`, `remote`, `field` and `value` say which, when they apply. A rejected advertised value is never shown. Shown as `promisor warning: …` lines in the human output and `promisor warning` bullets in `--markdown`. | Example: ```json { "remote": "origin", "dry_run": false, "rejected": false, "updates": [ { "ref": "refs/remotes/origin/main", "remote_ref": "refs/heads/main", "status": "fast_forward", "old_oid": "a8e620a111111111111111111111111111111111", "new_oid": "b52cca6222222222222222222222222222222222" } ], "updated": 1 } ``` Dry run: ```json { "remote": "origin", "dry_run": true, "rejected": false, "updates": [ { "ref": "refs/remotes/origin/main", "remote_ref": "refs/heads/main", "status": "fast_forward", "old_oid": "a8e620a111111111111111111111111111111111", "new_oid": "b52cca6222222222222222222222222222222222" } ], "updated": 0 } ``` ### `--all` Schema: [all v1](https://grit-scm.com/docs/fetch/schemas/fetch.all/v1.json/index.md) When `--all` is used, JSON has no top-level `remote` field. Each entry in `remotes` matches the single-remote shape (`remote`, `updates`, `updated`) plus an optional `error` string when that remote could not be fetched. | Field | Type | Meaning | | ----- | ---- | ------- | | `dry_run` | boolean | True when `--dry-run` was used. | | `remotes` | array | One object per remote attempted (skipFetchAll remotes omitted). | | `updated` | number | Total refs changed across all successful remotes. Always **0** when `dry_run` is true. | Example: ```json { "remote": "origin", "updates": [], "updated": 0, "dry_run": false, "rejected": false } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v1](https://grit-scm.com/docs/fetch/schemas/fetch/v1.json/index.md) Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract. ```text Already up to date with `origin`. ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success ([`success`](https://grit-scm.com/docs/exit-codes/index.md)). | | `1` | Command failed ([`failure`](https://grit-scm.com/docs/exit-codes/index.md)). | | `2` | Invalid flags or arguments ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | | `128` | Could not reach or read the remote: missing repository, DNS or connection failure, HTTP error status ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md) for shared rules and structured `--json` `kind` values. An HTTPS remote that wants credentials fails with `kind` `auth_required` (none available) or `auth_rejected` (refused). Credentials come from your credential helper, then an askpass program (`GIT_ASKPASS`, `core.askPass`, `SSH_ASKPASS`), as in Git; save a user name and token for any host with `grit auth --username --token `. See [Credentials](https://grit-scm.com/docs/agents/index.md#credentials-https). ## See also [grit pull](https://grit-scm.com/docs/pull/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md), [grit remote](https://grit-scm.com/docs/remote/index.md) # https://grit-scm.com/docs/pull/index.md # grit pull > Fetch from the remote and bring the current branch up to date. ## Synopsis ```text grit pull grit pull [] […] grit pull --ff-only grit pull --rebase grit pull --no-rebase grit pull --autostash grit pull --check [] […] grit pull # in a snapshot checkout grit pull origin # the same ``` ## Description Runs [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) (same shared fetch flags: tags, prune, dry-run, quiet), then merges the fetched upstream into the **current** branch, as [`grit merge`](https://grit-scm.com/docs/merge/index.md) would: a fast-forward when you have no new commits of your own, and a merge commit when both sides do. Pathnames in human, stderr conflict lines, and `--markdown` output use the same quoting rules as [`grit status`](https://grit-scm.com/docs/status/index.md) (see **Description** there). On a branch with no commits yet, it simply takes the remote's. Positional arguments follow [`grit fetch`](https://grit-scm.com/docs/fetch/index.md): an optional remote (configured name, URL, or path), then optional refspecs. With `grit pull origin feature`, grit fetches that branch and integrates the tip recorded in `FETCH_HEAD`, even when no remote-tracking ref exists yet — the same model as `git pull origin feature`. The default remote is `branch..remote`, or `origin`; every mode (`--ff-only`, `--rebase`, `--autostash`, `--check`) fetches from that remote, so a branch tracking `backup/main` pulls from `backup`. With no refspecs, the upstream is `branch..merge`, or `refs/remotes//`. The remote's `remote..fetch` refspecs decide which local ref holds each fetched branch. With `branch..remote = .` the upstream is a local branch, and `grit pull` merges it without fetching. On a branch with no commits yet, the branch is created at the upstream commit with an `initial pull` reflog entry. Like `grit merge`, `grit pull` uses the same scoped local-change rules as [`grit switch`](https://grit-scm.com/docs/switch/index.md) and won't run with a detached HEAD (except to refresh a [snapshot checkout](#in-a-snapshot-checkout)). Conflicts follow the same model as `grit merge` and `grit rebase`: the pull stops with conflict markers and an operation in progress (a merge, or a rebase), and the result tells you how to finish it. The fetch step uses the same terminal progress as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) and [`grit clone`](https://grit-scm.com/docs/clone/index.md): a `Pulling ` line, then live stderr progress with an overall bar on a TTY in human mode, silent when stderr is piped or when you pass `--json` or `--markdown`. When the fetch received objects, the result line is followed by the same `time`, `data` and `objects` summary rows as `grit fetch`. When you need an explicit fetch refspec or fetch-only flags (`--depth`, `--deepen`, `--unshallow`, `--tags`, `--no-tags`, `--prune`, `--no-prune`, `--dry-run`, `-q`), run [`grit fetch`](https://grit-scm.com/docs/fetch/index.md) first, then integrate with `grit merge` or the pull integration flags below. Integration mode follows Git's `pull.ff`, `pull.rebase`, and `branch..rebase` unless overridden on the command line. With rebase, local commits replay onto the fetched upstream tip via the history engine, exactly as [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) does. Rebasing uses the upstream tracking ref's reflog fork point (as `git pull --rebase` does), so commits a teammate dropped with a force-push are not replayed from your older view of the branch. When a commit conflicts, the rebase stops (exit **1**) with conflict markers, unmerged paths and Git-compatible `.git/rebase-merge/` state; the branch still points at its old tip until the rebase finishes. Resolve, `grit add`, then `grit rebase --continue`, or run `grit rebase --skip` / `grit rebase --abort` (`git rebase --continue` / `--abort` work on the same state). The rebase only stops when it can do so without losing work: if staged or unstaged changes exist, or an untracked file sits where the stop would check out a path, the pull refuses with `kind: dirty_worktree` (or the overwrite error) and nothing changes. Use `--autostash` or commit first. `pull.rebase=interactive` is rejected. For a standalone rebase without fetching, use [`grit rebase`](https://grit-scm.com/docs/pull/rebase.md/index.md). The integration step records the branch's pre-pull tip in `ORIG_HEAD`, the way [`grit merge`](https://grit-scm.com/docs/merge/index.md) and [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) do, so `grit reset --hard ORIG_HEAD` undoes a pull. A branch with no commits yet has no previous tip, so the first pull onto it leaves `ORIG_HEAD` alone. Integration runs the same hooks as `git pull`: `post-merge 0` after a fast-forward or merge commit (in rebase mode too, when the branch is only behind and simply fast-forwards), and `post-checkout 1` plus `post-rewrite rebase` after a rebase (see [`grit hooks`](https://grit-scm.com/docs/hooks/index.md)). Before anything is recorded it also runs `pre-merge-commit`, `prepare-commit-msg` and `commit-msg` for a merge commit (as [`grit merge`](https://grit-scm.com/docs/merge/index.md) does), and `pre-rebase ` before a rebase replays commits; a hook that exits non-zero stops the pull. `--autostash` stashes dirty index/worktree changes (including untracked files) before integrating, then re-applies them afterward. Config `merge.autoStash` / `rebase.autoStash` enables the same behavior by default for merge and rebase pulls respectively. On a branch with no commits yet, autostash is skipped and the upstream tip is checked out instead (same as Git). If re-applying the stash conflicts, the pull integration is kept, the stash entry remains on `refs/stash`, and the result is `autostash_conflict` (exit **1**). When a rebase pull stops on conflicts, the stash is not applied over the conflict markers: it stays on `refs/stash` (reported as `autostash`) so you can `grit stash pop` once the rebase is finished or aborted. When a hook refuses the merge commit, the merge stays in progress and the stash waits in `MERGE_AUTOSTASH`, as with Git: your edits stay out of the merge, and `grit merge --continue` (or `grit commit`) or `grit merge --abort` puts them back. ### In a snapshot checkout In a [snapshot checkout](https://grit-scm.com/docs/checkout/index.md), `grit pull` with no refspecs **refreshes** the checkout (so does `grit pull origin`, or a pull naming whatever remote has the checkout's server URL now): 1. It asks the server for a snapshot of the newest commit of the target branch the checkout was made from (the server keeps following that branch even when its `HEAD` moves to another), made on top of the checkout's last snapshot. 2. It gives the current branch's commits made with plain `git` a change id, as [`grit checkin`](https://grit-scm.com/docs/checkin/index.md#change-ids) does, so the rebase below keeps an id the server can match them by (`Gave 1 commit made with git a change id.`; not with `--check`). 3. It fetches that snapshot into `origin/` (`refs/remotes/origin/`) from the server the checkout came from, with an explicit refspec and no tags, whatever `origin` is configured as now. Only what changed in the checkout's paths comes down. The checkout records the new snapshot only once it has arrived and is the one the server described. 4. It brings the current branch onto it: a rebase unless `--ff-only` or `--no-rebase` says otherwise. Commits already merged into the target drop out. Commits of a branch this checkout checked in and [integrated](https://grit-scm.com/docs/integrate/index.md) into the branch it follows are never replayed, since the snapshot already has their result (replaying them one by one could conflict with themselves): a branch with nothing above them moves to the new snapshot, keeping uncommitted and untracked changes as `git reset --keep` does (`landed`), and one with commits of its own above them rebases only those, as `git rebase --onto origin/ ` would. When the rebase hits a conflict, it **stops** in a resumable rebase, as [`grit rebase`](https://grit-scm.com/docs/rebase/index.md) does: resolve the files, `grit add` them, then `grit rebase --continue` (or `grit rebase --abort` to put the branch back on the older snapshot). Until then, another `grit pull` refuses to start. When the index or worktree has changes of their own, the rebase can't stop there, so nothing changes; commit or stash them and pull again. 5. A local branch named after the target (a `main` you made with `grit branch main origin/main`) that has no commits of its own follows to the new snapshot, and so does any other branch whose commits have all been integrated. Every other branch with commits of its own that still builds on an older snapshot is named, with how to bring it up: `grit switch `, then `grit pull` (which leaves out its integrated commits, too). With `HEAD` detached, the refresh still fetches the new snapshot into `origin/` and leaves `HEAD` where it is. It works the same from any worktree of the checkout. The first lines say how far the target moved and what changed in the checkout's paths (as `git diff --shortstat` counts it), or that it hasn't moved: ```console $ grit pull main moved 4f06b71 → 3182ed4; new snapshot 39dfeba at origin/main 1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths Rebased onto origin/main (2b87e20) main follows to 39dfeba side still builds on an older snapshot; run `grit switch side`, then `grit pull` ``` ```console $ grit pull main moved e8d5aa5 → f3dbd6f; new snapshot 552fbc6 at origin/main 1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths CONFLICT (both_modified): src/a.rs Rebasing onto origin/main stopped on a conflict; the rebase is in progress. Resolve the conflicts, `grit add` the files, then run `grit rebase --continue`; or run `grit rebase --abort` to put the branch back where it was. $ grit add src/a.rs && grit rebase --continue Rebased 1 commit(s) ``` ### A server branch in a snapshot checkout In a snapshot checkout, `grit pull ` (or `grit pull origin `, naming the checkout's server) brings your `` onto the server's branch of that name, as your checkout sees it. That is how you pick up a teammate's branch, or work on one with someone whose checkout has other paths. `` must not be the name of a configured remote (then it is an ordinary pull from that remote); naming the branch the checkout follows (`grit pull main`) is just a refresh. 1. The server **shows you its branch**: each of its commits that the target lacks is rewritten with its tree cut down to your checkout's paths, on top of your newest snapshot under it, at `refs/checkouts//in/heads/` (see [`grit serve`](https://grit-scm.com/docs/serve/index.md#snapshot-checkouts)). Author, date and message are kept. A commit that only touched paths you don't have shows up as an empty commit, so the history still lines up with the server's. Your own commits that the server's are grafts of come back as they are, and files outside your paths that they added stay in the commits above them while they are still files there (one the server turned into a directory is dropped). Another checkout's commit is never shown to you as it is when it has files outside your paths, even on the same snapshot. On a server whose file system can't tell names apart by case, a name that differs from the server's branch only in case is that branch, and you get it under the server's spelling (`grit pull feature` creates `Feature`), so its check-ins aren't refused as a case conflict. 2. It **fetches** that into `origin/` (`refs/remotes/origin/`) from the server the checkout came from, with no tags, and checks that what arrived is what the server described. 3. It gives the branch's commits made with plain `git` a change id, as `grit checkin` does. 4. It **brings your branch onto it**: - a branch you don't have yet is **created** at the server's (`created`; switch to it with `grit switch `); - a branch that has every commit already is left alone (`up_to_date`: `feature already has them.`); - one with nothing of its own on top moves to it (`fast_forward`), keeping uncommitted changes when it is the current branch; - otherwise **your own commits are rebased onto it** (`rebased`): those above the newer of where your branch meets the server's and the newest snapshot it builds on. Copies of the server's commits that your branch holds (made when a refresh rebased it onto a newer snapshot, say) are left out, recognized by change id or by patch, so only your work moves. A rebase that conflicts **stops** for you to resolve, then `grit rebase --continue` (or `--abort`), as a refresh's does (`rebase_stopped`). When the branch is not the current one, you are switched to it first, as `git rebase ` does, and switched back when the rebase can't go ahead (local changes it would overwrite, say). A branch that another worktree has checked out, or is rebasing or bisecting, is refused. A rebase of yours goes through cleanly when the server's branch turned a directory into a file (or the other way round) and your commits never touched it. Checking the branch in afterwards is a fast-forward on top of the server's: work you build on its commits is grafted onto the real commits they stand for (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md#sharing-a-branch)). It always rebases, so `--ff-only`, `--no-rebase`, `--autostash` and `--dry-run` are refused; `--check` says what it would do to the branch without changing it (the server still shows the branch, and it is fetched). ```console $ grit pull feature The server's feature is at bcd6c48: 2 commits on this checkout's snapshots, at origin/feature (19a3116). Rebased feature onto origin/feature (4c2d9e1), 1 commit of yours on top. feature builds on the server's now; `grit checkin feature` sends it. $ grit pull feature The server's feature is at bcd6c48: 2 commits on this checkout's snapshots, at origin/feature (19a3116). feature already has them. $ grit pull theirs The server's theirs is at 6f1c2d3: 1 commit on this checkout's snapshots, at origin/theirs (a2b3c4d). Created theirs at a2b3c4d, the server's; `grit switch theirs` to work on it. ``` The server refuses a branch it doesn't have, one the target already has every commit of, and one that builds on a commit from before your checkout's first snapshot (its author can rebase it onto a newer target first). A local branch by that name that shares nothing with the server's is refused too; rename it to get the server's. A merge commit a `--no-rebase` refresh makes checks in as a merge whose result keeps the target's changes outside your paths (see [`grit checkin`](https://grit-scm.com/docs/checkin/index.md)). A later rebasing refresh drops the merge commits a `--no-rebase` refresh made and replays your own commits onto the new snapshot. `--dry-run` asks the server where the target is now and says whether a refresh would move, without the server making a snapshot, and without fetching or changing anything here. `--check` refreshes for real (the server makes the snapshot and it is fetched into `origin/`), then reports what bringing the branch onto it would do, without changing the branch, the index or the worktree. `--check` fetches (always for real — not a dry run) and reports whether the branch could fast-forward or is already up to date, without changing `HEAD`, the index, the worktree, or reflogs. In rebase mode it also predicts whether the replay would stop on conflicts (`would` is `conflicts`). It cannot be combined with `--autostash` or integration mode overrides (`--ff-only`, `--rebase`, `--no-rebase`). ## Options | Option | Description | | --- | --- | | `` | Remote to pull from (same rules as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md); defaults to the branch remote or `origin`). In a snapshot checkout, a name that is not a configured remote is a branch: `grit pull ` brings it onto the [server's branch](#a-server-branch-in-a-snapshot-checkout). | | `…` | Refspecs to fetch before integrating (same as fetch); integration uses `FETCH_HEAD` when refspecs are given. | | `--tags` / `--no-tags` | Tag fetching policy (same as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md)). | | `--all` | Fetch all configured remotes before integrating (same as [`grit fetch`](https://grit-scm.com/docs/fetch/index.md); cannot combine with `` or refspecs). | | `--depth N` | Shallow fetch: keep at most N commits from each tip (same as fetch). | | `--deepen N` | Deepen a shallow clone by N commits (same as fetch). | | `--unshallow` | Fetch full history and drop shallow boundaries (same as fetch). | | `--prune` / `--no-prune` | Prune stale remote-tracking refs after fetch. | | `--dry-run` | Fetch dry-run only: report ref updates without writing refs or objects; integration is skipped. | | `-f`, `--force` | Same as [`grit fetch --force`](https://grit-scm.com/docs/fetch/index.md) (tag clobber with `--tags`, forced refspecs). | | `-q`, `--quiet` | Suppress fetch progress (human mode). | | `--ff-only` | Refuse to create a merge commit when the current branch has local commits; exit with `refused_not_ff` in `--json` output instead. Honors `pull.ff=only` when set. Conflicts with `--rebase`, `--no-rebase`, and `--check`. | | `--rebase` | Rebase local commits onto the upstream tip, overriding `pull.rebase=false`. As with `git pull --rebase`, merge commits on the branch (such as an earlier merge pull) are dropped, and the branch's own commits are replayed one after another on top of the upstream tip, skipping any whose change is already upstream. Conflicts with `--ff-only`, `--no-rebase`, and `--check`. | | `--no-rebase` | After fetch, merge the upstream with a merge commit when a fast-forward is not possible (the default when `pull.rebase` is not true). Conflicts with `--ff-only`, `--rebase`, and `--check`. | | `--autostash` | Stash before integrating and re-apply after (see `merge.autoStash` / `rebase.autoStash`). Conflicts with `--check`. | | `--check` | Fetch and report whether a fast-forward or up-to-date result is possible; exit **0** when yes, **1** when a merge or rebase would be required. Conflicts with `--autostash` and mode overrides. | All [global options](https://grit-scm.com/docs/global-options/index.md) apply as well. ## Examples ```console $ grit pull Fast-forwarded origin/main → 9119bc7 time ███························· 8ms █ copying 0ms · finish 5ms data 318 B received objects 3 · 1 commit · 1 tree · 1 blob $ grit pull origin feature Fetched 1 update from origin. Fast-forwarded origin/feature → d4e5f6a $ grit pull --check Would fast-forward (0 ahead, 2 behind). Fast-forward possible. $ grit pull --autostash Merged origin/main into the current branch (acd1d4b) ``` When a rebase pull conflicts: ```console $ grit pull --rebase CONFLICT (both_modified): f Rebase stopped on conflicts; fix them and run `grit rebase --continue`, or `grit rebase --abort` / `grit rebase --skip`. $ grit status Rebasing main onto 3f6a904 … $ grit add f $ grit rebase --continue Rebased 1 commit(s) commit 1e64458 → e79b420 (local) refs/heads/main 1e64458 → e79b420 ``` When the branch has no upstream yet: ```console $ grit pull error: no upstream configured for branch main hint: pull a branch by name with `grit pull origin main`, or publish this one and track it with `grit push -u origin main` ``` While a rebase is paused (for example after a conflict), `grit pull` refuses with the same guidance as [`grit switch`](https://grit-scm.com/docs/switch/index.md): ```console $ grit pull error: cannot pull while a rebase is in progress; finish it with `grit rebase --continue` or cancel it with `grit rebase --abort` ``` When local edits on a path the pull would update would be overwritten (fast-forward, merge, or rebase): ```console $ grit pull error: local changes would be overwritten by merge f hint: commit them with `grit commit`, or set them aside with `grit stash`, then try again ``` On overwrite refusal with `--json`, stdout is a single object with `kind` `would_overwrite` and `would_overwrite.reason` (`local_changes` or `untracked`) plus a sorted `paths` array, and a `hint` — the same shape as [`grit merge`](https://grit-scm.com/docs/merge/index.md) and [`grit switch`](https://grit-scm.com/docs/switch/index.md). For example `{"error":"local changes would be overwritten by merge","hint":"…","kind":"would_overwrite","would_overwrite":{"paths":["f"],"reason":"local_changes"}}`. See the [error schema](https://grit-scm.com/docs/pull/schemas/error/v1.json/index.md). With `--json` that is `{"error":"no upstream configured for branch main","hint":"…","kind":"branch_no_upstream"}`. A missing remote is `kind` `remote_not_found` and an authentication failure `auth_required` or `auth_rejected`, each with a `hint` (see [Exit codes](https://grit-scm.com/docs/exit-codes/index.md)). ## JSON output Schema: [v2](https://grit-scm.com/docs/pull/schemas/pull/v2.json/index.md) · [v1](https://grit-scm.com/docs/pull/schemas/pull/v1.json/index.md) Pass `--json` for stable, scripting-friendly output: Exit codes (also apply to default human output): **0** on success (`up_to_date`, `fast_forward`, `merged`, `rebased`, `set_upstream`, `detached`, `landed`, or `created`) and on `--check` when `check.fast_forward_possible` is true; **128** when `--ff-only` (or `pull.ff=only`) refuses diverged history (`refused_not_ff`; the branch is unchanged), as with `grit merge --ff-only`; **1** when integration stops with conflicts (`conflicts`, with `operation` `merge` or `rebase` in progress), a snapshot checkout's refresh stops in a rebase (`rebase_stopped`), `--check` when a merge or rebase would be required, or `autostash_conflict`. | Field | Type | Meaning | | ----- | ---- | ------- | | `result` | string | `up_to_date`, `fast_forward`, `merged`, `rebased`, `refused_not_ff`, `conflicts`, `set_upstream`, `autostash_conflict`, `rebase_stopped` (a snapshot checkout's rebase stopped on a conflict and is in progress), `detached` (a snapshot checkout refreshed with `HEAD` detached: only `origin/` moved), `landed` (in a snapshot checkout, every commit of the branch was integrated, so it moved to the new snapshot, keeping uncommitted changes), or `created` (`grit pull ` in a snapshot checkout made the branch at the server's). | | `branch` | string | Remote branch label that was integrated (or checked). | | `oid` | string or null | Commit the current branch points at after the pull, when applicable (absent when a rebase stopped). | | `change_id` | string or null | Stored `change-id` on `oid` when present. | | `upstream` | string or null | For `set_upstream`, the remote-tracking branch that was adopted. | | `conflicts` | array of strings or null | Path names when `result` is `conflicts` or `rebase_stopped` (legacy list). | | `conflict_details` | array or null | Structured conflict items when `result` is `conflicts` or `rebase_stopped`: `path`, a [conflict `kind`](https://grit-scm.com/docs/status/index.md#conflict-kinds) (the same names `grit status` uses, plus `rename_rename` and the `directory_rename_*` kinds), and for merges a `summary`. | | `operation` | string or null | When `result` is `conflicts` or `rebase_stopped`: the operation left in progress, `merge` or `rebase`. | | `commit` | string or null | When `operation` is `rebase`: the local commit that could not be replayed. | | `next_steps` | array of strings or null | When `result` is `conflicts`: ordered `grit` commands to finish (for a rebase, ending in `grit rebase --continue`). | | `alternatives` | array of strings or null | When `result` is `conflicts`: other ways out (`grit merge --abort`, or `grit rebase --abort` / `grit rebase --skip`). | | `autostash` | string or null | Autostash commit kept on `refs/stash` because a rebase stopped or re-applying it conflicted. | | `ahead` | integer or null | Local-only commits when `result` is `refused_not_ff` or with `--check`. | | `behind` | integer or null | Upstream-only commits when `result` is `refused_not_ff` or with `--check`. | | `check` | object or null | Present with `--check`: `ahead`, `behind`, `fast_forward_possible`, and `would` (same result strings as `result`). | | `refresh` | object or omitted | In a snapshot checkout, the refresh (fields below). | | `refresh.target` | string | The server's target branch the checkout follows. | | `refresh.upstream_ref` | string | The local ref holding the newest snapshot, `refs/remotes/origin/`. | | `refresh.base` | string | The real commit the newest snapshot stands for. With `--dry-run`, where the target is now. | | `refresh.snapshot` | string | The newest snapshot commit, now at `upstream_ref`. With `--dry-run`, the checkout's snapshot as it is. | | `refresh.previous_base` | string or null | The real commit the checkout's previous snapshot stood for. | | `refresh.previous_snapshot` | string or null | The checkout's previous snapshot. | | `refresh.moved` | boolean | Whether the target moved since the checkout's last snapshot. | | `refresh.changes` | object or null | What changed in the checkout's paths between the two snapshots: `files`, `insertions`, `deletions`; null when the target didn't move. | | `refresh.dry_run` | boolean | True with `--dry-run`: nothing was fetched or changed, and the server made no snapshot. | | `refresh.followed` | array | Local branches with no commits of their own that moved along (the one named after the target, and any whose commits were all integrated): `name`, `from`, `to`. | | `refresh.behind` | array | Other branches with commits of their own still on an older snapshot: `name`, `tip`. | | `refresh.gave_change_ids` | integer | Commits made with plain `git` on the current branch that were given a change id before the rebase (the branch was rewritten); `0` when none needed one. | | `server_branch` | object or omitted | In a snapshot checkout, `grit pull `: the server's branch and what your branch did (fields below). `branch` is then `origin/` and `oid` where your branch is now. | | `server_branch.name` | string | The branch, as the server spells it (which can differ in case from the name you gave, on a server that ignores case). | | `server_branch.upstream_ref` | string | The local ref holding the server's branch as the checkout sees it, `refs/remotes/origin/`. | | `server_branch.tip` | string | Where the server's branch is, on its real history. | | `server_branch.projected` | string | What the checkout sees of it, now at `upstream_ref`. | | `server_branch.commits` | integer | The server branch's commits the target lacks, all shown to the checkout. | | `server_branch.made` | integer | How many of them were made afresh for this checkout. | | `server_branch.reused` | integer | How many were commits that were there already: checkout commits on the same snapshots that the server's are grafts of (your own among them), and what you were shown before. | | `server_branch.previous` | string or null | Where your branch was; null when it was `created`. | | `server_branch.own` | integer | Your commits replayed onto the server's (`rebased`), without the copies of the server's that were left out. | | `server_branch.switched` | boolean | Whether `HEAD` was moved onto the branch to rebase it. | | `server_branch.was_on` | string or null | The branch `HEAD` was on before. | | `server_branch.gave_change_ids` | integer | Commits made with plain `git` on the branch that were given a change id first. | Example: ```json { "result": "fast_forward", "branch": "origin/main", "oid": "b52cca65378cf17309f0b1f917c6dc4fdd9256f2" } ``` A rebase pull that stopped on conflicts: ```json { "result": "conflicts", "branch": "origin/main", "conflicts": ["f"], "conflict_details": [{ "path": "f", "kind": "both_modified" }], "operation": "rebase", "commit": "1e644589243fb885b773ec4d697b779000495741", "next_steps": ["grit diff", "grit add .", "grit rebase --continue"], "alternatives": ["grit rebase --abort", "grit rebase --skip"] } ``` In a snapshot checkout: ```json { "result": "rebased", "branch": "origin/main", "oid": "2b87e20c6d1f0a9e8b7c6d5e4f3a2b1c0d9e8f7a", "refresh": { "target": "main", "upstream_ref": "refs/remotes/origin/main", "base": "3182ed489b694ae64834b5f6648079c4f30c5e64", "snapshot": "39dfeba2cfa4b1d0e9f8a7b6c5d4e3f2a1b0c9d8", "previous_base": "4f06b71eca1af2057ee312b06eecac8f40c15b00", "previous_snapshot": "5c892b5783dbdeb57f7228eb6a13ffb2fa17d832", "moved": true, "changes": { "files": 1, "insertions": 1, "deletions": 1 }, "dry_run": false, "followed": [ { "name": "main", "from": "5c892b5783dbdeb57f7228eb6a13ffb2fa17d832", "to": "39dfeba2cfa4b1d0e9f8a7b6c5d4e3f2a1b0c9d8" } ], "behind": [ { "name": "side", "tip": "8e2d26b0a1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6" } ], "gave_change_ids": 0 } } ``` `grit pull feature` in a snapshot checkout, from another branch: ```json { "result": "rebased", "branch": "origin/feature", "oid": "4c2d9e1b7a6f5e4d3c2b1a0f9e8d7c6b5a4f3e2d", "server_branch": { "name": "feature", "upstream_ref": "refs/remotes/origin/feature", "tip": "bcd6c48a1f2e3d4c5b6a79881726354a5b6c7d8e", "projected": "19a3116f0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b", "commits": 2, "made": 1, "reused": 1, "previous": "8e2d26b0a1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6", "own": 1, "switched": true, "was_on": "alice/elm-orchid", "gave_change_ids": 1 } } ``` With `--check`: ```json { "result": "fast_forward", "branch": "origin/main", "ahead": 0, "behind": 2, "check": { "ahead": 0, "behind": 2, "fast_forward_possible": true, "would": "fast_forward" } } ``` ## Markdown output Pass [`--markdown`](https://grit-scm.com/docs/global-options/index.md) for agent-friendly output. Schema: [v2](https://grit-scm.com/docs/pull/schemas/pull/v2.json/index.md) · [v1](https://grit-scm.com/docs/pull/schemas/pull/v1.json/index.md) Markdown uses headings, bullet lists, and fenced blocks; pipe characters inside table cells are escaped. See the JSON output section for the stable field contract. ```text ## Pull - Fast-forwarded **`origin/main`** → `d0f5bdf` ``` In a snapshot checkout, the refresh comes first, and branches it moved or left behind follow the result: ```text ## Pull - Refresh: **`main`** moved `4f06b71` → `3182ed4` · new snapshot `39dfeba` at `refs/remotes/origin/main` · 1 file changed, 1 insertion(+), 1 deletion(-) in this checkout's paths - Rebased onto **`origin/main`** · `2b87e20` - `main` follows to `39dfeba` - `side` still builds on an older snapshot → `grit switch side`, then `grit pull` ``` `grit pull ` in a snapshot checkout names the server's branch first: ```text ## Pull - Change ids: gave 1 commit made with git a change id - Server branch: **`feature`** at `bcd6c48` · 2 commits on this checkout's snapshots · at `refs/remotes/origin/feature` (`19a3116`) - Rebased **`feature`** onto **`origin/feature`** · `4c2d9e1` · 1 commit of yours on top → `grit checkin feature` sends it - Now on `feature` (was `alice/elm-orchid`) ``` ## Exit status | Code | Meaning | | ---: | --- | | `0` | Success (`up_to_date`, `fast_forward`, `merged`, `rebased`, `set_upstream`, `detached`, `landed`, `created`) or `--check` when fast-forward is possible. | | `1` | Conflicts, refused merge/rebase, a snapshot checkout's rebase stopped in progress (`rebase_stopped`), a refresh refused while a rebase or merge is in progress, `--check` when integration would be required, `autostash_conflict`, or a server branch `grit pull ` can't take (the server has none, or it is already on the target or older than the checkout's first snapshot). | | `2` | Invalid flags ([`usage`](https://grit-scm.com/docs/exit-codes/index.md)). | | `128` | `--ff-only` or `pull.ff=only` when history diverged ([`refused_not_ff`](https://grit-scm.com/docs/exit-codes/index.md)). | | `128` | The fetch could not reach or read the remote ([`remote_unreadable`](https://grit-scm.com/docs/exit-codes/index.md)). | See [Exit codes](https://grit-scm.com/docs/exit-codes/index.md). ## See also [grit fetch](https://grit-scm.com/docs/fetch/index.md), [grit merge](https://grit-scm.com/docs/merge/index.md), [grit push](https://grit-scm.com/docs/push/index.md) # https://grit-scm.com/docs/push/index.md # grit push > Publish branches, tags, or explicit refspecs to a remote. ## Synopsis ```text grit push [] [...] grit push / ... grit push --tags grit push [] --delete ... grit push --dry-run grit push --force-with-lease[=] grit push --force grit push -u [--set-upstream] grit push --atomic grit push -o