git2_testing/
lib.rs

1use git2::Repository;
2use tempfile::TempDir;
3
4///
5pub fn repo_init_empty() -> (TempDir, Repository) {
6	init_log();
7
8	sandbox_config_files();
9
10	let td = TempDir::new().unwrap();
11	let repo = Repository::init(td.path()).unwrap();
12	{
13		let mut config = repo.config().unwrap();
14		config.set_str("user.name", "name").unwrap();
15		config.set_str("user.email", "email").unwrap();
16	}
17
18	(td, repo)
19}
20
21///
22pub fn repo_init() -> (TempDir, Repository) {
23	init_log();
24
25	sandbox_config_files();
26
27	let td = TempDir::new().unwrap();
28	let repo = Repository::init(td.path()).unwrap();
29	{
30		let mut config = repo.config().unwrap();
31		config.set_str("user.name", "name").unwrap();
32		config.set_str("user.email", "email").unwrap();
33
34		let mut index = repo.index().unwrap();
35		let id = index.write_tree().unwrap();
36
37		let tree = repo.find_tree(id).unwrap();
38		let sig = repo.signature().unwrap();
39		repo.commit(Some("HEAD"), &sig, &sig, "initial", &tree, &[])
40			.unwrap();
41	}
42
43	(td, repo)
44}
45
46// init log
47fn init_log() {
48	let _ = env_logger::builder()
49		.is_test(true)
50		.filter_level(log::LevelFilter::Trace)
51		.try_init();
52}
53
54/// Same as `repo_init`, but the repo is a bare repo (--bare)
55pub fn repo_init_bare() -> (TempDir, Repository) {
56	init_log();
57
58	let tmp_repo_dir = TempDir::new().unwrap();
59	let bare_repo =
60		Repository::init_bare(tmp_repo_dir.path()).unwrap();
61
62	(tmp_repo_dir, bare_repo)
63}
64
65/// Calling `set_search_path` with an empty directory makes sure that there
66/// is no git config interfering with our tests (for example user-local
67/// `.gitconfig`).
68#[allow(unsafe_code)]
69fn sandbox_config_files() {
70	use git2::{opts::set_search_path, ConfigLevel};
71	use std::sync::Once;
72
73	static INIT: Once = Once::new();
74
75	// Adapted from https://github.com/rust-lang/cargo/pull/9035
76	INIT.call_once(|| unsafe {
77		let temp_dir = TempDir::new().unwrap();
78		let path = temp_dir.path();
79
80		set_search_path(ConfigLevel::System, path).unwrap();
81		set_search_path(ConfigLevel::Global, path).unwrap();
82		set_search_path(ConfigLevel::XDG, path).unwrap();
83		set_search_path(ConfigLevel::ProgramData, path).unwrap();
84	});
85}