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
use crate::input::Input;
use crate::input::TaskDef;
use crate::task_lookup_error;
use std::fmt;

#[derive(Debug)]
pub enum TaskError {
    Invalid(Vec<TaskLookup>),
    Serde(serde_yaml::Error),
}

#[derive(Debug)]
pub enum TaskLookup {
    Found { target: String, path: Vec<PathItem> },
    NotFound { target: String, path: Vec<PathItem> },
}

#[derive(Debug, Clone)]
pub enum PathItem {
    String(String),
    Index(usize),
}

impl fmt::Display for PathItem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            PathItem::String(s) => write!(f, "`{}`", s),
            PathItem::Index(s) => write!(f, "[index: {}]", s),
        }
    }
}

impl fmt::Display for TaskError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            TaskError::Invalid(lookups) => {
                let output = lookups
                    .iter()
                    .map(|l| match l {
                        TaskLookup::NotFound { target, path } => {
                            task_lookup_error::print(target, path)
                        }
                        _ => String::new(),
                    })
                    .collect::<Vec<String>>()
                    .join("\n");
                write!(f, "{}", output)
            }
            TaskError::Serde(e) => write!(f, "{}", e),
        }
    }
}

///
/// Select a sequence of tasks based on the YAML input string
///
pub fn select(input: &Input, names: &Vec<String>) -> Result<Vec<TaskLookup>, TaskError> {
    let parsed = names
        .iter()
        .map(|n| validate(&input, &n, &n, vec![]))
        .collect::<Vec<TaskLookup>>();

    let all_valid = parsed.iter().all(|lookup| match lookup {
        TaskLookup::Found { .. } => true,
        TaskLookup::NotFound { .. } => false,
    });

    if all_valid {
        Ok(parsed)
    } else {
        Err(TaskError::Invalid(parsed))
    }
}

pub fn validate(input: &Input, target: &str, name: &str, prev_path: Vec<PathItem>) -> TaskLookup {
    input.tasks.get(name).map_or_else(
        || {
            let mut next_path = prev_path.clone();
            next_path.push(PathItem::String(name.to_string()));
            TaskLookup::NotFound {
                target: target.to_string(),
                path: next_path,
            }
        },
        |item| {
            let mut next_path = prev_path.clone();
            next_path.push(PathItem::String(name.to_string()));
            match item {
                TaskDef::CmdString(s) => validate_string(input, target, s.to_string(), next_path),
                TaskDef::TaskObj { .. } => TaskLookup::Found {
                    target: target.to_string(),
                    path: next_path,
                },
                TaskDef::TaskSeq(seq) => validate_seq(input, target, name, seq, next_path),
                TaskDef::TaskSeqObj { tasks, .. } => {
                    validate_seq(input, target, name, tasks, next_path)
                }
            }
        },
    )
}

fn validate_seq(
    input: &Input,
    target: &str,
    name: &str,
    seq: &Vec<TaskDef>,
    path: Vec<PathItem>,
) -> TaskLookup {
    let out = seq
        .iter()
        .enumerate()
        .map(|(index, seq_item)| {
            let mut next_path = path.clone();
            next_path.push(PathItem::Index(index));
            match seq_item {
                TaskDef::CmdString(s) => validate_string(input, target, s.to_string(), next_path),
                TaskDef::TaskSeq(seq) => validate_seq(input, target, name, seq, next_path),
                TaskDef::TaskSeqObj { tasks, .. } => {
                    validate_seq(input, target, name, tasks, next_path)
                }
                TaskDef::TaskObj { .. } => TaskLookup::Found {
                    target: target.to_string(),
                    path: next_path,
                },
            }
        })
        .collect::<Vec<TaskLookup>>();

    let first_fail = out.into_iter().find(|lookup| match lookup {
        TaskLookup::Found { .. } => false,
        TaskLookup::NotFound { .. } => true,
    });

    if first_fail.is_some() {
        first_fail.unwrap()
    } else {
        TaskLookup::Found {
            target: target.to_string(),
            path,
        }
    }
}

fn validate_string(
    input: &Input,
    target: &str,
    string_input: String,
    path: Vec<PathItem>,
) -> TaskLookup {
    match &string_input[0..1] {
        "@" => validate(input, target, &string_input[1..string_input.len()], path),
        _ => TaskLookup::Found {
            target: target.to_string(),
            path,
        },
    }
}