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
use git2::{build::CheckoutBuilder, BranchType, Direction, ObjectType, Repository};
use log::info;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
pub struct Page {
pub secret: String,
pub repo: String,
pub path: String,
pub branch: String,
}
impl Page {
fn create_repo(&self) -> Repository {
let repo = Repository::open(&self.path);
if let Ok(repo) = repo {
return repo;
} else {
info!("Cloning repository {} at {}", self.repo, self.path);
Repository::clone(&self.repo, &self.path).unwrap()
};
let repo = Repository::open(&self.path).unwrap();
{
self._fetch_upstream(&repo, &self.branch);
let branch = repo
.find_branch(&format!("origin/{}", &self.branch), BranchType::Remote)
.unwrap();
let mut checkout_options = CheckoutBuilder::new();
checkout_options.force();
let tree = branch.get().peel(ObjectType::Tree).unwrap();
repo.checkout_tree(&tree, Some(&mut checkout_options))
.unwrap();
repo.set_head(branch.get().name().unwrap()).unwrap();
}
repo
}
fn _fetch_upstream(&self, repo: &Repository, branch: &str) {
let mut remote = repo.find_remote("origin").unwrap();
remote.connect(Direction::Fetch).unwrap();
info!("Updating repository {}", self.repo);
remote.fetch(&[branch], None, None).unwrap();
remote.disconnect().unwrap();
}
pub fn fetch_upstream(&self, branch: &str) {
let repo = self.create_repo();
self._fetch_upstream(&repo, branch);
}
}
#[cfg(test)]
mod tests {
use super::*;
use mktemp::Temp;
#[actix_rt::test]
async fn pages_works() {
let tmp_dir = Temp::new_dir().unwrap();
assert!(tmp_dir.exists(), "tmp directory successully created");
let page = Page {
secret: String::default(),
repo: "https://github.com/mcaptcha/website".to_owned(),
path: tmp_dir.to_str().unwrap().to_string(),
branch: "gh-pages".to_string(),
};
assert!(
Repository::open(tmp_dir.as_path()).is_err(),
"repository doesn't exist yet"
);
let repo = page.create_repo();
assert!(!repo.is_bare(), "repository isn't bare");
page.create_repo();
assert!(
Repository::open(tmp_dir.as_path()).is_ok(),
"repository exists yet"
);
}
}