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
use std::collections::VecDeque;
use std::iter::{Chain, Iterator, Once};
use std::process::ExitStatus;
use std::rc::Rc;
use std::collections::vec_deque::Iter;
use std::sync::Arc;

use futures::future::join_all;
use futures::join;

use async_recursion::async_recursion;
use async_trait::async_trait;

#[async_trait]
pub trait Command {
    async fn run(&self, args: VarArgs) -> Result<ExitStatus, ()>;
}

pub type VarArgs = VecDeque<Arc<String>>;
#[derive(Debug)]
pub struct ScriptGroup<CommandGeneric: Command> {
    pub bail: bool,
    // Enforces that there's always at least 1 script
    pub first: Script<CommandGeneric>,
    pub rest: VecDeque<Script<CommandGeneric>>,
}

impl<CommandGeneric: Command> ScriptGroup<CommandGeneric> {
    fn iter(&self) -> Chain<Once<&'_ Script<CommandGeneric>>, Iter<'_, Script<CommandGeneric>>> {
        std::iter::once(&self.first).chain(self.rest.iter())
    }
}

/**
 * TODO: Choose a better name
 */
#[derive(Debug)]
pub enum CommandGroup<CommandGeneric: Command> {
    Parallel(ScriptGroup<CommandGeneric>),
    Series(ScriptGroup<CommandGeneric>),
}

fn merge_status(status1: ExitStatus, status2: ExitStatus) -> ExitStatus {
    if !status1.success() {
        return status2;
    }
    return status1;
}

impl<CommandGeneric: Command> CommandGroup<CommandGeneric> {
    async fn run(
        &self,
        parser: &impl ScriptParser<CommandGeneric>,
        args: VarArgs,
    ) -> Result<ExitStatus, ()> {
        // TODO: Figure out what to do with args
        match self {
            Self::Parallel(group) => {
                if group.bail {
                    println!("Warning: Bail in parallel groups are currently not supported");
                }

                let mut promises = Vec::<_>::new();

                let mut group_iter = group.iter();
                let mut command = group_iter.next().unwrap();

                while let Some(next_command) = group_iter.next() {
                    promises.push(command.run(parser, VecDeque::new()));

                    command = next_command;
                }

                let last_result = command.run(parser, args);
                let (results, last) = join!(
                    join_all(promises),
                    last_result
                );

                let final_status = results.into_iter().fold(
                    last.unwrap(),
                    |prev_exit_status, this_result| {
                        if let Ok(current_status) = this_result {
                            return merge_status(prev_exit_status, current_status);
                        } else {
                            // TODO: Do something with the error
                            return prev_exit_status;
                        }
                    },
                );

                return Ok(final_status);
            }
            Self::Series(group) => {               
                let mut rest_iter = group.rest.iter();
                if let Some(last_command) = rest_iter.next_back() {
                    let mut exit_status = group.first.run(parser, VecDeque::new()).await.unwrap();

                    for command in rest_iter {
                        exit_status = merge_status(exit_status, command.run(parser, VecDeque::new()).await.unwrap());
                    }

                    exit_status = merge_status(exit_status, last_command.run(parser, args).await.unwrap());

                    Ok(exit_status)
                } else {
                    Ok(group.first.run(parser, args).await.unwrap())
                }
            }
        }
    }
}

#[derive(Debug)]
pub struct Alias {
    pub task: String,
    pub args: VarArgs,
}

/**
 * TODO: Choose a better name
 */
#[derive(Debug)]
pub enum Script<CommandGeneric: Command> {
    Command(CommandGeneric),
    Group(Box<CommandGroup<CommandGeneric>>),
    Alias(Alias),
}

impl<CommandGeneric: Command> Script<CommandGeneric> {
    #[async_recursion(?Send)]
    pub async fn run(
        &self,
        parser: &impl ScriptParser<CommandGeneric>,
        args: VarArgs,
    ) -> Result<ExitStatus, ()> {
        match self {
            Script::Command(cmd) => cmd.run(args).await,
            Script::Group(group) => group.run(parser, args).await,
            Script::Alias(alias) => {
                let joined_args: VecDeque<Arc<String>> = alias
                    .args
                    .iter()
                    .into_iter()
                    .map(|arg| arg.clone())
                    .chain(args.into_iter())
                    .collect();

                parser
                    .parse(alias.task.as_str())
                    .unwrap()
                    .run(parser, joined_args)
                    .await
            }
        }
    }
}

pub trait ScriptParser<CommandGeneric: Command> {
    fn parse(&self, task: &str) -> Result<Rc<Script<CommandGeneric>>, ()>;
}