1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
mod model;

pub use model::*;

use assert_cmd::output::OutputOkExt;
use bstr::ByteSlice;
use eyre::WrapErr;

impl Dag {
    pub fn load(path: &std::path::Path) -> eyre::Result<Self> {
        let data = std::fs::read_to_string(path)
            .wrap_err_with(|| format!("Could not read {}", path.display()))?;

        let mut dag: Self = match path.extension().and_then(std::ffi::OsStr::to_str) {
            Some("yaml") | Some("yml") => serde_yaml::from_str(&data)
                .wrap_err_with(|| format!("Could not parse {}", path.display()))?,
            Some("json") => serde_json::from_str(&data)
                .wrap_err_with(|| format!("Could not parse {}", path.display()))?,
            Some("toml") => toml::from_str(&data)
                .wrap_err_with(|| format!("Could not parse {}", path.display()))?,
            Some(other) => {
                return Err(eyre::eyre!("Unknown extension: {:?}", other));
            }
            None => {
                return Err(eyre::eyre!("No extension for {}", path.display()));
            }
        };

        dag.import_root = Some(
            path.parent()
                .unwrap_or_else(|| std::path::Path::new(""))
                .to_owned(),
        );

        Ok(dag)
    }

    pub fn save(&self, path: &std::path::Path) -> eyre::Result<()> {
        let raw: String = match path.extension().and_then(std::ffi::OsStr::to_str) {
            Some("yaml") | Some("yml") => serde_yaml::to_string(self)
                .wrap_err_with(|| format!("Could not parse {}", path.display()))?,
            Some("json") => serde_json::to_string(self)
                .wrap_err_with(|| format!("Could not parse {}", path.display()))?,
            Some("toml") => toml::to_string(self)
                .wrap_err_with(|| format!("Could not parse {}", path.display()))?,
            Some(other) => {
                return Err(eyre::eyre!("Unknown extension: {:?}", other));
            }
            None => {
                return Err(eyre::eyre!("No extension for {}", path.display()));
            }
        };

        std::fs::write(path, &raw)
            .wrap_err_with(|| format!("Could not write {}", path.display()))?;

        Ok(())
    }

    pub fn run(self, cwd: &std::path::Path) -> eyre::Result<()> {
        if self.init {
            std::process::Command::new("git")
                .arg("init")
                .current_dir(cwd)
                .ok()
                .wrap_err("'git init' failed")?;
        }

        let mut marks: std::collections::HashMap<String, String> = Default::default();
        self.run_events(
            &self.events,
            cwd,
            self.import_root
                .as_deref()
                .unwrap_or_else(|| std::path::Path::new("")),
            &mut marks,
        )?;

        Ok(())
    }

    // Note: shelling out to git to minimize programming bugs
    fn run_events(
        &self,
        events: &[Event],
        cwd: &std::path::Path,
        import_root: &std::path::Path,
        marks: &mut std::collections::HashMap<String, String>,
    ) -> eyre::Result<()> {
        for event in events.iter() {
            match event {
                Event::Import(path) => {
                    let path = import_root.join(path);
                    let mut child_dag = Dag::load(&path)?;
                    child_dag.init = false;
                    child_dag.sleep = child_dag.sleep.or(self.sleep);
                    child_dag.run(cwd).wrap_err_with(|| {
                        format!("Failed when running imported fixcture {}", path.display())
                    })?;
                }
                Event::Tree(tree) => {
                    let output = std::process::Command::new("git")
                        .arg("ls-files")
                        .current_dir(cwd)
                        .ok()?;
                    for relpath in output.stdout.lines() {
                        let relpath = std::path::Path::new(relpath.to_os_str()?);
                        std::process::Command::new("git")
                            .arg("rm")
                            .arg("-f")
                            .arg(relpath)
                            .current_dir(cwd)
                            .ok()
                            .wrap_err_with(|| format!("Failed to remove {}", relpath.display()))?;
                    }
                    for (relpath, content) in tree.tracked.iter() {
                        let path = cwd.join(relpath);
                        if let Some(parent) = path.parent() {
                            std::fs::create_dir_all(parent).wrap_err_with(|| {
                                format!("Failed to create {}", parent.display())
                            })?;
                        }
                        std::fs::write(&path, content.as_bytes())
                            .wrap_err_with(|| format!("Failed to write {}", path.display()))?;
                        if !tree.state.is_tracked() {
                            std::process::Command::new("git")
                                .arg("add")
                                .arg(relpath)
                                .current_dir(cwd)
                                .ok()?;
                        }
                    }
                    if tree.state.is_committed() {
                        // Detach
                        if let Ok(pre_commit) = current_oid(cwd) {
                            checkout(cwd, &pre_commit)?;
                        }

                        let mut p = std::process::Command::new("git");
                        p.arg("commit")
                            .arg("-m")
                            .arg(tree.message.as_deref().unwrap_or("Automated"))
                            .current_dir(cwd);
                        if let Some(author) = tree.author.as_deref() {
                            p.arg("--author").arg(author);
                        }
                        p.ok()?;
                        if let Some(sleep) = self.sleep {
                            std::thread::sleep(sleep);
                        }

                        if let Some(branch) = tree.branch.as_ref() {
                            let _ = std::process::Command::new("git")
                                .arg("branch")
                                .arg("-D")
                                .arg(branch.as_str())
                                .current_dir(cwd)
                                .ok();
                            std::process::Command::new("git")
                                .arg("checkout")
                                .arg("-b")
                                .arg(branch.as_str())
                                .current_dir(cwd)
                                .ok()?;
                        }

                        if let Some(mark) = tree.mark.as_ref() {
                            let commit = current_oid(cwd)?;
                            marks.insert(mark.as_str().to_owned(), commit);
                        }
                    }
                }
                Event::Children(events) => {
                    let start_commit = current_oid(cwd)?;
                    for run in events {
                        checkout(cwd, &start_commit)?;
                        self.run_events(run, cwd, import_root, marks)?;
                    }
                }
                Event::Head(reference) => {
                    let revspec = match &reference {
                        Reference::Mark(mark) => marks
                            .get(mark.as_str())
                            .ok_or_else(|| eyre::eyre!("Reference doesn't exist: {:?}", mark))?
                            .as_str(),
                        Reference::Branch(branch) => branch.as_str(),
                    };
                    checkout(cwd, revspec)?;
                }
            }
        }

        Ok(())
    }
}

pub fn checkout(cwd: &std::path::Path, refspec: &str) -> eyre::Result<()> {
    std::process::Command::new("git")
        .arg("checkout")
        .arg(refspec)
        .current_dir(cwd)
        .ok()?;
    Ok(())
}

pub fn current_oid(cwd: &std::path::Path) -> eyre::Result<String> {
    let output = std::process::Command::new("git")
        .arg("rev-parse")
        .arg("--short")
        .arg("HEAD")
        .current_dir(cwd)
        .ok()?;
    let commit = String::from_utf8(output.stdout)?.trim().to_owned();
    Ok(commit)
}