Extract with_repo_or_exit

This will run a given function in a git repo, or print an error message
and exit if the current working directory is not within a git repo.
This commit is contained in:
Martin Frost 2020-05-22 22:22:42 +02:00
parent 41908686ed
commit ee7c56e0a0
2 changed files with 13 additions and 11 deletions

View File

@ -1,21 +1,12 @@
use git2::Repository;
use std::process;
use std::fs::File;
use git_mob::{get_main_author, gitmessage_template_file_path};
use git_mob::{get_main_author, gitmessage_template_file_path, with_repo_or_exit};
fn main() {
let main_author = get_main_author();
println!("{}", main_author);
match Repository::open_from_env() {
Ok(repo) => {
truncate_gitmessage_template(repo);
}
Err(_e) => {
eprintln!("Not in a git repository");
process::exit(1);
}
}
with_repo_or_exit(truncate_gitmessage_template);
}
fn truncate_gitmessage_template(repo: Repository) {

View File

@ -8,6 +8,7 @@ use std::io::BufReader;
use std::fs::File;
use std::error::Error;
use std::string::String;
use std::process;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Author {
@ -58,3 +59,13 @@ fn parse_coauthors_file() -> Result<BTreeMap<String, Author>, Box<dyn Error>> {
pub fn gitmessage_template_file_path(repo: Repository) -> std::path::PathBuf {
repo.path().join(".gitmessage")
}
pub fn with_repo_or_exit<F: FnOnce(Repository)>(f: F) {
match Repository::open_from_env() {
Ok(repo) => f(repo),
Err(_e) => {
eprintln!("Not in a git repository");
process::exit(1);
}
}
}