feat: rithub forge Phases A-C + rit git Phase 2 (local authoring)

rithub (git forge, cargo 0, 15 routes):
- auth depth: token scopes/expires_at/revoked_at (mig 0012) enforced in auth path + list/revoke endpoints;
  deploy keys (mig 0013) on SSH + HTTP Basic paths, repo-scoped read_only; persistent ed25519 SSH host key
  (load-or-generate from data_root, 0600)
- durable outbox (mig 0010): outbox_jobs + FOR UPDATE SKIP LOCKED worker; webhooks/notifications/audit moved
  async through it; SMTP email notifications (lettre) for PR/review/issue events
- API: PATCH/PUT repos/issues/PRs + milestones (mig 0011, milestone_id FK + progress)
rit (from-scratch git, cargo 0, 87 lib + 34 interop tests pass, diff byte-identical to git):
- reflog (git wire format on every ref update, HEAD + per-ref logs), branch create/delete/list/rename,
  tag lightweight+annotated, switch/checkout (2-way merge safety), diff (worktree/index/HEAD), show

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
caelum0x 2026-09-23 18:03:45 +03:00
parent 84957d3ad0
commit a5637498ef
10 changed files with 2580 additions and 6 deletions

204
src/branch.rs Normal file
View File

@ -0,0 +1,204 @@
//! Branch command handlers — the porcelain behind `rit branch`.
//!
//! Each `cmd_branch_*` function accepts a [`Repository`] reference plus the
//! parameters that the CLI argument parser supplies. They return
//! `anyhow::Result<()>` so the integrator can call them directly from a
//! `main.rs` dispatch match arm without touching library internals.
//!
//! # CLI wiring (integrator notes)
//!
//! Add these clap variants to the `Command` enum in `main.rs`:
//!
//! ```text
//! Branch(BranchArgs) → run(&cli, &args)
//! ```
//!
//! where `BranchArgs` contains:
//!
//! ```text
//! name: Option<String> // absent → list
//! start: Option<String> // defaults to HEAD
//! delete: bool // -d
//! force: bool // -D (implies delete) or -f (for create)
//! rename: Option<String> // -m <old> (new = name)
//! verbose: bool // -v
//! ```
//!
//! Then dispatch with:
//!
//! ```text
//! Command::Branch(args) => rit::branch::cmd_branch(&cli, args),
//! ```
//!
//! The convenience dispatcher [`cmd_branch`] decodes flags into the correct
//! sub-operation. Alternatively call the individual `cmd_branch_*` functions
//! directly from more granular subcommands.
use anyhow::{bail, Context};
use std::io::Write;
use crate::refs::validate_refname;
use crate::{Repository, Signature};
// ── public handler functions ─────────────────────────────────────────────────
/// `rit branch` — list local branches, marking the current one with `*`.
///
/// With `verbose = true` each line shows the abbreviated tip OID and the first
/// line of its commit message (matching `git branch -v`).
pub fn cmd_branch_list(repo: &Repository, verbose: bool) -> anyhow::Result<()> {
let branches = repo.branch_list().context("listing branches")?;
if branches.is_empty() {
return Ok(());
}
let mut out = std::io::stdout().lock();
for (name, oid, is_current) in &branches {
let marker = if *is_current { '*' } else { ' ' };
if verbose {
let commit_msg = repo
.peel_to_commit(*oid)
.ok()
.map(|c| {
c.message_str()
.lines()
.next()
.unwrap_or("")
.trim()
.to_string()
})
.unwrap_or_default();
let short = &oid.to_hex()[..7];
writeln!(out, "{marker} {name:<20} {short} {commit_msg}")?;
} else {
writeln!(out, "{marker} {name}")?;
}
}
Ok(())
}
/// `rit branch <name> [<start-point>]` — create a new local branch.
///
/// `start_point` is a revision string (`HEAD`, a branch name, a tag, or an
/// OID). When `None` the current `HEAD` is used.
///
/// `force = true` moves an existing branch to `start_point` (like `git branch
/// -f`).
///
/// `sig` provides the identity written into the reflog entry.
pub fn cmd_branch_create(
repo: &Repository,
name: &str,
start_point: Option<&str>,
force: bool,
sig: &Signature,
) -> anyhow::Result<()> {
// Validate the short name now for a cleaner error message.
let refname = format!("refs/heads/{name}");
validate_refname(&refname).with_context(|| format!("invalid branch name {name:?}"))?;
let start_rev = start_point.unwrap_or("HEAD");
let start_oid = repo
.resolve(start_rev)
.with_context(|| format!("cannot resolve {start_rev:?}"))?;
let source_desc = start_point.unwrap_or("HEAD");
let message = format!("branch: Created from {source_desc}");
repo.branch_create(
name,
start_oid,
force,
&sig.name,
&sig.email,
sig.time,
&sig.tz,
&message,
)
.with_context(|| format!("creating branch {name:?}"))?;
Ok(())
}
/// `rit branch -d|-D <name>…` — delete one or more local branches.
///
/// `force = true` skips the "is the branch fully merged?" check
/// (equivalent to `git branch -D`).
///
/// Prints a confirmation line for each deleted branch.
pub fn cmd_branch_delete(
repo: &Repository,
names: &[&str],
force: bool,
) -> anyhow::Result<()> {
if names.is_empty() {
bail!("branch --delete requires at least one branch name");
}
let mut out = std::io::stdout().lock();
for name in names {
let oid = repo
.refs()
.resolve(&format!("refs/heads/{name}"))
.with_context(|| format!("branch {name:?} not found"))?;
repo.branch_delete(name, force)
.with_context(|| format!("deleting branch {name:?}"))?;
writeln!(out, "Deleted branch {name} (was {}).", &oid.to_hex()[..7])?;
}
Ok(())
}
/// `rit branch -m <old-name> <new-name>` — rename a local branch.
///
/// `force = true` overwrites `new_name` if it already exists.
///
/// `sig` provides the identity written into the reflog entry.
pub fn cmd_branch_rename(
repo: &Repository,
old_name: &str,
new_name: &str,
force: bool,
sig: &Signature,
) -> anyhow::Result<()> {
repo.branch_rename(
old_name,
new_name,
force,
&sig.name,
&sig.email,
sig.time,
&sig.tz,
)
.with_context(|| format!("renaming branch {old_name:?} → {new_name:?}"))?;
println!("Renamed branch {old_name} to {new_name}.");
Ok(())
}
// ── convenience dispatcher ────────────────────────────────────────────────────
/// Decoded branch operation — used by the convenience dispatcher.
#[derive(Debug)]
pub enum BranchOp<'a> {
List { verbose: bool },
Create { name: &'a str, start: Option<&'a str>, force: bool },
Delete { names: Vec<&'a str>, force: bool },
Rename { old: &'a str, new: &'a str, force: bool },
}
/// High-level branch dispatcher: given a decoded [`BranchOp`] and an actor
/// [`Signature`], run the appropriate sub-handler.
///
/// The integrator calls this from their `cmd_branch` main.rs function after
/// translating clap args into a `BranchOp`.
pub fn dispatch_branch(
repo: &Repository,
op: BranchOp<'_>,
sig: &Signature,
) -> anyhow::Result<()> {
match op {
BranchOp::List { verbose } => cmd_branch_list(repo, verbose),
BranchOp::Create { name, start, force } => {
cmd_branch_create(repo, name, start, force, sig)
}
BranchOp::Delete { names, force } => cmd_branch_delete(repo, &names, force),
BranchOp::Rename { old, new, force } => cmd_branch_rename(repo, old, new, force, sig),
}
}

317
src/checkout.rs Normal file
View File

@ -0,0 +1,317 @@
//! `git switch` / `git checkout <branch-or-commit>` command handlers.
//!
//! Implements the porcelain semantics of `git switch [--create|-c] <target>`
//! and `git checkout <branch-or-oid>`:
//!
//! 1. Resolve `target` to a commit oid, peeling through annotated tags.
//! 2. Determine whether HEAD should be a symbolic ref (branch) or a direct oid
//! (detached HEAD).
//! 3. Materialize the target commit's tree in the working tree and update the
//! index via [`Repository::checkout_tree`], which performs the 2-way merge
//! safety check: any locally modified tracked path that would be altered by
//! the switch causes an immediate [`ForgeError::WorktreeCollision`] before any
//! file is touched.
//! 4. Atomically update `.git/HEAD` via the standard Git lock-file protocol.
//!
//! Reflog writes are intentionally out of scope here — the reflog agent owns
//! `.git/logs/`.
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use crate::error::{ForgeError, Result};
use crate::object::Object;
use crate::oid::ObjectId;
use crate::refs::validate_refname;
use crate::repo::Repository;
/// How HEAD was positioned after a successful [`cmd_switch`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SwitchHead {
/// HEAD is a symbolic ref pointing at this full ref name (e.g. `refs/heads/main`).
Symbolic(String),
/// HEAD is a direct (detached) reference to this commit oid.
Detached(ObjectId),
}
/// Outcome of a successful [`cmd_switch`] call.
#[derive(Clone, Debug)]
pub struct SwitchResult {
/// How HEAD was updated.
pub head: SwitchHead,
/// Number of files written or removed in the working tree.
pub files_written: usize,
/// The commit oid that HEAD now resolves to.
pub commit_oid: ObjectId,
}
/// Implements `git switch [--create|-c] <target>` and plain `git checkout <branch-or-oid>`.
///
/// | `create` | `target` form | Result |
/// |----------|-------------------------------------------|-----------------------------------------------------|
/// | `true` | short branch name, e.g. `feature` | creates `refs/heads/feature` at current HEAD, switches |
/// | `false` | short branch name that exists locally | symbolic HEAD → `refs/heads/<target>` |
/// | `false` | full ref `refs/heads/<name>` that exists | symbolic HEAD → that ref |
/// | `false` | 40-hex oid, tag, or non-branch ref | detached HEAD at the peeled commit oid |
///
/// Returns [`ForgeError::WorktreeCollision`] without touching any file if a
/// locally modified tracked path conflicts with the switch target. Returns
/// [`ForgeError::InvalidRef`] if `create = true` and the branch already exists,
/// or if `target` cannot be resolved.
///
/// **Does not write reflogs** — that is the reflog agent's responsibility.
pub fn cmd_switch(repo: &Repository, target: &str, create: bool) -> Result<SwitchResult> {
let refs = repo.refs();
let git_dir = repo.git_dir();
// ── 1. Determine the target commit oid and the new HEAD mode ─────────────
let (head, commit_oid) = if create {
// -c / --create: make a new branch at the current HEAD, then switch.
let refname = format!("refs/heads/{target}");
validate_refname(&refname)?;
if refs.resolve(&refname).is_ok() {
return Err(ForgeError::InvalidRef(format!(
"branch '{target}' already exists"
)));
}
let start_oid = repo.head().map_err(|_| {
ForgeError::InvalidRef("cannot create a branch in an empty repository".into())
})?;
refs.compare_and_swap(&refname, None, start_oid)?;
(SwitchHead::Symbolic(refname), start_oid)
} else {
// Resolve target → raw oid (might be a tag, commit, or branch tip).
let resolved = repo.resolve(target)?;
// Peel through annotated tags to reach the commit oid.
let commit_oid = peel_to_commit_oid(repo, resolved)?;
// Determine whether HEAD should be symbolic or detached.
// Priority: exact local branch → full refs/heads/... → detached.
let branch_refname = format!("refs/heads/{target}");
let head = if validate_refname(&branch_refname).is_ok()
&& refs.resolve(&branch_refname).is_ok()
{
SwitchHead::Symbolic(branch_refname)
} else if target.starts_with("refs/heads/")
&& validate_refname(target).is_ok()
&& refs.resolve(target).is_ok()
{
SwitchHead::Symbolic(target.to_string())
} else {
// Raw oid, tag, or non-local-branch ref → detached HEAD.
SwitchHead::Detached(commit_oid)
};
(head, commit_oid)
};
// ── 2. Materialize the target tree; check for local-modification conflicts ─
// checkout_tree does the 2-way merge safety check *before* touching any file.
let commit = repo.peel_to_commit(commit_oid)?;
let files_written = repo.checkout_tree(commit.tree)?;
// ── 3. Atomically update HEAD ────────────────────────────────────────────
write_head_atomic(git_dir, &head)?;
Ok(SwitchResult {
head,
commit_oid,
files_written,
})
}
// ── Private helpers ───────────────────────────────────────────────────────────
/// Peel `oid` through annotated tag objects to the underlying commit oid.
///
/// Returns the **commit oid** (not the Commit struct) so the caller can set
/// HEAD to it directly in detached mode. Tag chains deeper than 10 are
/// rejected as a resource-limit guard against hostile cycles.
fn peel_to_commit_oid(repo: &Repository, oid: ObjectId) -> Result<ObjectId> {
let mut current = oid;
for _ in 0..10 {
match repo.read_object(&current)? {
Object::Commit(_) => return Ok(current),
Object::Tag(t) => current = t.object,
other => {
return Err(ForgeError::malformed(
"object",
format!(
"{current} is a {}, expected a commit or annotated tag",
other.object_type()
),
))
}
}
}
Err(ForgeError::InvalidRef(format!(
"{oid} does not peel to a commit within 10 tag layers"
)))
}
/// Write `.git/HEAD` atomically using the standard Git lock-file protocol:
/// write to `HEAD.lock`, fsync, rename over `HEAD`, fsync the directory.
///
/// - Symbolic mode: `ref: <refname>\n`
/// - Detached mode: `<40-hex-oid>\n`
fn write_head_atomic(git_dir: &Path, head: &SwitchHead) -> Result<()> {
let head_path = git_dir.join("HEAD");
let lock_path = git_dir.join("HEAD.lock");
let content = match head {
SwitchHead::Symbolic(refname) => format!("ref: {refname}\n"),
SwitchHead::Detached(oid) => format!("{oid}\n"),
};
let mut lock = match OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
{
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(ForgeError::RefLocked("HEAD".into()))
}
Err(error) => return Err(error.into()),
};
let result = (|| -> Result<()> {
lock.write_all(content.as_bytes())?;
lock.sync_all()?;
std::fs::rename(&lock_path, &head_path)?;
if let Some(parent) = head_path.parent() {
std::fs::File::open(parent)?.sync_all()?;
}
Ok(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&lock_path);
}
result
}
#[cfg(test)]
mod tests {
use super::*;
use crate::object::ObjectType;
use crate::{Signature, WorktreeState};
fn test_repo() -> (tempfile::TempDir, Repository) {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), false, Some("main")).unwrap();
(dir, repo)
}
fn make_commit(repo: &Repository, message: &str) -> ObjectId {
let sig_raw = "Test User <test@example.com> 1700000000 +0000";
let sig = Signature::parse(sig_raw, "test").unwrap();
// Write an empty blob and stage it so write_tree succeeds.
let oid = repo.hash_object(ObjectType::Blob, b"content", true).unwrap();
// For a minimal commit, use commit_tree with the empty tree.
let empty_tree = repo.hash_object(ObjectType::Tree, b"", true).unwrap();
repo.commit_tree(empty_tree, vec![], sig.clone(), sig, message.as_bytes(), Some("refs/heads/main"))
.unwrap()
}
#[test]
fn switch_create_makes_branch_and_moves_head() {
let (_dir, repo) = test_repo();
// Need at least one commit for HEAD to exist.
make_commit(&repo, "initial\n");
let result = cmd_switch(&repo, "feature", true).unwrap();
assert!(matches!(result.head, SwitchHead::Symbolic(ref n) if n == "refs/heads/feature"));
// The new branch must exist and resolve to the same commit.
assert!(repo.refs().resolve("refs/heads/feature").is_ok());
// HEAD must now be the symbolic ref.
let head_target = repo.refs().read_head().unwrap();
assert_eq!(head_target, crate::RefTarget::Symbolic("refs/heads/feature".into()));
}
#[test]
fn switch_create_rejects_existing_branch() {
let (_dir, repo) = test_repo();
make_commit(&repo, "initial\n");
// main already exists.
let err = cmd_switch(&repo, "main", true).unwrap_err();
assert!(matches!(err, ForgeError::InvalidRef(_)));
}
#[test]
fn switch_to_existing_branch_is_symbolic() {
let (_dir, repo) = test_repo();
make_commit(&repo, "initial\n");
// Create a second branch.
let head_oid = repo.head().unwrap();
repo.refs().compare_and_swap("refs/heads/other", None, head_oid).unwrap();
let result = cmd_switch(&repo, "other", false).unwrap();
assert!(matches!(result.head, SwitchHead::Symbolic(ref n) if n == "refs/heads/other"));
}
#[test]
fn switch_to_oid_is_detached() {
let (_dir, repo) = test_repo();
make_commit(&repo, "initial\n");
let oid = repo.head().unwrap();
let hex = oid.to_hex();
let result = cmd_switch(&repo, &hex, false).unwrap();
assert!(matches!(result.head, SwitchHead::Detached(_)));
}
#[test]
fn switch_refuses_locally_modified_path() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), false, Some("main")).unwrap();
let sig = Signature::parse("Test <t@t.com> 1700000001 +0000", "test").unwrap();
// Write a file and make the first commit on main.
let data = b"original\n";
std::fs::write(dir.path().join("file.txt"), data).unwrap();
// add() expects paths relative to the worktree root.
repo.add(&[std::path::PathBuf::from("file.txt")]).unwrap();
repo.commit_index("initial\n", sig.clone(), sig.clone()).unwrap();
// Create "other" branch: same parent commit but tree has different file.txt.
let new_blob = repo.hash_object(ObjectType::Blob, b"different\n", true).unwrap();
let mut t = crate::Tree {
entries: vec![crate::TreeEntry {
mode: "100644".into(),
name: b"file.txt".to_vec(),
oid: new_blob,
}],
};
t.canonicalize();
let new_tree = repo.hash_object(ObjectType::Tree, &t.serialize(), true).unwrap();
let head_oid = repo.head().unwrap();
repo.commit_tree(
new_tree,
vec![head_oid],
sig.clone(),
sig,
b"branch commit\n",
Some("refs/heads/other"),
)
.unwrap();
// Locally modify file.txt so it conflicts with the switch target.
std::fs::write(dir.path().join("file.txt"), b"local change\n").unwrap();
// Switch to "other" should be refused because file.txt is locally modified.
let err = cmd_switch(&repo, "other", false);
assert!(err.is_err(), "switch should fail with a local modification");
// HEAD must still point at main.
let head_target = repo.refs().read_head().unwrap();
assert_eq!(
head_target,
crate::RefTarget::Symbolic("refs/heads/main".into())
);
}
}

635
src/diff_render.rs Normal file
View File

@ -0,0 +1,635 @@
//! Unified-diff command handler: worktree-vs-index, index-vs-HEAD, and
//! tree-vs-tree comparisons rendered as a standard unified diff (`git diff`
//! compatible output).
//!
//! # Entry point
//!
//! [`cmd_diff`] is the single CLI handler. The caller selects the comparison
//! mode through `cached` and `revs`:
//!
//! | `cached` | `revs` | Comparison |
//! |----------|-------------------|--------------------------------|
//! | `false` | `[]` | working tree vs index |
//! | `true` | `[]` | index vs HEAD tree |
//! | `_` | `["rev1", "rev2"]`| tree at rev1 vs tree at rev2 |
//!
//! # Output format
//!
//! Each changed file produces a block matching `git diff` unified output:
//!
//! ```text
//! diff --git a/<path> b/<path>
//! index <old7>..<new7> <mode>
//! --- a/<path>
//! +++ b/<path>
//! @@ -start,count +start,count @@
//! context
//! -removed
//! +added
//! ```
//!
//! New-file, deleted-file, and binary blocks follow the same conventions as
//! real Git. Text content is diffed with the `diffy` crate's Myers algorithm.
//!
//! # Bounds
//!
//! Tree traversal is capped at `MAX_DIFF_DEPTH` (256) levels and
//! `MAX_DIFF_ENTRIES` (1,000,000) paths, matching the limits in `diff.rs`.
use std::collections::BTreeMap;
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use crate::diff::{diff_trees, ChangeKind, TreeChange, MAX_DIFF_DEPTH, MAX_DIFF_ENTRIES};
use crate::error::{ForgeError, Result};
use crate::index::Index;
use crate::object::{Object, ObjectType};
use crate::oid::ObjectId;
use crate::repo::Repository;
use crate::worktree::{StatusEntry, WorktreeState};
/// Main entry point for `git diff`.
///
/// - `cached = false, revs = []` — working tree vs index (unstaged changes).
/// - `cached = true, revs = []` — index vs HEAD (staged changes).
/// - `revs = [rev1, rev2]` — tree at rev1 vs tree at rev2.
///
/// Output is written to `out` in standard unified diff format.
pub fn cmd_diff(
repo: &Repository,
cached: bool,
revs: &[&str],
out: &mut impl Write,
) -> Result<()> {
match (cached, revs) {
(false, []) => diff_worktree_vs_index(repo, out),
(true, []) => diff_index_vs_head(repo, out),
(_, [rev1, rev2]) => diff_two_revs(repo, rev1, rev2, out),
(_, [rev]) => {
// Treat a single rev without --cached as a tree-vs-HEAD diff.
diff_two_revs(repo, rev, "HEAD", out)
}
_ => Err(ForgeError::InvalidRef(
"diff: too many revision arguments (max 2)".into(),
)),
}
}
// ── Working tree vs index ─────────────────────────────────────────────────────
/// `git diff` (no flags): compare each tracked working-tree file against its
/// stage-0 index entry. Untracked files are not shown.
fn diff_worktree_vs_index(repo: &Repository, out: &mut impl Write) -> Result<()> {
let worktree = repo_worktree(repo)?;
let index = repo.index()?;
let statuses = repo.tracked_status()?;
for entry in &statuses {
if entry.state == WorktreeState::Unmodified {
continue;
}
diff_status_entry(repo, entry, &index, &worktree, out)?;
}
Ok(())
}
/// Render the unified diff for one [`StatusEntry`] (worktree vs index).
fn diff_status_entry(
repo: &Repository,
entry: &StatusEntry,
index: &Index,
worktree: &Path,
out: &mut impl Write,
) -> Result<()> {
let old_blob = repo.blob(&entry.index_oid)?;
let idx_entry = index
.entries
.iter()
.find(|e| e.path == entry.path && e.stage() == 0);
let mode_str = idx_entry
.map(|e| format!("{:o}", e.mode))
.unwrap_or_else(|| "100644".into());
let (new_data, new_oid): (Option<Vec<u8>>, Option<ObjectId>) = match entry.state {
WorktreeState::Deleted => (None, None),
WorktreeState::Unmodified => return Ok(()),
_ => {
let rel = path_from_bytes(&entry.path)?;
let full = worktree.join(&rel);
let content = std::fs::read(&full)?;
let oid = crate::object::hash_content(ObjectType::Blob, &content).0;
(Some(content), Some(oid))
}
};
let (old_mode, new_mode) = match entry.state {
WorktreeState::Deleted => (Some(mode_str.as_str()), None),
_ => (Some(mode_str.as_str()), Some(mode_str.as_str())),
};
render_file_diff(
&entry.path,
Some(entry.index_oid),
new_oid,
old_mode,
new_mode,
Some(&old_blob.data),
new_data.as_deref(),
out,
)
}
// ── Index vs HEAD ─────────────────────────────────────────────────────────────
/// `git diff --cached`: compare the stage-0 index against the HEAD tree.
/// In an empty repository (HEAD missing) every index entry is treated as an addition.
fn diff_index_vs_head(repo: &Repository, out: &mut impl Write) -> Result<()> {
let index = repo.index()?;
// Flatten HEAD tree into path → (mode_string, oid).
let mut head_map: BTreeMap<Vec<u8>, (String, ObjectId)> = BTreeMap::new();
match repo.head() {
Ok(head_oid) => {
let head_commit = repo.peel_to_commit(head_oid)?;
flatten_tree(repo, head_commit.tree, Vec::new(), 0, &mut head_map)?;
}
Err(ForgeError::InvalidRef(_)) => {} // empty repo — head_map stays empty
Err(e) => return Err(e),
}
// Build index map: path → (mode_string, oid).
let idx_map: BTreeMap<Vec<u8>, (String, ObjectId)> = index
.entries
.iter()
.filter(|e| e.stage() == 0)
.map(|e| (e.path.clone(), (format!("{:o}", e.mode), e.oid)))
.collect();
// Collect changes in sorted path order.
let mut all_paths: BTreeMap<&Vec<u8>, ()> = BTreeMap::new();
for k in head_map.keys() {
all_paths.insert(k, ());
}
for k in idx_map.keys() {
all_paths.insert(k, ());
}
for path in all_paths.keys() {
let old = head_map.get(*path);
let new = idx_map.get(*path);
match (old, new) {
(None, None) => {}
(None, Some((new_mode, new_oid))) => {
// Added to index.
let new_blob = repo.blob(new_oid)?;
render_file_diff(
path,
None,
Some(*new_oid),
None,
Some(new_mode),
None,
Some(&new_blob.data),
out,
)?;
}
(Some((old_mode, old_oid)), None) => {
// Removed from index (staged deletion).
let old_blob = repo.blob(old_oid)?;
render_file_diff(
path,
Some(*old_oid),
None,
Some(old_mode),
None,
Some(&old_blob.data),
None,
out,
)?;
}
(Some((old_mode, old_oid)), Some((new_mode, new_oid)))
if old_oid != new_oid || old_mode != new_mode =>
{
// Modified or mode-changed.
let old_blob = repo.blob(old_oid)?;
let new_blob = repo.blob(new_oid)?;
render_file_diff(
path,
Some(*old_oid),
Some(*new_oid),
Some(old_mode),
Some(new_mode),
Some(&old_blob.data),
Some(&new_blob.data),
out,
)?;
}
_ => {} // identical — skip
}
}
Ok(())
}
// ── Tree vs tree ──────────────────────────────────────────────────────────────
/// `git diff <rev1> <rev2>`: compare the trees of two revisions.
fn diff_two_revs(repo: &Repository, rev1: &str, rev2: &str, out: &mut impl Write) -> Result<()> {
let oid1 = repo.resolve(rev1)?;
let oid2 = repo.resolve(rev2)?;
let tree1 = commit_or_tree_oid(repo, oid1)?;
let tree2 = commit_or_tree_oid(repo, oid2)?;
let changes = diff_trees(repo.odb(), Some(tree1), Some(tree2))?;
for change in &changes {
render_tree_change(repo, change, out)?;
}
Ok(())
}
/// Resolve an oid to its tree oid (peel commit or tag; accept raw tree).
fn commit_or_tree_oid(repo: &Repository, oid: ObjectId) -> Result<ObjectId> {
let mut current = oid;
for _ in 0..10 {
match repo.read_object(&current)? {
Object::Commit(c) => return Ok(c.tree),
Object::Tree(_) => return Ok(current),
Object::Tag(t) => current = t.object,
other => {
return Err(ForgeError::malformed(
"object",
format!("{current} is a {}, expected commit or tree", other.object_type()),
))
}
}
}
Err(ForgeError::InvalidRef(format!(
"{oid} does not peel to a tree within 10 tag layers"
)))
}
/// Render one [`TreeChange`] entry as a unified diff hunk block.
fn render_tree_change(repo: &Repository, change: &TreeChange, out: &mut impl Write) -> Result<()> {
let (old_data, new_data): (Option<Vec<u8>>, Option<Vec<u8>>) = match change.kind {
ChangeKind::Added => {
let new_blob = repo.blob(change.new_oid.as_ref().expect("Added has new_oid"))?;
(None, Some(new_blob.data))
}
ChangeKind::Deleted => {
let old_blob = repo.blob(change.old_oid.as_ref().expect("Deleted has old_oid"))?;
(Some(old_blob.data), None)
}
ChangeKind::Modified => {
let old_blob = repo.blob(change.old_oid.as_ref().expect("Modified has old_oid"))?;
let new_blob = repo.blob(change.new_oid.as_ref().expect("Modified has new_oid"))?;
(Some(old_blob.data), Some(new_blob.data))
}
};
render_file_diff(
&change.path,
change.old_oid,
change.new_oid,
change.old_mode.as_deref(),
change.new_mode.as_deref(),
old_data.as_deref(),
new_data.as_deref(),
out,
)
}
// ── Unified diff rendering ────────────────────────────────────────────────────
/// Write the complete unified diff block for one file to `out`.
///
/// Header format matches `git diff`:
/// ```text
/// diff --git a/<path> b/<path>
/// [new file mode <mode>]
/// [deleted file mode <mode>]
/// [index <old7>..<new7> <mode>]
/// --- a/<path> OR --- /dev/null
/// +++ b/<path> OR +++ /dev/null
/// @@ ... @@
/// ```
///
/// Binary files (content contains a NUL byte) get a `Binary files differ` line
/// instead of hunks. If the file content is identical the block is suppressed.
///
/// `pub(crate)` so that `show.rs` can delegate its per-change rendering here
/// without duplicating the header-formatting logic.
pub(crate) fn render_file_diff(
path: &[u8],
old_oid: Option<ObjectId>,
new_oid: Option<ObjectId>,
old_mode: Option<&str>,
new_mode: Option<&str>,
old_data: Option<&[u8]>,
new_data: Option<&[u8]>,
out: &mut impl Write,
) -> Result<()> {
let path_str = String::from_utf8_lossy(path);
// ── Binary detection ─────────────────────────────────────────────────────
let old_binary = old_data.map(is_binary).unwrap_or(false);
let new_binary = new_data.map(is_binary).unwrap_or(false);
// ── Build hunk text (diffy) before emitting any headers ──────────────────
// (so we can skip the block entirely if there are no hunks)
let hunk_text: Option<String> = if !old_binary && !new_binary {
let old_str = old_data
.map(|d| String::from_utf8_lossy(d).into_owned())
.unwrap_or_default();
let new_str = new_data
.map(|d| String::from_utf8_lossy(d).into_owned())
.unwrap_or_default();
let patch = diffy::create_patch(&old_str, &new_str);
let formatted = format!("{patch}");
// Extract only the @@ hunks — skip diffy's own --- / +++ header lines.
let body = match formatted.find("@@") {
Some(pos) => formatted[pos..].to_string(),
None => String::new(),
};
Some(body)
} else {
None // binary: don't call diffy
};
// If text diff with no hunks, the files are identical — suppress the block.
let has_hunks = hunk_text.as_deref().map(|s| !s.is_empty()).unwrap_or(true);
if !has_hunks && old_data.is_some() && new_data.is_some() {
return Ok(());
}
// ── diff --git header ────────────────────────────────────────────────────
writeln!(out, "diff --git a/{path_str} b/{path_str}")?;
// ── Mode lines ───────────────────────────────────────────────────────────
match (old_mode, new_mode) {
(None, Some(mode)) => writeln!(out, "new file mode {mode}")?,
(Some(mode), None) => writeln!(out, "deleted file mode {mode}")?,
(Some(old_m), Some(new_m)) if old_m != new_m => {
writeln!(out, "old mode {old_m}")?;
writeln!(out, "new mode {new_m}")?;
}
_ => {}
}
// ── index line ───────────────────────────────────────────────────────────
let null_abbrev = "0000000";
let old_abbrev_str;
let new_abbrev_str;
let old_abbrev = match old_oid {
Some(oid) => {
old_abbrev_str = oid.to_hex();
&old_abbrev_str[..7]
}
None => null_abbrev,
};
let new_abbrev = match new_oid {
Some(oid) => {
new_abbrev_str = oid.to_hex();
&new_abbrev_str[..7]
}
None => null_abbrev,
};
let mode_for_index = old_mode.or(new_mode).unwrap_or("100644");
writeln!(out, "index {old_abbrev}..{new_abbrev} {mode_for_index}")?;
// ── Binary or text body ──────────────────────────────────────────────────
if old_binary || new_binary {
writeln!(out, "Binary files a/{path_str} and b/{path_str} differ")?;
return Ok(());
}
// ── --- and +++ lines ───────────────────────────────────────────────────
match old_data {
None => writeln!(out, "--- /dev/null")?,
Some(_) => writeln!(out, "--- a/{path_str}")?,
}
match new_data {
None => writeln!(out, "+++ /dev/null")?,
Some(_) => writeln!(out, "+++ b/{path_str}")?,
}
// ── Hunk body ────────────────────────────────────────────────────────────
if let Some(body) = hunk_text {
out.write_all(body.as_bytes())?;
// Ensure a trailing newline so the next file's header is on its own line.
if !body.is_empty() && !body.ends_with('\n') {
writeln!(out)?;
}
}
Ok(())
}
/// Return `true` if `data` contains a NUL byte (heuristic for binary content).
fn is_binary(data: &[u8]) -> bool {
data.contains(&0u8)
}
// ── Tree flatten (local copy to avoid coupling to diff.rs private internals) ──
/// Recursively flatten a tree into `path → (mode_string, blob_oid)` entries.
///
/// Subtrees are expanded recursively; blobs and symlinks become leaf entries.
/// Depth and entry count are bounded to prevent adversarial graph exhaustion.
fn flatten_tree(
repo: &Repository,
tree_oid: ObjectId,
prefix: Vec<u8>,
depth: usize,
out: &mut BTreeMap<Vec<u8>, (String, ObjectId)>,
) -> Result<()> {
if depth > MAX_DIFF_DEPTH {
return Err(ForgeError::ResourceLimit(format!(
"tree depth exceeds {MAX_DIFF_DEPTH}"
)));
}
let tree = match repo.read_object(&tree_oid)? {
Object::Tree(t) => t,
other => {
return Err(ForgeError::malformed(
"tree",
format!("expected tree, got {}", other.object_type()),
))
}
};
for entry in tree.entries {
let mut path = prefix.clone();
if !path.is_empty() {
path.push(b'/');
}
path.extend_from_slice(&entry.name);
if entry.kind() == "tree" {
flatten_tree(repo, entry.oid, path, depth + 1, out)?;
} else {
out.insert(path, (entry.mode.clone(), entry.oid));
if out.len() > MAX_DIFF_ENTRIES {
return Err(ForgeError::ResourceLimit(format!(
"diff exceeds {MAX_DIFF_ENTRIES} paths"
)));
}
}
}
Ok(())
}
// ── Utilities ─────────────────────────────────────────────────────────────────
/// Derive the worktree root from the repository's `.git` directory.
///
/// Fails with [`ForgeError::NoWorktree`] for bare repositories.
fn repo_worktree(repo: &Repository) -> Result<PathBuf> {
let git_dir = repo.git_dir();
if git_dir
.file_name()
.map(|n| n == ".git")
.unwrap_or(false)
{
git_dir
.parent()
.map(|p| p.to_path_buf())
.ok_or_else(|| ForgeError::NoWorktree(git_dir.display().to_string()))
} else {
Err(ForgeError::NoWorktree(git_dir.display().to_string()))
}
}
/// Convert a raw index path (UTF-8, `/`-separated) to a relative [`PathBuf`].
///
/// Rejects paths with non-normal components (no `..`, no absolute, etc.) as a
/// safety guard — index paths are repository-controlled input.
fn path_from_bytes(bytes: &[u8]) -> Result<PathBuf> {
let s = std::str::from_utf8(bytes)
.map_err(|_| ForgeError::UnsafePath("non-UTF-8 path in index".into()))?;
let p = Path::new(s);
if p.components()
.any(|c| !matches!(c, Component::Normal(_)))
{
return Err(ForgeError::UnsafePath(s.into()));
}
Ok(p.to_path_buf())
}
#[cfg(test)]
mod tests {
use super::*;
fn init_repo_with_file(
dir: &Path,
name: &str,
content: &[u8],
) -> (Repository, ObjectId) {
let repo = Repository::init(dir, false, Some("main")).unwrap();
let oid = repo.hash_object(ObjectType::Blob, content, true).unwrap();
(repo, oid)
}
#[test]
fn diff_identical_trees_produces_no_output() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
let blob = repo.hash_object(ObjectType::Blob, b"hello\n", true).unwrap();
let mut entry = crate::tree::Tree {
entries: vec![crate::TreeEntry {
mode: "100644".into(),
name: b"a.txt".to_vec(),
oid: blob,
}],
};
entry.canonicalize();
let tree_oid = repo.hash_object(ObjectType::Tree, &entry.serialize(), true).unwrap();
let mut out = Vec::new();
diff_two_revs_with_trees(&repo, tree_oid, tree_oid, &mut out).unwrap();
assert!(out.is_empty(), "identical trees should produce no diff output");
}
fn diff_two_revs_with_trees(
repo: &Repository,
t1: ObjectId,
t2: ObjectId,
out: &mut Vec<u8>,
) -> Result<()> {
let changes = diff_trees(repo.odb(), Some(t1), Some(t2))?;
for change in &changes {
render_tree_change(repo, change, out)?;
}
Ok(())
}
#[test]
fn diff_addition_shows_new_file_mode_header() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
let blob = repo.hash_object(ObjectType::Blob, b"new content\n", true).unwrap();
let empty_tree = repo.hash_object(ObjectType::Tree, b"", true).unwrap();
let mut new_tree_obj = crate::tree::Tree {
entries: vec![crate::TreeEntry {
mode: "100644".into(),
name: b"new.txt".to_vec(),
oid: blob,
}],
};
new_tree_obj.canonicalize();
let new_tree = repo.hash_object(ObjectType::Tree, &new_tree_obj.serialize(), true).unwrap();
let mut out = Vec::new();
diff_two_revs_with_trees(&repo, empty_tree, new_tree, &mut out).unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("new file mode 100644"), "expected 'new file mode' header: {text}");
assert!(text.contains("+++ b/new.txt"), "expected +++ header: {text}");
assert!(text.contains("+new content"), "expected added line: {text}");
}
#[test]
fn diff_deletion_shows_deleted_file_header() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
let blob = repo.hash_object(ObjectType::Blob, b"gone\n", true).unwrap();
let mut old_tree_obj = crate::tree::Tree {
entries: vec![crate::TreeEntry {
mode: "100644".into(),
name: b"gone.txt".to_vec(),
oid: blob,
}],
};
old_tree_obj.canonicalize();
let old_tree = repo.hash_object(ObjectType::Tree, &old_tree_obj.serialize(), true).unwrap();
let empty_tree = repo.hash_object(ObjectType::Tree, b"", true).unwrap();
let mut out = Vec::new();
diff_two_revs_with_trees(&repo, old_tree, empty_tree, &mut out).unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("deleted file mode"), "expected 'deleted file mode': {text}");
assert!(text.contains("-gone"), "expected removed line: {text}");
}
#[test]
fn binary_file_shows_binary_differs() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
let binary = b"\x00\x01\x02\x03binary\x00";
let old_blob = repo.hash_object(ObjectType::Blob, binary, true).unwrap();
let new_data = b"\x00changed\x00";
let new_blob = repo.hash_object(ObjectType::Blob, new_data, true).unwrap();
let mut out = Vec::new();
render_file_diff(
b"bin.dat",
Some(old_blob),
Some(new_blob),
Some("100644"),
Some("100644"),
Some(binary),
Some(new_data),
&mut out,
)
.unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("Binary files"), "expected binary marker: {text}");
}
}

View File

@ -57,8 +57,11 @@
//! quarantine, connectivity, publication, and ref-policy ownership.
pub mod blob;
pub mod branch;
pub mod checkout;
pub mod commit;
pub mod diff;
pub mod diff_render;
pub mod error;
pub mod fsck;
pub mod headers;
@ -70,11 +73,14 @@ pub mod oid;
pub mod pack;
pub mod receive;
pub mod receive_pack;
pub mod reflog;
pub mod refs;
pub mod repo;
pub mod server;
pub mod show;
pub mod signature;
pub mod tag;
pub mod tag_ops;
pub mod tree;
pub mod upload_pack;
pub mod wire;
@ -113,3 +119,11 @@ pub use wire::{
PacketLine, PacketLineLimits, ReceivePackCommand, ReceivePackRequest, ReceiveStatus,
};
pub use worktree::{StatusEntry, WorktreeState};
pub use branch::{BranchOp, dispatch_branch, cmd_branch_list, cmd_branch_create,
cmd_branch_delete, cmd_branch_rename};
pub use checkout::{cmd_switch, SwitchHead, SwitchResult};
pub use diff_render::cmd_diff;
pub use show::cmd_show;
pub use tag_ops::{TagOp, dispatch_tag, cmd_tag_list, cmd_tag_create_lightweight,
cmd_tag_create_annotated, cmd_tag_delete};
pub use reflog::{ReflogEntry, read_reflog, append_reflog_file, log_path_for_ref, NULL_OID_HEX};

View File

@ -10,8 +10,9 @@ use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand};
use rit::object::Object;
use rit::{
advertise_receive_pack, execute_receive_pack, parse_receive_pack_request, ObjectType,
PacketLineLimits, ReceiveLimits, ReceivePackCommand, ReceivePackPolicy, Repository, Signature,
advertise_receive_pack, cmd_diff, cmd_show, cmd_switch, dispatch_branch, dispatch_tag,
execute_receive_pack, parse_receive_pack_request, BranchOp, ObjectType, PacketLineLimits,
ReceiveLimits, ReceivePackCommand, ReceivePackPolicy, Repository, Signature, SwitchHead, TagOp,
WorktreeState, RECEIVE_PACK_CAPABILITIES,
};
@ -54,6 +55,18 @@ enum Command {
Commit(CommitArgs),
/// Safely materialize a commit/tree snapshot and synchronize the index without moving HEAD.
CheckoutTree(CheckoutTreeArgs),
/// List, create, delete, or rename local branches. Like `git branch`.
Branch(BranchArgs),
/// List, create, or delete tags (lightweight or annotated). Like `git tag`.
Tag(TagArgs),
/// Switch branches or restore a detached HEAD, updating the worktree. Like `git switch`.
Switch(SwitchArgs),
/// Switch to a branch or commit, optionally creating it. Like `git checkout`.
Checkout(CheckoutArgs),
/// Show changes between commits, the index, and the worktree. Like `git diff`.
Diff(DiffArgs),
/// Show an object (commit, tag, tree, or blob) with its diff. Like `git show`.
Show(ShowArgs),
/// Restore tracked paths from the current index.
Restore(RestoreArgs),
/// Serve one stateful Git receive-pack session over stdin/stdout.
@ -146,6 +159,84 @@ struct RestoreArgs {
paths: Vec<PathBuf>,
}
#[derive(Args)]
struct BranchArgs {
/// Delete a branch (must be fully merged unless forced). Like `git branch -d`.
#[arg(short = 'd', long = "delete")]
delete: bool,
/// Force-delete a branch even if unmerged. Like `git branch -D`.
#[arg(short = 'D')]
delete_force: bool,
/// Rename a branch: `<old> <new>`. Like `git branch -m`.
#[arg(short = 'm', long = "move")]
rename: bool,
/// Force create/rename over an existing branch. Like `git branch -f`.
#[arg(short = 'f', long = "force")]
force: bool,
/// Show the tip commit id and subject alongside each branch.
#[arg(short = 'v', long = "verbose")]
verbose: bool,
/// Branch names / start-point. Absent → list; one → create; two → create-at or rename.
names: Vec<String>,
}
#[derive(Args)]
struct TagArgs {
/// Create an annotated tag object (requires `-m`). Like `git tag -a`.
#[arg(short = 'a', long = "annotate")]
annotate: bool,
/// Annotation message. Its presence implies an annotated tag.
#[arg(short = 'm', long = "message")]
message: Option<String>,
/// Delete the named tags. Like `git tag -d`.
#[arg(short = 'd', long = "delete")]
delete: bool,
/// Replace an existing tag with the same name. Like `git tag -f`.
#[arg(short = 'f', long = "force")]
force: bool,
/// List tags (default when no name is given). Like `git tag -l`.
#[arg(short = 'l', long = "list")]
list: bool,
/// When listing, print the first line of each tag's annotation. Like `git tag -n`.
#[arg(short = 'n')]
show_annotation: bool,
/// Tag name and optional target revision (defaults to HEAD).
names: Vec<String>,
}
#[derive(Args)]
struct SwitchArgs {
/// Create a new branch at the current HEAD before switching. Like `git switch -c`.
#[arg(short = 'c', long = "create")]
create: bool,
/// Branch name, commit, or tag to switch to.
target: String,
}
#[derive(Args)]
struct CheckoutArgs {
/// Create a new branch at the current HEAD before switching. Like `git checkout -b`.
#[arg(short = 'b')]
create: bool,
/// Branch name, commit, or tag to check out.
target: String,
}
#[derive(Args)]
struct DiffArgs {
/// Compare the staged index against HEAD instead of the worktree.
#[arg(long = "cached", visible_alias = "staged")]
cached: bool,
/// Optional revisions: none (worktree/index), or two trees to compare.
revs: Vec<String>,
}
#[derive(Args)]
struct ShowArgs {
/// Object to show (commit, tag, tree, or blob). Defaults to HEAD.
object: Option<String>,
}
#[derive(Args)]
struct ReceivePackArgs {
/// Exact bare repository/git directory supplied by Git's transport.
@ -184,6 +275,12 @@ fn run() -> Result<()> {
Command::WriteTree => cmd_write_tree(&cli),
Command::Commit(args) => cmd_commit(&cli, args),
Command::CheckoutTree(args) => cmd_checkout_tree(&cli, args),
Command::Branch(args) => cmd_branch(&cli, args),
Command::Tag(args) => cmd_tag(&cli, args),
Command::Switch(args) => cmd_switch_cli(&cli, args),
Command::Checkout(args) => cmd_checkout(&cli, args),
Command::Diff(args) => cmd_diff_cli(&cli, args),
Command::Show(args) => cmd_show_cli(&cli, args),
Command::Restore(args) => cmd_restore(&cli, args),
Command::ReceivePack(args) => cmd_receive_pack(args),
Command::UploadPack(args) => cmd_upload_pack(args),
@ -513,15 +610,157 @@ fn cmd_write_tree(cli: &Cli) -> Result<()> {
fn cmd_commit(cli: &Cli, args: &CommitArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let (name, email) = git_identity(repo.git_dir())?;
let signature = current_signature(repo.git_dir())?;
let oid = repo.commit_index(&args.message, signature.clone(), signature)?;
println!("{oid}");
Ok(())
}
/// Build a [`Signature`] for the configured identity stamped at the current
/// wall-clock time in UTC. Shared by `commit`, `branch`, and `tag` handlers.
fn current_signature(git_dir: &std::path::Path) -> Result<Signature> {
let (name, email) = git_identity(git_dir)?;
let seconds = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.context("system clock is before unix epoch")?
.as_secs();
let raw = format!("{name} <{email}> {seconds} +0000");
let signature = Signature::parse(&raw, "commit")?;
let oid = repo.commit_index(&args.message, signature.clone(), signature)?;
println!("{oid}");
Ok(Signature::parse(&raw, "commit")?)
}
fn cmd_branch(cli: &Cli, args: &BranchArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let names: Vec<&str> = args.names.iter().map(String::as_str).collect();
let delete = args.delete || args.delete_force;
let op = if delete {
if names.is_empty() {
bail!("branch -d/-D requires at least one branch name");
}
BranchOp::Delete {
names,
force: args.delete_force,
}
} else if args.rename {
match names.as_slice() {
[new] => {
// `git branch -m <new>` renames the current branch.
let current = match repo.refs().read_head()? {
rit::RefTarget::Symbolic(refname) => refname
.strip_prefix("refs/heads/")
.unwrap_or(&refname)
.to_string(),
rit::RefTarget::Direct(_) => {
bail!("branch -m with one argument requires being on a branch (HEAD is detached)")
}
};
let sig = current_signature(repo.git_dir())?;
return rit::cmd_branch_rename(&repo, &current, new, args.force, &sig);
}
[old, new] => BranchOp::Rename {
old,
new,
force: args.force,
},
_ => bail!("branch -m requires <old> <new> (or <new> to rename the current branch)"),
}
} else if names.is_empty() {
BranchOp::List {
verbose: args.verbose,
}
} else {
BranchOp::Create {
name: names[0],
start: names.get(1).copied(),
force: args.force,
}
};
let sig = current_signature(repo.git_dir())?;
dispatch_branch(&repo, op, &sig)
}
fn cmd_tag(cli: &Cli, args: &TagArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let names: Vec<&str> = args.names.iter().map(String::as_str).collect();
let op = if args.delete {
if names.is_empty() {
bail!("tag -d requires at least one tag name");
}
TagOp::Delete { names }
} else if args.list || names.is_empty() {
TagOp::List {
show_annotation: args.show_annotation,
}
} else if args.annotate || args.message.is_some() {
let message = args
.message
.as_deref()
.context("annotated tag requires a message (-m)")?;
TagOp::CreateAnnotated {
name: names[0],
target: names.get(1).copied(),
message,
force: args.force,
}
} else {
TagOp::CreateLightweight {
name: names[0],
target: names.get(1).copied(),
force: args.force,
}
};
let sig = current_signature(repo.git_dir())?;
dispatch_tag(&repo, op, Some(&sig))
}
fn cmd_switch_cli(cli: &Cli, args: &SwitchArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let result = cmd_switch(&repo, &args.target, args.create)?;
report_switch(&result);
Ok(())
}
fn cmd_checkout(cli: &Cli, args: &CheckoutArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let result = cmd_switch(&repo, &args.target, args.create)?;
report_switch(&result);
Ok(())
}
/// Emit a `git switch`-style confirmation line for a completed switch.
fn report_switch(result: &rit::SwitchResult) {
match &result.head {
SwitchHead::Symbolic(refname) => {
let short = refname.strip_prefix("refs/heads/").unwrap_or(refname);
println!("Switched to branch '{short}'");
}
SwitchHead::Detached(oid) => {
println!("HEAD is now at {}", &oid.to_hex()[..7]);
}
}
}
fn cmd_diff_cli(cli: &Cli, args: &DiffArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let revs: Vec<&str> = args.revs.iter().map(String::as_str).collect();
let mut out = std::io::stdout().lock();
cmd_diff(&repo, args.cached, &revs, &mut out)?;
Ok(())
}
fn cmd_show_cli(cli: &Cli, args: &ShowArgs) -> Result<()> {
let repo = Repository::discover(&cli.repo)
.with_context(|| format!("opening repo at {}", cli.repo.display()))?;
let mut out = std::io::stdout().lock();
cmd_show(&repo, args.object.as_deref(), &mut out)?;
Ok(())
}

278
src/reflog.rs Normal file
View File

@ -0,0 +1,278 @@
//! Reflog: read and append `.git/logs/{HEAD,refs/…}`.
//!
//! Git on-disk format — one LF-terminated line per entry:
//!
//! ```text
//! <old-sha1> SP <new-sha1> SP <name> SP <LT>email<GT> SP <unix-ts> SP <tz> TAB <message>
//! ```
//!
//! When a ref is created for the first time the `<old-sha1>` field is the
//! all-zeros null OID. HEAD and the branch ref receive separate (but usually
//! identical) log files under `.git/logs/`.
use crate::error::Result;
use std::io::Write;
use std::path::{Path, PathBuf};
/// All-zeros OID written as `<old-sha1>` when a ref is created (no predecessor).
pub const NULL_OID_HEX: &str = "0000000000000000000000000000000000000000";
/// Hard upper bound on entries returned by [`read_reflog`] (guards against
/// enormous log files produced by an adversarial or buggy writer).
const MAX_REFLOG_ENTRIES: usize = 100_000;
/// One parsed reflog entry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReflogEntry {
/// Previous OID (40-hex; null-OID string when the ref was created).
pub old_oid: String,
/// New OID (40-hex).
pub new_oid: String,
/// Actor display name (may contain spaces).
pub name: String,
/// Actor email address (without angle brackets).
pub email: String,
/// Unix epoch timestamp.
pub timestamp: i64,
/// Timezone offset token, e.g. `+0000` or `-0700`.
pub tz: String,
/// Human-readable log message (the text that follows the TAB separator).
pub message: String,
}
impl ReflogEntry {
/// Serialize to a git-compatible reflog line **without** a trailing newline.
pub fn format_line(&self) -> String {
format!(
"{} {} {} <{}> {} {}\t{}",
self.old_oid,
self.new_oid,
self.name,
self.email,
self.timestamp,
self.tz,
self.message,
)
}
/// Parse one line from a reflog file.
///
/// Returns `None` for blank lines and `#`-prefixed comment lines (git
/// never writes those, but they appear in test fixtures and documentation).
pub fn parse(line: &str) -> Option<Self> {
let line = line.trim_end_matches('\n').trim_end_matches('\r');
if line.is_empty() || line.starts_with('#') {
return None;
}
// TAB splits identity block from the free-text message.
let (identity, message) = match line.split_once('\t') {
Some((i, m)) => (i, m),
None => (line, ""),
};
// First two whitespace tokens: old OID, new OID.
let mut tokens = identity.splitn(3, ' ');
let old_oid = tokens.next()?.to_string();
let new_oid = tokens.next()?.to_string();
let rest = tokens.next().unwrap_or("").trim();
// `rest` = "Name With Spaces <email@host> <unix-ts> <tz>".
// Locate `<email>` via angle brackets to separate name from timestamp.
let lt = rest.find('<')?;
// Search for `>` starting from just after `<`.
let gt_rel = rest[lt + 1..].find('>')?;
let gt = lt + 1 + gt_rel;
let name = rest[..lt].trim().to_string();
let email = rest[lt + 1..gt].to_string();
let after = rest[gt + 1..].trim();
let (ts_str, tz_str) = after.split_once(' ')?;
let timestamp = ts_str.parse::<i64>().ok()?;
let tz = tz_str.trim().to_string();
Some(Self {
old_oid,
new_oid,
name,
email,
timestamp,
tz,
message: message.to_string(),
})
}
}
// ---- path helpers -----------------------------------------------------------
/// Return `.git/logs/<refname>` for the given fully-qualified ref name.
///
/// For `HEAD` pass `"HEAD"` literally; for a branch pass `"refs/heads/main"`.
pub fn log_path_for_ref(git_dir: &Path, refname: &str) -> PathBuf {
git_dir.join("logs").join(refname)
}
// ---- writer -----------------------------------------------------------------
/// Append `entry` to `log_path`, creating the file and its parent directories
/// when absent.
///
/// The write is fsynced: a crash immediately after this call leaves a complete,
/// correctly-terminated trailing line (no partial writes silently truncating the
/// log).
pub fn append_reflog_file(log_path: &Path, entry: &ReflogEntry) -> Result<()> {
if let Some(parent) = log_path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(log_path)?;
writeln!(file, "{}", entry.format_line())?;
file.sync_all()?;
Ok(())
}
// ---- reader -----------------------------------------------------------------
/// Read up to `limit` reflog entries for `refname`, **newest first**.
///
/// The log file is stored oldest-first (append-only); this function reverses
/// the order before returning so callers see the most-recent entries first,
/// matching `git reflog show` output.
///
/// An absent log file is not an error — it is normal for a ref that has never
/// been logged, so an empty vec is returned.
///
/// `limit` is capped at [`MAX_REFLOG_ENTRIES`] regardless of the caller value.
pub fn read_reflog(git_dir: &Path, refname: &str, limit: usize) -> Result<Vec<ReflogEntry>> {
let path = log_path_for_ref(git_dir, refname);
let raw = match std::fs::read_to_string(&path) {
Ok(r) => r,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.into()),
};
let cap = limit.min(MAX_REFLOG_ENTRIES);
let entries: Vec<ReflogEntry> = raw
.lines()
.rev()
.filter_map(ReflogEntry::parse)
.take(cap)
.collect();
Ok(entries)
}
// ---- tests ------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_parse_roundtrip() {
let entry = ReflogEntry {
old_oid: NULL_OID_HEX.to_string(),
new_oid: "abc123def0abc123def0abc123def0abc123def0".to_string(),
name: "Alice Example".to_string(),
email: "alice@example.com".to_string(),
timestamp: 1_700_000_000,
tz: "+0000".to_string(),
message: "commit (initial): init".to_string(),
};
let line = entry.format_line();
let parsed = ReflogEntry::parse(&line).expect("should parse a well-formed line");
assert_eq!(parsed.old_oid, entry.old_oid);
assert_eq!(parsed.new_oid, entry.new_oid);
assert_eq!(parsed.name, entry.name);
assert_eq!(parsed.email, entry.email);
assert_eq!(parsed.timestamp, entry.timestamp);
assert_eq!(parsed.tz, entry.tz);
assert_eq!(parsed.message, entry.message);
}
#[test]
fn name_with_spaces_parses() {
let line = "0000000000000000000000000000000000000000 1111111111111111111111111111111111111111 \
Joe Q Public <joe@example.com> 1700000001 +0100\tbranch: Created from HEAD";
let e = ReflogEntry::parse(line).unwrap();
assert_eq!(e.name, "Joe Q Public");
assert_eq!(e.email, "joe@example.com");
assert_eq!(e.tz, "+0100");
assert_eq!(e.message, "branch: Created from HEAD");
}
#[test]
fn parse_skips_blank_and_comment_lines() {
assert!(ReflogEntry::parse("").is_none());
assert!(ReflogEntry::parse(" \n").is_none());
assert!(ReflogEntry::parse("# comment").is_none());
}
#[test]
fn append_and_read_reflog_roundtrip() {
let dir = tempfile::tempdir().unwrap();
let git_dir = dir.path();
let first = ReflogEntry {
old_oid: NULL_OID_HEX.to_string(),
new_oid: "1111111111111111111111111111111111111111".to_string(),
name: "Bob".to_string(),
email: "bob@example.com".to_string(),
timestamp: 1_700_000_000,
tz: "+0000".to_string(),
message: "commit (initial): first".to_string(),
};
let second = ReflogEntry {
old_oid: "1111111111111111111111111111111111111111".to_string(),
new_oid: "2222222222222222222222222222222222222222".to_string(),
name: "Bob".to_string(),
email: "bob@example.com".to_string(),
timestamp: 1_700_000_001,
tz: "+0000".to_string(),
message: "commit: second".to_string(),
};
let path = log_path_for_ref(git_dir, "refs/heads/main");
append_reflog_file(&path, &first).unwrap();
append_reflog_file(&path, &second).unwrap();
// Read unbounded — should return newest first.
let entries = read_reflog(git_dir, "refs/heads/main", 100).unwrap();
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].new_oid, "2222222222222222222222222222222222222222");
assert_eq!(entries[1].new_oid, "1111111111111111111111111111111111111111");
}
#[test]
fn read_reflog_absent_is_empty() {
let dir = tempfile::tempdir().unwrap();
let entries = read_reflog(dir.path(), "refs/heads/nonexistent", 10).unwrap();
assert!(entries.is_empty());
}
#[test]
fn read_reflog_limit_is_respected() {
let dir = tempfile::tempdir().unwrap();
let git_dir = dir.path();
let path = log_path_for_ref(git_dir, "refs/heads/main");
for i in 0..5u32 {
let prev = format!("{:040x}", i);
let next = format!("{:040x}", i + 1);
let e = ReflogEntry {
old_oid: prev,
new_oid: next,
name: "A".to_string(),
email: "a@b.c".to_string(),
timestamp: i as i64,
tz: "+0000".to_string(),
message: format!("commit: {i}"),
};
append_reflog_file(&path, &e).unwrap();
}
let limited = read_reflog(git_dir, "refs/heads/main", 3).unwrap();
assert_eq!(limited.len(), 3);
// Newest first — entry for i=4 should be first.
assert_eq!(limited[0].timestamp, 4);
}
}

View File

@ -238,6 +238,51 @@ impl Refs {
result
}
/// Append one reflog entry to `.git/logs/<refname>` and, when this ref is
/// HEAD's current symbolic target, also to `.git/logs/HEAD`.
///
/// `old` is `None` when the ref is being created (the all-zeros null OID is
/// written in that position). Both log files are created with their parent
/// directories on first use; the write is fsynced before returning.
///
/// This is intentionally a low-level primitive — callers supply the
/// identity and message so higher-level operations (commit, branch-create,
/// branch-rename, …) can record the appropriate context.
pub fn append_reflog(
&self,
refname: &str,
old: Option<ObjectId>,
new: ObjectId,
name: &str,
email: &str,
timestamp: i64,
tz: &str,
message: &str,
) -> Result<()> {
use crate::reflog::{append_reflog_file, log_path_for_ref, ReflogEntry, NULL_OID_HEX};
let entry = ReflogEntry {
old_oid: old
.map(|oid| oid.to_hex())
.unwrap_or_else(|| NULL_OID_HEX.to_string()),
new_oid: new.to_hex(),
name: name.to_string(),
email: email.to_string(),
timestamp,
tz: tz.to_string(),
message: message.to_string(),
};
// Always write to the ref's own log file.
append_reflog_file(&log_path_for_ref(&self.git_dir, refname), &entry)?;
// When HEAD is a symbolic ref pointing at this ref, also update logs/HEAD
// so that `git reflog` (which reads logs/HEAD) sees the same history.
if let Ok(RefTarget::Symbolic(head_target)) = self.read_head() {
if head_target == refname {
append_reflog_file(&log_path_for_ref(&self.git_dir, "HEAD"), &entry)?;
}
}
Ok(())
}
/// Parse `.git/packed-refs` into a name -> oid map (peel lines ignored).
fn read_packed_refs(&self) -> Result<HashMap<String, ObjectId>> {
let path = self.git_dir.join("packed-refs");

View File

@ -261,6 +261,9 @@ impl Repository {
Err(error) => return Err(error),
};
let tree = self.write_tree()?;
// Clone before moving into the Commit struct so we can use the fields
// for the reflog entry below.
let committer_for_log = committer.clone();
let commit = Commit {
tree,
parents: expected.into_iter().collect(),
@ -271,6 +274,30 @@ impl Repository {
};
let oid = self.odb.write(ObjectType::Commit, &commit.serialize())?;
self.refs.compare_and_swap(&head_ref, expected, oid)?;
// Reflog: "commit (initial): <first line>" or "commit: <first line>".
let first_line = commit
.message_str()
.lines()
.next()
.unwrap_or("")
.to_string();
let reflog_msg = if expected.is_none() {
format!("commit (initial): {first_line}")
} else {
format!("commit: {first_line}")
};
// Reflog failure is non-fatal: the commit object + ref are already
// durably written, so we surface the error but don't roll back.
self.refs.append_reflog(
&head_ref,
expected,
oid,
&committer_for_log.name,
&committer_for_log.email,
committer_for_log.time,
&committer_for_log.tz,
&reflog_msg,
)?;
Ok(oid)
}
@ -308,6 +335,9 @@ impl Repository {
Object::Tree(_) => {}
other => return Err(type_error(&tree, "tree", other)),
}
// Clone before moving into Commit so committer fields are available
// for the reflog entry below.
let committer_for_log = committer.clone();
let commit = Commit {
tree,
parents,
@ -325,6 +355,27 @@ impl Repository {
Err(error) => return Err(error),
};
self.refs.compare_and_swap(refname, expected, oid)?;
// Reflog for the explicit ref update.
let first_line = std::str::from_utf8(message)
.ok()
.and_then(|s| s.lines().next())
.unwrap_or("")
.to_string();
let reflog_msg = if expected.is_none() {
format!("commit (initial): {first_line}")
} else {
format!("commit: {first_line}")
};
self.refs.append_reflog(
refname,
expected,
oid,
&committer_for_log.name,
&committer_for_log.email,
committer_for_log.time,
&committer_for_log.tz,
&reflog_msg,
)?;
}
Ok(oid)
}
@ -651,6 +702,315 @@ impl Repository {
)))
}
// --- branch operations ---------------------------------------------------
/// Create a new branch `name` pointing at `start_oid`.
///
/// When `force` is false (the default) the branch must not already exist.
/// When `force` is true the branch is moved even if it already points
/// somewhere else (equivalent to `git branch -f`).
///
/// Writes a reflog entry using the supplied actor identity and message.
pub fn branch_create(
&self,
name: &str,
start_oid: ObjectId,
force: bool,
actor_name: &str,
actor_email: &str,
timestamp: i64,
tz: &str,
message: &str,
) -> Result<()> {
let refname = format!("refs/heads/{name}");
validate_refname(&refname)?;
let expected = match self.refs.resolve(&refname) {
Ok(oid) => {
if !force {
return Err(ForgeError::InvalidRef(format!(
"branch {name} already exists (use force to move it)"
)));
}
Some(oid)
}
Err(ForgeError::InvalidRef(_)) => None,
Err(e) => return Err(e),
};
self.refs.compare_and_swap(&refname, expected, start_oid)?;
self.refs.append_reflog(
&refname,
expected,
start_oid,
actor_name,
actor_email,
timestamp,
tz,
message,
)?;
Ok(())
}
/// Delete branch `name`.
///
/// When `force` is false (equivalent to `git branch -d`) the operation
/// fails if the branch tip is not an ancestor of HEAD (i.e. the branch
/// has unmerged commits). When `force` is true (`git branch -D`) the
/// check is skipped.
///
/// No reflog entry is written on deletion (git also leaves the log file
/// intact; it is pruned by `git reflog expire`).
pub fn branch_delete(&self, name: &str, force: bool) -> Result<()> {
let refname = format!("refs/heads/{name}");
validate_refname(&refname)?;
let tip = self.refs.resolve(&refname)?;
if !force {
// Safety check: branch tip must be reachable from HEAD.
if let Ok(head_oid) = self.refs.resolve_head() {
let merged = crate::fsck::is_ancestor(
self.odb(),
tip,
head_oid,
crate::fsck::ConnectivityLimits::default(),
)
.unwrap_or(false);
if !merged {
return Err(ForgeError::NonFastForward {
name: name.to_string(),
old: tip.to_hex(),
new: head_oid.to_hex(),
});
}
}
}
// Guard: refuse to delete the currently-checked-out branch.
if let Ok(crate::RefTarget::Symbolic(head_target)) = self.refs.read_head() {
if head_target == refname {
return Err(ForgeError::InvalidRef(format!(
"cannot delete branch {name}: it is currently checked out"
)));
}
}
self.refs.compare_and_delete(&refname, tip)?;
Ok(())
}
/// List all local branches as `(short_name, tip_oid, is_current)` triples,
/// sorted alphabetically by name.
///
/// `is_current` is true when HEAD is a symbolic ref pointing at that branch.
pub fn branch_list(&self) -> Result<Vec<(String, ObjectId, bool)>> {
let current = match self.refs.read_head()? {
crate::RefTarget::Symbolic(name) => Some(name),
crate::RefTarget::Direct(_) => None,
};
let all = self.refs.list()?;
let mut branches: Vec<(String, ObjectId, bool)> = all
.into_iter()
.filter_map(|(refname, oid)| {
refname
.strip_prefix("refs/heads/")
.map(|short| {
let is_current = current
.as_deref()
.map(|c| c == refname)
.unwrap_or(false);
(short.to_string(), oid, is_current)
})
})
.collect();
branches.sort_by(|a, b| a.0.cmp(&b.0));
Ok(branches)
}
/// Rename branch `old_name` to `new_name`.
///
/// When `force` is false the destination must not already exist.
/// Writes reflog entries on both the new branch and (if HEAD points at it)
/// on HEAD.
pub fn branch_rename(
&self,
old_name: &str,
new_name: &str,
force: bool,
actor_name: &str,
actor_email: &str,
timestamp: i64,
tz: &str,
) -> Result<()> {
let old_ref = format!("refs/heads/{old_name}");
let new_ref = format!("refs/heads/{new_name}");
validate_refname(&old_ref)?;
validate_refname(&new_ref)?;
let tip = self.refs.resolve(&old_ref)?;
// Create the new ref first (CAS on "absent").
let new_expected = match self.refs.resolve(&new_ref) {
Ok(oid) => {
if !force {
return Err(ForgeError::InvalidRef(format!(
"branch {new_name} already exists (use force to overwrite)"
)));
}
Some(oid)
}
Err(ForgeError::InvalidRef(_)) => None,
Err(e) => return Err(e),
};
self.refs.compare_and_swap(&new_ref, new_expected, tip)?;
let rename_msg = format!("branch: renamed refs/heads/{old_name} to refs/heads/{new_name}");
self.refs.append_reflog(
&new_ref,
None, // treat as creation of the new name
tip,
actor_name,
actor_email,
timestamp,
tz,
&rename_msg,
)?;
// If HEAD points at the old ref, update it to the new one.
if let Ok(crate::RefTarget::Symbolic(head_target)) = self.refs.read_head() {
if head_target == old_ref {
let head_path = self.git_dir.join("HEAD");
let lock_path = head_path.with_extension("lock");
let mut lock = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&lock_path)
.map_err(|_| ForgeError::RefLocked("HEAD".into()))?;
let result = (|| {
writeln!(lock, "ref: {new_ref}")?;
lock.sync_all()?;
std::fs::rename(&lock_path, &head_path)?;
Ok::<_, ForgeError>(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&lock_path);
result?;
}
}
}
// Remove the old ref.
self.refs.compare_and_delete(&old_ref, tip)?;
Ok(())
}
// --- tag operations ------------------------------------------------------
/// List all tags as `(name, oid)` pairs sorted alphabetically.
///
/// `oid` is the tag object OID for annotated tags, or the commit/blob/tree
/// OID for lightweight tags (matching `git show-ref --tags`).
pub fn tag_list(&self) -> Result<Vec<(String, ObjectId)>> {
let all = self.refs.list()?;
let mut tags: Vec<(String, ObjectId)> = all
.into_iter()
.filter_map(|(refname, oid)| {
refname
.strip_prefix("refs/tags/")
.map(|short| (short.to_string(), oid))
})
.collect();
tags.sort_by(|a, b| a.0.cmp(&b.0));
Ok(tags)
}
/// Create a **lightweight** tag: a ref in `refs/tags/<name>` pointing
/// directly at `target_oid` (no tag object is written).
///
/// When `force` is false the tag must not already exist.
pub fn tag_create_lightweight(
&self,
name: &str,
target_oid: ObjectId,
force: bool,
) -> Result<()> {
let refname = format!("refs/tags/{name}");
validate_refname(&refname)?;
let expected = match self.refs.resolve(&refname) {
Ok(oid) => {
if !force {
return Err(ForgeError::InvalidRef(format!(
"tag {name} already exists (use force to replace)"
)));
}
Some(oid)
}
Err(ForgeError::InvalidRef(_)) => None,
Err(e) => return Err(e),
};
self.refs.compare_and_swap(&refname, expected, target_oid)?;
Ok(())
}
/// Create an **annotated** tag: write a `tag` object pointing at
/// `target_oid`, then create a ref in `refs/tags/<name>` pointing at the
/// tag object.
///
/// When `force` is false the tag must not already exist.
///
/// Returns the OID of the written tag object.
pub fn tag_create_annotated(
&self,
name: &str,
target_oid: ObjectId,
target_type: crate::object::ObjectType,
message: &[u8],
tagger: Signature,
force: bool,
) -> Result<ObjectId> {
let refname = format!("refs/tags/{name}");
validate_refname(&refname)?;
let tag_obj = crate::tag::Tag {
object: target_oid,
object_type: target_type,
tag: name.to_string(),
tagger: Some(tagger),
extra_headers: Vec::new(),
message: message.to_vec(),
};
let tag_oid = self.odb.write(ObjectType::Tag, &tag_obj.serialize())?;
let expected = match self.refs.resolve(&refname) {
Ok(oid) => {
if !force {
return Err(ForgeError::InvalidRef(format!(
"tag {name} already exists (use force to replace)"
)));
}
Some(oid)
}
Err(ForgeError::InvalidRef(_)) => None,
Err(e) => return Err(e),
};
self.refs.compare_and_swap(&refname, expected, tag_oid)?;
Ok(tag_oid)
}
/// Delete tag `name`.
///
/// When `force` is true the check that the ref currently exists is still
/// performed (you cannot delete what isn't there), but the merge-safety
/// check is bypassed. For tags, force-delete (`git tag -d` always acts
/// like `-D`) is the default — the boolean is accepted for API symmetry
/// with `branch_delete`.
pub fn tag_delete(&self, name: &str) -> Result<()> {
let refname = format!("refs/tags/{name}");
validate_refname(&refname)?;
let tip = self.refs.resolve(&refname).map_err(|_| {
ForgeError::InvalidRef(format!("tag {name} not found"))
})?;
self.refs.compare_and_delete(&refname, tip)?;
Ok(())
}
/// `git log`: walk history from `start`, newest first by committer time.
///
/// Bounded by a visited set so cycles or malicious graphs cannot loop

290
src/show.rs Normal file
View File

@ -0,0 +1,290 @@
//! `git show [<object>]` command handler.
//!
//! Shows the content of a Git object in a human-readable form, matching `git show`:
//!
//! | Object type | Output |
//! |-------------|-----------------------------------------------------|
//! | **Commit** | Commit metadata (like `git log -1`) followed by the |
//! | | unified diff of the commit vs its first parent (or |
//! | | all-additions for a root commit). |
//! | **Tag** | The raw annotated-tag payload (`git cat-file -p`). |
//! | **Tree** | Directory listing (`git ls-tree` format). |
//! | **Blob** | Raw file content (like `cat`). |
//!
//! The object argument may be any revision syntax accepted by
//! [`Repository::resolve`]: `HEAD`, a branch/tag name, a full 40-hex oid, or an
//! unambiguous abbreviated prefix.
use std::io::Write;
use crate::commit::Commit;
use crate::diff::{diff_trees, ChangeKind, TreeChange};
use crate::diff_render::render_file_diff;
use crate::error::Result;
use crate::object::Object;
use crate::oid::ObjectId;
use crate::repo::Repository;
/// Implements `git show [<object>]`.
///
/// When `object` is `None` the default is `HEAD`.
/// Output is written to `out`.
pub fn cmd_show(repo: &Repository, object: Option<&str>, out: &mut impl Write) -> Result<()> {
let rev = object.unwrap_or("HEAD");
let oid = repo.resolve(rev)?;
match repo.read_object(&oid)? {
Object::Commit(commit) => show_commit(repo, oid, &commit, out),
Object::Tag(tag) => {
// Print the annotated-tag payload verbatim (same as `git cat-file -p`).
out.write_all(&tag.serialize())?;
// If the tagged object is a commit, also show that commit's diff.
let tagged_oid = tag.object;
match repo.read_object(&tagged_oid)? {
Object::Commit(commit) => {
writeln!(out)?;
show_commit(repo, tagged_oid, &commit, out)?;
}
_ => {} // non-commit tags: just show the tag payload
}
Ok(())
}
Object::Tree(tree) => {
// ls-tree style: "<mode> <kind> <oid>\t<name>"
for entry in &tree.entries {
writeln!(
out,
"{} {} {}\t{}",
entry.display_mode(),
entry.kind(),
entry.oid,
entry.name_str()
)?;
}
Ok(())
}
Object::Blob(blob) => {
out.write_all(&blob.data)?;
Ok(())
}
}
}
// ── Commit display ────────────────────────────────────────────────────────────
/// Write the full `git show` block for one commit to `out`:
/// metadata header, body, then unified diff vs first parent.
fn show_commit(
repo: &Repository,
oid: ObjectId,
commit: &Commit,
out: &mut impl Write,
) -> Result<()> {
// ── Header ────────────────────────────────────────────────────────────────
writeln!(out, "commit {oid}")?;
// Merge commits get an extra "Merge:" line.
if commit.parents.len() > 1 {
let parents: Vec<String> = commit
.parents
.iter()
.map(|p| p.to_hex()[..7].to_string())
.collect();
writeln!(out, "Merge: {}", parents.join(" "))?;
}
writeln!(
out,
"Author: {} <{}>",
commit.author.name, commit.author.email
)?;
writeln!(out, "Date: {} {}", commit.author.time, commit.author.tz)?;
writeln!(out)?;
// ── Message body ──────────────────────────────────────────────────────────
for line in commit.message_str().lines() {
writeln!(out, " {line}")?;
}
writeln!(out)?;
// ── Diff vs first parent (or empty tree for root commits) ─────────────────
let parent_tree: Option<ObjectId> = match commit.parents.first() {
Some(parent_oid) => {
let parent_commit = repo.peel_to_commit(*parent_oid)?;
Some(parent_commit.tree)
}
None => None, // root commit → diff against empty tree
};
let changes = diff_trees(repo.odb(), parent_tree, Some(commit.tree))?;
for change in &changes {
render_show_change(repo, change, out)?;
}
Ok(())
}
/// Render one [`TreeChange`] for `show` output (delegates to [`render_file_diff`]).
fn render_show_change(repo: &Repository, change: &TreeChange, out: &mut impl Write) -> Result<()> {
let (old_data, new_data) = match change.kind {
ChangeKind::Added => {
let new_blob = repo.blob(change.new_oid.as_ref().expect("Added has new_oid"))?;
(None, Some(new_blob.data))
}
ChangeKind::Deleted => {
let old_blob = repo.blob(change.old_oid.as_ref().expect("Deleted has old_oid"))?;
(Some(old_blob.data), None)
}
ChangeKind::Modified => {
let old_blob = repo.blob(change.old_oid.as_ref().expect("Modified has old_oid"))?;
let new_blob = repo.blob(change.new_oid.as_ref().expect("Modified has new_oid"))?;
(Some(old_blob.data), Some(new_blob.data))
}
};
render_file_diff(
&change.path,
change.old_oid,
change.new_oid,
change.old_mode.as_deref(),
change.new_mode.as_deref(),
old_data.as_deref(),
new_data.as_deref(),
out,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::object::ObjectType;
use crate::{Signature, Tree, TreeEntry};
fn make_repo_with_commit(
dir: &std::path::Path,
file: &str,
content: &[u8],
) -> (Repository, ObjectId) {
let repo = Repository::init(dir, false, Some("main")).unwrap();
let blob = repo.hash_object(ObjectType::Blob, content, true).unwrap();
let mut tree_obj = Tree {
entries: vec![TreeEntry {
mode: "100644".into(),
name: file.as_bytes().to_vec(),
oid: blob,
}],
};
tree_obj.canonicalize();
let tree_oid = repo.hash_object(ObjectType::Tree, &tree_obj.serialize(), true).unwrap();
let sig = Signature::parse("Test <t@t.com> 1700000000 +0000", "test").unwrap();
let commit_oid = repo
.commit_tree(
tree_oid,
vec![],
sig.clone(),
sig,
b"root commit\n",
Some("refs/heads/main"),
)
.unwrap();
(repo, commit_oid)
}
#[test]
fn show_commit_prints_header_and_diff() {
let dir = tempfile::tempdir().unwrap();
let (repo, _) = make_repo_with_commit(dir.path(), "hello.txt", b"hello\n");
let mut out = Vec::new();
cmd_show(&repo, None, &mut out).unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("commit "), "expected 'commit' header: {text}");
assert!(text.contains("Author: Test"), "expected author: {text}");
assert!(text.contains(" root commit"), "expected message: {text}");
assert!(text.contains("new file mode 100644"), "expected new file: {text}");
assert!(text.contains("+hello"), "expected diff line: {text}");
}
#[test]
fn show_blob_prints_raw_content() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
let content = b"raw bytes here\n";
let oid = repo.hash_object(ObjectType::Blob, content, true).unwrap();
let mut out = Vec::new();
cmd_show(&repo, Some(&oid.to_hex()), &mut out).unwrap();
assert_eq!(out, content);
}
#[test]
fn show_tree_prints_ls_tree_format() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), true, Some("main")).unwrap();
let blob = repo.hash_object(ObjectType::Blob, b"x", true).unwrap();
let mut tree_obj = Tree {
entries: vec![TreeEntry {
mode: "100644".into(),
name: b"x.txt".to_vec(),
oid: blob,
}],
};
tree_obj.canonicalize();
let tree_oid = repo.hash_object(ObjectType::Tree, &tree_obj.serialize(), true).unwrap();
let mut out = Vec::new();
cmd_show(&repo, Some(&tree_oid.to_hex()), &mut out).unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("100644 blob"), "expected blob entry: {text}");
assert!(text.contains("x.txt"), "expected file name: {text}");
}
#[test]
fn show_commit_with_parent_shows_modification_diff() {
let dir = tempfile::tempdir().unwrap();
let repo = Repository::init(dir.path(), false, Some("main")).unwrap();
let sig = Signature::parse("Test <t@t.com> 1700000000 +0000", "test").unwrap();
// First commit: file.txt = "version 1\n"
let blob1 = repo.hash_object(ObjectType::Blob, b"version 1\n", true).unwrap();
let mut t1 = Tree {
entries: vec![TreeEntry {
mode: "100644".into(),
name: b"file.txt".to_vec(),
oid: blob1,
}],
};
t1.canonicalize();
let tree1 = repo.hash_object(ObjectType::Tree, &t1.serialize(), true).unwrap();
let commit1 = repo
.commit_tree(tree1, vec![], sig.clone(), sig.clone(), b"v1\n", Some("refs/heads/main"))
.unwrap();
// Second commit: file.txt = "version 2\n"
let blob2 = repo.hash_object(ObjectType::Blob, b"version 2\n", true).unwrap();
let mut t2 = Tree {
entries: vec![TreeEntry {
mode: "100644".into(),
name: b"file.txt".to_vec(),
oid: blob2,
}],
};
t2.canonicalize();
let tree2 = repo.hash_object(ObjectType::Tree, &t2.serialize(), true).unwrap();
let commit2 = repo
.commit_tree(tree2, vec![commit1], sig.clone(), sig, b"v2\n", Some("refs/heads/main"))
.unwrap();
let mut out = Vec::new();
cmd_show(&repo, Some(&commit2.to_hex()), &mut out).unwrap();
let text = String::from_utf8(out).unwrap();
assert!(text.contains("-version 1"), "expected deletion line: {text}");
assert!(text.contains("+version 2"), "expected addition line: {text}");
}
}

192
src/tag_ops.rs Normal file
View File

@ -0,0 +1,192 @@
//! Tag command handlers — the porcelain behind `rit tag`.
//!
//! Each `cmd_tag_*` function accepts a [`Repository`] reference plus the
//! parameters that the CLI argument parser supplies. They return
//! `anyhow::Result<()>` so the integrator can call them directly from a
//! `main.rs` dispatch match arm.
//!
//! # CLI wiring (integrator notes)
//!
//! Add a `Tag(TagArgs)` variant to the `Command` enum in `main.rs`:
//!
//! ```text
//! Command::Tag(args) => rit::tag_ops::cmd_tag(&cli, args),
//! ```
//!
//! where `TagArgs` contains:
//!
//! ```text
//! name: Option<String> // absent → list
//! target: Option<String> // revision the tag points at (default HEAD)
//! message: Option<String> // -m: annotated tag when present
//! delete: bool // -d
//! force: bool // -f
//! list: bool // -l (explicit list; also default when name absent)
//! ```
//!
//! Then dispatch with the high-level convenience helper [`dispatch_tag`].
use anyhow::{bail, Context};
use std::io::Write;
use crate::{Repository, Signature};
// ── public handler functions ─────────────────────────────────────────────────
/// `rit tag` / `rit tag -l` — list all tags, one per line, alphabetically.
///
/// With `show_annotation = true` the first line of the annotation message is
/// printed after the tag name, separated by a space (matching `git tag -n1`).
pub fn cmd_tag_list(repo: &Repository, show_annotation: bool) -> anyhow::Result<()> {
let tags = repo.tag_list().context("listing tags")?;
if tags.is_empty() {
return Ok(());
}
let mut out = std::io::stdout().lock();
for (name, oid) in &tags {
if show_annotation {
// Try to read the tag object for annotated tags; fall back to the
// commit/blob/tree message when the ref is lightweight.
let annotation = repo
.read_object(oid)
.ok()
.and_then(|obj| match obj {
crate::object::Object::Tag(t) => {
t.message_str()
.lines()
.next()
.map(|l| l.trim().to_string())
}
crate::object::Object::Commit(c) => {
c.message_str()
.lines()
.next()
.map(|l| l.trim().to_string())
}
_ => None,
})
.unwrap_or_default();
if annotation.is_empty() {
writeln!(out, "{name}")?;
} else {
writeln!(out, "{name:<20} {annotation}")?;
}
} else {
writeln!(out, "{name}")?;
}
}
Ok(())
}
/// `rit tag <name> [<target>]` — create a **lightweight** tag.
///
/// `target` is a revision string; defaults to `HEAD` when `None`.
/// `force = true` replaces an existing tag with the same name.
pub fn cmd_tag_create_lightweight(
repo: &Repository,
name: &str,
target: Option<&str>,
force: bool,
) -> anyhow::Result<()> {
let rev = target.unwrap_or("HEAD");
let target_oid = repo
.resolve(rev)
.with_context(|| format!("cannot resolve {rev:?}"))?;
repo.tag_create_lightweight(name, target_oid, force)
.with_context(|| format!("creating lightweight tag {name:?}"))?;
Ok(())
}
/// `rit tag -a -m <msg> <name> [<target>]` — create an **annotated** tag.
///
/// Writes a tag object with `tagger`, `message`, and the resolved target type,
/// then creates the ref. `force = true` replaces an existing tag.
///
/// Returns the OID of the written tag object.
pub fn cmd_tag_create_annotated(
repo: &Repository,
name: &str,
target: Option<&str>,
message: &str,
tagger: &Signature,
force: bool,
) -> anyhow::Result<crate::ObjectId> {
if message.trim().is_empty() {
bail!("annotated tag requires a non-empty message (-m)");
}
let rev = target.unwrap_or("HEAD");
let target_oid = repo
.resolve(rev)
.with_context(|| format!("cannot resolve {rev:?}"))?;
let target_type = repo
.object_type(&target_oid)
.with_context(|| format!("reading type of {}", target_oid.to_hex()))?;
let tag_oid = repo
.tag_create_annotated(
name,
target_oid,
target_type,
message.as_bytes(),
tagger.clone(),
force,
)
.with_context(|| format!("creating annotated tag {name:?}"))?;
Ok(tag_oid)
}
/// `rit tag -d <name>…` — delete one or more tags.
///
/// Prints a confirmation line for each deleted tag.
pub fn cmd_tag_delete(repo: &Repository, names: &[&str]) -> anyhow::Result<()> {
if names.is_empty() {
bail!("tag --delete requires at least one tag name");
}
let mut out = std::io::stdout().lock();
for name in names {
let oid = repo
.refs()
.resolve(&format!("refs/tags/{name}"))
.with_context(|| format!("tag {name:?} not found"))?;
repo.tag_delete(name)
.with_context(|| format!("deleting tag {name:?}"))?;
writeln!(out, "Deleted tag {name} (was {}).", &oid.to_hex()[..7])?;
}
Ok(())
}
// ── convenience dispatcher ────────────────────────────────────────────────────
/// Decoded tag operation — used by the convenience dispatcher.
#[derive(Debug)]
pub enum TagOp<'a> {
List { show_annotation: bool },
CreateLightweight { name: &'a str, target: Option<&'a str>, force: bool },
CreateAnnotated { name: &'a str, target: Option<&'a str>, message: &'a str, force: bool },
Delete { names: Vec<&'a str> },
}
/// High-level tag dispatcher: given a decoded [`TagOp`] and an optional actor
/// [`Signature`] (required for annotated), run the appropriate sub-handler.
///
/// The integrator calls this from their `cmd_tag` main.rs function after
/// translating clap args into a `TagOp`.
pub fn dispatch_tag(
repo: &Repository,
op: TagOp<'_>,
sig: Option<&Signature>,
) -> anyhow::Result<()> {
match op {
TagOp::List { show_annotation } => cmd_tag_list(repo, show_annotation),
TagOp::CreateLightweight { name, target, force } => {
cmd_tag_create_lightweight(repo, name, target, force)
}
TagOp::CreateAnnotated { name, target, message, force } => {
let tagger = sig
.ok_or_else(|| anyhow::anyhow!("annotated tag requires an actor signature"))?;
cmd_tag_create_annotated(repo, name, target, message, tagger, force)?;
Ok(())
}
TagOp::Delete { names } => cmd_tag_delete(repo, &names),
}
}