# grit blame

> Show who last modified each line of a file.

## Synopsis

```text
grit blame [<rev>] [--rev <commit>] [--contents <file>] [-L RANGE] [--first-parent]
  [--group] [-w] [-M] [-C]... [--ignore-rev <REV>]... [--ignore-revs-file <FILE>]... [--] <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 (`<rev>` or `--rev`, including `HEAD`) blames that commit's file and ignores the working tree. `--contents <file>` 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 |
| --- | --- |
| `<rev>` | Optional revision before `--` (same values as `--rev`). Without a revision the working-tree file is blamed on top of `HEAD`. |
| `--rev <commit>` | Blame the file as committed at this revision, ignoring the working tree. Cannot be combined with a positional `<rev>`. |
| `--contents <file>` | 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 <REV>` | Treat this commit as transparent while walking history (repeatable). Unknown revisions are an error. |
| `--ignore-revs-file <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.<oid>.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.<oid>.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 (`<oid> <orig> <final> <count>`). 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
