Debian Codegraph @

examples/rev-list.rs

raw
1 /*
2 * libgit2 "rev-list" example - shows how to transform a rev-spec into a list
3 * of commit ids
4 *
5 * Written by the libgit2 contributors
6 *
7 * To the extent possible under law, the author(s) have dedicated all copyright
8 * and related and neighboring rights to this software to the public domain
9 * worldwide. This software is distributed without any warranty.
10 *
11 * You should have received a copy of the CC0 Public Domain Dedication along
12 * with this software. If not, see
13 * <http://creativecommons.org/publicdomain/zero/1.0/>.
14 */
15
16 #![deny(warnings)]
17
18 use clap::Parser;
19 use git2::{Error, Oid, Repository, Revwalk};
20
21 #[derive(Parser)]
22 struct Args {
23 #[structopt(name = "topo-order", long)]
24 /// sort commits in topological order
25 flag_topo_order: bool,
26 #[structopt(name = "date-order", long)]
27 /// sort commits in date order
28 flag_date_order: bool,
29 #[structopt(name = "reverse", long)]
30 /// sort commits in reverse
31 flag_reverse: bool,
32 #[structopt(name = "not")]
33 /// don't show <spec>
34 flag_not: Vec<String>,
35 #[structopt(name = "spec", last = true)]
36 arg_spec: Vec<String>,
37 }
38
39 fn run(args: &Args) -> Result<(), git2::Error> {
40 let repo = Repository::open(".")?;
41 let mut revwalk = repo.revwalk()?;
42
43 let base = if args.flag_reverse {
44 git2::Sort::REVERSE
45 } else {
46 git2::Sort::NONE
47 };
48 revwalk.set_sorting(
49 base | if args.flag_topo_order {
50 git2::Sort::TOPOLOGICAL
51 } else if args.flag_date_order {
52 git2::Sort::TIME
53 } else {
54 git2::Sort::NONE
55 },
56 )?;
57
58 let specs = args
59 .flag_not
60 .iter()
61 .map(|s| (s, true))
62 .chain(args.arg_spec.iter().map(|s| (s, false)))
63 .map(|(spec, hide)| {
64 if spec.starts_with('^') {
65 (&spec[1..], !hide)
66 } else {
67 (&spec[..], hide)
68 }
69 });
70 for (spec, hide) in specs {
71 let id = if spec.contains("..") {
72 let revspec = repo.revparse(spec)?;
73 if revspec.mode().contains(git2::RevparseMode::MERGE_BASE) {
74 return Err(Error::from_str("merge bases not implemented"));
75 }
76 push(&mut revwalk, revspec.from().unwrap().id(), !hide)?;
77 revspec.to().unwrap().id()
78 } else {
79 repo.revparse_single(spec)?.id()
80 };
81 push(&mut revwalk, id, hide)?;
82 }
83
84 for id in revwalk {
85 let id = id?;
86 println!("{}", id);
87 }
88 Ok(())
89 }
90
91 fn push(revwalk: &mut Revwalk, id: Oid, hide: bool) -> Result<(), Error> {
92 if hide {
93 revwalk.hide(id)
94 } else {
95 revwalk.push(id)
96 }
97 }
98
99 fn main() {
100 let args = Args::parse();
101 match run(&args) {
102 Ok(()) => {}
103 Err(e) => println!("error: {}", e),
104 }
105 }