Crate better_commands

Source
Expand description

§Better Commands

This crate provides the ability to more easily run a Command while also doing something with its output as it runs, as well as providing some extra functionality:

  • Specifies whether a Line is printed to stderr or stderr
  • Provides a timestamp for each Line
  • Provides timestamps for the command as a whole (start, end, and duration)

A basic example (see run):

use better_commands::run;
use std::process::Command;

let output = run(Command::new("sleep").arg("1"));
println!("{:?}", output.duration());

A more complex example - this lets you provide a function to be run using the output from the command in real-time (see run_funcs_with_lines):

use better_commands::run_funcs_with_lines;
use better_commands::Line;
use std::process::Command;
let cmd = run_funcs_with_lines(&mut Command::new("echo").arg("hi"), {
    |stdout_lines| { // your function *must* return the lines
        let mut lines = Vec::new();
        for line in stdout_lines {
            lines.push(Line::from_stdout(line.unwrap()));
            /* send line to database */
            }
            return lines;
        }
    },
    {
    |stderr_lines| {
        // this code is for stderr and won't run because echo won't print anything to stderr, so we'll just put this placeholder here
        return Vec::new();
    }
});

// prints the following: [Line { printed_to: Stdout, time: Instant { tv_sec: 16316, tv_nsec: 283884648 }, content: "hi" }]
// (timestamp varies)
assert_eq!("hi", cmd.lines().unwrap()[0].content);

Structs§

  • Holds the output for a command
  • A single line from the output of a command

Enums§

  • Specifies what a line was printed to - stdout or stderr

Functions§

  • Runs a command, returning a CmdOutput (which will contain Some(lines), not a None)
  • Runs a command while simultaneously running a provided Fn as the command prints line-by-line
  • Runs a command while simultaneously running a provided Fn as the command prints line-by-line, including line handling