grit-lib 0.5.32

Core library for the grit Git implementation
Documentation
//! Shallow/deepen handling for [`super::upload_pack`].

use std::collections::{HashMap, HashSet};

use crate::objects::{ObjectId, ObjectKind};
use crate::repo::Repository;
use crate::rev_list::{
    shallow_boundary_oids, upload_pack_shallow_depth_state, upload_pack_shallow_rev_list_state,
    UploadPackDepthShallowState,
};
use crate::shallow::INFINITE_DEPTH;

/// Client shallow/deepen parameters from an upload-pack request.
#[derive(Debug, Default)]
pub(crate) struct ShallowRequest {
    pub client_shallow: Vec<ObjectId>,
    pub depth: Option<u32>,
    pub deepen_since: Option<i64>,
    pub deepen_not: Vec<ObjectId>,
    pub deepen_relative: bool,
}

impl ShallowRequest {
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.depth.is_some()
            || self.deepen_since.is_some()
            || !self.deepen_not.is_empty()
            || !self.client_shallow.is_empty()
    }

    /// Whether v0/v1 stateless RPC must emit the flush-terminated shallow section
    /// before negotiation ACKs (Git `send_shallow_list` for deepen arguments).
    #[must_use]
    pub fn sends_v0_shallow_list(&self) -> bool {
        self.depth.is_some() || self.deepen_since.is_some() || !self.deepen_not.is_empty()
    }
}

/// Shallow/unshallow lines to send and graft state for pack enumeration.
#[derive(Debug, Default)]
pub(crate) struct ShallowResponse {
    pub shallow: Vec<ObjectId>,
    pub unshallow: Vec<ObjectId>,
    /// Extra commit tips to include in the pack (parents of unshallowed commits).
    pub extra_wants: Vec<ObjectId>,
    /// Shallow grafts on the `have` side (client shallow boundaries for this request).
    pub have_shallow_grafts: HashSet<ObjectId>,
    /// Shallow grafts for `pack-objects` send side (do not walk past these commits' parents).
    pub pack_shallow_grafts: HashSet<ObjectId>,
}

/// Compute shallow/unshallow updates and pack grafts for one upload-pack fetch.
pub(crate) fn compute_shallow_response(
    repo: &Repository,
    wants: &[ObjectId],
    req: &ShallowRequest,
) -> crate::error::Result<ShallowResponse> {
    let mut out = ShallowResponse::default();
    if wants.is_empty() || !req.is_active() {
        return Ok(out);
    }

    let server_shallow = shallow_boundary_oids(repo.git_dir());
    let client_set: HashSet<ObjectId> = req.client_shallow.iter().copied().collect();

    if req.depth == Some(INFINITE_DEPTH) && server_shallow.is_empty() {
        for oid in &req.client_shallow {
            out.unshallow.push(*oid);
            out.extra_wants.extend(parent_commits(repo, *oid)?);
        }
        out.pack_shallow_grafts = server_shallow;
        return Ok(out);
    }

    let deepening = req.depth.is_some() || req.deepen_since.is_some() || !req.deepen_not.is_empty();
    let mut depth_state = UploadPackDepthShallowState::default();
    if let Some(depth) = req.depth.filter(|d| *d > 0 && *d != INFINITE_DEPTH) {
        let depth = usize::try_from(depth).unwrap_or(usize::MAX);
        let depth = if req.deepen_relative {
            match relative_deepen_depth_for_request(repo, wants, &req.client_shallow, depth) {
                Some(d) => d,
                None => return Ok(out),
            }
        } else {
            depth
        };
        let tips = crate::rev_list::peel_to_commit_tips(repo, wants);
        depth_state = upload_pack_shallow_depth_state(repo, &tips, depth, &server_shallow);
        for oid in &depth_state.border_commits {
            if !client_set.contains(oid) {
                out.shallow.push(*oid);
            }
        }
    } else if req.deepen_since.is_some() || !req.deepen_not.is_empty() {
        depth_state =
            upload_pack_shallow_rev_list_state(repo, wants, req.deepen_since, &req.deepen_not)?;
        for oid in &depth_state.border_commits {
            if !client_set.contains(oid) {
                out.shallow.push(*oid);
            }
        }
    } else if !server_shallow.is_empty() {
        let new_shallow = crate::rev_list::shallow_borders_reachable_from_wants(repo, wants);
        for oid in &new_shallow {
            if !client_set.contains(oid) {
                out.shallow.push(*oid);
            }
        }
    }

    if deepening {
        for oid in &req.client_shallow {
            if !depth_state.interior_commits.contains(oid) {
                continue;
            }
            if parents_in_repo(repo, *oid)? {
                out.unshallow.push(*oid);
                out.extra_wants.extend(parent_commits(repo, *oid)?);
            }
        }
    }

    out.have_shallow_grafts = client_set;
    out.pack_shallow_grafts = server_shallow;
    out.pack_shallow_grafts.extend(out.shallow.iter().copied());
    for oid in &req.client_shallow {
        if !out.unshallow.contains(oid) {
            out.pack_shallow_grafts.insert(*oid);
        }
    }

    Ok(out)
}

fn parent_commits(repo: &Repository, oid: ObjectId) -> crate::error::Result<Vec<ObjectId>> {
    let obj = repo.odb().read(&oid)?;
    if obj.kind != ObjectKind::Commit {
        return Ok(Vec::new());
    }
    Ok(crate::objects::parse_commit(&obj.data)?.parents)
}

fn parents_in_repo(repo: &Repository, oid: ObjectId) -> crate::error::Result<bool> {
    for p in parent_commits(repo, oid)? {
        if !repo.odb().contains(&p)? {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Mirrors Git `get_shallows_depth` + `deepen_relative` depth adjustment.
fn relative_deepen_depth_for_request(
    repo: &Repository,
    wants: &[ObjectId],
    client_shallow: &[ObjectId],
    deepen: usize,
) -> Option<usize> {
    if client_shallow.is_empty() {
        return None;
    }
    let client_set: HashSet<ObjectId> = client_shallow.iter().copied().collect();
    let mut best_depth: HashMap<ObjectId, usize> = HashMap::new();
    let mut q: std::collections::VecDeque<(ObjectId, usize)> = std::collections::VecDeque::new();
    for w in crate::rev_list::peel_to_commit_tips(repo, wants) {
        best_depth.insert(w, 1);
        q.push_back((w, 1));
    }
    let mut max_to_shallow = 0usize;
    while let Some((oid, depth)) = q.pop_front() {
        if best_depth.get(&oid).copied() != Some(depth) {
            continue;
        }
        if client_set.contains(&oid) {
            max_to_shallow = max_to_shallow.max(depth);
        }
        for p in parent_commits(repo, oid).ok()? {
            let nd = depth.saturating_add(1);
            let prev = best_depth.get(&p).copied().unwrap_or(usize::MAX);
            if nd < prev {
                best_depth.insert(p, nd);
                q.push_back((p, nd));
            }
        }
    }
    if max_to_shallow == 0 {
        return None;
    }
    Some(max_to_shallow.saturating_add(deepen))
}

#[cfg(test)]
mod depth_tests {
    use std::path::Path;
    use std::process::Command;

    use super::{compute_shallow_response, ShallowRequest};
    use crate::objects::{ObjectId, ObjectKind};
    use crate::repo::{InitOptions, Repository};

    const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

    fn init_single_commit_bare(dir: &Path) -> (Repository, ObjectId) {
        let (repo, _) = Repository::init(
            dir,
            &InitOptions::new()
                .with_bare(true)
                .with_initial_branch("main".to_owned()),
        )
        .expect("init");
        let commit_body = format!(
            "tree {EMPTY_TREE}\nauthor T <t@x> 1 +0000\ncommitter T <t@x> 1 +0000\n\nonly\n"
        );
        let tip = repo
            .odb()
            .write_loose_materialize(ObjectKind::Commit, commit_body.as_bytes())
            .expect("commit");
        crate::refs::write_ref(dir, "refs/heads/main", &tip).expect("ref");
        (repo, tip)
    }

    fn shallow_for_depth(repo: &Repository, wants: &[ObjectId], depth: u32) -> Vec<ObjectId> {
        let req = ShallowRequest {
            depth: Some(depth),
            ..ShallowRequest::default()
        };
        compute_shallow_response(repo, wants, &req)
            .expect("shallow response")
            .shallow
    }

    #[test]
    fn deepen_one_on_root_commit_advertises_it_shallow() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (repo, tip) = init_single_commit_bare(dir.path());
        assert_eq!(shallow_for_depth(&repo, &[tip], 1), vec![tip]);
    }

    #[test]
    fn deepen_beyond_history_advertises_nothing() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (repo, tip) = init_single_commit_bare(dir.path());
        assert!(shallow_for_depth(&repo, &[tip], 5).is_empty());
    }

    #[test]
    fn tag_wants_count_from_the_tagged_commit() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (repo, tip) = init_single_commit_bare(dir.path());
        let tag_body = format!(
            "object {}\ntype commit\ntag v1\ntagger T <t@x> 1 +0000\n\nv1\n",
            tip.to_hex()
        );
        let tag = repo
            .odb()
            .write_loose_materialize(ObjectKind::Tag, tag_body.as_bytes())
            .expect("tag");
        assert_eq!(shallow_for_depth(&repo, &[tag], 1), vec![tip]);
        assert_eq!(shallow_for_depth(&repo, &[tip, tag], 1), vec![tip]);
        let tree = ObjectId::from_hex(EMPTY_TREE).expect("empty tree");
        assert!(shallow_for_depth(&repo, &[tree], 1).is_empty());
    }

    fn git_clone_depth(bare: &Path, dest: &Path, depth: u32) -> bool {
        Command::new("git")
            .args(["clone", "-q", "--depth", &depth.to_string()])
            .arg(format!("file://{}", bare.display()))
            .arg(dest)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .status()
            .is_ok_and(|s| s.success())
    }

    #[cfg_attr(
        not(feature = "full-tests"),
        ignore = "starts system git or is heavy; run with --features full-tests"
    )]
    #[test]
    fn single_commit_shallow_borders_match_git_clone_depth() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (repo, tip) = init_single_commit_bare(dir.path());
        assert_eq!(shallow_for_depth(&repo, &[tip], 1).len(), 1);
        assert!(shallow_for_depth(&repo, &[tip], 5).is_empty());

        let d1 = dir.path().join("git-d1");
        let d5 = dir.path().join("git-d5");
        assert!(git_clone_depth(dir.path(), &d1, 1), "git clone --depth 1");
        assert!(git_clone_depth(dir.path(), &d5, 5), "git clone --depth 5");
        assert!(d1.join(".git/shallow").is_file());
        assert!(!d5.join(".git/shallow").is_file());
    }
}