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
use std::collections::{BTreeMap, VecDeque};
use std::fmt::{Debug, Display, Formatter};

use indexmap::IndexMap;
use itertools::Itertools;
use strum::EnumTryAs;

use crate::{Spec, SpecArg, SpecCommand, SpecFlag};

pub struct ParseOutput<'a> {
    pub cmd: &'a SpecCommand,
    pub cmds: Vec<&'a SpecCommand>,
    pub args: IndexMap<&'a SpecArg, ParseValue>,
    pub flags: IndexMap<SpecFlag, ParseValue>,
    pub available_flags: BTreeMap<String, SpecFlag>,
    pub flag_awaiting_value: Option<SpecFlag>,
}

#[derive(Debug, EnumTryAs)]
pub enum ParseValue {
    Bool(bool),
    String(String),
    MultiBool(Vec<bool>),
    MultiString(Vec<String>),
}

pub fn parse<'a>(spec: &'a Spec, input: &[String]) -> Result<ParseOutput<'a>, miette::Error> {
    let mut input = input.iter().cloned().collect::<VecDeque<_>>();
    let mut cmd = &spec.cmd;
    let mut cmds = vec![];
    input.pop_front();
    cmds.push(cmd);

    let gather_flags = |cmd: &SpecCommand| {
        cmd.flags
            .iter()
            .flat_map(|f| {
                f.long
                    .iter()
                    .map(|l| (format!("--{}", l), f.clone()))
                    .chain(f.short.iter().map(|s| (format!("-{}", s), f.clone())))
            })
            .collect()
    };

    let mut available_flags: BTreeMap<String, SpecFlag> = gather_flags(cmd);

    while !input.is_empty() {
        if let Some(subcommand) = cmd.find_subcommand(&input[0]) {
            available_flags.retain(|_, f| f.global);
            available_flags.extend(gather_flags(subcommand));
            input.pop_front();
            cmds.push(subcommand);
            cmd = subcommand;
        } else {
            break;
        }
    }

    let mut args: IndexMap<&SpecArg, ParseValue> = IndexMap::new();
    let mut flags: IndexMap<SpecFlag, ParseValue> = IndexMap::new();
    let mut next_arg = cmd.args.first();
    let mut flag_awaiting_value: Option<SpecFlag> = None;
    let mut enable_flags = true;

    while !input.is_empty() {
        let w = input.pop_front().unwrap();

        if let Some(flag) = flag_awaiting_value {
            flag_awaiting_value = None;
            if flag.var {
                let arr = flags
                    .entry(flag)
                    .or_insert_with(|| ParseValue::MultiString(vec![]))
                    .try_as_multi_string_mut()
                    .unwrap();
                arr.push(w);
            } else {
                flags.insert(flag, ParseValue::String(w));
            }
            continue;
        }

        if w == "--" {
            enable_flags = false;
            continue;
        }

        // long flags
        if enable_flags && w.starts_with("--") {
            let (word, val) = w.split_once('=').unwrap_or_else(|| (&w, ""));
            if !val.is_empty() {
                input.push_front(val.to_string());
            }
            if let Some(f) = available_flags.get(word) {
                if f.arg.is_some() {
                    flag_awaiting_value = Some(f.clone());
                } else if f.var {
                    let arr = flags
                        .entry(f.clone())
                        .or_insert_with(|| ParseValue::MultiBool(vec![]))
                        .try_as_multi_bool_mut()
                        .unwrap();
                    arr.push(true);
                } else {
                    flags.insert(f.clone(), ParseValue::Bool(true));
                }
                continue;
            }
        }

        // short flags
        if enable_flags && w.starts_with('-') && w.len() > 1 {
            let short = w.chars().nth(1).unwrap();
            if let Some(f) = available_flags.get(&format!("-{}", short)) {
                let mut next = format!("-{}", &w[2..]);
                if f.arg.is_some() {
                    flag_awaiting_value = Some(f.clone());
                    next = w[2..].to_string();
                }
                if next != "-" {
                    input.push_front(next);
                }
                if f.var {
                    let arr = flags
                        .entry(f.clone())
                        .or_insert_with(|| ParseValue::MultiBool(vec![]))
                        .try_as_multi_bool_mut()
                        .unwrap();
                    arr.push(true);
                } else {
                    flags.insert(f.clone(), ParseValue::Bool(true));
                }
                continue;
            }
        }

        if let Some(arg) = next_arg {
            if arg.var {
                let arr = args
                    .entry(arg)
                    .or_insert_with(|| ParseValue::MultiString(vec![]))
                    .try_as_multi_string_mut()
                    .unwrap();
                arr.push(w);
                if arr.len() >= arg.var_max.unwrap_or(usize::MAX) {
                    next_arg = cmd.args.get(args.len());
                }
            } else {
                args.insert(arg, ParseValue::String(w));
                next_arg = cmd.args.get(args.len());
            }
            continue;
        }
        panic!("unexpected word: {w}");
    }

    Ok(ParseOutput {
        cmd,
        cmds,
        args,
        flags,
        available_flags,
        flag_awaiting_value,
    })
}

impl Display for ParseValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseValue::Bool(b) => write!(f, "{}", b),
            ParseValue::String(s) => write!(f, "{}", s),
            ParseValue::MultiBool(b) => write!(f, "{:?}", b),
            ParseValue::MultiString(s) => write!(f, "{:?}", s),
        }
    }
}

impl Debug for ParseOutput<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParseOutput")
            .field("cmds", &self.cmds.iter().map(|c| &c.name).join(" ").trim())
            .field(
                "args",
                &self
                    .args
                    .iter()
                    .map(|(a, w)| format!("{}: {w}", &a.name))
                    .collect_vec(),
            )
            .field(
                "available_flags",
                &self
                    .available_flags
                    .iter()
                    .map(|(f, w)| format!("{f}: {w}"))
                    .collect_vec(),
            )
            .field(
                "flags",
                &self
                    .flags
                    .iter()
                    .map(|(f, w)| format!("{}: {w}", &f.name))
                    .collect_vec(),
            )
            .finish()
    }
}