papyrus 0.17.2

A rust repl and script runner
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Extendable commands for REPL.
//!
//! The REPL makes use of the crate [`cmdtree`](https://crates.io/crates/cmdtree) to handle commands
//! that can provide additional functionality over just a Rust REPL.
//! A command is prefixed by a colon (`:`) and a number of defaults. To see the commands that are
//! included, type `:help`.
//!
//! # Common Commands
//!
//! There are three common commands, `help`, `cancel` or `c`, and `exit`, which can be invoked in any
//! class.
//!
//! | cmd      | action                                          |
//! | -------- | ----------------------------------------------- |
//! | `help`   | displays help information for the current class |
//! | `cancel` | moves the class back to the command root        |
//! | `exit`   | quit the REPL                                   |
//!
//! Other commands are context based off the command tree, they can be invoked with something similar
//! to `a nested command action` syntax. There is also a 'verbatim' mode.
//!
//! ## Verbatim Mode
//! 'verbatim' mode can be used to read stdin directly without processing of tabs, newlines, and other
//! keys which usually are interpreted to mean other things, such as completion or the end of an input.
//! To enter verbatim mode, use `Ctrl+o`. Verbatim mode will read stdin until the break command is
//! reached, which is `Ctrl+d`. Verbatim mode is especially useful for inputing multi-line strings and
//! if injecting code into the REPL from another program using stdin.
//!
//! ## Mutable Mode
//! The `mut` command will place the REPL into mutable mode, which makes access to `app_data` a `&mut`
//! pointer. Mutable mode avoids having state change on each REPL cycle, rather, when in mutable mode,
//! the expression will _not be saved_ such that it will only be run once. Developers can use this mode
//! to control how changes to `app_data` need to occur, especially by ensuring mutable access is
//! harding to achieve.
//!
//! ## Modules
//! The `mod` command allows more than just the `lib` module to exist in the REPL. Use `mod` to have
//! different REPL sessions all sharing the same compilation cycle. This can be useful to switch
//! contexts if need be.
//!
//! There is also a `clear` command which can be used to clear the previous REPL inputs. It supports
//! glob patterns matching module paths, for example `:mod clear test/**` will clear all inputs under
//! the module path `test/`. _`:mod clear` clears all previous REPL input in the **current module**._
//!
//! ## Static Files
//! The `static-files` command allows the importing of file-system based rust documents into the REPL
//! compilation. Rust files must be relative to the REPL working directory, and will be imported using
//! a module path based off the relative file name. For example, `:static-files add foo.rs` will copy
//! the contents of `foo.rs` into a file that is _adjacent_ to the root library file, so can be access
//! in the REPL through `foo::*`. The file `foo/mod.rs` would similarly be accessible through `foo::*`.
//! If the file `foo/bar.rs` was imported, it would _not_ be accessible unless there was also a `foo`
//! static file, and the contents of that file would have to contain a `pub mod bar;`.
//!
//! Static files can also reference crates. If a static file contains `extern crate name;` **at the
//! beginning** of the file, these crates are added to the compilation and can be referenced.
//!
//! To add static files, it is possible to use glob patterns to add multiple files in one go. For
//! example to add _all_ files in the working directory the command `:static-files add *.rs` can be
//! used. To recursively add files `**/*.rs` can be used. This applies to removing static files using
//! the `rm` command.
//!
//! # Extending Commands
//! ## Setup
//!
//! This tutorial works through the example at
//! [`papyrus/examples/custom-cmds.rs`](https://github.com/kurtlawrence/papyrus/blob/master/papyrus/examples/custom-cmds.rs).
//!
//! To begin, start a binary project with the following scaffolding in the main source code. We define
//! a `custom_cmds` function that will be used to build our custom commands. To highlight the
//! versatility of commands, the REPL is configured to have a persistent app data through a `String`.
//! Notice also the method to alter the prompt name through the `Builder::new` method.
//!
//! ```rust,no_run
//! #[macro_use]
//! extern crate papyrus;
//!
//! use papyrus::cmdtree::{Builder, BuilderChain};
//! use papyrus::cmds::CommandResult;
//!
//! # #[cfg(not(feature = "runnable"))]
//! # fn main() {}
//!
//! # #[cfg(feature = "runnable")]
//! fn main() {
//!     // Build a REPL that will use a String as the persistent app_data.
//!     let mut repl = repl!(String);
//!
//!     // Inject our custom commands.
//!     repl.data.with_cmdtree_builder(custom_cmds()).unwrap();
//!
//!     // Create the persistent data.
//!     let mut app_data = String::new();
//!
//!     // Run the REPL and collect all the output.
//!     let output = repl.run(papyrus::run::RunCallbacks::new(&mut app_data)).unwrap();
//!
//!     // Print the output.
//!     println!("{}", output);
//! }
//!
//! // Define our custom commands.
//! // The CommandResult takes the same type as the app_data,
//! // in this instance it is a String. We could define it as
//! // a generic type but then it loses resolution to interact with
//! // the app_data through commands.
//! fn custom_cmds() -> Builder<CommandResult<String>> {
//!     // The string defines the name and the prompt that will be used.
//!     Builder::new("custom-cmds-app")
//! }
//! ```
//!
//! ## Echo
//!
//! Let's begin with a simple echo command. This command takes the data after the command and prints it
//! to screen. All these commands will be additions to the `Builder::new`.
//! Adding the following action with `add_action` method, the arguments are written to the `Write`able
//! `writer`. The REPL provides the writer and so captures the output. `args` is passed through as a
//! slice of string slices, `cmdtree` provides this, and are always split on word boundaries.
//! Finally, `CommandResult::Empty` is returned which `papyrus` further processes. `Empty` won't do
//! anything but the API provides alternatives.
//!
//! ```rust
//! # extern crate papyrus;
//! # use papyrus::cmdtree::BuilderChain;
//! # use papyrus::cmds::CommandResult;
//! # type Builder = papyrus::cmdtree::Builder<CommandResult<String>>;
//! Builder::new("custom-cmds-app")
//!     .add_action("echo", "repeat back input after command", |writer, args| {
//!     writeln!(writer, "{}", args.join(" ")).ok();
//!     CommandResult::Empty
//!     })
//!     .unwrap()
//! # ;
//! ```
//!
//! Now when the binary is run the REPL runs as usual. If `:help` is entered you should see the
//! following output.
//!
//! ```text
//! [lib] custom-cmds-app=> :help
//! help -- prints the help messages
//! cancel | c -- returns to the root class
//! exit -- sends the exit signal to end the interactive loop
//! Classes:
//!     edit -- Edit previous input
//!     mod -- Handle modules
//! Actions:
//!     echo -- repeat back input after command
//!     mut -- Begin a mutable block of code
//! [lib] custom-cmds-app=>
//! ```
//!
//! The `echo` command exists as a root level action, with the help message displayed. Try calling
//! `:echo Hello, world!` and see what it does!
//!
//!
//! ## Alter app data
//!
//! To extend what the commands can do, lets create a command set that can convert the persistent app
//! data case.
//! The actual actions are nested under a 'class' named `case`. This means to invoke the action, one
//! would call it through `:case upper` or `:case lower`.
//!
//! ```rust
//! # extern crate papyrus;
//! # use papyrus::cmdtree::BuilderChain;
//! # use papyrus::cmds::CommandResult;
//! # type Builder = papyrus::cmdtree::Builder<CommandResult<String>>;
//! Builder::new("custom-cmds-app")
//!     .add_action("echo", "repeat back input after command", |writer, args| {
//!     writeln!(writer, "{}", args.join(" ")).ok();
//!     CommandResult::Empty
//!     })
//!     .begin_class("case", "change case of app_data")
//!     .add_action("upper", "make app_data uppercase", |_, _|
//!     CommandResult::<String>::app_data_fn(|app_data, _repldata, _| {
//!         *app_data = app_data.to_uppercase();
//!         String::new()
//!         })
//!     )
//!         .add_action("lower", "make app_data lowercase", |_, _|
//!     CommandResult::<String>::app_data_fn(|app_data, _repldata, _| {
//!         *app_data = app_data.to_lowercase();
//!         String::new()
//!         })
//!     )
//!     .end_class()
//!     .unwrap()
//! # ;
//! ```
//!
//! An example output is below. To inject some data into the persistent app data, a mutable code block
//! must be entered first.
//!
//! ```text
//! [lib] papyrus=> :mut
//! beginning mut block
//! [lib] custom-cmds-app-mut=> app_data.push_str("Hello, world!")
//! finished mutating block: ()
//! [lib] custom-cmds-app=> app_data.as_str()
//! custom-cmds-app [out0]: "Hello, world!"
//! [lib] custom-cmds-app=> :case upper
//! [lib] custom-cmds-app=> app_data.as_str()
//! custom-cmds-app [out1]: "HELLO, WORLD!"
//! [lib] custom-cmds-app=> :case lower
//! [lib] custom-cmds-app=> app_data.as_str()
//! custom-cmds-app [out2]: "hello, world!"
//! ```
use super::*;
use crate::repl::{Editing, EditingIndex, ReplData};
use cmdtree::{BuildError, Builder, BuilderChain, Commander};
use std::{
    fs,
    io::Write,
    path::{Path, PathBuf},
};

pub use cmdtree::Builder as CommandBuilder;

/// The action to take. Passes through a mutable reference to the `ReplData`.
///
/// Use [`CommandResult::repl_data_fn`](CommandResult::repl_data_fn) for convenience.
pub type ReplDataAction<D> = Box<dyn Fn(&mut ReplData<D>, &mut dyn Write) -> String>;

/// The action to take. Passes through a mutable reference to the data `D` _and_ the `ReplData<D>`.
///
/// > _Mutably borrows_ `D` such that a lock must be taken. Use only when necessary.
///
/// Use [`CommandResult::app_data_fn`](CommandResult::app_data_fn) for convenience.
pub type AppDataAction<D> = Box<dyn Fn(&mut D, &mut ReplData<D>, &mut dyn Write) -> String>;

/// The result of a [`cmdtree action`].
/// This result is handed in the repl's evaluating stage, and can alter `ReplData` or the data `D`.
///
/// [`cmdtree action`]: cmdtree::Action
pub enum CommandResult<D> {
    /// Flag to begin a mutating block.
    BeginMutBlock,
    /// Flag to alter a previous statement, item, or crate.
    EditAlter(EditingIndex),
    /// Replace a previous statement, item, or crate with value.
    EditReplace(EditingIndex, String),
    /// Switch to a module.
    SwitchModule(PathBuf),
    /// Take an action on the `ReplData`.
    ActionOnReplData(ReplDataAction<D>),
    /// Take an action on data `D` and/or `ReplData`.
    ActionOnAppData(AppDataAction<D>),
    /// A blank variant with no action.
    Empty,
}

impl<D> CommandResult<D> {
    /// Convenience function boxing an action on app data.
    ///
    /// > _Mutably borrows_ `D` such that a lock must be taken. Use only when necessary.
    pub fn app_data_fn<F>(func: F) -> Self
    where
        F: 'static + Fn(&mut D, &mut ReplData<D>, &mut dyn Write) -> String,
    {
        CommandResult::ActionOnAppData(Box::new(func))
    }

    /// Convenience function boxing an action on repl data.
    pub fn repl_data_fn<F>(func: F) -> Self
    where
        F: 'static + Fn(&mut ReplData<D>, &mut dyn Write) -> String,
    {
        CommandResult::ActionOnReplData(Box::new(func))
    }
}

impl<D> ReplData<D> {
    /// Uses the given `Builder` as the root of the command tree.
    ///
    /// An error will be returned if any command already exists.
    pub fn with_cmdtree_builder(
        &mut self,
        builder: Builder<CommandResult<D>>,
    ) -> Result<&mut Self, BuildError> {
        self.cmdtree = papyrus_cmdr(builder)?;
        Ok(self)
    }
}

fn papyrus_cmdr<D>(
    builder: Builder<CommandResult<D>>,
) -> Result<Commander<CommandResult<D>>, BuildError> {
    builder
        .root()
        .add_action("mut", "Begin a mutable block of code", |_, _| {
            CommandResult::BeginMutBlock
        })
        .begin_class("edit", "Edit previous input")
        .begin_class("stmt", "Edit previous statements")
        .add_action(
            "alter",
            "Alter statement contents. args: stmt-number",
            |wtr, args| edit_alter_priv(args, wtr, Editing::Stmt),
        )
        .add_action(
            "replace",
            "Replace statement contents. args: stmt-number value",
            |wtr, args| edit_replace_priv(args, wtr, Editing::Stmt),
        )
        .end_class()
        .end_class()
        .begin_class("mod", "Handle modules")
        .add_action(
            "switch",
            "Switch to a module, creating one if necessary. switch path/to/module",
            |wtr, args| switch_module_priv(args, wtr),
        )
        .add_action(
            "clear",
            "Clear previous input. args: mod-path or glob pattern",
            |wtr, args| clear_modules(args, wtr),
        )
        .end_class()
        .begin_class("static-files", "Handle static files")
        .add_action(
            "add",
            "Import a static file. args: file-path or glob pattern",
            |wtr, args| add_static_file(wtr, args),
        )
        .add_action(
            "rm",
            "Remove a static file. args: file-path or glob pattern",
            |wtr, args| rm_static_file(wtr, args),
        )
        .add_action("ls", "List imported static files", |_, _| ls_static_files())
        .end_class()
        .into_commander()
}

// ------ MODULES --------------------------------------------------------------
fn switch_module_priv<D, W: Write>(args: &[&str], mut wtr: W) -> CommandResult<D> {
    if let Some(path) = args.get(0) {
        if let Some(path) = make_path(path) {
            CommandResult::SwitchModule(path)
        } else {
            writeln!(wtr, "failed to parse {} into a valid module path", path).unwrap();
            CommandResult::Empty
        }
    } else {
        writeln!(wtr, "switch expects a path to module argument").unwrap();
        CommandResult::Empty
    }
}

fn make_all_parents(path: &Path) -> Vec<PathBuf> {
    let components: Vec<_> = path.iter().collect();

    (1..components.len())
        .map(|idx| components[0..idx].iter().collect::<PathBuf>())
        .collect()
}

fn make_path(path: &str) -> Option<PathBuf> {
    let path = path.trim();

    let path = path.replace(".rs", "").replace("mod", "").replace("-", "_");

    if path == "lib" {
        return Some(PathBuf::from("lib"));
    }

    let x: &[_] = &['/', '\\'];
    let path = path.trim_matches(x); // remove starting or trailing slashes

    if path.is_empty() {
        return None;
    }

    Some(PathBuf::from(path))
}

fn edit_alter_priv<D, W: Write>(args: &[&str], mut wtr: W, t: Editing) -> CommandResult<D> {
    if let Some(idx) = args.get(0) {
        match parse_idx(idx, t) {
            Ok(ei) => CommandResult::EditAlter(ei),
            Err(e) => {
                writeln!(wtr, "failed parsing {} as number: {}", idx, e).ok();
                CommandResult::Empty
            }
        }
    } else {
        writeln!(wtr, "alter expects an index number").ok();
        CommandResult::Empty
    }
}

fn edit_replace_priv<D, W: Write>(args: &[&str], mut wtr: W, t: Editing) -> CommandResult<D> {
    if let Some(idx) = args.get(0) {
        match parse_idx(idx, t) {
            Ok(ei) => CommandResult::EditReplace(ei, args[1..].iter().copied().collect::<String>()),
            Err(e) => {
                writeln!(wtr, "failed parsing {} as number: {}", idx, e).ok();
                CommandResult::Empty
            }
        }
    } else {
        writeln!(wtr, "replace expects an index number").ok();
        CommandResult::Empty
    }
}

fn parse_idx(s: &str, editing: Editing) -> Result<EditingIndex, String> {
    s.parse()
        .map_err(|e| format!("{}", e))
        .map(|index| EditingIndex { editing, index })
}

pub(crate) fn edit_alter<D>(data: &mut ReplData<D>, ei: EditingIndex) -> &'static str {
    let src = data.current_src();

    let len = match ei.editing {
        Editing::Stmt => src.stmts.len(),
        Editing::Item => src.items.len(),
        Editing::Crate => src.crates.len(),
    };

    if ei.index >= len {
        "index is outside of range"
    } else {
        data.editing = Some(ei);
        ""
    }
}

pub(crate) fn switch_module<D>(data: &mut ReplData<D>, path: &Path) -> &'static str {
    let mut all = make_all_parents(path);
    all.push(path.to_path_buf());

    for x in all {
        data.mods_map.entry(x).or_default();
    }

    data.current_mod = path.to_path_buf();

    ""
}

fn clear_modules<D, W: Write>(args: &[&str], mut wtr: W) -> CommandResult<D> {
    if let Some(pat) = args.get(0) {
        match glob::Pattern::new(pat) {
            Ok(pattern) => CommandResult::repl_data_fn(move |data, wtr| {
                for (path, src_code) in &mut data.mods_map {
                    if pattern.matches_path(&path) {
                        src_code.clear();
                        writeln!(wtr, "cleared inputs in `{}`", path.display()).ok();
                    }
                }

                String::from("cleared all previous inputs")
            }),
            Err(e) => {
                writeln!(wtr, "unrecognisable pattern: {}", e).ok();
                CommandResult::Empty
            }
        }
    } else {
        CommandResult::repl_data_fn(move |data, _| {
            let p = data.current_mod().to_owned();
            if let Some(src) = data.mods_map.get_mut(&p) {
                src.clear()
            }
            format!("cleared previous input in `{}`", p.display())
        })
    }
}

// ------ STATIC FILES ---------------------------------------------------------
fn add_static_file<D>(wtr: &mut dyn Write, args: &[&str]) -> CommandResult<D> {
    if let Some(&path) = args.get(0) {
        let glob = path.to_string();
        CommandResult::repl_data_fn(move |data, wtr| {
            foreach_glob_path(&glob, wtr, |path, wtr| {
                match fs::read_to_string(&path) {
                    Ok(s) => match data.add_static_file(path.clone(), &s) {
                        Ok(_) => {
                            writeln!(wtr, "imported/overwrote static file: `{}`", path.display())
                        }
                        Err(e) => writeln!(wtr, "failed to add `{}`: {}", path.display(), e),
                    },
                    Err(e) => writeln!(wtr, "failed to read `{}`: {}", path.display(), e),
                }
                .ok();
            });
            String::new()
        })
    } else {
        writeln!(wtr, "add expects a file path or glob pattern").ok();
        CommandResult::Empty
    }
}

fn rm_static_file<D>(wtr: &mut dyn Write, args: &[&str]) -> CommandResult<D> {
    if let Some(&path) = args.get(0) {
        let glob = path.to_string();
        CommandResult::repl_data_fn(move |data, wtr| {
            foreach_glob_path(&glob, wtr, |path, wtr| {
                if data.remove_static_file(&path) {
                    writeln!(wtr, "removed static file `{}`", path.display()).ok();
                }
            });
            String::from("removed static files")
        })
    } else {
        writeln!(wtr, "rm expects a file path or glob pattern").ok();
        CommandResult::Empty
    }
}

fn ls_static_files<D>() -> CommandResult<D> {
    CommandResult::repl_data_fn(|data, wtr| {
        let sfs = data.static_files();
        if sfs.is_empty() {
            writeln!(wtr, "no static files imported").ok();
        } else {
            for sf in data.static_files() {
                write!(wtr, "{}", sf.path.display()).ok();
                if let Some(name) = crate::code::static_file_mod_name(&sf.path) {
                    write!(wtr, " -> {}", name).ok();
                }
                writeln!(wtr).ok();
            }
        }
        String::new()
    })
}

fn foreach_glob_path<F>(glob: &str, wtr: &mut dyn Write, mut f: F)
where
    F: FnMut(PathBuf, &mut dyn Write),
{
    match glob::glob(glob) {
        Ok(iter) => {
            for path in iter.filter_map(Result::ok) {
                f(path, wtr)
            }
        }
        Err(e) => {
            writeln!(wtr, "reading `{}` failed: {}", glob, e).ok();
        }
    }
}

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

    #[test]
    fn make_path_test() {
        assert_eq!(make_path("   "), None);

        assert_eq!(make_path("lib"), Some(PathBuf::from("lib")));
        assert_eq!(make_path("lib.rs"), Some(PathBuf::from("lib")));

        assert_eq!(make_path("test"), Some(PathBuf::from("test")));
        assert_eq!(make_path("test/inner"), Some(PathBuf::from("test/inner")));
        assert_eq!(make_path("inner/test"), Some(PathBuf::from("inner/test")));

        assert_eq!(make_path("//"), None);

        assert_eq!(make_path("\\hello\\"), Some(PathBuf::from("hello")));
    }

    #[test]
    fn make_all_parents_test() {
        // only handle parents
        assert_eq!(make_all_parents(Path::new("")), Vec::<PathBuf>::new());
        assert_eq!(make_all_parents(Path::new("test")), Vec::<PathBuf>::new());

        assert_eq!(
            make_all_parents(Path::new("test/inner")),
            vec![PathBuf::from("test")]
        );
        assert_eq!(
            make_all_parents(Path::new("test/inner/deep")),
            vec![PathBuf::from("test"), PathBuf::from("test/inner")]
        );
    }

    #[test]
    fn test_switch_module_priv() {
        let mut buf = Vec::new();
        switch_module_priv::<(), _>(&[], &mut buf);
        assert_eq!(
            buf.as_slice(),
            &b"switch expects a path to module argument\n"[..]
        );

        buf.clear();
        switch_module_priv::<(), _>(&["foo"], &mut buf);
        assert_eq!(buf.as_slice(), &b""[..]);

        buf.clear();
        switch_module_priv::<(), _>(&[""], &mut buf);
        println!("{:?}", std::str::from_utf8(&buf));
        assert_eq!(
            buf.as_slice(),
            &b"failed to parse  into a valid module path\n"[..]
        );
    }

    #[test]
    fn test_static_file_interface() {
        let mut buf = Vec::new();
        add_static_file::<()>(&mut buf, &[]);
        println!("{:?}", std::str::from_utf8(&buf));
        assert_eq!(
            buf.as_slice(),
            &b"add expects a file path or glob pattern\n"[..]
        );

        buf.clear();
        rm_static_file::<()>(&mut buf, &[]);
        println!("{:?}", std::str::from_utf8(&buf));
        assert_eq!(
            buf.as_slice(),
            &b"rm expects a file path or glob pattern\n"[..]
        );

        buf.clear();
        rm_static_file::<()>(&mut buf, &["what"]);
    }
}