1use anyhow::{Context, Result};
2use std::path::Path;
3use crate::config::Config;
4
5pub fn run_git(config: &Config, args: &[String]) -> Result<()> {
6 let cmd = build_git_command(config, args);
7 run_in_dir(&cmd, &config.storage_dir)
8}
9
10pub fn run_autogit(config: &Config) -> Result<()> {
11 let cmd = format!(
12 "git add . && git commit -m \"$(date)\" && git pull {} {} && git push {} {}",
13 config.git_remote, config.git_branch,
14 config.git_remote, config.git_branch,
15 );
16 run_in_dir(&cmd, &config.storage_dir)
17}
18
19pub fn run_cmd(config: &Config, args: &[String]) -> Result<()> {
20 let cmd = args.join(" ");
21 run_in_dir(&cmd, &config.storage_dir)
22}
23
24fn build_git_command(config: &Config, args: &[String]) -> String {
25 match args.first().map(|s| s.as_str()) {
26 Some("auto") => format!(
27 "git add . && git commit -m \"$(date)\" && git pull {} {} && git push {} {}",
28 config.git_remote, config.git_branch,
29 config.git_remote, config.git_branch,
30 ),
31 Some("autocommit") => "git add . && git commit -m \"$(date)\"".into(),
32 Some(_) => format!("git {}", shell_join(args)),
33 None => "git status".into(),
34 }
35}
36
37fn shell_join(args: &[String]) -> String {
38 args.iter()
39 .map(|a| if a.contains(' ') { format!("\"{}\"", a) } else { a.clone() })
40 .collect::<Vec<_>>()
41 .join(" ")
42}
43
44fn run_in_dir(cmd: &str, dir: &Path) -> Result<()> {
45 std::process::Command::new("sh")
46 .arg("-c")
47 .arg(cmd)
48 .current_dir(dir)
49 .status()
50 .with_context(|| format!("failed to run: {}", cmd))?;
51 Ok(())
52}