Browse Source

Testing Command

master
Julio Biason 8 months ago
parent
commit
7939394a34
  1. 1
      commandtest/.gitignore
  2. 8
      commandtest/Cargo.toml
  3. 5
      commandtest/README.md
  4. 32
      commandtest/src/main.rs
  5. 11
      commandtest/src/the_script.sh

1
commandtest/.gitignore vendored

@ -0,0 +1 @@
script.log

8
commandtest/Cargo.toml

@ -0,0 +1,8 @@
[package]
name = "commandtest"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

5
commandtest/README.md

@ -0,0 +1,5 @@
# CommandTest
Playing a bit with `Command`, trying to send the output of a command to a file
(easy) while capturing it at the same time, looking for some special strings
(hard).

32
commandtest/src/main.rs

@ -0,0 +1,32 @@
use std::ffi::OsString;
use std::fs::File;
use std::path::PathBuf;
use std::process::Command;
fn search_in_path(name: &str) -> Option<PathBuf> {
let path = std::env::var_os("PATH").unwrap_or_else(OsString::new);
std::env::split_paths(&path).find_map(|dir| {
let full_path = dir.join(name);
if full_path.is_file() {
Some(full_path)
} else {
None
}
})
}
fn main() {
// this requires always running with `cargo run`
let base = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let log_file = File::create("script.log").unwrap();
let the_script = base.join("src").join("the_script.sh");
let bash = search_in_path("bash").unwrap();
let mut cmd = Command::new(bash)
.arg(the_script)
.stdout(log_file)
.spawn()
.unwrap();
cmd.wait().unwrap();
}

11
commandtest/src/the_script.sh

@ -0,0 +1,11 @@
#!/usr/bin/env bash
echo "Hello, I'm a script!"
echo "I write stuff in the output."
echo "Everything should go to a file."
echo "But also, you need to capture this:"
echo "WARNING: This is a warning"
echo " It continues if the line starts with spaces"
echo " And keeps going till there are no more spaces-prefixes"
echo "Like this."
echo "Then you're good to go."
Loading…
Cancel
Save