mit_commit_message_lints/mit/cmd/
get_authors.rs

1use std::{
2    convert::TryFrom,
3    fs,
4    path::PathBuf,
5    process::{Command, Stdio},
6};
7
8use miette::{IntoDiagnostic, Result};
9
10use crate::mit::Authors;
11
12/// A generic structure to pass around details needed to get authors
13#[derive(Debug, Clone)]
14pub struct GenericArgs<'a> {
15    /// Command to be executed
16    pub author_command: Option<&'a str>,
17    /// Location of file with author info in
18    pub author_file: Option<&'a str>,
19}
20
21impl AuthorArgs for GenericArgs<'_> {
22    fn author_command(&self) -> Option<&str> {
23        self.author_command
24    }
25
26    fn author_file(&self) -> Option<&str> {
27        self.author_file
28    }
29}
30
31/// From a cli args, get the author configuration
32pub trait AuthorArgs {
33    /// Get the command to run to generate the authors file
34    fn author_command(&self) -> Option<&str>;
35
36    /// Get path to author file
37    fn author_file(&self) -> Option<&str>;
38}
39
40/// Get authors from config
41///
42/// # Errors
43///
44/// miette error on failure of command
45pub fn get_authors<'a>(args: &'a dyn AuthorArgs) -> Result<Authors<'a>> {
46    let toml = args
47        .author_command()
48        .map_or_else(|| from_file(args), from_exec)?;
49    let authors: Authors<'a> = Authors::try_from(toml)?;
50    Ok(authors)
51}
52
53fn from_file(args: &dyn AuthorArgs) -> Result<String> {
54    args.author_file()
55        .map_or_else(|| Err(super::errors::Error::AuthorFileNotSet.into()), Ok)
56        .and_then(|path| match path {
57            "$HOME/.config/git-mit/mit.toml" => author_file_path(),
58            _ => Ok(path.into()),
59        })
60        .map(|path| fs::read_to_string(path).unwrap_or_default())
61}
62
63#[cfg(not(target_os = "windows"))]
64fn author_file_path() -> Result<String> {
65    let home: PathBuf = std::env::var("HOME").into_diagnostic()?.into();
66    Ok(home
67        .join(".config")
68        .join("git-mit")
69        .join("mit.toml")
70        .to_string_lossy()
71        .to_string())
72}
73
74#[cfg(target_os = "windows")]
75fn author_file_path() -> Result<String> {
76    std::env::var("APPDATA")
77        .map(|x| {
78            PathBuf::from(x)
79                .join("git-mit")
80                .join("mit.toml")
81                .to_string_lossy()
82                .into()
83        })
84        .into_diagnostic()
85}
86
87fn from_exec(command: &str) -> Result<String> {
88    let commandline = shell_words::split(command).into_diagnostic()?;
89    Command::new(commandline.first().unwrap_or(&String::new()))
90        .stderr(Stdio::inherit())
91        .args(commandline.iter().skip(1))
92        .output()
93        .into_diagnostic()
94        .and_then(|output| {
95            String::from_utf8(output.stdout).map_err(|source| {
96                super::errors::Error::ExecUtf8 {
97                    source,
98                    command: command.to_string(),
99                }
100                .into()
101            })
102        })
103}