gh_workflow/
generate.rs

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
use std::path::PathBuf;
use std::process::Command;

use derive_setters::Setters;

use crate::error::{Error, Result};
use crate::Workflow;

#[derive(Setters, Clone)]
#[setters(into)]
pub struct Generate {
    workflow: Workflow,
    name: String,
}

impl Generate {
    pub fn new(workflow: Workflow) -> Self {
        Self { workflow, name: "ci.yml".to_string() }
    }

    pub fn generate(&self) -> Result<()> {
        let comment = include_str!("./comment.yml");

        let root_dir = String::from_utf8(
            Command::new("git")
                .args(["rev-parse", "--show-toplevel"])
                .output()?
                .stdout,
        )?;

        let path = PathBuf::from(root_dir.trim())
            .join(".github")
            .join("workflows")
            .join(self.name.as_str());

        let content = format!("{}\n{}", comment, self.workflow.to_string()?);

        if std::env::var("CI").is_ok() {
            if let Ok(prev) = std::fs::read_to_string(&path) {
                if content != prev {
                    Err(Error::OutdatedWorkflow)
                } else {
                    println!(
                        "Workflow file is up-to-date: {}",
                        path.canonicalize()?.display()
                    );
                    Ok(())
                }
            } else {
                Err(Error::MissingWorkflowFile(path.clone()))
            }
        } else {
            std::fs::write(path.clone(), content)?;
            println!(
                "Generated workflow file: {}",
                path.canonicalize()?.display()
            );
            Ok(())
        }
    }
}