Skip to content

Commit

Permalink
Merge pull request #2 from triarius/min-args
Browse files Browse the repository at this point in the history
Use min args in clap derive to ensure a command is provided
  • Loading branch information
triarius authored Aug 31, 2024
2 parents 16fe034 + 75f3437 commit 27d3edf
Showing 1 changed file with 8 additions and 31 deletions.
39 changes: 8 additions & 31 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,61 +1,38 @@
use clap::Parser;
use eyre::Result;
use std::{path::PathBuf, str::FromStr};
use std::path::PathBuf;

/// A command runner that optionally logs the I/O streams to files.
#[derive(Debug, Parser, PartialEq)]
#[command(version)]
struct Cli {
/// The file to log stdin to.
#[clap(short, long, env)]
in_file: Option<String>,
in_file: Option<PathBuf>,

/// The file to log stdout to.
#[clap(short, long, env)]
out_file: Option<String>,
out_file: Option<PathBuf>,

/// The file to log stderr to.
#[clap(short, long, env)]
err_file: Option<String>,
err_file: Option<PathBuf>,

/// The command to run and its arguments. A command must be specified, arguments are space delimited.
#[clap(last = true)]
#[clap(last = true, required = true, num_args = 1..)]
exec: Vec<String>,
}

fn main() -> Result<()> {
let cli = Cli::parse();

let exec = cli.exec.iter().map(String::as_str).collect::<Vec<&str>>();
if exec.is_empty() {
use clap::CommandFactory;
eprintln!("EXEC must have at least one argument.");
eprintln!("{}", Cli::command().render_long_help());
std::process::exit(1);
}

let in_file = cli
.in_file
.as_ref()
.map(|s| PathBuf::from_str(s))
.transpose()?;
let out_file = cli
.out_file
.as_ref()
.map(|s| PathBuf::from_str(s))
.transpose()?;
let err_file = cli
.err_file
.as_ref()
.map(|s| PathBuf::from_str(s))
.transpose()?;

let code = runner::run(
exec[0],
&exec[1..],
in_file.as_deref(),
out_file.as_deref(),
err_file.as_deref(),
cli.in_file.as_deref(),
cli.out_file.as_deref(),
cli.err_file.as_deref(),
)?;

std::process::exit(code);
Expand Down

0 comments on commit 27d3edf

Please sign in to comment.