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