Skip to content

Instantly share code, notes, and snippets.

@System-Glitch
Last active December 31, 2019 20:17
Show Gist options
  • Save System-Glitch/a8210a6266b634cc8946ebfc1cb066ee to your computer and use it in GitHub Desktop.
Save System-Glitch/a8210a6266b634cc8946ebfc1cb066ee to your computer and use it in GitHub Desktop.

Rust Pipe

A rust implementation of the pipe operator.

Example

# Using cargo run
cargo run -- --in curl https://systemglitch.me --out grep SystemGlitch

./my-pipe --in curl https://systemglitch.me --out grep SystemGlitch

To pass arguments to sub-commands, you may need to escape hyphens:

./my-pipe --in find ./target \\-name '*cargo*' \\-exec sleep 1 \; \\-exec echo {} \;  --out grep "cargo"
use clap::{Arg, App}; // Dependency: clap = "2.33.0"
use std::io;
use std::process::{self, Command, Stdio};
fn main() -> io::Result<()> {
let matches = App::new("rust-pipe")
.version("0.1.0")
.author("Jérémy LAMBERT (SystemGlitch) <[email protected]>")
.about("Rust pipe implementation")
.arg(
Arg::with_name("in")
.short("i")
.long("in")
.value_name("input_command")
.help("Input command")
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("out")
.short("o")
.long("out")
.value_name("output_command")
.help("Output command")
.takes_value(true)
.multiple(true),
)
.get_matches();
let mut in_cmd: Vec<String> = matches.values_of("in")
.unwrap().map(|x| {
x.replace("\\-", "-")
}).collect();
let mut out_cmd: Vec<String> = matches.values_of("out")
.unwrap().map(|x| {
x.replace("\\-", "-")
}).collect();
let input = Command::new(in_cmd.remove(0))
.args(in_cmd)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn().unwrap();
let output = Command::new(out_cmd.remove(0))
.args(out_cmd)
.stdin(input.stdout.unwrap())
.stderr(Stdio::inherit())
.stdout(Stdio::inherit())
.output()
.unwrap();
if output.status.success() {
print!("{}", String::from_utf8(output.stdout).unwrap());
Ok(())
} else {
print!("{}", String::from_utf8(output.stderr).unwrap());
process::exit(output.status.code().unwrap())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment