Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use min args in clap derive to ensure a command is provided #2

Merged
merged 1 commit into from
Aug 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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