diff --git a/src/bin/git-add-coauthor.rs b/src/bin/git-add-coauthor.rs new file mode 100644 index 0000000..2e5afb7 --- /dev/null +++ b/src/bin/git-add-coauthor.rs @@ -0,0 +1,24 @@ +use git_mob::{Author, get_available_coauthors, write_coauthors_file} ; +use structopt::StructOpt; + +#[derive(StructOpt,Debug)] +struct Opt { + /// Co-author initials + initials: String, + /// The name of the co-author, in quotes, e.g. "Foo Bar" + name: String, + /// The email of the co-author + email: String, +} + +fn main() { + let opt = Opt::from_args(); + let mut authors = get_available_coauthors(); + let new_author = Author { + name: opt.name, + email: opt.email, + }; + authors.insert(opt.initials, new_author); + + write_coauthors_file(authors); +} diff --git a/src/lib.rs b/src/lib.rs index 9c13318..19e6426 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use std::fs; use git2::{Config, Repository}; use std::fmt; use std::collections::BTreeMap; @@ -12,8 +13,8 @@ use std::process; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Author { - name: String, - email: String, + pub name: String, + pub email: String, } impl fmt::Display for Author { @@ -44,7 +45,7 @@ pub fn get_available_coauthors() -> BTreeMap { } fn parse_coauthors_file() -> Result, Box> { - let coauthors_path = home_dir().unwrap().join(".git-coauthors"); + let coauthors_path = coauthors_file_path(); let coauthors_file = File::open(coauthors_path)?; let reader = BufReader::new(coauthors_file); @@ -69,3 +70,20 @@ pub fn with_repo_or_exit(f: F) { } } } + +pub fn write_coauthors_file(authors: BTreeMap) { + let mut wrapper_tree = BTreeMap::new(); + wrapper_tree.insert("coauthors", authors); + let json_data = serde_json::to_string_pretty(&wrapper_tree).unwrap(); + match fs::write(coauthors_file_path(), json_data) { + Ok(_) => {}, + Err(e) => { + eprintln!("Error writing git-coauthors file: {:?}", e); + process::exit(1); + } + } +} + +fn coauthors_file_path() -> std::path::PathBuf { + home_dir().unwrap().join(".git-coauthors") +}