1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
use std::{
path::{Path, PathBuf},
sync::Arc,
};
use anyhow::{anyhow, Error, Result};
use git2::{Oid, Signature};
use parking_lot::Mutex;
use crate::{commit_diff_loader::CommitDiffLoader, Commit, CommitDiff, CommitDiffLoaderOptions, Config, Reference};
#[derive(Clone)]
pub struct Repository {
repository: Arc<Mutex<git2::Repository>>,
}
impl Repository {
#[inline]
pub fn open_from_env() -> Result<Self> {
let repository = git2::Repository::open_from_env()
.map_err(|e| anyhow!(String::from(e.message())).context("Could not open repository from environment"))?;
Ok(Self {
repository: Arc::new(Mutex::new(repository)),
})
}
#[inline]
pub fn open_from_path(path: &Path) -> Result<Self> {
let repository = git2::Repository::open(path)
.map_err(|e| anyhow!(String::from(e.message())).context("Could not open repository from path"))?;
Ok(Self {
repository: Arc::new(Mutex::new(repository)),
})
}
#[inline]
pub fn load_config(&self) -> Result<Config> {
self.repository
.lock()
.config()
.map_err(|e| anyhow!(String::from(e.message())))
}
#[inline]
pub fn load_commit_diff(&self, hash: &str, config: &CommitDiffLoaderOptions) -> Result<CommitDiff> {
let oid = self.repository.lock().revparse_single(hash)?.id();
let diff_loader_repository = Arc::clone(&self.repository);
let loader = CommitDiffLoader::new(diff_loader_repository, config);
Ok(loader.load_from_hash(oid).map_err(|e| anyhow!("{}", e))?.remove(0))
}
#[inline]
pub fn find_reference(&self, reference: &str) -> Result<Reference> {
let repo = self.repository.lock();
let git2_reference = repo.find_reference(reference)?;
Ok(Reference::from(&git2_reference))
}
#[inline]
pub fn find_commit(&self, reference: &str) -> Result<Commit> {
let repo = self.repository.lock();
let git2_reference = repo.find_reference(reference)?;
Commit::try_from(&git2_reference)
}
pub(crate) fn repo_path(&self) -> PathBuf {
self.repository.lock().path().to_path_buf()
}
pub(crate) fn head_id(&self, head_name: &str) -> Result<Oid> {
let repo = self.repository.lock();
let ref_name = format!("refs/heads/{}", head_name);
let revision = repo.revparse_single(ref_name.as_str())?;
Ok(revision.id())
}
pub(crate) fn commit_id_from_ref(&self, reference: &str) -> Result<Oid> {
let repo = self.repository.lock();
let commit = repo.find_reference(reference)?.peel_to_commit()?;
Ok(commit.id())
}
pub(crate) fn add_path_to_index(&self, path: &Path) -> Result<()> {
let repo = self.repository.lock();
let mut index = repo.index()?;
index.add_path(path).map_err(Error::from)
}
pub(crate) fn remove_path_from_index(&self, path: &Path) -> Result<()> {
let repo = self.repository.lock();
let mut index = repo.index()?;
index.remove_path(path).map_err(Error::from)
}
pub(crate) fn create_commit_on_index(
&self,
reference: &str,
author: &Signature<'_>,
committer: &Signature<'_>,
message: &str,
) -> Result<()> {
let repo = self.repository.lock();
let tree = repo.find_tree(repo.index()?.write_tree()?)?;
let head = repo.find_reference(reference)?.peel_to_commit()?;
let _ = repo.commit(Some("HEAD"), author, committer, message, &tree, &[&head])?;
Ok(())
}
#[cfg(test)]
pub(crate) fn repository(&self) -> Arc<Mutex<git2::Repository>> {
self.repository.clone()
}
}
impl From<git2::Repository> for Repository {
#[inline]
fn from(repository: git2::Repository) -> Self {
Self {
repository: Arc::new(Mutex::new(repository)),
}
}
}
impl ::std::fmt::Debug for Repository {
#[inline]
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> Result<(), ::std::fmt::Error> {
f.debug_struct("Repository")
.field("[path]", &self.repository.lock().path())
.finish()
}
}
#[cfg(all(unix, test))]
mod tests {
use std::env::set_var;
use super::*;
use crate::testutil::{commit_id_from_ref, create_commit, with_temp_bare_repository, with_temp_repository};
#[test]
#[serial_test::serial]
fn open_from_env() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("test")
.join("fixtures")
.join("simple");
set_var("GIT_DIR", path.to_str().unwrap());
assert!(Repository::open_from_env().is_ok());
}
#[test]
#[serial_test::serial]
fn open_from_env_error() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("test")
.join("fixtures")
.join("does-not-exist");
set_var("GIT_DIR", path.to_str().unwrap());
assert_eq!(
format!("{:#}", Repository::open_from_env().err().unwrap()),
format!(
"Could not open repository from environment: failed to resolve path '{}': No such file or directory",
path.to_str().unwrap()
)
);
}
#[test]
fn open_from_path() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("test")
.join("fixtures")
.join("simple");
assert!(Repository::open_from_path(&path).is_ok());
}
#[test]
fn open_from_path_error() {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("test")
.join("fixtures")
.join("does-not-exist");
assert_eq!(
format!("{:#}", Repository::open_from_path(&path).err().unwrap()),
format!(
"Could not open repository from path: failed to resolve path '{}': No such file or directory",
path.to_str().unwrap()
)
);
}
#[test]
fn load_config() {
with_temp_bare_repository(|repo| {
let _repo = repo.load_config()?;
Ok(())
});
}
#[test]
fn load_commit_diff() {
with_temp_repository(|repository| {
create_commit(&repository, None);
let id = commit_id_from_ref(&repository, "refs/heads/main");
let _diff = repository
.load_commit_diff(id.to_string().as_str(), &CommitDiffLoaderOptions::new())
.unwrap();
Ok(())
});
}
#[test]
fn fmt() {
with_temp_bare_repository(|repository| {
let formatted = format!("{:?}", repository);
let path = repository.repo_path().canonicalize().unwrap();
assert_eq!(
formatted,
format!("Repository {{ [path]: \"{}/\" }}", path.to_str().unwrap())
);
Ok(())
});
}
}