Skip to main content

gluesql_git_storage/
command_ext.rs

1use {
2    crate::ResultExt,
3    gluesql_core::error::{Error, Result},
4    std::process::Command,
5};
6
7pub trait CommandExt {
8    fn execute(&mut self) -> Result<(), Error>;
9}
10
11impl CommandExt for Command {
12    fn execute(&mut self) -> Result<(), Error> {
13        let output = self.output().map_storage_err()?;
14
15        if !output.status.success() {
16            let stdout = String::from_utf8_lossy(&output.stdout);
17            let stderr = String::from_utf8_lossy(&output.stderr);
18
19            let out_and_err = [
20                (!stdout.is_empty()).then(|| format!("[stdout] {stdout}")),
21                (!stderr.is_empty()).then(|| format!("[stderr] {stderr}")),
22            ]
23            .into_iter()
24            .flatten()
25            .collect::<String>();
26
27            return Err(Error::StorageMsg(out_and_err));
28        }
29
30        Ok(())
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use {crate::CommandExt, std::process::Command};
37
38    #[test]
39    fn test_command_ext() {
40        let path = "tmp/command_ext_test";
41
42        Command::new("mkdir").arg("-p").arg(path).execute().unwrap();
43        Command::new("git")
44            .current_dir(path)
45            .arg("init")
46            .execute()
47            .unwrap();
48        Command::new("git")
49            .current_dir(path)
50            .arg("checkout")
51            .arg("-b")
52            .arg("main")
53            .execute()
54            .unwrap();
55
56        let executed = Command::new("git")
57            .current_dir(path)
58            .arg("commit")
59            .arg("-m")
60            .arg("test")
61            .execute();
62        assert!(executed.is_err());
63        assert_eq!(
64            executed.unwrap_err().to_string(),
65            "storage: [stdout] On branch main\n\nInitial commit\n\nnothing to commit (create/copy files and use \"git add\" to track)\n"
66        );
67
68        let executed = Command::new("git")
69            .current_dir(path)
70            .arg("commit")
71            .arg("-m")
72            .arg("test")
73            .arg("--amend")
74            .execute();
75        assert!(executed.is_err());
76        assert_eq!(
77            executed.unwrap_err().to_string(),
78            "storage: [stderr] fatal: You have nothing to amend.\n"
79        );
80    }
81}