Skip to content
This repository has been archived by the owner on Sep 26, 2023. It is now read-only.

Commit

Permalink
Handle errors when loading git repos
Browse files Browse the repository at this point in the history
Replace mutable loop with functional code
Add handling for more failure cases
Silently discard repos that failed to load
  • Loading branch information
Kit committed Apr 5, 2019
1 parent ab34296 commit de7bf87
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 18 deletions.
39 changes: 22 additions & 17 deletions git/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
pub extern crate git2;

use git2::{Error, Repository};
use std::{collections::HashMap, fs, io, path::Path};
use std::{collections::HashMap, fs, path::Path};

pub trait GitOps {
fn cat_file(
Expand Down Expand Up @@ -32,23 +32,28 @@ impl GitOps for LibGitOps {
}
}

pub fn load_repos(root_path: &Path) -> Result<HashMap<String, Repository>, io::Error> {
let mut repos = HashMap::new();
if root_path.is_dir() {
for entry in fs::read_dir(root_path)? {
let path = entry.map(|x| x.path())?;
if path.is_dir() {
if let Some(fstem) = path.to_owned().file_stem() {
// Just ignoring any error opening the repo as it means a directory is
// not a valid git repo.
let _ = Repository::open(path).map(|repo| {
repos.insert(fstem.to_os_string().into_string().unwrap(), repo) //TODO remove unwrap
});
pub fn load_repos(root_path: &Path) -> HashMap<String, Repository> {
fs::read_dir(root_path)
.expect("Failed to read repos directory")
.filter_map(|entry| {
entry.ok().and_then(|e| {
let path = e.path();
if path.is_dir() {
let local_path = path.clone();
let repo_name = local_path
.file_stem()
.and_then(|name| name.to_os_string().into_string().ok());

repo_name.and_then(|name| {
Repository::open(path).ok().and_then(|repo| Some((name, repo)))
})
} else {
None
}
}
}
}
Ok(repos)
})
})
.into_iter()
.collect()
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub struct AppState {
fn run_server(host: &str, port: &str, repo_root: &Path) {
let _sys = System::new("gitkv-server");

let addr = GitRepos::new(git::load_repos(&repo_root).expect("can't load repos")).start();
let addr = GitRepos::new(git::load_repos(&repo_root)).start();

let listen_address = format!("{}:{}", host, port);

Expand Down

0 comments on commit de7bf87

Please sign in to comment.