Skip to content

Commit

Permalink
Eliminate std::process::exit
Browse files Browse the repository at this point in the history
  • Loading branch information
theory committed Aug 1, 2024
1 parent c0d37e2 commit 3ec2959
Showing 1 changed file with 35 additions and 15 deletions.
50 changes: 35 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,65 @@ use std::{
ffi::OsString,
fs::File,
io::{self, Write},
process::ExitCode,
};

use pgxn_meta::Validator;
use serde_json::Value;

fn main() -> Result<(), Box<dyn Error>> {
fn main() -> Result<ExitCode, Box<dyn Error>> {
run(io::stdout(), env::args_os().collect::<Vec<_>>())
}

fn run<I>(mut out: impl Write, args: I) -> Result<(), Box<dyn Error>>
fn run<I>(mut out: impl Write, args: I) -> Result<ExitCode, Box<dyn Error>>
where
I: IntoIterator,
I::Item: Into<OsString>,
{
let file = parse_args(&mut out, args)?;
validate(&file)
let res = parse_args(&mut out, args)?;
if !res.exit {
validate(&res.file)?;
}
Ok(ExitCode::SUCCESS)
}

struct Args {
exit: bool,
file: String,
}

fn parse_args<I>(out: &mut impl Write, args: I) -> Result<String, Box<dyn Error>>
fn parse_args<I>(out: &mut impl Write, args: I) -> Result<Args, Box<dyn Error>>
where
I: IntoIterator,
I::Item: Into<OsString>,
{
use lexopt::prelude::*;
let mut file = String::from("META.json");
let mut res = Args {
exit: false,
file: String::from("META.json"),
};
let mut parser = lexopt::Parser::from_iter(args);

while let Some(arg) = parser.next()? {
match arg {
Short('h') | Long("help") => usage(out, &parser)?,
Short('v') | Long("version") => version(out, &parser)?,
Short('m') | Long("man") => docs(out)?,
Value(val) => file = val.string()?,
Short('h') | Long("help") => {
usage(out, &parser)?;
res.exit = true
}
Short('v') | Long("version") => {
version(out, &parser)?;
res.exit = true
}
Short('m') | Long("man") => {
docs(out)?;
res.exit = true
}
Value(val) => res.file = val.string()?,
_ => return Err(Box::new(arg.unexpected())),
}
}

Ok(file)
Ok(res)
}

fn validate(file: &str) -> Result<(), Box<dyn Error>> {
Expand All @@ -68,16 +89,15 @@ fn usage(out: &mut impl Write, p: &lexopt::Parser) -> Result<(), Box<dyn Error>>
\x20 -v --version Print the version number and exit",
bn!(p),
)?;

std::process::exit(0);
Ok(())
}

fn version(out: &mut impl Write, p: &lexopt::Parser) -> Result<(), Box<dyn Error>> {
writeln!(out, "{} {}", bn!(p), env!("CARGO_PKG_VERSION"))?;
std::process::exit(0);
Ok(())
}

fn docs(out: &mut impl Write) -> Result<(), Box<dyn Error>> {
writeln!(out, "Docs")?;
std::process::exit(0);
Ok(())
}

0 comments on commit 3ec2959

Please sign in to comment.