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
use serde::{Deserialize, Serialize};

use crate::run::{ExitStatus, Run, RunStatus};
use crate::runner::{self, io, Output, Runned, Runner};

#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct RunItem {
    name: String,
    args: Vec<String>,
}

impl RunItem {
    pub fn new(name: String, args: Vec<String>) -> Self {
        Self { name, args }
    }

    pub fn run_async(&self) -> Runned {
        Runner::new(self.name.clone(), self.args.clone()).run_async()
    }
}

struct RunItemStatus {
    status: io::Result<Output>,
}

struct StatusHelper {
    status: runner::ExitStatus,
}

impl ExitStatus for StatusHelper {
    fn success(&self) -> bool {
        self.status.success()
    }

    fn code(&self) -> Option<i32> {
        self.status.code()
    }
}

impl RunStatus for RunItemStatus {
    fn status(&self) -> Result<Box<dyn ExitStatus>, String> {
        match &self.status {
            Ok(ok) => Ok(Box::new(StatusHelper { status: ok.status })),
            Err(e) => Err(format!("{}", e)),
        }
    }
}

impl Run for RunItem {
    fn run(&self) -> Box<dyn RunStatus> {
        Box::new(RunItemStatus {
            status: Runner::new(self.name.clone(), self.args.clone()).run(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn create() {
        let result = RunItem::new("true".to_string(), vec![])
            .run()
            .status()
            .expect("failed to execute process");
        assert!(result.success());

        let result = RunItem::new(
            "true".to_string(),
            vec!["1", "2", "3"]
                .iter()
                .cloned()
                .map(String::from)
                .collect(),
        )
        .run()
        .status()
        .expect("failed to execute process");
        assert!(result.success());
    }

    #[test]
    fn create_async() {
        let result = RunItem::new("true".to_string(), vec![])
            .run_async()
            .wait()
            .expect("failed to wait");
        assert!(result.success());

        let result = RunItem::new(
            "true".to_string(),
            vec!["1", "2", "3"]
                .iter()
                .cloned()
                .map(String::from)
                .collect(),
        )
        .run_async()
        .wait()
        .expect("failed to wait");
        assert!(result.success());
    }
}