From 3ec2959143c54cf93e7b20637d1847ef45ae2ace Mon Sep 17 00:00:00 2001 From: "David E. Wheeler" Date: Thu, 1 Aug 2024 17:06:20 -0400 Subject: [PATCH] Eliminate std::process::exit --- src/main.rs | 50 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index c1f94dc..252ebe7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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> { +fn main() -> Result> { run(io::stdout(), env::args_os().collect::>()) } -fn run(mut out: impl Write, args: I) -> Result<(), Box> +fn run(mut out: impl Write, args: I) -> Result> where I: IntoIterator, I::Item: Into, { - 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(out: &mut impl Write, args: I) -> Result> +fn parse_args(out: &mut impl Write, args: I) -> Result> where I: IntoIterator, I::Item: Into, { 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> { @@ -68,16 +89,15 @@ fn usage(out: &mut impl Write, p: &lexopt::Parser) -> Result<(), Box> \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> { writeln!(out, "{} {}", bn!(p), env!("CARGO_PKG_VERSION"))?; - std::process::exit(0); + Ok(()) } fn docs(out: &mut impl Write) -> Result<(), Box> { writeln!(out, "Docs")?; - std::process::exit(0); + Ok(()) }