git_digger/
lib.rs

1use std::env;
2use std::error::Error;
3use std::fs;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use once_cell::sync::Lazy;
8use regex::Regex;
9
10const URL_REGEXES: [&str; 3] = [
11    "^https?://(github.com)/([^/]+)/([^/]+)/?.*$",
12    "^https?://(gitlab.com)/([^/]+)/([^/]+)/?.*$",
13    "^https?://(salsa.debian.org)/([^/]+)/([^/]+)/?.*$",
14];
15
16#[derive(Debug, PartialEq)]
17#[allow(dead_code)]
18pub struct Repository {
19    host: String,
20    owner: String,
21    repo: String,
22}
23
24#[allow(dead_code)]
25impl Repository {
26    /// Represent a git repository in one of the git hosting providers
27    fn new(host: &str, owner: &str, repo: &str) -> Self {
28        Self {
29            host: host.to_string(),
30            owner: owner.to_string(),
31            repo: repo.to_string(),
32        }
33    }
34
35    /// Extracts the owner and repository name from a URL.
36    ///
37    /// Returns Repository
38    ///
39    /// Where host is either "github" or "gitlab" for now.
40    ///
41    /// e.g. https://github.com/szabgab/rust-digger -> ("github", "szabgab", "rust-digger")
42    pub fn from_url(url: &str) -> Result<Self, Box<dyn Error>> {
43        static REGS: Lazy<Vec<Regex>> = Lazy::new(|| {
44            URL_REGEXES
45                .iter()
46                .map(|reg| Regex::new(reg).unwrap())
47                .collect::<Vec<Regex>>()
48        });
49
50        for re in REGS.iter() {
51            if let Some(repo_url) = re.captures(url) {
52                let host = repo_url[1].to_lowercase();
53                let owner = repo_url[2].to_lowercase();
54                let repo = repo_url[3].to_lowercase();
55                return Ok(Self { host, owner, repo });
56            }
57        }
58        Err(format!("No match for repo in '{}'", &url).into())
59    }
60
61    pub fn url(&self) -> String {
62        format!("https://{}/{}/{}", self.host, self.owner, self.repo)
63    }
64
65    pub fn path(&self, root: &Path) -> PathBuf {
66        self.owner_path(root).join(&self.repo)
67    }
68
69    pub fn owner_path(&self, root: &Path) -> PathBuf {
70        root.join(&self.host).join(&self.owner)
71    }
72
73    pub fn is_github(&self) -> bool {
74        &self.host == "github.com"
75    }
76
77    pub fn is_gitlab(&self) -> bool {
78        ["gitlab.com", "salsa.debian.org"].contains(&self.host.as_str())
79    }
80
81    //let _ = git2::Repository::clone(repo, temp_dir_str);
82    /// Run `git clone` or `git pull` to update a single repository
83    pub fn update_repository(&self, root: &Path, clone: bool) -> Result<(), Box<dyn Error>> {
84        let owner_path = self.owner_path(root);
85        let current_dir = env::current_dir()?;
86        log::info!(
87            "Creating owner_path {:?} while current_dir is {:?}",
88            &owner_path,
89            &current_dir
90        );
91        fs::create_dir_all(&owner_path)?;
92        let repo_path = self.path(root);
93        if Path::new(&repo_path).exists() {
94            if clone {
95                log::info!("repo exist but we only clone now.  Skipping.");
96            } else {
97                log::info!("repo exist; cd to {:?}", &repo_path);
98                env::set_current_dir(&repo_path)?;
99                self.git_pull();
100            }
101        } else {
102            log::info!("new repo; cd to {:?}", &owner_path);
103            env::set_current_dir(owner_path)?;
104            self.git_clone();
105        }
106        env::set_current_dir(current_dir)?;
107        Ok(())
108    }
109
110    fn git_pull(&self) {
111        if !self.check_url() {
112            log::error!("Repository URL is not reachable: {}", self.url());
113            return;
114        }
115
116        let current_dir = env::current_dir().unwrap();
117        log::info!("git pull in {current_dir:?}");
118
119        match Command::new("git").arg("pull").output() {
120            Ok(result) => {
121                if result.status.success() {
122                    log::info!(
123                        "git_pull exit code: '{}' in folder {:?}",
124                        result.status,
125                        current_dir
126                    );
127                } else {
128                    log::warn!(
129                        "git_pull exit code: '{}' in folder {:?}",
130                        result.status,
131                        current_dir
132                    );
133                }
134            }
135            Err(err) => {
136                log::error!("Could not run git_pull in folder {current_dir:?} error: {err}")
137            }
138        }
139    }
140
141    fn git_clone(&self) {
142        if !self.check_url() {
143            log::error!("Repository URL is not reachable: {}", self.url());
144            return;
145        }
146
147        let current_dir = env::current_dir().unwrap();
148
149        let url = self.url();
150        log::info!("git clone {url} in {current_dir:?}");
151
152        match Command::new("git").arg("clone").arg(self.url()).output() {
153            Ok(result) => {
154                if result.status.success() {
155                    log::info!("git_clone exit code: '{}'", result.status);
156                } else {
157                    log::warn!(
158                        "git_clone exit code: '{}' for url '{}' in '{current_dir:?}'",
159                        result.status,
160                        url,
161                    );
162                }
163            }
164            Err(err) => {
165                log::error!("Could not run `git clone {url}` in {current_dir:?} error: {err}")
166            }
167        }
168    }
169
170    fn check_url(&self) -> bool {
171        let url = self.url();
172        let response = ureq::get(&url).call();
173        match response {
174            Ok(_) => true,
175            Err(err) => {
176                log::error!("Error checking URL '{}': {}", url, err);
177                false
178            }
179        }
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn test_get_owner_and_repo() {
189        let root = Path::new("/tmp");
190        let expected = Repository::new("github.com", "szabgab", "rust-digger");
191
192        // test https github.com, no slash at the end
193        let repo = Repository::from_url("https://github.com/szabgab/rust-digger").unwrap();
194        assert_eq!(repo, expected);
195        assert_eq!(repo.url(), "https://github.com/szabgab/rust-digger");
196        assert_eq!(
197            repo.path(root).to_str(),
198            Some("/tmp/github.com/szabgab/rust-digger")
199        );
200        assert!(repo.is_github());
201        assert!(!repo.is_gitlab());
202
203        // test http github.com trailing slash
204        let repo = Repository::from_url("https://github.com/szabgab/rust-digger/").unwrap();
205        assert_eq!(repo, expected);
206        assert_eq!(repo.url(), "https://github.com/szabgab/rust-digger");
207        assert!(repo.is_github());
208
209        // test http github.com trailing slash
210        let repo = Repository::from_url("http://github.com/szabgab/rust-digger/").unwrap();
211        assert_eq!(repo, expected);
212        assert_eq!(repo.url(), "https://github.com/szabgab/rust-digger");
213        assert!(repo.is_github());
214
215        // test https github.com link to a file
216        let repo = Repository::from_url(
217            "https://github.com/crypto-crawler/crypto-crawler-rs/tree/main/crypto-market-type",
218        )
219        .unwrap();
220        assert_eq!(
221            repo,
222            Repository::new("github.com", "crypto-crawler", "crypto-crawler-rs",)
223        );
224        assert_eq!(
225            repo.url(),
226            "https://github.com/crypto-crawler/crypto-crawler-rs"
227        );
228        assert!(repo.is_github());
229
230        // test https gitlab.com
231        let repo = Repository::from_url("https://gitlab.com/szabgab/rust-digger").unwrap();
232        assert_eq!(
233            repo,
234            Repository::new("gitlab.com", "szabgab", "rust-digger")
235        );
236        assert_eq!(repo.url(), "https://gitlab.com/szabgab/rust-digger");
237        assert!(!repo.is_github());
238        assert!(repo.is_gitlab());
239
240        // test converting to lowercase  gitlab.com
241        let repo = Repository::from_url("https://gitlab.com/Szabgab/Rust-digger/").unwrap();
242        assert_eq!(
243            repo,
244            Repository::new("gitlab.com", "szabgab", "rust-digger")
245        );
246        assert_eq!(repo.url(), "https://gitlab.com/szabgab/rust-digger");
247        assert_eq!(repo.owner, "szabgab");
248        assert_eq!(repo.repo, "rust-digger");
249        assert_eq!(
250            repo.path(root).to_str(),
251            Some("/tmp/gitlab.com/szabgab/rust-digger")
252        );
253
254        // test salsa
255        let repo = Repository::from_url("https://salsa.debian.org/szabgab/rust-digger/").unwrap();
256        assert_eq!(
257            repo,
258            Repository::new("salsa.debian.org", "szabgab", "rust-digger")
259        );
260        assert_eq!(repo.url(), "https://salsa.debian.org/szabgab/rust-digger");
261        assert_eq!(repo.owner, "szabgab");
262        assert_eq!(repo.repo, "rust-digger");
263        assert_eq!(
264            repo.path(root).to_str(),
265            Some("/tmp/salsa.debian.org/szabgab/rust-digger")
266        );
267        assert!(!repo.is_github());
268        assert!(repo.is_gitlab());
269
270        // test incorrect URL
271        let res = Repository::from_url("https://blabla.com/");
272        assert!(res.is_err());
273        assert_eq!(
274            res.unwrap_err().to_string(),
275            "No match for repo in 'https://blabla.com/'"
276        );
277    }
278
279    #[test]
280    fn test_check_good_url() {
281        let repo = Repository::from_url("https://github.com/szabgab/git-digger").unwrap();
282        assert!(repo.check_url());
283    }
284
285    #[test]
286    fn test_check_missing_url() {
287        let repo = Repository::from_url("https://github.com/szabgab/no-such-repo").unwrap();
288        assert!(!repo.check_url());
289    }
290
291    #[test]
292    fn test_clone_missing_repo() {
293        let temp_folder = tempfile::tempdir().unwrap();
294        let repo = Repository::from_url("https://github.com/szabgab/no-such-repo").unwrap();
295        repo.update_repository(Path::new(temp_folder.path()), true)
296            .unwrap();
297        let owner_path = temp_folder.path().join("github.com").join("szabgab");
298        assert!(owner_path.exists());
299        assert!(!owner_path.join("no-such-repo").exists());
300    }
301
302    #[test]
303    fn test_clone_this_repo() {
304        let temp_folder = tempfile::tempdir().unwrap();
305        let repo = Repository::from_url("https://github.com/szabgab/git-digger").unwrap();
306        repo.update_repository(Path::new(temp_folder.path()), true)
307            .unwrap();
308        let owner_path = temp_folder.path().join("github.com").join("szabgab");
309        assert!(owner_path.exists());
310        assert!(owner_path.join("git-digger").exists());
311    }
312}