refactor(exe_zip_maker): use lexopt for CLI argument parsing (#4406) Hand-rolled positional slice indexing in `exe_zip_maker` provides no structured flag handling or typed options. Parse CLI arguments with `lexopt` into a typed `Options` struct and delegate from `run_cli`. Work towards #4250
diff --git a/MODULE.bazel b/MODULE.bazel index 1b119a1..6ebc202 100644 --- a/MODULE.bazel +++ b/MODULE.bazel
@@ -111,10 +111,17 @@ "crate", dev_dependency = TOOL_DEPS_DEV_ONLY, ) + +# keep-sorted start block=yes +rust_crates.spec( + package = "lexopt", + version = "0.3.2", +) rust_crates.spec( package = "sha2", version = "0.10.8", ) +# keep-sorted end # The crates must build for every platform in dev/platforms. Conditional # dependencies are resolved for these triples; rules_rust matches them by CPU @@ -140,7 +147,7 @@ # rules_rust has no @rules_rust//rust/platform config_setting for Linux ppc64le, # so don't mark the crates as incompatible with platforms that don't match one # of the triples above. Such platforms get only the unconditional dependencies, -# which suffice for sha2. +# which suffice for lexopt and sha2. rust_crates.render_config( generate_target_compatible_with = False, )
diff --git a/crates/Cargo.Bazel.lock b/crates/Cargo.Bazel.lock index 06af896..c7dbb08 100644 --- a/crates/Cargo.Bazel.lock +++ b/crates/Cargo.Bazel.lock
@@ -1,5 +1,5 @@ { - "checksum": "c47fbc0efe861336e9b62c6afdb15fda13bccd0cfb7557f9395de7d407fb3318", + "checksum": "30f93d6303d71ee7044f0ee40523812209c2025ff5210bb2c7008ee2eee9782a", "crates": { "block-buffer 0.10.4": { "name": "block-buffer", @@ -303,6 +303,10 @@ "deps": { "common": [ { + "id": "lexopt 0.3.2", + "target": "lexopt" + }, + { "id": "sha2 0.10.9", "target": "sha2" } @@ -407,6 +411,44 @@ ], "license_file": "LICENSE" }, + "lexopt 0.3.2": { + "name": "lexopt", + "version": "0.3.2", + "package_url": "https://github.com/blyxxyz/lexopt", + "repository": { + "Http": { + "url": "https://static.crates.io/crates/lexopt/0.3.2/download", + "sha256": "803ec87c9cfb29b9d2633f20cba1f488db3fd53f2158b1024cbefb47ba05d413" + } + }, + "targets": [ + { + "Library": { + "crate_name": "lexopt", + "crate_root": "src/lib.rs", + "srcs": { + "allow_empty": true, + "include": [ + "**/*.rs" + ] + } + } + } + ], + "library_target_name": "lexopt", + "common_attrs": { + "compile_data_glob": [ + "**" + ], + "edition": "2018", + "version": "0.3.2" + }, + "license": "MIT", + "license_ids": [ + "MIT" + ], + "license_file": "LICENSE" + }, "libc 0.2.191": { "name": "libc", "version": "0.2.191", @@ -675,6 +717,7 @@ ] }, "direct_deps": [ + "lexopt 0.3.2", "sha2 0.10.9" ], "direct_dev_deps": [],
diff --git a/crates/Cargo.lock b/crates/Cargo.lock index fbd5c9c..05055d4 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock
@@ -50,6 +50,7 @@ name = "direct-cargo-bazel-deps" version = "0.0.1" dependencies = [ + "lexopt", "sha2", ] @@ -64,6 +65,12 @@ ] [[package]] +name = "lexopt" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "803ec87c9cfb29b9d2633f20cba1f488db3fd53f2158b1024cbefb47ba05d413" + +[[package]] name = "libc" version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/crates/exe_zip_maker/BUILD.bazel b/crates/exe_zip_maker/BUILD.bazel index bb7e741..bf307f4 100644 --- a/crates/exe_zip_maker/BUILD.bazel +++ b/crates/exe_zip_maker/BUILD.bazel
@@ -9,7 +9,10 @@ name = "exe_zip_maker_lib", srcs = ["src/lib.rs"], edition = "2021", - deps = ["@crates//:sha2"], + deps = [ + "@crates//:lexopt", + "@crates//:sha2", + ], ) distribution_filegroup(
diff --git a/crates/exe_zip_maker/src/lib.rs b/crates/exe_zip_maker/src/lib.rs index 9afa6d3..936cc96 100644 --- a/crates/exe_zip_maker/src/lib.rs +++ b/crates/exe_zip_maker/src/lib.rs
@@ -3,7 +3,7 @@ use std::ffi::OsString; use std::fs::{self, File}; use std::io::{self, BufReader, BufWriter, Read, Write}; -use std::path::Path; +use std::path::{Path, PathBuf}; use sha2::{Digest, Sha256}; @@ -79,6 +79,38 @@ Ok(()) } +/// Parses CLI arguments (excluding `argv[0]` and subcommand name) into [`Options`]. +pub fn parse_args<I, T>(args: I) -> Result<Options, String> +where + I: IntoIterator<Item = T>, + T: Into<OsString>, +{ + use lexopt::prelude::*; + + const USAGE: &str = "Usage: exe_zip_maker <preamble> <zip> <output>"; + let mut positional = Vec::with_capacity(3); + let mut parser = lexopt::Parser::from_args(args); + while let Some(arg) = parser.next().map_err(|e| format!("{e}\n{USAGE}"))? { + match arg { + Short('h') | Long("help") => return Err(USAGE.to_string()), + Value(val) => { + positional.push(PathBuf::from(val)); + } + _ => return Err(format!("{}\n{USAGE}", arg.unexpected())), + } + } + + if positional.len() != 3 { + return Err(USAGE.to_string()); + } + + Ok(Options { + preamble_path: positional.remove(0), + zip_path: positional.remove(0), + output_path: positional.remove(0), + }) +} + /// Parses subcommand arguments (`<preamble> <zip> <output>`) and creates a self-executable zip /// archive, returning the process exit code. pub fn run_cli<I, T>(args: I) -> i32 @@ -86,17 +118,33 @@ I: IntoIterator<Item = T>, T: Into<OsString>, { - let os_args: Vec<OsString> = args.into_iter().map(Into::into).collect(); - if os_args.len() != 3 { - eprintln!("Usage: exe_zip_maker <preamble> <zip> <output>"); - return 1; - } - let preamble_path = Path::new(&os_args[0]); - let zip_path = Path::new(&os_args[1]); - let output_path = Path::new(&os_args[2]); - if let Err(e) = create_exe_zip(preamble_path, zip_path, output_path) { - eprintln!("exe_zip_maker: error: {}", e); + let options = match parse_args(args) { + Ok(opts) => opts, + Err(msg) => { + eprintln!("exe_zip_maker: error: {msg}"); + return 1; + } + }; + if let Err(e) = create_exe_zip( + &options.preamble_path, + &options.zip_path, + &options.output_path, + ) { + eprintln!("exe_zip_maker: error: {e}"); return 1; } 0 } + +/// Parsed command-line options for `exe_zip_maker`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Options { + /// Path to the executable preamble file to prepend, relative to the current working directory + /// or absolute. + pub preamble_path: PathBuf, + /// Path to the input zip archive, relative to the current working directory or absolute. + pub zip_path: PathBuf, + /// Path to the output self-executable zip archive, relative to the current working directory + /// or absolute. + pub output_path: PathBuf, +}
diff --git a/tests/exe_zip_maker/exe_zip_maker_test.rs b/tests/exe_zip_maker/exe_zip_maker_test.rs index d521a11..76ce96d 100644 --- a/tests/exe_zip_maker/exe_zip_maker_test.rs +++ b/tests/exe_zip_maker/exe_zip_maker_test.rs
@@ -1,7 +1,11 @@ use std::env; use std::fs; +use std::path::PathBuf; -use exe_zip_maker_lib::{compute_file_sha256_hex, create_exe_zip, replace_bytes, PLACEHOLDER}; +use exe_zip_maker_lib::{ + compute_file_sha256_hex, create_exe_zip, parse_args, replace_bytes, run_cli, Options, + PLACEHOLDER, +}; #[test] fn test_replace_bytes_none() { @@ -151,3 +155,40 @@ let _ = fs::remove_dir_all(&temp_dir); } + +#[test] +fn test_parse_args_and_run_cli() { + assert_eq!( + parse_args(["a.sh", "b.zip", "c.pyz"]), + Ok(Options { + preamble_path: PathBuf::from("a.sh"), + zip_path: PathBuf::from("b.zip"), + output_path: PathBuf::from("c.pyz"), + }) + ); + assert!(parse_args(["only_one"]).is_err()); + assert!(parse_args(["a", "b", "c", "d"]).is_err()); + assert!(parse_args(["--help", "b", "c"]).is_err()); + assert!(parse_args(["--unknown", "b", "c"]).is_err()); + + let temp_dir = env::temp_dir().join(format!("exe_zip_cli_{}", std::process::id())); + fs::create_dir_all(&temp_dir).unwrap(); + let preamble_path = temp_dir.join("preamble.sh"); + let zip_path = temp_dir.join("data.zip"); + let output_path = temp_dir.join("output.exe"); + fs::write(&preamble_path, b"#!/bin/sh\n# %ZIP_HASH%\n").unwrap(); + fs::write(&zip_path, b"PK\x03\x04dummy").unwrap(); + + assert_eq!(run_cli(["missing_args"]), 1); + assert_eq!( + run_cli([ + preamble_path.as_os_str(), + zip_path.as_os_str(), + output_path.as_os_str(), + ]), + 0 + ); + assert!(output_path.exists()); + + let _ = fs::remove_dir_all(&temp_dir); +}