# Revwalk

> Resolve revisions, walk history with rev-list, ranges (A..B), ordering, and merge bases.

History walks start from one or more **tips** (resolved ref names or expressions), follow parent links, optionally subtract another set of tips, then sort the result. Everything that needs a repository is a method on [`RevWalk`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html), the handle [`Repository::revwalk`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.revwalk) returns: resolving revisions, listing and counting commits, merge bases and reachability, log decorations and author grouping. The `revwalk::rev_parse` and `revwalk::rev_list` modules keep only the option and result types and pure helpers that parse strings.

## Rev-parse

[`RevWalk::resolve`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.resolve) turns a single spec (`HEAD`, `main`, `v1.0`, `abc1234`, `main^`, `HEAD~3`, `HEAD:path`, `@{-1}`, `:/message`, peel suffixes and more) into an [`ObjectId`](https://docs.rs/grit-lib/latest/grit_lib/objects/struct.ObjectId.html). [`ResolveOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.ResolveOptions.html) says how:

| Field | Values | Effect |
| --- | --- | --- |
| [`peel`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.Peel.html) | `Any` (default), `Commit`, `Tree`, `Blob` | The kind the result is peeled to. The kind also breaks ties when abbreviated hex matches several objects. `Commit` reads `A..B` as `B` and `A...B` as the merge base, like the commit-ish arguments of `log` or `reset`. |
| [`index_dwim`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.IndexDwim.html) | `On` (default), `Off` | Whether a name that matches no ref or object is reported as a possible path (`RevParseError::AmbiguousArgument`) or as a bad revision (`RevParseError::InvalidObjectName`). |
| [`purpose`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.ResolvePurpose.html) | `Revision` (default), `RangeEnd`, `CheckoutNoGuess` | `RangeEnd` makes ambiguous abbreviated hex prefer a commit, as range endpoints and `rev-parse --verify` do. `CheckoutNoGuess` stops a bare name from matching the one remote-tracking branch of that name (`checkout --no-guess`). |

```rust
use grit_lib::revwalk::{IndexDwim, Peel, ResolveOptions, ResolvePurpose};

# fn demo(repo: &grit_lib::repo::Repository) -> grit_lib::error::Result<()> {
let revwalk = repo.revwalk();
// git rev-parse --verify <spec>
let verify = ResolveOptions::default()
    .with_index_dwim(IndexDwim::Off)
    .with_purpose(ResolvePurpose::RangeEnd);
let head = revwalk.resolve("HEAD", &verify)?;
// The commit and the root tree of a tag
let commit = revwalk.resolve("v1.0", &ResolveOptions::default().with_peel(Peel::Commit))?;
let tree = revwalk.resolve("v1.0", &ResolveOptions::default().with_peel(Peel::Tree))?;
# let _ = (head, commit, tree);
# Ok(())
# }
```

The same handle peels ids you already hold ([`peel_to_commit`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.peel_to_commit), [`peel_to_tree`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.peel_to_tree)), names refs ([`symbolic_full_name`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.symbolic_full_name), [`upstream_symbolic_name`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.upstream_symbolic_name) for `@{upstream}` and `@{push}`), and shortens ids ([`abbreviate`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.abbreviate) with an [`AbbrevLength`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.AbbrevLength.html): `core.abbrev` or a minimum length; [`abbrev_matches`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.abbrev_matches) lists every object a prefix names).

Common helpers that do not need a repository:

- [`split_double_dot_range`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_parse/fn.split_double_dot_range.html) — split `main..feature` into two tokens (ignores `...` and path segments).
- [`abbreviate_ref_name`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_parse/fn.abbreviate_ref_name.html) — shorten `refs/heads/main` to `main` for display.

## Listing commits on a repository handle

`RevWalk` has two ways to list commits:

- [`RevWalk::commits`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.commits), [`rev_list_result`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.rev_list_result) and [`count`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.count) take revision **tokens** (`&["main", "^v1.0"]`, `&["main...topic"]`) plus [`RevWalkListOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.RevWalkListOptions.html). This is the API most callers want. Ref selections (`--all`, `--branches`) go in `RevWalkListOptions::refs` and path limits in [`RevWalkListOptions::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.RevWalkListOptions.html#structfield.pathspec) (default [`Pathspec::entire_tree`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html#method.entire_tree)), not in the tokens. Build that value with [`Repository::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/repo/struct.Repository.html#method.pathspec) or [`Pathspec::scoped`](https://docs.rs/grit-lib/latest/grit_lib/worktree/pathspec/struct.Pathspec.html#method.scoped).
- For plain default-order walks (no path limits, filters, or symmetric diff markers), [`RevWalk::commits_stream`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.commits_stream) yields commits lazily with the same tokens and options, optionally retaining raw commit bytes the walk already read (`RevWalkListOptions::retain_commit_data`). Set `RevWalkListOptions::retained_commit_extent` to [`CommitExtent::ThroughSubject`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.CommitExtent.html) when the listing shows only one line per commit (author, dates, change id, subject): the walk then reads each commit only through its subject line instead of inflating its whole message, and the retained bytes are that prefix (see [`Odb::read_commit_through_subject`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.Odb.html#method.read_commit_through_subject)). `grit log` and `grit revs` do this for human and Markdown output; JSON rows carry the full message and keep [`CommitExtent::Whole`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.CommitExtent.html).
- [`RevWalk::walk`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.walk) takes **one** spec (`main`, `^tip`, `A..B` or `A...B`) plus the full engine [`RevListOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html) described below. Options, `--`, and several space-separated tokens fail with `RevListError::UnsupportedWalkSpec`, so use `commits` for those.

Both list the symmetric difference for `A...B`, exactly like `git rev-list A...B`. [`RevWalk::parse_tokens`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.parse_tokens) does the expansion if you call [`RevWalk::rev_list`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.rev_list) yourself.

When expanding symmetric ranges on ordinary histories, endpoint navigation such as
`HEAD~500` shares the parent links and timestamps it parses with the following walk.
Standalone revision resolution does not retain this metadata. Navigation seeds at most 1,024
entries, so resolving a distant ancestor alone does not retain its entire history.
Shallow boundaries, grafts, promisor repositories and replacement objects keep their
existing traversal rules.

## Rev-list

[`RevWalk::rev_list`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.rev_list) takes positive and negative revision specs plus [`RevListOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html). It returns a [`RevListResult`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListResult.html) whose `commits` field is the final oid list (after skip, max-count, and reverse).

For counts, read [`RevListResult::commit_count`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListResult.html#method.commit_count) or use `RevWalk::count`: count-only walks can leave `commits` empty. For an unlimited count with only author, committer or message filters, the walk visits each reachable commit once, matches its borrowed bytes and discards the payload. It retains visited ids rather than parsed commit maps or a sorted list, including when subtracting excluded ancestry; shallow boundaries and grafts still apply.

| Option | Meaning |
| --- | --- |
| [`ordering`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html) | [`OrderingMode`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/enum.OrderingMode.html) — default date order, topo, author-date variants. |
| `first_parent` | Follow only the first parent at merges. |
| `max_count` / `skip` | Limit how many commits are returned. |
| `reverse` | Reverse the selected list after sorting. |
| `commit_filter` | Optional [`CommitFilter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/filter/struct.CommitFilter.html) (`--author`, `--committer`, `--grep`, mailmap). |
| `pickaxe` | Optional [`Pickaxe`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html) (`-S` / `-G` tree-diff filters). |
| `retain_commit_data` | Keep the commits the walk parses in [`RevListResult::commit_data`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListResult.html), so code that prints the listed commits does not read them again. |

With [`RevListOptions::default`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html) and [`OrderingMode::Default`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/enum.OrderingMode.html#variant.Default), every listing path — bounded or unbounded [`max_count`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html#structfield.max_count), [`RevWalk::commits`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.commits), [`RevWalk::walk`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.walk), and [`RevWalk::commits_iter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.commits_iter) — uses the same ungated committer-date priority queue as `git rev-list` (newest committer date first, equal dates broken by tip insertion order). When a limit is set and there are no negative specs, the walk stops as soon as it has enough commits. [`OrderingMode::DateOrderWalk`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/enum.OrderingMode.html#variant.DateOrderWalk) is Git's `--date-order` variant: the same heap with a parent-after-children gate so skewed clocks do not print ancestors before descendants. The default enables the on-disk commit-graph for parent/date lookup when `core.commitGraph` allows it, matching `git rev-list` speed on large histories; set `use_commit_graph: false` to parse every commit object. A repository with a custom primary object store never reads graph files from `objects/`; its walks use the graph attached with [`OdbBuilder::commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/objects/odb/struct.OdbBuilder.html#method.commit_graph) instead, built with [`Maintenance::build_commit_graph`](https://docs.rs/grit-lib/latest/grit_lib/maintenance/struct.Maintenance.html#method.build_commit_graph) (see [Object stores](https://grit-scm.com/docs/library/revwalk/object-stores.md/index.md#commit-graphs-for-a-custom-store)).

To print the listed commits, collect the ref labels once with [`RevWalk::decorations`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.decorations) ([`DecorationOptions`](https://docs.rs/grit-lib/latest/grit_lib/porcelain/log/struct.DecorationOptions.html) picks full or short names, the `--decorate-refs` filter, and optionally only the commits you show), set `retain_commit_data`, and hand `commit_data` to [`RevWalk::load_commits`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.load_commits). It moves out the commits the walk parsed and reads only the rest, such as commits whose parents came from a commit-graph; pass `&mut ()` when you hold none.

Path-limited walks compare the requested entries directly in tree data and reuse packed delta bases. At a merge, ordinary path history follows the first parent whose tree matches the requested paths. Setting `sparse: true` keeps every commit reached along those selected parent links, including merges whose paths match a parent. These rules work with SHA-1 and SHA-256 repositories, with or without commit-graph Bloom filters.

For a range `main..feature`, pass `feature` as a positive spec and `main` as a negative spec (or split with [`split_double_dot_range`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_parse/fn.split_double_dot_range.html) as the example does). A symmetric range `main...feature` needs every merge base, so expand it with `RevWalk::parse_tokens` and copy its `symmetric_left` / `symmetric_right` into the options; `rev_list` rejects a raw `A...B` spec with `RevListError::UnexpandedSymmetricRange`. That matches `git rev-list main..feature`, order included. In default order, with or without `max_count`, a range walk paints both sides down to their common frontier and lists only commits reachable from the positive tips but not from the excluded tips — the same set as `git rev-list`, not the whole history behind `main`. Committer dates order the paint heap but do not define membership; when generations are unavailable the paint may need an extra pass so hide-side commits with skewed dates still mark shared ancestors hidden. An expanded `main...feature` uses that same walk and stops at its merge bases, except with `OrderingMode::Topo` (`--graph`), which sorts the whole symmetric range. `OrderingMode::DateOrderWalk` (`--date-order`) and output filters such as paths or `--left-right` still sort the whole range first.

### Commit filters

[`CommitFilter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/filter/struct.CommitFilter.html) mirrors `git rev-list` / `git log` identity and message filtering. Build one with [`CommitFilterBuilder`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/filter/struct.CommitFilterBuilder.html): author and committer patterns OR together; `--grep` patterns OR together unless `all_match` is set; `invert_grep` negates only the grep group; `-i` applies to all. Patterns default to Git’s POSIX BRE rules (use `fixed_strings` for literal `-F` mode). Load a [`MailmapTable`](https://docs.rs/grit-lib/latest/grit_lib/config/mailmap/struct.MailmapTable.html) with [`repo.config().mailmap()`](https://docs.rs/grit-lib/latest/grit_lib/config/struct.Config.html#method.mailmap) and pass it to the builder — the filter never reads config on its own. Set [`RevListOptions::commit_filter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html) or [`RevWalkListOptions::commit_filter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.RevWalkListOptions.html); filtered commits stay traversable (like `--no-merges`), and `-n` / `--count` apply after filtering.

Bounded default-order filters inflate each visited commit once and reuse those bytes for traversal and matching; only the walk's queued frontier is held at a time. Set `retain_commit_data` when loading log rows: selected matches are returned in `RevListResult::commit_data`, including with a commit-graph, and can be passed to [`RevWalk::load_commits`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.load_commits). Skipped and nonmatching payloads are discarded, so selective filters do not retain every scanned message.

## Pickaxe (`-S` / `-G`)

[`Pickaxe`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html) filters commits by tree diffs against the first parent (Git `log -S` / `-G`). Build with [`Pickaxe::occurrences`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html#method.occurrences) or [`Pickaxe::line_grep`](https://docs.rs/grit-lib/latest/grit_lib/diff/struct.Pickaxe.html#method.line_grep), then set [`RevListOptions::pickaxe`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/rev_list/struct.RevListOptions.html) or [`RevWalkListOptions::pickaxe`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.RevWalkListOptions.html). Evaluation runs after cheap [`CommitFilter`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/filter/struct.CommitFilter.html) checks; [`RevWalkListOptions::pathspec`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.RevWalkListOptions.html#structfield.pathspec) limits which files are diffed.

```rust
//! List commits matching an author pattern via [`CommitFilter`](https://grit-scm.com/docs/library/revwalk/grit_lib::revwalk::CommitFilter/index.md) and [`RevWalk::rev_list`](https://grit-scm.com/docs/library/revwalk/grit_lib::revwalk::RevWalk::rev_list/index.md).
//!
//! Source for the library guide "Revwalk" page (included in the docs site).

use grit_lib::progress::{CancelToken, NullProgress};

use anyhow::Result;
use std::path::Path;
use std::sync::Arc;

use grit_lib::config::environment::RepositoryOptions;
use grit_lib::repo::Repository;
use grit_lib::revwalk::rev_list::RevListOptions;
use grit_lib::revwalk::CommitFilterBuilder;

fn main() -> Result<()> {
    let mut args = std::env::args().skip(1);
    let repo_root = args.next().map(std::path::PathBuf::from).ok_or_else(|| {
        anyhow::anyhow!("usage: log_by_author <repo> <author-pattern> [revision…]".to_owned(),)
    })?;
    let author = args
        .next()
        .ok_or_else(|| anyhow::anyhow!("missing author pattern"))?;
    let tips: Vec<String> = args.collect();
    let tips = if tips.is_empty() {
        vec!["HEAD".to_owned()]
    } else {
        tips
    };

    let repo = open_repo(&repo_root)?;
    let mut builder = CommitFilterBuilder::new().author(author);
    if let Ok(table) = repo.config().mailmap() {
        if !table.is_empty() {
            builder = builder.mailmap(table);
        }
    }
    let filter = Arc::new(builder.build()?);
    let opts = RevListOptions::default().with_commit_filter(Some(filter));
    let result =
        repo.revwalk()
            .rev_list(&tips, &[], &opts, &mut NullProgress, &CancelToken::never())?;
    for oid in &result.commits {
        println!("{oid}");
    }
    Ok(())
}

fn open_repo(root: &Path) -> Result<Repository> {
    Ok(Repository::discover(
        Some(root),
        &RepositoryOptions::from_process(),
    )?)
}
```

## Merge base

[`RevWalk::merge_bases`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.merge_bases) takes the commits and a [`MergeBaseMode`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/enum.MergeBaseMode.html): `Best` is `git merge-base A B...` (the best common ancestor of the first commit and a merge of the rest), `All` is `--all` and `Octopus` is `--octopus`. For diff-style “exactly one base or fail”, use [`merge_base_for_diff`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.merge_base_for_diff).

The other reachability questions are methods too:

| Method | Git equivalent |
| --- | --- |
| [`is_ancestor`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.is_ancestor) | `git merge-base --is-ancestor` |
| [`independent`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.independent) | `git merge-base --independent` |
| [`fork_point`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.fork_point) | `git merge-base --fork-point` (`None` when the upstream's reflog has no fork point) |
| [`ahead_behind`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.ahead_behind) | `git rev-list --left-right --count A...B`, with the newest commits of each side on request ([`AheadBehindOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.AheadBehindOptions.html)) |
| [`reachable_excluding`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.reachable_excluding) | `git rev-list tips ^hide`, bounded and date-cut by [`ReachableWalkOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.ReachableWalkOptions.html) |
| [`count_reachable_excluding`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.count_reachable_excluding) | `git rev-list --count tips ^hide` |

## Describe (nearest tag)

[`RevWalk::describe`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/handle/struct.RevWalk.html#method.describe) picks the reachable tag with the smallest exact range count from the tag’s peeled commit to the target revision ([`DescribeOptions`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.DescribeOptions.html), [`DescribedCommit`](https://docs.rs/grit-lib/latest/grit_lib/revwalk/struct.DescribedCommit.html)). The distance matches `grit revs --count tag..rev`, not necessarily Git’s lazy `git describe` depth. When commit-graph generations are available, one backward walk from the target discovers reachable tags (Git’s internal `describe` model): each commit is visited at most once, within flags propagate to parents, and the walk can stop early when the best candidate’s cone covers the queue. Walk depth picks the winner; the library runs one exact `peeled..rev` count for that tag only (not per candidate). Without a commit-graph, the same exact distances come from a single fixpoint pass over the reachable subgraph (within bits from tag peels, then one sweep)—not a separate rev-list count per tag. With `first_parent`, only the first parent is followed in either path.

## Example

The program below opens a repository (created by system Git in tests), walks `main..feature`, prints each commit oid, then prints the merge base of the range tips:

```rust
//! Walk commit history with [`RevWalk::rev_list`](https://grit-scm.com/docs/library/revwalk/grit_lib::revwalk::RevWalk::rev_list/index.md) and compute a merge base.
//!
//! Source for the library guide "Revwalk" page (included in the docs site).

use grit_lib::progress::{CancelToken, NullProgress};

use anyhow::Result;
use grit_lib::config::environment::RepositoryOptions;
use grit_lib::repo::Repository;
use grit_lib::revwalk::{MergeBaseMode, ResolveOptions};

use grit_lib::revwalk::rev_list::RevListOptions;
use grit_lib::revwalk::rev_parse::split_double_dot_range;
use std::path::Path;

fn main() -> Result<()> {
    let mut args = std::env::args().skip(1);
    let repo_root = args
        .next()
        .map(std::path::PathBuf::from)
        .ok_or_else(|| anyhow::anyhow!("usage: guide_revwalk <repo> [main..feature]"))?;
    let range = args.next().unwrap_or_else(|| "main..feature".to_owned());

    let repo = open_repo(&repo_root)?;
    let options = RevListOptions::default();
    let result = if let Some((left, right)) = split_double_dot_range(&range) {
        let mut positive = Vec::new();
        let mut negative = Vec::new();
        if !right.is_empty() {
            positive.push(right.to_owned());
        }
        if !left.is_empty() {
            negative.push(left.to_owned());
        }
        repo.revwalk().rev_list(
            &positive,
            &negative,
            &options,
            &mut NullProgress,
            &CancelToken::never(),
        )?
    } else {
        repo.revwalk().rev_list(
            std::slice::from_ref(&range),
            &[],
            &options,
            &mut NullProgress,
            &CancelToken::never(),
        )?
    };

    for oid in &result.commits {
        println!("{oid}");
    }

    let (left_name, right_name) = range_names(&range)?;
    let left = repo
        .revwalk()
        .resolve(left_name, &ResolveOptions::default())?;
    let right = repo
        .revwalk()
        .resolve(right_name, &ResolveOptions::default())?;
    let bases = repo
        .revwalk()
        .merge_bases(&[left, right], MergeBaseMode::Best)?;
    let Some(base) = bases.first() else {
        return Err(anyhow::anyhow!("no merge base for range tips".to_owned(),));
    };
    println!("merge_base={base}");

    Ok(())
}

fn open_repo(root: &Path) -> Result<Repository> {
    let git_dir = if root.join(".git").is_dir() {
        root.join(".git")
    } else {
        root.to_path_buf()
    };
    let work_tree = if root.join(".git").is_dir() {
        Some(root)
    } else {
        None
    };
    let mut opts = RepositoryOptions::from_process();
    if let Some(wt) = work_tree {
        opts = opts.with_work_tree(wt);
    }
    Ok(Repository::open(&git_dir, &opts)?)
}

fn range_names(range: &str) -> Result<(&str, &str), anyhow::Error> {
    split_double_dot_range(range)
        .ok_or_else(|| anyhow::anyhow!("expected a double-dot range, got {range:?}"))
}
```

Run against a repo with diverged `main` and `feature` branches:

```bash
cargo run --bin guide_revwalk /path/to/repo main..feature
```

The integration test `guide_revwalk` checks commit order against `git rev-list` and the merge base against `git merge-base`.
