kawauso-process 0.2.1

External programs for Kawauso applications
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
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! The description of one external command
//!
//! An invocation names the program of a command, the arguments of the
//! program, and the directory in which the command runs. It also carries the
//! variables that the caller sets in the environment of the command. This
//! module holds the invocation and the types of its parts.
//!
//! An invocation is a value, and nothing starts a program when an application
//! builds one. An application can therefore describe a command once, write
//! the command to a log, and name it in an error.
//!
//! The [run][run] method starts the command that the invocation describes,
//! and it reports what the command produced. The [start][start] method starts
//! the same command and gives its output to the caller while the command
//! runs.
//!
//! [run]: Invocation::run
//! [start]: Invocation::start

pub mod argument;
pub mod program;
pub mod variable;
pub mod variable_name;
pub mod variable_value;
pub mod working_directory;

use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::process::Stdio;
use std::time::Instant;

use tokio::process::Command;

pub use self::argument::Argument;
pub use self::program::Program;
pub use self::variable::Variable;
pub use self::variable_name::VariableName;
pub use self::variable_value::VariableValue;
pub use self::working_directory::WorkingDirectory;
use crate::error::RunCommandError;
use crate::execution::Capture;
use crate::execution::Execution;
use crate::process_id::ProcessId;
use crate::run::Run;

/// The description of one external command
///
/// An invocation holds the program that the command starts, the arguments of
/// the program, and the directory in which the command runs. The arguments
/// keep the order in which the caller named them, and the working directory
/// is optional.
///
/// An invocation also holds the variables that the caller sets for the
/// command. The command inherits the environment of the process that runs
/// it, and a variable of the invocation replaces a variable of the process
/// with the same name.
///
/// No shell reads the command. Nothing splits an argument at a space, removes
/// a quotation mark, or expands a character such as `*`, so the program
/// receives every argument as the caller wrote it. An application that wants
/// a shell names the shell as the program, and gives the command line to it
/// as one argument.
///
/// The type renders as a command line through [`Display`], which gives a log
/// line or an error message the name of the command.
///
/// # Examples
///
/// A command with two arguments:
///
/// ```
/// use kawauso_process::Invocation;
///
/// let invocation = Invocation::new("git").arg("status").arg("--short");
///
/// assert_eq!(invocation.to_string(), "git status --short");
/// ```
///
/// A command that runs in a directory of its own:
///
/// ```
/// use std::path::Path;
///
/// use kawauso_process::Invocation;
/// use kawauso_process::invocation::WorkingDirectory;
///
/// let invocation = Invocation::new("cargo")
///     .arg("build")
///     .in_directory("crates/example");
///
/// assert_eq!(
///     invocation.working_directory().map(WorkingDirectory::get),
///     Some(Path::new("crates/example"))
/// );
/// ```
///
/// A command that reads a variable of its environment:
///
/// ```
/// use kawauso_process::Invocation;
///
/// let invocation = Invocation::new("cargo")
///     .arg("nextest")
///     .arg("run")
///     .env("NEXTEST_EXPERIMENTAL_LIBTEST_JSON", "1");
///
/// assert_eq!(
///     invocation.to_string(),
///     "NEXTEST_EXPERIMENTAL_LIBTEST_JSON=1 cargo nextest run"
/// );
/// ```
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct Invocation {
    /// The program that the command starts
    program: Program,

    /// The arguments that the program receives
    ///
    /// The order is the order in which the caller named them, because it is
    /// the order in which the program receives them.
    arguments: Vec<Argument>,

    /// The variables that the caller sets in the environment of the command
    ///
    /// The order is the order in which the caller set them, and a name
    /// appears once. The command inherits the environment of the process that
    /// runs it, and these variables come on top of that environment.
    environment: Vec<Variable>,

    /// The names that the caller takes out of the environment of the command
    ///
    /// The order is the order in which the caller named them, and a name
    /// appears once. A name of this list appears in no variable of the
    /// environment above, because a name is either set or taken out.
    removals: Vec<VariableName>,

    /// The directory in which the command runs
    ///
    /// `None` when the caller named no directory. The command then runs where
    /// the process runs.
    working_directory: Option<WorkingDirectory>,
}

impl Invocation {
    /// Describes a command that starts the program that the caller names
    ///
    /// The program is the path of an executable file, or the bare name of
    /// one. The command has no argument yet, and it runs where the process
    /// runs. [`arg`][arg] adds an argument, and
    /// [`in_directory`][in-directory] names a working directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("git");
    ///
    /// assert_eq!(invocation.program().get(), std::path::Path::new("git"));
    /// ```
    ///
    /// [arg]: Invocation::arg
    /// [in-directory]: Invocation::in_directory
    // process[impl invocation.program]
    pub fn new(program: impl Into<Program>) -> Self {
        Self {
            program: program.into(),
            arguments: Vec::new(),
            environment: Vec::new(),
            removals: Vec::new(),
            working_directory: None,
        }
    }

    /// Adds one argument to the command
    ///
    /// Every call adds one argument, and the program receives the arguments
    /// in the order of the calls. The value reaches the program as the caller
    /// wrote it, so an argument that holds a space stays one argument.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("git")
    ///     .arg("commit")
    ///     .arg("--message=two words");
    ///
    /// assert_eq!(invocation.arguments().len(), 2);
    /// ```
    // process[impl invocation.arguments]
    pub fn arg(mut self, argument: impl Into<Argument>) -> Self {
        self.arguments.push(argument.into());

        self
    }

    /// Adds every argument of an iterator to the command
    ///
    /// The command keeps the order of the iterator, and a later call appends
    /// to the arguments that the command holds. Use this method for a caller
    /// that holds its arguments in a collection, and [`arg`][arg] for one
    /// that names them.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("cargo").args(["build", "--release"]);
    ///
    /// assert_eq!(invocation.to_string(), "cargo build --release");
    /// ```
    ///
    /// [arg]: Invocation::arg
    pub fn args(mut self, arguments: impl IntoIterator<Item = impl Into<Argument>>) -> Self {
        self.arguments.extend(arguments.into_iter().map(Into::into));

        self
    }

    /// Returns the arguments of the command, in the order of the calls
    pub fn arguments(&self) -> &[Argument] {
        &self.arguments
    }

    /// Builds the command that a run starts
    ///
    /// Both forms of a run start the same command, so both take it from here.
    /// The command pipes both output streams, because a run reports what the
    /// command wrote to each of them.
    ///
    /// The command carries no call that clears the environment, so the
    /// command inherits the environment of this process. The variables of the
    /// invocation come on top of it, and a variable with the name of one that
    /// the process holds replaces it for the command alone. The program
    /// travels as the caller wrote it, and the operating system resolves a
    /// bare name.
    // process[impl run.environment]
    // process[impl run.resolution]
    fn command(&self) -> Command {
        let mut command = Command::new(self.program.get());

        command
            .args(self.arguments.iter().map(Argument::get))
            // process[impl invocation.environment]
            .envs(
                self.environment
                    .iter()
                    .map(|variable| (variable.name().get(), variable.value().get())),
            )
            // process[impl run.stdin]
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            // process[impl run.abandonment]
            // process[impl stream.abandonment]
            .kill_on_drop(true);

        // process[impl invocation.environment.removal]
        for name in &self.removals {
            command.env_remove(name.get());
        }

        if let Some(directory) = &self.working_directory {
            command.current_dir(directory.get());
        }

        command
    }

    /// Sets one variable in the environment of the command
    ///
    /// The command inherits the environment of the process that runs it, and
    /// the variable comes on top of that environment. A variable with the
    /// name of one that the process holds replaces the value for the command
    /// alone, and the process keeps its own.
    ///
    /// A later call with the same name replaces the value of the earlier
    /// call, because a variable holds one value. The variable keeps the place
    /// of the earlier call.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("cargo")
    ///     .arg("build")
    ///     .env("RUSTUP_TOOLCHAIN", "nightly");
    ///
    /// assert_eq!(invocation.environment().len(), 1);
    /// ```
    // process[impl invocation.environment]
    pub fn env(mut self, name: impl Into<VariableName>, value: impl Into<VariableValue>) -> Self {
        self.set(Variable::new(name, value));

        self
    }

    /// Returns the variables that the caller set, in the order of the calls
    pub fn environment(&self) -> &[Variable] {
        &self.environment
    }

    /// Takes one name out of the environment of the command
    ///
    /// The command inherits the environment of the process that runs it, and
    /// this name is the exception: the command runs as if the process never
    /// held it. Use this method for a program that reads a variable which the
    /// caller cannot set to a value that would be right, such as one that
    /// names the repository of a version control system to a child of a hook.
    ///
    /// The process keeps its own environment. Nothing here changes the
    /// variables that this process holds, which is what makes the method safe
    /// in a program that runs several commands at once.
    ///
    /// A name is either set or taken out, so this call undoes an earlier
    /// [`env`][env] with the same name, and a later [`env`][env] with the name
    /// undoes this call. A repeated call keeps the place of the earlier one.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("git")
    ///     .arg("status")
    ///     .env_remove("GIT_DIR");
    ///
    /// assert_eq!(invocation.to_string(), "-GIT_DIR git status");
    /// ```
    ///
    /// [env]: Invocation::env
    // process[impl invocation.environment.removal]
    // process[impl invocation.environment.exclusion]
    pub fn env_remove(mut self, name: impl Into<VariableName>) -> Self {
        let name = name.into();

        self.environment.retain(|variable| *variable.name() != name);

        if !self.removals.contains(&name) {
            self.removals.push(name);
        }

        self
    }

    /// Returns the names that the caller took out, in the order of the calls
    pub fn removals(&self) -> &[VariableName] {
        &self.removals
    }

    /// Sets every variable of an iterator in the environment of the command
    ///
    /// Each variable goes through the same steps as one that [`env`][env]
    /// sets, so a later variable with the name of an earlier one replaces its
    /// value. A pair of a name and a value is a variable, so a caller that
    /// holds its variables as pairs gives them as they are. Use this method
    /// for a caller that holds its variables in a collection, and
    /// [`env`][env] for one that names them.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("cargo")
    ///     .arg("build")
    ///     .envs([("RUSTUP_TOOLCHAIN", "nightly"), ("CARGO_TERM_COLOR", "always")]);
    ///
    /// assert_eq!(invocation.environment().len(), 2);
    /// ```
    ///
    /// [env]: Invocation::env
    // process[impl invocation.environment]
    pub fn envs(mut self, variables: impl IntoIterator<Item = impl Into<Variable>>) -> Self {
        for variable in variables {
            self.set(variable.into());
        }

        self
    }

    /// Runs the command in the directory that the caller names
    ///
    /// Use this method for a command that works on the directory that it runs
    /// in, such as a build tool that reads the manifest of a project. A
    /// command without a working directory runs where the process runs.
    ///
    /// A later call replaces the directory of an earlier one, because a
    /// command runs in one directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use kawauso_process::Invocation;
    ///
    /// let invocation = Invocation::new("cargo")
    ///     .arg("test")
    ///     .in_directory("crates/example");
    ///
    /// assert!(invocation.working_directory().is_some());
    /// ```
    // process[impl invocation.directory]
    pub fn in_directory(mut self, directory: impl Into<WorkingDirectory>) -> Self {
        self.working_directory = Some(directory.into());

        self
    }

    /// Returns the program that the command starts
    pub fn program(&self) -> &Program {
        &self.program
    }

    /// Runs the command and reports what it produced
    ///
    /// The method starts the program, reads what the command writes to its
    /// standard output and to its standard error, and waits for the command
    /// to end. A command that fills a pipe stops until a reader empties it,
    /// so the run reads both streams while it waits. A command that writes
    /// more than a pipe holds therefore never stops the run.
    ///
    /// The command starts with a standard input that is null, so a command
    /// that reads its input sees the end of the input at once. A program that
    /// asks for a password ends instead of waiting for an answer. The command
    /// inherits the environment of the process that runs it, and it reads the
    /// variables of the invocation on top of that environment. The operating
    /// system resolves the program with the rules of the platform, and the
    /// crate searches no path of its own.
    ///
    /// A command that ends without success is no failure of this method. The
    /// status travels in the result, and [`require_success`][require-success]
    /// turns a status that is not a success into an error.
    ///
    /// The future of this method owns the command. A caller that drops the
    /// future, after a timeout for example, ends the command with it.
    ///
    /// On Windows, a program whose name ends in `.cmd` or `.bat` starts
    /// through `cmd.exe`. Rust escapes the arguments for that interpreter and
    /// refuses an argument that it cannot pass safely, so an argument reaches
    /// the program as the caller wrote it or the run fails.
    ///
    /// # Errors
    ///
    /// Returns [`UnstartableCommand`][unstartable] when the program does not
    /// start, and [`IncompleteRun`][incomplete] when the command started and
    /// the crate could not collect its result.
    ///
    /// # Panics
    ///
    /// Panics when no Tokio runtime drives the future. The runtime watches
    /// the streams and the end of the command, and the crate has no way to
    /// run the command without one.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use kawauso_process::Invocation;
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let execution = Invocation::new("git").arg("status").run().await?;
    ///
    /// println!("{}", execution.stdout());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [incomplete]: RunCommandError::IncompleteRun
    /// [require-success]: Execution::require_success
    /// [unstartable]: RunCommandError::UnstartableCommand
    // process[impl run]
    pub async fn run(&self) -> Result<Execution, RunCommandError> {
        let start = Instant::now();

        let child =
            self.command()
                .spawn()
                .map_err(|source| RunCommandError::UnstartableCommand {
                    invocation: Box::new(self.clone()),
                    source,
                })?;

        // The wait takes the command, and the identifier of a command that
        // ended is gone. The run therefore reads the identifier here, so
        // that the result can carry it.
        // process[impl run.identity]
        let id = child.id().map(ProcessId::from);

        // The wait reads both streams while it waits for the end of the
        // command. A wait that read one stream after the other, or that read
        // nothing until the end, would stop on a command that fills a pipe.
        // process[impl run.drain]
        let output =
            child
                .wait_with_output()
                .await
                .map_err(|source| RunCommandError::IncompleteRun {
                    invocation: Box::new(self.clone()),
                    source,
                })?;

        Ok(Execution::new(
            self.clone(),
            id,
            output.status,
            Capture::new(output.stdout),
            Capture::new(output.stderr),
            start.elapsed(),
        ))
    }

    /// Puts one variable into the environment of the command
    ///
    /// A variable with a name that the environment holds replaces the value
    /// of that variable and keeps its place, because a variable holds one
    /// value. A variable with a new name goes to the end, so that the
    /// environment keeps the order of the calls.
    // process[impl invocation.environment.replacement]
    // process[impl invocation.environment.exclusion]
    fn set(&mut self, variable: Variable) {
        self.removals.retain(|name| name != variable.name());

        let existing = self
            .environment
            .iter_mut()
            .find(|existing| existing.name() == variable.name());

        match existing {
            Some(existing) => *existing = variable,
            None => self.environment.push(variable),
        }
    }

    /// Starts the command and reports its output while the command runs
    ///
    /// The method starts the program and returns a handle. The handle gives
    /// the output of the command to the caller as lines, in the order in
    /// which the lines arrive, and it collects the same capture that
    /// [`run`][run] collects. Use this method for an application that shows
    /// the progress of a command, or that turns the output of a command into
    /// events of its own, and [`run`][run] for one that needs the result
    /// alone.
    ///
    /// The command starts with the same decisions that [`run`][run] makes.
    /// The standard input is null, the command inherits the environment of
    /// the process that runs it, and the operating system resolves the
    /// program. The variables of the invocation reach the command as well.
    ///
    /// The handle owns the command. A caller that drops the handle kills the
    /// command with it, and a caller that asks the command to end first calls
    /// [`stop`][stop] on the handle.
    ///
    /// # Errors
    ///
    /// Returns [`UnstartableCommand`][unstartable] when the program does not
    /// start.
    ///
    /// # Panics
    ///
    /// Panics when no Tokio runtime runs. The runtime watches the streams and
    /// the end of the command, and the crate has no way to run the command
    /// without one.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use kawauso_process::Invocation;
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut run = Invocation::new("cargo").arg("build").start()?;
    ///
    /// while let Some(line) = run.next_line().await? {
    ///     println!("[{}] {line}", line.stream());
    /// }
    ///
    /// println!("{}", run.wait().await?.status());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [run]: Invocation::run
    /// [stop]: Run::stop
    /// [unstartable]: RunCommandError::UnstartableCommand
    // process[impl stream]
    pub fn start(&self) -> Result<Run, RunCommandError> {
        let started = Instant::now();

        let child =
            self.command()
                .spawn()
                .map_err(|source| RunCommandError::UnstartableCommand {
                    invocation: Box::new(self.clone()),
                    source,
                })?;

        Ok(Run::new(self.clone(), child, started))
    }

    /// Returns the directory in which the command runs
    ///
    /// `None` when the caller named no directory. The command then runs where
    /// the process runs.
    pub fn working_directory(&self) -> Option<&WorkingDirectory> {
        self.working_directory.as_ref()
    }
}

/// Renders the command as a command line for a reader
///
/// The line names every name that the caller took out, then every variable
/// that the caller set, then the program, and then every argument, each in the
/// order in which the caller named them. A variable shows as its name, an
/// equals sign, and its value, which is the form in which a shell sets a
/// variable for one command. A name that the caller took out shows behind a
/// minus sign, which is the form of the `env` program, because no shell takes
/// a name out of the environment of one command. The line does not name the
/// working directory, because a command line holds the command and not the
/// place that it runs in.
///
/// The line is for a person. No caller reads it back, and no shell runs it,
/// so it is not a command line that a shell has to accept.
// process[impl invocation.display]
// process[impl invocation.environment.display]
// process[impl invocation.environment.removal.display]
impl Display for Invocation {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        // process[impl invocation.environment.removal.display]
        for name in &self.removals {
            write!(formatter, "-{name} ")?;
        }

        for variable in &self.environment {
            write!(formatter, "{}=", variable.name())?;
            write_word(formatter, &variable.value().get().to_string_lossy())?;
            formatter.write_str(" ")?;
        }

        write_word(formatter, &self.program.get().to_string_lossy())?;

        for argument in &self.arguments {
            formatter.write_str(" ")?;
            write_word(formatter, &argument.get().to_string_lossy())?;
        }

        Ok(())
    }
}

/// Writes one word of a command line
///
/// A space separates the words of the line, so a word that holds a space
/// reads as two words, and a word that is empty reads as none. Such a word
/// goes between quotation marks, and a reader then sees where it starts and
/// where it ends.
///
/// The value of a variable is a word of this kind as well. The marks go around
/// the value alone, and not around the name, which is how a shell writes a
/// variable whose value holds a space.
///
/// The marks are for the reader. A word that holds a quotation mark of its own
/// keeps it, because no shell parses the line.
///
/// # Errors
///
/// Returns the error of the formatter when it cannot take the text.
fn write_word(formatter: &mut Formatter<'_>, word: &str) -> FmtResult {
    if word.is_empty() || word.contains(char::is_whitespace) {
        write!(formatter, "\"{word}\"")
    } else {
        formatter.write_str(word)
    }
}

#[cfg(test)]
mod tests {
    // An assertion in a test panics by design. A `# Panics` section on every
    // test would repeat that and give the reader no information.
    #![allow(clippy::missing_panics_doc)]

    use super::*;

    // A caller keeps an invocation in a field of a type that another thread
    // reads. This test holds the invocation to the auto traits that make this
    // possible, because a private field of a later version could take them
    // away without a word from the compiler.
    #[test]
    fn invocation_is_send_and_sync() {
        fn assert_send_and_sync<T: Send + Sync>() {}

        assert_send_and_sync::<Invocation>();
    }
}