Use `git config` to get author name in `mdbook init` (#649)

* Use `git config` to get author name in `mdbook init`

* Return `None` if `git` command fails

* Use `.ok()?` to convert from Result to Option and return early if `None`
This commit is contained in:
Anders Rasmussen 2018-03-27 01:37:11 +11:00 committed by Michael Bryan
parent 5fb3675151
commit eb0f7179ab
1 changed files with 9 additions and 14 deletions

View File

@ -1,6 +1,6 @@
use std::io; use std::io;
use std::io::Write; use std::io::Write;
use std::env; use std::process::Command;
use clap::{App, ArgMatches, SubCommand}; use clap::{App, ArgMatches, SubCommand};
use mdbook::MDBook; use mdbook::MDBook;
use mdbook::errors::Result; use mdbook::errors::Result;
@ -68,20 +68,15 @@ pub fn execute(args: &ArgMatches) -> Result<()> {
Ok(()) Ok(())
} }
/// Obtains author name from git config file if it can be located. /// Obtains author name from git config file by running the `git config` command.
fn get_author_name() -> Option<String> { fn get_author_name() -> Option<String> {
if let Some(home) = env::home_dir() { let output = Command::new("git")
let git_config_path = home.join(".gitconfig"); .args(&["config", "--get", "user.name"])
let content = utils::fs::file_to_string(git_config_path).unwrap(); .output()
let user_name = content .ok()?;
.lines()
.filter(|x| !x.starts_with("#")) if output.status.success() {
.map(|x| x.trim_left()) Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())
.filter(|x| x.starts_with("name"))
.next();
user_name
.and_then(|x| x.rsplit("=").next())
.map(|x| x.trim().to_owned())
} else { } else {
None None
} }