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
use std::path::Path;
use std::path::PathBuf;
use failure::Fail;
use git2;
use git2::Repository;
use log;
use crate::types::ResultDynError;
#[derive(Debug, Fail)]
pub enum GitRepoError {
#[fail(display = "Repo is empty")]
EmptyRepoError,
}
pub struct GitRepo {
repo: Repository,
}
pub struct Commit<'repo> {
pub hash: String,
pub message: String,
raw_commit: git2::Commit<'repo>,
}
pub struct CommitIterator<'repo> {
git_repo: &'repo GitRepo,
revision_walker: git2::Revwalk<'repo>,
}
impl<'repo> Iterator for CommitIterator<'repo> {
type Item = ResultDynError<Commit<'repo>>;
fn next(&mut self) -> Option<ResultDynError<Commit<'repo>>> {
let oid: Option<Result<git2::Oid, git2::Error>> = self.revision_walker.next();
log::debug!("Iterating {:?}", oid);
if oid.is_none() {
return None;
}
let oid: ResultDynError<git2::Oid> = oid.unwrap().map_err(failure::Error::from);
let oid = oid.map(|oid| {
return format!("{}", oid);
});
let commit = oid.map(|oid| format!("{}", oid)).and_then(|oid| {
return self.git_repo.find_commit_by_id(&oid);
});
return Some(commit);
}
}
impl GitRepo {
pub fn new(repo_path: impl AsRef<Path>) -> ResultDynError<GitRepo> {
let repo = Repository::discover(repo_path.as_ref())?;
return Ok(GitRepo { repo });
}
pub fn upsert(repo_path: impl AsRef<Path>) -> ResultDynError<GitRepo> {
let repo_path = PathBuf::from(repo_path.as_ref());
let repo = Repository::init(&repo_path)?;
return Ok(GitRepo { repo });
}
}
impl GitRepo {
pub fn find_commit_by_id(&self, hash: &str) -> ResultDynError<Commit> {
let commit = self.repo.find_commit(git2::Oid::from_str(hash)?)?;
return Ok(Commit {
hash: String::from(hash),
message: String::from(commit.message().unwrap()),
raw_commit: commit,
});
}
pub fn commit_file(&self, filepath: impl AsRef<Path>, message: &str) -> ResultDynError<()> {
let mut repo_index = self.repo.index()?;
let filepath = PathBuf::from(filepath.as_ref());
let old_tree = self.repo.find_tree(repo_index.write_tree()?)?;
repo_index.add_path(filepath.as_ref())?;
repo_index.write()?;
log::debug!("Getting the oid for write tree");
let current_oid = repo_index.write_tree()?;
log::debug!(
"Got oid {}, now finding the current tree by oid",
current_oid
);
let current_tree = self.repo.find_tree(current_oid)?;
if self.repo.is_empty()? {
log::debug!("Creating initial commit..");
self.repo.commit(
Some("HEAD"),
&self.repo.signature()?,
&self.repo.signature()?,
&message,
¤t_tree,
&vec![],
)?;
} else {
log::debug!("Finding repo head..");
let head = self.repo.head()?;
let head_commit = self.repo.find_commit(head.target().unwrap())?;
log::debug!(
"Found repo head: {:?}, adding {:?} to index path",
head_commit,
filepath
);
let diff = self
.repo
.diff_tree_to_index(Some(&old_tree), Some(&repo_index), None)?;
log::debug!("Diff deltas {:?}", diff.deltas().collect::<Vec<_>>());
if diff.deltas().len() == 0 {
return Ok(());
}
self.repo.commit(
Some("HEAD"),
&self.repo.signature()?,
&self.repo.signature()?,
&message,
¤t_tree,
&[&head_commit],
)?;
}
return Ok(());
}
pub fn commit_iterator(&self) -> ResultDynError<CommitIterator> {
self.make_sure_repo_not_empty()?;
log::debug!("Getting revwalk");
let mut revision_walker = self.repo.revwalk()?;
log::debug!("Moving pointer to HEAD");
revision_walker.push_head()?;
return Ok(CommitIterator {
git_repo: self,
revision_walker: revision_walker,
});
}
pub fn last_commit_hash(&self) -> ResultDynError<String> {
return self
.commit_iterator()
.and_then(|iterator: CommitIterator| iterator.take(1).next().unwrap())
.map(|commit: Commit| commit.hash);
}
pub fn get_file_content_at_commit(
&self,
filepath: impl AsRef<Path>,
hash: &str,
) -> ResultDynError<Vec<u8>> {
let filepath = PathBuf::from(filepath.as_ref());
let commit = self.find_commit_by_id(hash)?;
let commit_tree = commit.raw_commit.tree()?;
let sql = commit_tree.get_path(filepath.as_ref())?;
let sql = sql.to_object(&self.repo)?;
let sql = sql
.as_blob()
.expect(&format!("{:?} is not a blob", filepath))
.content();
return Ok(Vec::from(sql));
}
fn make_sure_repo_not_empty(&self) -> ResultDynError<()> {
if self.repo.is_empty()? {
return Err(GitRepoError::EmptyRepoError.into());
}
return Ok(());
}
}
#[cfg(test)]
mod test {
use super::*;
use std::fs;
struct DirCleaner {
dir: String,
}
impl Drop for DirCleaner {
fn drop(&mut self) {
fs::remove_dir_all(&self.dir).unwrap();
}
}
mod upsert {
use super::*;
#[test]
fn it_should_create_repo_when_repo_does_not_exist() {
let repo_path = String::from("/tmp/test-repo");
let _dir_cleaner = DirCleaner {
dir: repo_path.clone(),
};
GitRepo::upsert("/tmp/test-repo").unwrap();
assert!(PathBuf::from(&repo_path).exists());
assert!(PathBuf::from(&repo_path).join(".git").exists());
}
}
mod commit {
use super::*;
#[test]
fn it_should_create_initial_commit_on_bare_repo() {}
}
}