printable-shell-command 0.2.4

A helper library to print shell commands.
Documentation
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
use std::{
    ffi::{OsStr, OsString},
    ops::{Deref, DerefMut},
    process::Command,
    str::Utf8Error,
};

use itertools::Itertools;

use crate::{
    command::{add_arg_from_command, add_arg_from_command_lossy},
    print_builder::PrintBuilder,
    shell_printable::{ShellPrintable, ShellPrintableWithOptions},
    FormattingOptions,
};

pub struct PrintableShellCommand {
    arg_groups: Vec<Vec<OsString>>,
    command: Command,
}

// TODO: this depends on the interface to `Command` supporting the *appending*
// of algs but not the removal/reordering/editing of any args added so far. Is
// it even remotely possible to fail compilation if the args in `Command` become
// mutable like this?
impl PrintableShellCommand {
    pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
        Self {
            arg_groups: vec![],
            command: Command::new(program),
        }
    }

    /// Add args using `.arg(…)` each, in bulk.
    pub fn arg_each<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.adopt_args();
        for arg in args {
            let arg = self.arg_without_adoption(arg);
            self.command.arg(arg);
        }
        self
    }

    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
        self.adopt_args();
        let arg = self.arg_without_adoption(arg);
        self.command.arg(arg);
        self
    }

    fn arg_without_adoption<S: AsRef<OsStr>>(&mut self, arg: S) -> S {
        self.arg_groups.push(vec![(&arg).into()]);
        arg
    }

    pub fn args<I, S>(&mut self, args: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.adopt_args();
        let args = self.args_without_adoption(args);
        self.command.args(args);
        self
    }

    fn args_without_adoption<I, S>(&mut self, args: I) -> Vec<OsString>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        let args: Vec<OsString> = args
            .into_iter()
            .map(|arg| std::convert::Into::<OsString>::into(&arg))
            .collect();
        self.arg_groups.push(args.clone());
        args
    }

    fn args_to_adopt(&self) -> Vec<OsString> {
        let mut to_adopt: Vec<OsString> = vec![];
        for either_or_both in self
            .arg_groups
            .iter()
            .flatten()
            .zip_longest(self.command.get_args())
        {
            match either_or_both {
                itertools::EitherOrBoth::Both(a, b) => {
                    if a != b {
                        panic!("Command args do not match. This should not be possible.")
                    }
                }
                itertools::EitherOrBoth::Left(_) => {
                    panic!("Command is missing a previously seen arg. This should not be possible.")
                }
                itertools::EitherOrBoth::Right(arg) => {
                    to_adopt.push(arg.to_owned());
                }
            }
        }
        to_adopt
    }

    /// Adopt any args that were added to the underlying `Command` (from a
    /// `Deref`). Calling this function caches args instead of requiring
    /// throwaway work when subsequently generating printable strings (which
    /// would be inefficient when done multiple times).
    pub fn adopt_args(&mut self) -> &mut Self {
        for arg in self.args_to_adopt() {
            self.arg_without_adoption(arg);
        }
        self
    }

    fn add_unadopted_args_lossy(&self, print_builder: &mut PrintBuilder) {
        for arg in self.args_to_adopt() {
            add_arg_from_command_lossy(print_builder, arg.as_os_str());
        }
    }

    fn add_unadopted_args(&self, print_builder: &mut PrintBuilder) -> Result<(), Utf8Error> {
        for arg in self.args_to_adopt() {
            add_arg_from_command(print_builder, arg.as_os_str())?;
        }
        Ok(())
    }
}

impl Deref for PrintableShellCommand {
    type Target = Command;

    fn deref(&self) -> &Command {
        &self.command
    }
}

impl DerefMut for PrintableShellCommand {
    /// If args are added to the underlying command, they will be added as individual arg groups by `PrintableShellCommand`.
    fn deref_mut(&mut self) -> &mut Command {
        &mut self.command
    }
}

impl From<Command> for PrintableShellCommand {
    /// Adopts a `Command`, treating each arg as its own group (i.e. each arg will be printed on a separate line).
    fn from(command: Command) -> Self {
        let mut printable_shell_command = Self {
            arg_groups: vec![],
            command,
        };
        printable_shell_command.adopt_args();
        printable_shell_command
    }
}

impl ShellPrintableWithOptions for PrintableShellCommand {
    fn printable_invocation_string_lossy_with_options(
        &self,
        formatting_options: FormattingOptions,
    ) -> String {
        let mut print_builder =
            PrintBuilder::new(&self.get_program().to_string_lossy(), formatting_options);
        for arg_group in &self.arg_groups {
            let mut strings: Vec<String> = vec![];
            for arg in arg_group {
                strings.push(arg.to_string_lossy().to_string())
            }
            print_builder.add_arg_group(strings.iter());
        }
        self.add_unadopted_args_lossy(&mut print_builder);
        print_builder.get()
    }

    fn printable_invocation_string_with_options(
        &self,
        formatting_options: FormattingOptions,
    ) -> Result<String, Utf8Error> {
        let mut print_builder = PrintBuilder::new(
            TryInto::<&str>::try_into(self.get_program())?,
            formatting_options,
        );
        for arg_group in &self.arg_groups {
            let mut strings: Vec<&str> = vec![];
            for arg in arg_group {
                let s = TryInto::<&str>::try_into(arg.as_os_str())?;
                strings.push(s)
            }
            print_builder.add_arg_group(strings.into_iter());
        }
        self.add_unadopted_args(&mut print_builder)?;
        Ok(print_builder.get())
    }
}

impl ShellPrintable for PrintableShellCommand {
    fn printable_invocation_string(&self) -> Result<String, Utf8Error> {
        self.printable_invocation_string_with_options(Default::default())
    }

    fn printable_invocation_string_lossy(&self) -> String {
        self.printable_invocation_string_lossy_with_options(Default::default())
    }
}

#[cfg(test)]
mod tests {
    use std::{ops::DerefMut, process::Command, str::Utf8Error};

    use crate::{
        FormattingOptions, PrintableShellCommand, Quoting, ShellPrintable,
        ShellPrintableWithOptions,
    };

    #[test]
    fn echo() -> Result<(), Utf8Error> {
        let mut printable_shell_command = PrintableShellCommand::new("echo");
        printable_shell_command.args(["#hi"]);
        // Not printed by successful tests, but we can at least check this doesn't panic.
        let _ = printable_shell_command.print_invocation();

        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            "echo \\
  '#hi'"
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            printable_shell_command.printable_invocation_string_lossy(),
        );
        Ok(())
    }

    #[test]
    fn ffmpeg() -> Result<(), Utf8Error> {
        let mut printable_shell_command = PrintableShellCommand::new("ffmpeg");
        printable_shell_command
            .args(["-i", "./test/My video.mp4"])
            .args(["-filter:v", "setpts=2.0*PTS"])
            .args(["-filter:a", "atempo=0.5"])
            .arg("./test/My video (slow-mo).mov");
        // Not printed by successful tests, but we can at least check this doesn't panic.
        let _ = printable_shell_command.print_invocation();

        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            "ffmpeg \\
  -i './test/My video.mp4' \\
  -filter:v 'setpts=2.0*PTS' \\
  -filter:a atempo=0.5 \\
  './test/My video (slow-mo).mov'"
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            printable_shell_command.printable_invocation_string_lossy(),
        );
        Ok(())
    }

    #[test]
    fn from_command() -> Result<(), Utf8Error> {
        let mut command = Command::new("echo");
        command.args(["hello", "#world"]);
        // Not printed by tests, but we can at least check this doesn't panic.
        let mut printable_shell_command = PrintableShellCommand::from(command);
        let _ = printable_shell_command.print_invocation();

        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            "echo \\
  hello \\
  '#world'"
        );
        Ok(())
    }

    #[test]
    fn adoption() -> Result<(), Utf8Error> {
        let mut printable_shell_command = PrintableShellCommand::new("echo");

        {
            let command: &mut Command = printable_shell_command.deref_mut();
            command.arg("hello");
            command.arg("#world");
        }

        printable_shell_command.printable_invocation_string()?;
        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            "echo \\
  hello \\
  '#world'"
        );

        printable_shell_command.args(["wide", "web"]);

        printable_shell_command.printable_invocation_string()?;
        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            "echo \\
  hello \\
  '#world' \\
  wide web"
        );

        // Second adoption
        {
            let command: &mut Command = printable_shell_command.deref_mut();
            command.arg("to").arg("the").arg("internet");
        }
        // Test adoption idempotency.
        printable_shell_command.adopt_args();
        printable_shell_command.adopt_args();
        printable_shell_command.adopt_args();
        assert_eq!(
            printable_shell_command
                .printable_invocation_string()
                .unwrap(),
            "echo \\
  hello \\
  '#world' \\
  wide web \\
  to \\
  the \\
  internet"
        );

        Ok(())
    }

    // TODO: test invalid UTF-8

    fn rsync_command_for_testing() -> PrintableShellCommand {
        let mut printable_shell_command = PrintableShellCommand::new("rsync");
        printable_shell_command
            .arg("-avz")
            .args(["--exclude", ".DS_Store"])
            .args(["--exclude", ".git"])
            .arg("./dist/web/experiments.cubing.net/test/deploy/")
            .arg("experiments.cubing.net:~/experiments.cubing.net/test/deploy/");
        printable_shell_command
    }

    #[test]
    fn extra_safe_quoting() -> Result<(), Utf8Error> {
        let printable_shell_command = rsync_command_for_testing();
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    quoting: Some(Quoting::ExtraSafe),
                    ..Default::default()
                }
            )?,
            "'rsync' \\
  '-avz' \\
  '--exclude' '.DS_Store' \\
  '--exclude' '.git' \\
  './dist/web/experiments.cubing.net/test/deploy/' \\
  'experiments.cubing.net:~/experiments.cubing.net/test/deploy/'"
        );
        Ok(())
    }

    #[test]
    fn indentation() -> Result<(), Utf8Error> {
        let printable_shell_command = rsync_command_for_testing();
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    arg_indentation: Some("\t   \t".to_owned()),
                    ..Default::default()
                }
            )?,
            "rsync \\
	   	-avz \\
	   	--exclude .DS_Store \\
	   	--exclude .git \\
	   	./dist/web/experiments.cubing.net/test/deploy/ \\
	   	experiments.cubing.net:~/experiments.cubing.net/test/deploy/"
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    arg_indentation: Some("β†ͺ ".to_owned()),
                    ..Default::default()
                }
            )?,
            "rsync \\
β†ͺ -avz \\
β†ͺ --exclude .DS_Store \\
β†ͺ --exclude .git \\
β†ͺ ./dist/web/experiments.cubing.net/test/deploy/ \\
β†ͺ experiments.cubing.net:~/experiments.cubing.net/test/deploy/"
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    main_indentation: Some("  ".to_owned()),
                    ..Default::default()
                }
            )?,
            "  rsync \\
    -avz \\
    --exclude .DS_Store \\
    --exclude .git \\
    ./dist/web/experiments.cubing.net/test/deploy/ \\
    experiments.cubing.net:~/experiments.cubing.net/test/deploy/"
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    main_indentation: Some("πŸ™ˆ".to_owned()),
                    arg_indentation: Some("πŸ™‰".to_owned()),
                    ..Default::default()
                }
            )?,
            "πŸ™ˆrsync \\
πŸ™ˆπŸ™‰-avz \\
πŸ™ˆπŸ™‰--exclude .DS_Store \\
πŸ™ˆπŸ™‰--exclude .git \\
πŸ™ˆπŸ™‰./dist/web/experiments.cubing.net/test/deploy/ \\
πŸ™ˆπŸ™‰experiments.cubing.net:~/experiments.cubing.net/test/deploy/"
        );
        Ok(())
    }

    #[test]
    fn line_wrapping() -> Result<(), Utf8Error> {
        let printable_shell_command = rsync_command_for_testing();
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    argument_line_wrapping: Some(crate::ArgumentLineWrapping::ByEntry),
                    ..Default::default()
                }
            )?,
            printable_shell_command.printable_invocation_string()?
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    argument_line_wrapping: Some(crate::ArgumentLineWrapping::NestedByEntry),
                    ..Default::default()
                }
            )?,
            "rsync \\
  -avz \\
  --exclude \\
    .DS_Store \\
  --exclude \\
    .git \\
  ./dist/web/experiments.cubing.net/test/deploy/ \\
  experiments.cubing.net:~/experiments.cubing.net/test/deploy/"
        );
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    argument_line_wrapping: Some(crate::ArgumentLineWrapping::ByArgument),
                    ..Default::default()
                }
            )?,
            "rsync \\
  -avz \\
  --exclude \\
  .DS_Store \\
  --exclude \\
  .git \\
  ./dist/web/experiments.cubing.net/test/deploy/ \\
  experiments.cubing.net:~/experiments.cubing.net/test/deploy/"
        );
        Ok(())
    }

    #[test]
    fn command_with_space_is_escaped_by_default() -> Result<(), Utf8Error> {
        let printable_shell_command =
            PrintableShellCommand::new("/Applications/My App.app/Contents/Resources/my-app");
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    argument_line_wrapping: Some(crate::ArgumentLineWrapping::ByArgument),
                    ..Default::default()
                }
            )?,
            "'/Applications/My App.app/Contents/Resources/my-app'"
        );
        Ok(())
    }

    #[test]
    fn command_with_equal_sign_is_escaped_by_default() -> Result<(), Utf8Error> {
        let printable_shell_command = PrintableShellCommand::new("THIS_LOOKS_LIKE_AN=env-var");
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    argument_line_wrapping: Some(crate::ArgumentLineWrapping::ByArgument),
                    ..Default::default()
                }
            )?,
            "'THIS_LOOKS_LIKE_AN=env-var'"
        );
        Ok(())
    }

    #[test]
    fn arg_each() -> Result<(), Utf8Error> {
        let mut printable_shell_command = PrintableShellCommand::new("echo");
        printable_shell_command.arg_each(["hello", "world"]);
        assert_eq!(
            printable_shell_command.printable_invocation_string()?,
            "echo \\
  hello \\
  world"
        );
        Ok(())
    }

    #[test]
    fn dont_line_wrap_after_command() -> Result<(), Utf8Error> {
        let mut printable_shell_command = PrintableShellCommand::new("echo");
        printable_shell_command.args(["the", "rain", "in", "spain"]);
        printable_shell_command.arg("stays");
        printable_shell_command.args(["mainly", "in", "the", "plain"]);
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    skip_line_wrap_before_first_arg: Some(true),
                    ..Default::default()
                }
            )?,
            "echo the rain in spain \\
  stays \\
  mainly in the plain"
        );
        Ok(())
    }

    #[test]
    fn dont_line_wrap_after_command_when_there_are_no_args() -> Result<(), Utf8Error> {
        let printable_shell_command = PrintableShellCommand::new("echo");
        assert_eq!(
            printable_shell_command.printable_invocation_string_with_options(
                FormattingOptions {
                    skip_line_wrap_before_first_arg: Some(true),
                    ..Default::default()
                }
            )?,
            "echo"
        );
        Ok(())
    }
}