Debian Codegraph @

examples/init.rs

raw
1 /*
2 * libgit2 "init" example - shows how to initialize a new repo (also includes how to do an initial commit)
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
17 use clap::Parser;
18 use git2::ObjectFormat;
19 use git2::{Error, Repository, RepositoryInitMode, RepositoryInitOptions};
20 use std::path::{Path, PathBuf};
21
22 #[derive(Parser)]
23 struct Args {
24 #[structopt(name = "directory")]
25 arg_directory: String,
26 #[structopt(name = "quiet", short, long)]
27 /// don't print information to stdout
28 flag_quiet: bool,
29 #[structopt(name = "bare", long)]
30 /// initialize a new bare repository
31 flag_bare: bool,
32 #[structopt(name = "dir", long = "template")]
33 /// use <dir> as an initialization template
34 flag_template: Option<String>,
35 #[structopt(name = "separate-git-dir", long)]
36 /// use <dir> as the .git directory
37 flag_separate_git_dir: Option<String>,
38 #[structopt(name = "initial-commit", long)]
39 /// create an initial empty commit
40 flag_initial_commit: bool,
41 #[structopt(name = "perms", long = "shared")]
42 /// permissions to create the repository with
43 flag_shared: Option<String>,
44 #[structopt(name = "object-format", long, value_parser = parse_object_format)]
45 /// object format to use (sha1 or sha256, requires unstable-sha256 feature to use the sha256 format)
46 flag_object_format: Option<ObjectFormat>,
47 }
48
49 fn run(args: &Args) -> Result<(), Error> {
50 let mut path = PathBuf::from(&args.arg_directory);
51 let repo = if !args.flag_bare
52 && args.flag_template.is_none()
53 && args.flag_shared.is_none()
54 && args.flag_separate_git_dir.is_none()
55 && args.flag_object_format.is_none()
56 {
57 Repository::init(&path)?
58 } else {
59 let mut opts = RepositoryInitOptions::new();
60 opts.bare(args.flag_bare);
61 if let Some(ref s) = args.flag_template {
62 opts.template_path(Path::new(s));
63 }
64
65 // If you specified a separate git directory, then initialize
66 // the repository at that path and use the second path as the
67 // working directory of the repository (with a git-link file)
68 if let Some(ref s) = args.flag_separate_git_dir {
69 opts.workdir_path(&path);
70 path = PathBuf::from(s);
71 }
72
73 if let Some(ref s) = args.flag_shared {
74 opts.mode(parse_shared(s)?);
75 }
76
77 #[cfg(feature = "unstable-sha256")]
78 if let Some(format) = args.flag_object_format {
79 opts.object_format(format);
80 }
81
82 Repository::init_opts(&path, &opts)?
83 };
84
85 // Print a message to stdout like "git init" does
86 if !args.flag_quiet {
87 if args.flag_bare || args.flag_separate_git_dir.is_some() {
88 path = repo.path().to_path_buf();
89 } else {
90 path = repo.workdir().unwrap().to_path_buf();
91 }
92 println!("Initialized empty Git repository in {}", path.display());
93 }
94
95 if args.flag_initial_commit {
96 create_initial_commit(&repo)?;
97 println!("Created empty initial commit");
98 }
99
100 Ok(())
101 }
102
103 /// Unlike regular "git init", this example shows how to create an initial empty
104 /// commit in the repository. This is the helper function that does that.
105 fn create_initial_commit(repo: &Repository) -> Result<(), Error> {
106 // First use the config to initialize a commit signature for the user.
107 let sig = repo.signature()?;
108
109 // Now let's create an empty tree for this commit
110 let tree_id = {
111 let mut index = repo.index()?;
112
113 // Outside of this example, you could call index.add_path()
114 // here to put actual files into the index. For our purposes, we'll
115 // leave it empty for now.
116
117 index.write_tree()?
118 };
119
120 let tree = repo.find_tree(tree_id)?;
121
122 // Ready to create the initial commit.
123 //
124 // Normally creating a commit would involve looking up the current HEAD
125 // commit and making that be the parent of the initial commit, but here this
126 // is the first commit so there will be no parent.
127 repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])?;
128
129 Ok(())
130 }
131
132 fn parse_shared(shared: &str) -> Result<RepositoryInitMode, Error> {
133 match shared {
134 "false" | "umask" => Ok(git2::RepositoryInitMode::SHARED_UMASK),
135 "true" | "group" => Ok(git2::RepositoryInitMode::SHARED_GROUP),
136 "all" | "world" => Ok(git2::RepositoryInitMode::SHARED_ALL),
137 _ => {
138 if shared.starts_with('0') {
139 match u32::from_str_radix(&shared[1..], 8).ok() {
140 Some(n) => Ok(RepositoryInitMode::from_bits_truncate(n)),
141 None => Err(Error::from_str("invalid octal value for --shared")),
142 }
143 } else {
144 Err(Error::from_str("unknown value for --shared"))
145 }
146 }
147 }
148 }
149
150 fn parse_object_format(format: &str) -> Result<ObjectFormat, Error> {
151 match format {
152 "sha1" => Ok(ObjectFormat::Sha1),
153 #[cfg(feature = "unstable-sha256")]
154 "sha256" => Ok(ObjectFormat::Sha256),
155 _ => Err(Error::from_str("object format must be 'sha1' or 'sha256'")),
156 }
157 }
158
159 fn main() {
160 let args = Args::parse();
161 match run(&args) {
162 Ok(()) => {}
163 Err(e) => println!("error: {}", e),
164 }
165 }