Debian Codegraph @

examples/add.rs

raw
1 /*
2 * libgit2 "add" example - shows how to modify the index
3 *
4 * Written by the libgit2 contributors
5 *
6 * To the extent possible under law, the author(s) have dedicated all copyright
7 * and related and neighboring rights to this software to the public domain
8 * worldwide. This software is distributed without any warranty.
9 *
10 * You should have received a copy of the CC0 Public Domain Dedication along
11 * with this software. If not, see
12 * <http://creativecommons.org/publicdomain/zero/1.0/>.
13 */
14
15 #![deny(warnings)]
16 #![allow(trivial_casts)]
17
18 use clap::Parser;
19 use git2::Repository;
20 use std::path::Path;
21
22 #[derive(Parser)]
23 struct Args {
24 #[structopt(name = "spec")]
25 arg_spec: Vec<String>,
26 #[structopt(name = "dry_run", short = 'n', long)]
27 /// dry run
28 flag_dry_run: bool,
29 #[structopt(name = "verbose", short, long)]
30 /// be verbose
31 flag_verbose: bool,
32 #[structopt(name = "update", short, long)]
33 /// update tracked files
34 flag_update: bool,
35 }
36
37 fn run(args: &Args) -> Result<(), git2::Error> {
38 let repo = Repository::open(&Path::new("."))?;
39 let mut index = repo.index()?;
40
41 let cb = &mut |path: &Path, _matched_spec: &[u8]| -> i32 {
42 let status = repo.status_file(path).unwrap();
43
44 let ret = if status.contains(git2::Status::WT_MODIFIED)
45 || status.contains(git2::Status::WT_NEW)
46 {
47 println!("add '{}'", path.display());
48 0
49 } else {
50 1
51 };
52
53 if args.flag_dry_run {
54 1
55 } else {
56 ret
57 }
58 };
59 let cb = if args.flag_verbose || args.flag_update {
60 Some(cb as &mut git2::IndexMatchedPath)
61 } else {
62 None
63 };
64
65 if args.flag_update {
66 index.update_all(args.arg_spec.iter(), cb)?;
67 } else {
68 index.add_all(args.arg_spec.iter(), git2::IndexAddOption::DEFAULT, cb)?;
69 }
70
71 index.write()?;
72 Ok(())
73 }
74
75 fn main() {
76 let args = Args::parse();
77 match run(&args) {
78 Ok(()) => {}
79 Err(e) => println!("error: {}", e),
80 }
81 }