Debian Codegraph @

examples/file-latest-commit.rs

raw
1 #![deny(warnings)]
2
3 use clap::Parser;
4 use git2::{DiffOptions, Repository, Sort};
5
6 #[derive(Parser)]
7 struct Args {
8 /// Directory to use as the base directory
9 #[arg(short, long, default_value = ".")]
10 dir: String,
11
12 /// Path to the file relative to the git repo
13 #[arg(short, long)]
14 path: String,
15
16 /// Branch to check against, otherwise uses the default
17 #[arg(short, long)]
18 branch: Option<String>,
19 }
20
21 fn run(args: &Args) -> Result<(), git2::Error> {
22 let repo = Repository::open(args.dir.clone())?;
23
24 let mut revwalk = repo.revwalk()?;
25 match &args.branch {
26 Some(branch) => revwalk.push_ref(&format!("refs/heads/{}", branch))?,
27 None => revwalk.push_head()?,
28 };
29 revwalk.set_sorting(Sort::TIME)?;
30 let branch_display = match &args.branch {
31 Some(branch) => format!("on branch {}", branch),
32 None => "on default branch".to_string(),
33 };
34
35 for oid_result in revwalk {
36 let oid = oid_result?;
37 let commit = repo.find_commit(oid)?;
38
39 let tree = commit.tree()?;
40
41 let parent_tree = if commit.parent_count() > 0 {
42 Some(commit.parent(0)?.tree()?)
43 } else {
44 // Initial commit
45 None
46 };
47
48 let mut diff_opts = DiffOptions::new();
49 diff_opts.pathspec(args.path.clone());
50
51 let diff =
52 repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), Some(&mut diff_opts))?;
53
54 if diff.deltas().len() > 0 {
55 println!(
56 "Most recent commit modifying {} {}: {}",
57 args.path, branch_display, oid
58 );
59 return Ok(());
60 }
61 }
62
63 println!(
64 "Error: no modifying commit found modifying {} {}",
65 args.path, branch_display
66 );
67 Ok(())
68 }
69
70 fn main() {
71 let args = Args::parse();
72 match run(&args) {
73 Ok(()) => {}
74 Err(e) => println!("error: {}", e),
75 }
76 }