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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
use crate::maskfile::*;
use pulldown_cmark::Event::{Code, End, InlineHtml, Start, Text};
use pulldown_cmark::{Options, Parser, Tag};

pub fn parse(maskfile_contents: String) -> Maskfile {
    let parser = create_markdown_parser(&maskfile_contents);
    let mut commands = vec![];
    let mut current_command = Command::new(1);
    let mut current_option_flag = NamedFlag::new();
    let mut text = "".to_string();
    let mut list_level = 0;

    for event in parser {
        match event {
            Start(tag) => {
                match tag {
                    Tag::Header(heading_level) => {
                        // Add the last command before starting a new one.
                        // Don't add commands for level 1 heading blocks (the title).
                        if heading_level > 1 {
                            commands.push(current_command.build());
                        } else if heading_level == 1 && commands.len() > 0 {
                            // Found another level 1 heading block, so quit parsing.
                            break;
                        }
                        current_command = Command::new(heading_level as u8);
                    }
                    #[cfg(not(windows))]
                    Tag::CodeBlock(lang_code) => {
                        if lang_code.to_string() != "powershell"
                            && lang_code.to_string() != "batch"
                            && lang_code.to_string() != "cmd"
                        {
                            if let Some(s) = &mut current_command.script {
                                s.executor = lang_code.to_string();
                            }
                        }
                    }
                    #[cfg(windows)]
                    Tag::CodeBlock(lang_code) => {
                        if let Some(s) = &mut current_command.script {
                            s.executor = lang_code.to_string();
                        }
                    }
                    Tag::List(_) => {
                        // We're in an options list if the current text above it is "OPTIONS"
                        if text == "OPTIONS" || list_level > 0 {
                            list_level += 1;
                        }
                    }
                    _ => (),
                };

                // Reset all state
                text = "".to_string();
            }
            End(tag) => match tag {
                Tag::Header(_) => {
                    let (name, required_args) = parse_command_name_and_required_args(text.clone());
                    current_command.name = name;
                    current_command.required_args = required_args;
                }
                Tag::BlockQuote => {
                    current_command.description = text.clone();
                }
                #[cfg(not(windows))]
                Tag::CodeBlock(lang_code) => {
                    if lang_code.to_string() != "powershell"
                        && lang_code.to_string() != "batch"
                        && lang_code.to_string() != "cmd"
                    {
                        if let Some(s) = &mut current_command.script {
                            s.source = text.to_string();
                        }
                    }
                }
                #[cfg(windows)]
                Tag::CodeBlock(_) => {
                    if let Some(s) = &mut current_command.script {
                        s.source = text.to_string();
                    }
                }
                Tag::List(_) => {
                    // Don't go lower than zero (for cases where it's a non-OPTIONS list)
                    list_level = std::cmp::max(list_level - 1, 0);

                    // Must be finished parsing the current option
                    if list_level == 1 {
                        // Add the current one to the list and start a new one
                        current_command
                            .named_flags
                            .push(current_option_flag.clone());
                        current_option_flag = NamedFlag::new();
                    }
                }
                _ => (),
            },
            Text(body) => {
                text += &body.to_string();

                // Options level 1 is the flag name
                if list_level == 1 {
                    current_option_flag.name = text.clone();
                }
                // Options level 2 is the flag config
                else if list_level == 2 {
                    let mut config_split = text.splitn(2, ":");
                    let param = config_split.next().unwrap_or("").trim();
                    let val = config_split.next().unwrap_or("").trim();
                    match param {
                        "desc" => current_option_flag.description = val.to_string(),
                        "type" => {
                            if val == "string" || val == "number" {
                                current_option_flag.takes_value = true;
                            }

                            if val == "number" {
                                current_option_flag.validate_as_number = true;
                            }
                        }
                        // Parse out the short and long flag names
                        "flags" => {
                            let short_and_long_flags: Vec<&str> = val.splitn(2, " ").collect();
                            for flag in short_and_long_flags {
                                // Must be a long flag name
                                if flag.starts_with("--") {
                                    let name = flag.split("--").collect::<Vec<&str>>().join("");
                                    current_option_flag.long = name;
                                }
                                // Must be a short flag name
                                else if flag.starts_with("-") {
                                    // Get the single char
                                    let name = flag.get(1..2).unwrap_or("");
                                    current_option_flag.short = name.to_string();
                                }
                            }
                        }
                        "required" => {
                            current_option_flag.required = true;
                        }
                        _ => (),
                    };
                }
            }
            InlineHtml(html) => {
                text += &html.to_string();
            }
            Code(inline_code) => {
                text += &format!("`{}`", inline_code);
            }
            _ => (),
        };
    }

    // Add the last command
    commands.push(current_command.build());

    // Convert the flat commands array and to a tree of subcommands based on level
    let all = treeify_commands(commands);
    let root_command = all.first().expect("root command must exist");

    Maskfile {
        title: root_command.name.clone(),
        description: root_command.description.clone(),
        commands: root_command.subcommands.clone(),
    }
}

fn create_markdown_parser<'a>(maskfile_contents: &'a String) -> Parser<'a> {
    // Set up options and parser. Strikethroughs are not part of the CommonMark standard
    // and we therefore must enable it explicitly.
    let mut options = Options::empty();
    options.insert(Options::ENABLE_STRIKETHROUGH);
    let parser = Parser::new_ext(&maskfile_contents, options);
    parser
}

fn treeify_commands(commands: Vec<Command>) -> Vec<Command> {
    let mut command_tree = vec![];
    let mut current_command = commands.first().expect("command should exist").clone();
    let num_commands = commands.len();

    for i in 0..num_commands {
        let mut c = commands[i].clone();

        // This must be a subcommand
        if c.level > current_command.level {
            if c.name.starts_with(&current_command.name) {
                // remove parent command name prefixes from subcommand
                c.name = c
                    .name
                    .strip_prefix(&current_command.name)
                    .unwrap()
                    .trim()
                    .to_string();
            }
            current_command.subcommands.push(c);
        }
        // This must be a sibling command
        else if c.level == current_command.level {
            // Make sure the initial command doesn't skip itself before it finds children
            if i > 0 {
                // Found a sibling, so the current command has found all children.
                command_tree.push(current_command);
                current_command = c;
            }
        }
    }

    // Adding last command which was not added in the above loop
    command_tree.push(current_command);

    // Treeify all subcommands recursively
    for c in &mut command_tree {
        if !c.subcommands.is_empty() {
            c.subcommands = treeify_commands(c.subcommands.clone());
        }
    }

    // the command or any one of its subcommands must have script to be included in the tree
    // root level commands must be retained
    command_tree.retain(|c| c.script.is_some() || !c.subcommands.is_empty() || c.level == 1);

    command_tree
}

fn parse_command_name_and_required_args(text: String) -> (String, Vec<RequiredArg>) {
    // Find any required arguments. They look like this: (required_arg_name)
    let name_and_args: Vec<&str> = text.split(|c| c == '(' || c == ')').collect();
    let (name, args) = name_and_args.split_at(1);
    let name = name.join(" ").trim().to_string();
    let mut required_args: Vec<RequiredArg> = vec![];

    if !args.is_empty() {
        let args = args.join("");
        let args: Vec<&str> = args.split(" ").collect();
        required_args = args
            .iter()
            .map(|a| RequiredArg::new(a.to_string()))
            .collect();
    }

    (name, required_args)
}

#[cfg(test)]
const TEST_MASKFILE: &str = r#"
# Document Title

This is an example maskfile for the tests below.

## serve (port)

> Serve the app on the `port`

~~~bash
echo "Serving on port $port"
~~~

## node (name)

> An example node script

Valid lang codes: js, javascript

```js
const { name } = process.env;
console.log(`Hello, ${name}!`);
```

## parent
### parent subcommand
> This is a subcommand

~~~bash
echo hey
~~~

## no_script

This command has no source/script.
"#;

#[cfg(test)]
mod parse {
    use super::*;
    use serde_json::json;

    #[test]
    fn parses_the_maskfile_structure() {
        let maskfile = parse(TEST_MASKFILE.to_string());

        let verbose_flag = json!({
            "name": "verbose",
            "description": "Sets the level of verbosity",
            "short": "v",
            "long": "verbose",
            "multiple": false,
            "takes_value": false,
            "required": false,
            "validate_as_number": false,
        });

        assert_eq!(
            json!({
                "title": "Document Title",
                "description": "",
                "commands": [
                    {
                        "level": 2,
                        "name": "serve",
                        "description": "Serve the app on the `port`",
                        "script": {
                            "executor": "bash",
                            "source": "echo \"Serving on port $port\"\n",
                        },
                        "subcommands": [],
                        "required_args": [
                            {
                                "name": "port"
                            }
                        ],
                        "named_flags": [verbose_flag],
                    },
                    {
                        "level": 2,
                        "name": "node",
                        "description": "An example node script",
                        "script": {
                            "executor": "js",
                            "source": "const { name } = process.env;\nconsole.log(`Hello, ${name}!`);\n",
                        },
                        "subcommands": [],
                        "required_args": [
                            {
                                "name": "name"
                            }
                        ],
                        "named_flags": [verbose_flag],
                    },
                    {
                        "level": 2,
                        "name": "parent",
                        "description": "",
                        "script": null,
                        "subcommands": [
                            {
                                "level": 3,
                                "name": "subcommand",
                                "description": "This is a subcommand",
                                "script": {
                                    "executor": "bash",
                                    "source": "echo hey\n",
                                },
                                "subcommands": [],
                                "required_args": [],
                                "named_flags": [verbose_flag],
                            }
                        ],
                        "required_args": [],
                        "named_flags": [],
                    }
                ]
            }),
            maskfile.to_json().expect("should have serialized to json")
        );
    }
}