diff --git a/crates/shrubbery/BUILD.bazel b/crates/shrubbery/BUILD.bazel index 78198491e0..aa3fb6d36a 100644 --- a/crates/shrubbery/BUILD.bazel +++ b/crates/shrubbery/BUILD.bazel @@ -14,6 +14,7 @@ rust_library( "//crates/extract_wheel_files:extract_wheel_files_lib", "//crates/py_console_script_gen:py_console_script_gen_lib", "//crates/py_wheel_dist:py_wheel_dist_lib", + "//crates/venv_shebang_rewriter:venv_shebang_rewriter_lib", "//crates/wheelmaker:wheelmaker_lib", "//crates/zip_main_maker:zip_main_maker_lib", "//crates/zipper:zipper_lib", diff --git a/crates/shrubbery/src/lib.rs b/crates/shrubbery/src/lib.rs index 1ef313a025..d29a7108e8 100644 --- a/crates/shrubbery/src/lib.rs +++ b/crates/shrubbery/src/lib.rs @@ -14,6 +14,7 @@ pub mod subcommands { pub const EXTRACT_WHEEL_FILES: &str = "extract_wheel_files"; pub const PY_CONSOLE_SCRIPT_GEN: &str = "py_console_script_gen"; pub const PY_WHEEL_DIST: &str = "py_wheel_dist"; + pub const VENV_SHEBANG_REWRITER: &str = "venv_shebang_rewriter"; pub const WHEELMAKER: &str = "wheelmaker"; pub const ZIP_MAIN_MAKER: &str = "zip_main_maker"; pub const ZIPPER: &str = "zipper"; @@ -27,6 +28,7 @@ pub const SUBCOMMANDS: &[&str] = &[ subcommands::EXTRACT_WHEEL_FILES, subcommands::PY_CONSOLE_SCRIPT_GEN, subcommands::PY_WHEEL_DIST, + subcommands::VENV_SHEBANG_REWRITER, subcommands::WHEELMAKER, subcommands::ZIP_MAIN_MAKER, subcommands::ZIPPER, @@ -75,6 +77,7 @@ where subcommands::EXTRACT_WHEEL_FILES => extract_wheel_files_lib::run_cli(iter), subcommands::PY_CONSOLE_SCRIPT_GEN => py_console_script_gen_lib::run_cli(iter), subcommands::PY_WHEEL_DIST => py_wheel_dist_lib::run_cli(iter), + subcommands::VENV_SHEBANG_REWRITER => venv_shebang_rewriter_lib::run_cli(iter), subcommands::WHEELMAKER => wheelmaker_lib::run_cli(iter), subcommands::ZIP_MAIN_MAKER => zip_main_maker_lib::run_cli(iter), subcommands::ZIPPER => zipper_lib::run_cli(iter), diff --git a/crates/venv_shebang_rewriter/BUILD.bazel b/crates/venv_shebang_rewriter/BUILD.bazel new file mode 100644 index 0000000000..ea0c02e093 --- /dev/null +++ b/crates/venv_shebang_rewriter/BUILD.bazel @@ -0,0 +1,20 @@ +load("@rules_rust//rust:defs.bzl", "rust_library") +load("//python/private:distribution_filegroup.bzl", "distribution_filegroup") # buildifier: disable=bzl-visibility + +package(default_visibility = ["//:__subpackages__"]) + +licenses(["notice"]) + +rust_library( + name = "venv_shebang_rewriter_lib", + srcs = ["src/lib.rs"], + edition = "2024", + deps = [ + "@crates//:anyhow", + "@crates//:lexopt", + ], +) + +distribution_filegroup( + name = "distribution", +) diff --git a/crates/venv_shebang_rewriter/src/lib.rs b/crates/venv_shebang_rewriter/src/lib.rs new file mode 100644 index 0000000000..7daa0173f1 --- /dev/null +++ b/crates/venv_shebang_rewriter/src/lib.rs @@ -0,0 +1,209 @@ +//! Rewrites a `console_script` wrapper's shebang into a batch/shell-Python polyglot. +//! +//! Reads ``, replaces its first line with a platform-specific polyglot header for +//! ``, writes the result to ``, and marks the output executable on Unix. + +// Errors must be returned, not panicked; see the `rust-lint` config in .bazelrc. +#![deny(clippy::expect_used, clippy::unwrap_used)] + +use std::ffi::OsString; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::str::FromStr; + +use anyhow::{Context, Result, bail}; +use lexopt::prelude::*; + +mod flags { + // keep-sorted start + pub const HELP: &str = "help"; + pub const HELP_SHORT: char = 'h'; + // keep-sorted end +} + +/// Usage text for `--help`. `lexopt` does not generate help, so this is maintained by hand. +const USAGE: &str = "\ +Usage: venv_shebang_rewriter + +Rewrite a console_script wrapper's shebang into a batch/shell-Python polyglot. + +Arguments: + Path to the input script + Path to write the rewritten script to + Target OS family: 'unix' or 'windows' + +Options: + -h, --help Print this help"; + +/// Shell-Python polyglot header for Unix-like platforms. +pub const UNIX_HEADER: &[u8] = + b"#!/bin/sh\n'''exec' \"$(dirname \"$0\")/python3\" \"$0\" \"$@\"\n' '''\n"; + +/// Batch-Python polyglot header for Windows (`python.exe`). +pub const WINDOWS_PYTHON_HEADER: &[u8] = + b"@setlocal enabledelayedexpansion & \"%~dp0python.exe\" -x \"%~f0\" %* & exit /b !ERRORLEVEL!\r\n"; + +/// Batch-Python polyglot header for Windows GUI scripts (`pythonw.exe`). +pub const WINDOWS_PYTHONW_HEADER: &[u8] = + b"@setlocal enabledelayedexpansion & \"%~dp0pythonw.exe\" -x \"%~f0\" %* & exit /b !ERRORLEVEL!\r\n"; + +/// Splits `input` at the first `b'\n'` byte into `(first_line, rest)`. +/// +/// `first_line` includes the trailing `b'\n'` if one is present, or the entire slice +/// if `input` contains no newline. `rest` contains all bytes after the first `b'\n'`. +pub fn split_first_line(input: &[u8]) -> (&[u8], &[u8]) { + if let Some(pos) = input.iter().position(|&b| b == b'\n') { + (&input[..=pos], &input[pos + 1..]) + } else { + (input, b"") + } +} + +/// Rewrites the first line of `input` into a batch or shell-Python polyglot header, +/// preserving the remaining bytes verbatim. +pub fn rewrite_shebang_bytes(input: &[u8], target_os: TargetOs) -> Vec { + let (first_line, rest) = split_first_line(input); + let header = match target_os { + TargetOs::Windows if first_line.starts_with(b"#!pythonw") => WINDOWS_PYTHONW_HEADER, + TargetOs::Windows => WINDOWS_PYTHON_HEADER, + TargetOs::Unix => UNIX_HEADER, + }; + + let mut output = Vec::with_capacity(header.len() + rest.len()); + output.extend_from_slice(header); + output.extend_from_slice(rest); + output +} + +/// Reads `in_path`, rewrites the shebang for `target_os`, writes the result to `out_path`, +/// and sets executable permissions (`mode | 0o111`) on Unix. +/// +/// # Errors +/// +/// Returns an error if `in_path` cannot be read, or `out_path` cannot be written or +/// have its permissions updated. +pub fn rewrite_shebang(in_path: &Path, out_path: &Path, target_os: TargetOs) -> Result<()> { + let input = fs::read(in_path).with_context(|| format!("reading {}", in_path.display()))?; + let output = rewrite_shebang_bytes(&input, target_os); + + fs::write(out_path, &output).with_context(|| format!("writing {}", out_path.display()))?; + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut perms = fs::metadata(out_path) + .with_context(|| format!("reading metadata of {}", out_path.display()))? + .permissions(); + perms.set_mode(perms.mode() | 0o111); + fs::set_permissions(out_path, perms) + .with_context(|| format!("setting permissions on {}", out_path.display()))?; + } + + Ok(()) +} + +/// Target operating system family for generated shebang headers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TargetOs { + Unix, + Windows, +} + +impl FromStr for TargetOs { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + match s { + "unix" => Ok(Self::Unix), + "windows" => Ok(Self::Windows), + other => bail!("unsupported target_os '{other}': expected 'unix' or 'windows'"), + } + } +} + +/// Parsed command-line options for `venv_shebang_rewriter`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Options { + /// Path to the input script. + pub in_path: PathBuf, + /// Path to write the rewritten script to. + pub out_path: PathBuf, + /// Target OS family selecting the polyglot header. + pub target_os: TargetOs, +} + +/// Result of parsing the command line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Cli { + /// `--help` was requested. + Help, + /// Rewrite the shebang with the given options. + Run(Options), +} + +/// Parses command-line arguments (excluding `argv[0]` and subcommand name) into [`Cli`]. +/// +/// Expects exactly three positionals: ` `. +pub fn parse_args(args: I) -> Result +where + I: IntoIterator, + T: Into, +{ + let mut positional: Vec = Vec::new(); + + let mut parser = lexopt::Parser::from_args(args); + while let Some(arg) = parser.next()? { + match arg { + Short(flags::HELP_SHORT) | Long(flags::HELP) => return Ok(Cli::Help), + Value(val) => positional.push(val), + _ => bail!("{}", arg.unexpected()), + } + } + + if positional.len() != 3 { + bail!( + "expected 3 positional arguments, got {}\n{USAGE}", + positional.len() + ); + } + let mut positional = positional.into_iter(); + let in_path = PathBuf::from(positional.next().context("missing ")?); + let out_path = PathBuf::from(positional.next().context("missing ")?); + let target_os = positional.next().context("missing ")?; + let target_os = target_os + .to_str() + .with_context(|| format!("target_os is not valid UTF-8: {target_os:?}"))? + .parse::()?; + + Ok(Cli::Run(Options { + in_path, + out_path, + target_os, + })) +} + +/// Parses CLI arguments (excluding `argv[0]` and subcommand name), rewrites the shebang, and +/// returns the process exit code. +pub fn run_cli(args: I) -> ExitCode +where + I: IntoIterator, + T: Into, +{ + let options = match parse_args(args) { + Ok(Cli::Help) => { + println!("{USAGE}"); + return ExitCode::SUCCESS; + } + Ok(Cli::Run(opts)) => opts, + Err(err) => { + eprintln!("venv_shebang_rewriter: error: {err:#}"); + return ExitCode::FAILURE; + } + }; + if let Err(err) = rewrite_shebang(&options.in_path, &options.out_path, options.target_os) { + eprintln!("venv_shebang_rewriter: error: {err:#}"); + return ExitCode::FAILURE; + } + ExitCode::SUCCESS +} diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index 03a9e113d5..c55f35794a 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -456,6 +456,8 @@ bzl_library( "//python/private:common", "//python/private:py_info", "//python/private:rule_builders", + "//python/private:toolchain_types", + "//python/private/toolchains:shrubbery_toolchain", ], ) diff --git a/python/private/pypi/venv_rewrite_shebang.bzl b/python/private/pypi/venv_rewrite_shebang.bzl index c653211850..b8535d14a3 100644 --- a/python/private/pypi/venv_rewrite_shebang.bzl +++ b/python/private/pypi/venv_rewrite_shebang.bzl @@ -4,6 +4,8 @@ load("//python/private:attributes.bzl", "WINDOWS_CONSTRAINTS_ATTRS") load("//python/private:common.bzl", "is_windows_platform", "runfiles_root_path") load("//python/private:py_info.bzl", "PyInfoBuilder", "VenvSymlinkEntry", "VenvSymlinkKind") load("//python/private:rule_builders.bzl", "ruleb") +load("//python/private:toolchain_types.bzl", "SHRUBBERY_TOOLCHAIN_TYPE") +load("//python/private/toolchains:shrubbery_toolchain.bzl", "get_shrubbery_tool") def _venv_rewrite_shebang_impl(ctx): is_windows = is_windows_platform(ctx) @@ -16,20 +18,31 @@ def _venv_rewrite_shebang_impl(ctx): in_file = ctx.file.src action_args = ctx.actions.args() - rewriter_file = ctx.files._venv_shebang_rewriter[0] - inputs = depset([in_file, rewriter_file]) - - if rewriter_file.path.endswith(".ps1"): - action_exe = "powershell.exe" - action_args.add_all([ - "-ExecutionPolicy", - "Bypass", - "-NoProfile", - "-File", - rewriter_file, - ]) + tool = get_shrubbery_tool( + ctx, + "venv_shebang_rewriter", + ctx.attr._venv_shebang_rewriter, + ) + if tool.is_rust: + inputs = depset([in_file]) + action_exe = tool.files_to_run + action_toolchain = tool.toolchain + action_args.add_all(tool.prefix_args) else: - action_exe = ctx.attr._venv_shebang_rewriter[DefaultInfo].files_to_run + rewriter_file = ctx.files._venv_shebang_rewriter[0] + inputs = depset([in_file, rewriter_file]) + action_toolchain = None + if rewriter_file.path.endswith(".ps1"): + action_exe = "powershell.exe" + action_args.add_all([ + "-ExecutionPolicy", + "Bypass", + "-NoProfile", + "-File", + rewriter_file, + ]) + else: + action_exe = tool.files_to_run action_args.add(in_file) action_args.add(out_file) @@ -42,7 +55,7 @@ def _venv_rewrite_shebang_impl(ctx): arguments = [action_args], mnemonic = "PyVenvRewriteBin", progress_message = "Rewriting venv bin script %{input}", - toolchain = None, + toolchain = action_toolchain, ) symlink = VenvSymlinkEntry( @@ -66,6 +79,9 @@ def _venv_rewrite_shebang_impl(ctx): _builder = ruleb.Rule( implementation = _venv_rewrite_shebang_impl, executable = True, + toolchains = [ + ruleb.ToolchainType(SHRUBBERY_TOOLCHAIN_TYPE, mandatory = False), + ], ) _builder.attrs.update({ "package": attr.string(), diff --git a/tests/shrubbery/shrubbery_test.rs b/tests/shrubbery/shrubbery_test.rs index 6078a5a9ed..0aab936c3c 100644 --- a/tests/shrubbery/shrubbery_test.rs +++ b/tests/shrubbery/shrubbery_test.rs @@ -17,7 +17,7 @@ fn temp_test_dir(prefix: &str) -> PathBuf { #[test] fn test_subcommands_registry_sorted_and_complete() { - assert_eq!(SUBCOMMANDS.len(), 7); + assert_eq!(SUBCOMMANDS.len(), 8); let mut sorted = SUBCOMMANDS.to_vec(); sorted.sort_unstable(); assert_eq!(SUBCOMMANDS, sorted.as_slice()); diff --git a/tests/venv_shebang_rewriter/BUILD.bazel b/tests/venv_shebang_rewriter/BUILD.bazel new file mode 100644 index 0000000000..2641ff6fae --- /dev/null +++ b/tests/venv_shebang_rewriter/BUILD.bazel @@ -0,0 +1,21 @@ +load("@rules_rust//rust:defs.bzl", "rust_test") + +package(default_visibility = ["//:__subpackages__"]) + +licenses(["notice"]) + +rust_test( + name = "venv_shebang_rewriter_test", + size = "small", + srcs = ["venv_shebang_rewriter_test.rs"], + data = [ + "//crates/shrubbery", + ], + edition = "2024", + env = { + "SHRUBBERY_BIN": "$(rootpath //crates/shrubbery)", + }, + deps = [ + "//crates/venv_shebang_rewriter:venv_shebang_rewriter_lib", + ], +) diff --git a/tests/venv_shebang_rewriter/venv_shebang_rewriter_test.rs b/tests/venv_shebang_rewriter/venv_shebang_rewriter_test.rs new file mode 100644 index 0000000000..4a6df3d767 --- /dev/null +++ b/tests/venv_shebang_rewriter/venv_shebang_rewriter_test.rs @@ -0,0 +1,326 @@ +use std::env; +use std::fs; +use std::path::PathBuf; +use std::process::{Command, ExitCode}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use venv_shebang_rewriter_lib::{ + Cli, Options, TargetOs, UNIX_HEADER, WINDOWS_PYTHON_HEADER, WINDOWS_PYTHONW_HEADER, parse_args, + rewrite_shebang, rewrite_shebang_bytes, run_cli, split_first_line, +}; + +static COUNTER: AtomicUsize = AtomicUsize::new(0); + +fn parse_run(args: [&str; N]) -> Options { + match parse_args(args).expect("arguments should parse successfully") { + Cli::Run(options) => options, + Cli::Help => panic!("expected Cli::Run, got Cli::Help"), + } +} + +fn create_temp_dir(prefix: &str) -> PathBuf { + let id = COUNTER.fetch_add(1, Ordering::SeqCst); + let dir = env::temp_dir().join(format!( + "venv_shebang_rewriter_{}_{}_{}", + prefix, + std::process::id(), + id + )); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn test_split_first_line_standard() { + let (first, rest) = split_first_line(b"#!python\nimport sys\nprint(1)\n"); + assert_eq!(first, b"#!python\n"); + assert_eq!(rest, b"import sys\nprint(1)\n"); +} + +#[test] +fn test_split_first_line_no_newline() { + let (first, rest) = split_first_line(b"#!python"); + assert_eq!(first, b"#!python"); + assert_eq!(rest, b""); +} + +#[test] +fn test_split_first_line_empty() { + let (first, rest) = split_first_line(b""); + assert_eq!(first, b""); + assert_eq!(rest, b""); +} + +#[test] +fn test_unix_shebang_rewrite_and_permissions() { + let temp_dir = create_temp_dir("unix"); + let in_path = temp_dir.join("script_in"); + let out_path = temp_dir.join("script_out"); + + let body = b"# -*- coding: utf-8 -*-\nimport sys\nfrom pkg import main\nif __name__ == '__main__':\n sys.exit(main())\n"; + let mut input = b"#!python\n".to_vec(); + input.extend_from_slice(body); + fs::write(&in_path, &input).unwrap(); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&in_path, fs::Permissions::from_mode(0o644)).unwrap(); + } + + rewrite_shebang(&in_path, &out_path, TargetOs::Unix).unwrap(); + + let actual = fs::read(&out_path).unwrap(); + let mut expected = UNIX_HEADER.to_vec(); + expected.extend_from_slice(body); + assert_eq!(actual, expected); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&out_path).unwrap().permissions().mode(); + assert_eq!( + mode & 0o111, + 0o111, + "Expected all executable bits (0o111) to be set, got {mode:o}" + ); + } + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_windows_python_shebang_rewrite() { + let temp_dir = create_temp_dir("win_python"); + let in_path = temp_dir.join("script_in"); + let out_path = temp_dir.join("script_out.bat"); + + let body = b"import sys\r\nprint('hello from windows')\r\n"; + let mut input = b"#!python\r\n".to_vec(); + input.extend_from_slice(body); + fs::write(&in_path, &input).unwrap(); + + rewrite_shebang(&in_path, &out_path, TargetOs::Windows).unwrap(); + + let actual = fs::read(&out_path).unwrap(); + let mut expected = WINDOWS_PYTHON_HEADER.to_vec(); + expected.extend_from_slice(body); + assert_eq!(actual, expected); + assert!(actual.starts_with( + b"@setlocal enabledelayedexpansion & \"%~dp0python.exe\" -x \"%~f0\" %* & exit /b !ERRORLEVEL!\r\n" + )); + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_windows_pythonw_shebang_rewrite() { + let temp_dir = create_temp_dir("win_pythonw"); + let in_path = temp_dir.join("script_in"); + let out_path = temp_dir.join("script_out.bat"); + + let body = b"import sys\nprint('hello from pythonw')\n"; + let mut input = b"#!pythonw\n".to_vec(); + input.extend_from_slice(body); + fs::write(&in_path, &input).unwrap(); + + rewrite_shebang(&in_path, &out_path, TargetOs::Windows).unwrap(); + + let actual = fs::read(&out_path).unwrap(); + let mut expected = WINDOWS_PYTHONW_HEADER.to_vec(); + expected.extend_from_slice(body); + assert_eq!(actual, expected); + assert!(actual.starts_with( + b"@setlocal enabledelayedexpansion & \"%~dp0pythonw.exe\" -x \"%~f0\" %* & exit /b !ERRORLEVEL!\r\n" + )); + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_windows_pythonw_exe_or_flags_prefix() { + let input = b"#!pythonw.exe -u\nprint('gui')\n"; + let actual = rewrite_shebang_bytes(input, TargetOs::Windows); + let mut expected = WINDOWS_PYTHONW_HEADER.to_vec(); + expected.extend_from_slice(b"print('gui')\n"); + assert_eq!(actual, expected); +} + +#[test] +fn test_unix_ignores_pythonw_distinction() { + let input = b"#!pythonw\nprint('gui on unix')\n"; + let actual = rewrite_shebang_bytes(input, TargetOs::Unix); + let mut expected = UNIX_HEADER.to_vec(); + expected.extend_from_slice(b"print('gui on unix')\n"); + assert_eq!(actual, expected); +} + +#[test] +fn test_preserves_binary_and_non_utf8_bytes_verbatim() { + let temp_dir = create_temp_dir("binary_bytes"); + let in_path = temp_dir.join("binary_in"); + let out_path = temp_dir.join("binary_out"); + + // First line contains arbitrary bytes before '\n', body contains invalid UTF-8 and NUL bytes + // as well as mixed LF and CRLF sequences. + let first_line = b"#!python \xff\xfe\n"; + let binary_rest = b"\x00\x80\xfe\xff\r\nraw_bytes = b'\\x00'\n\x90\x91"; + let mut input = first_line.to_vec(); + input.extend_from_slice(binary_rest); + fs::write(&in_path, &input).unwrap(); + + rewrite_shebang(&in_path, &out_path, TargetOs::Unix).unwrap(); + + let actual = fs::read(&out_path).unwrap(); + let mut expected = UNIX_HEADER.to_vec(); + expected.extend_from_slice(binary_rest); + assert_eq!(actual, expected); + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_single_line_without_trailing_newline() { + let temp_dir = create_temp_dir("single_line"); + let in_path = temp_dir.join("single_in"); + let out_path_unix = temp_dir.join("single_out_unix"); + let out_path_win = temp_dir.join("single_out_win.bat"); + + fs::write(&in_path, b"#!pythonw").unwrap(); + + rewrite_shebang(&in_path, &out_path_unix, TargetOs::Unix).unwrap(); + assert_eq!(fs::read(&out_path_unix).unwrap(), UNIX_HEADER); + + rewrite_shebang(&in_path, &out_path_win, TargetOs::Windows).unwrap(); + assert_eq!(fs::read(&out_path_win).unwrap(), WINDOWS_PYTHONW_HEADER); + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_empty_file() { + let temp_dir = create_temp_dir("empty"); + let in_path = temp_dir.join("empty_in"); + let out_path_unix = temp_dir.join("empty_out_unix"); + let out_path_win = temp_dir.join("empty_out_win.bat"); + + fs::write(&in_path, b"").unwrap(); + + rewrite_shebang(&in_path, &out_path_unix, TargetOs::Unix).unwrap(); + assert_eq!(fs::read(&out_path_unix).unwrap(), UNIX_HEADER); + + rewrite_shebang(&in_path, &out_path_win, TargetOs::Windows).unwrap(); + assert_eq!(fs::read(&out_path_win).unwrap(), WINDOWS_PYTHON_HEADER); + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_parse_args_and_missing_args_error() { + assert!(parse_args::<_, &str>([]).is_err()); + assert!(parse_args(["in.py"]).is_err()); + assert!(parse_args(["in.py", "out.py"]).is_err()); + assert!(parse_args(["in.py", "out.py", "unix", "extra"]).is_err()); + assert!(parse_args(["in.py", "out.py", "macos"]).is_err()); + assert!(parse_args(["--unknown", "in.py", "out.py", "unix"]).is_err()); + assert_eq!(run_cli(["only_one_arg"]), ExitCode::FAILURE); + + assert_eq!( + parse_run(["in.py", "out.py", "windows"]), + Options { + in_path: PathBuf::from("in.py"), + out_path: PathBuf::from("out.py"), + target_os: TargetOs::Windows, + } + ); + assert_eq!( + parse_run(["in.py", "out.py", "unix"]).target_os, + TargetOs::Unix + ); +} + +#[test] +fn test_parse_args_help() { + assert_eq!( + parse_args(["--help"]).expect("--help should parse successfully"), + Cli::Help + ); + assert_eq!( + parse_args(["-h"]).expect("-h should parse successfully"), + Cli::Help + ); + assert_eq!(run_cli(["--help"]), ExitCode::SUCCESS); +} + +#[test] +fn test_nonexistent_input_file_returns_error() { + let temp_dir = create_temp_dir("missing_in"); + let missing_in = temp_dir.join("does_not_exist"); + let out_path = temp_dir.join("out"); + + assert!(rewrite_shebang(&missing_in, &out_path, TargetOs::Unix).is_err()); + assert_eq!( + run_cli([ + missing_in.to_str().unwrap(), + out_path.to_str().unwrap(), + "unix" + ]), + ExitCode::FAILURE + ); + + let _ = fs::remove_dir_all(&temp_dir); +} + +#[test] +fn test_cli_binary_execution_and_error_exit_code() { + let temp_dir = create_temp_dir("cli_bin"); + let in_path = temp_dir.join("cli_in.py"); + let out_path = temp_dir.join("cli_out"); + + fs::write(&in_path, b"#!/usr/bin/env python3\nprint('cli ok')\n").unwrap(); + assert_eq!( + run_cli([ + in_path.to_str().unwrap(), + out_path.to_str().unwrap(), + "unix" + ]), + ExitCode::SUCCESS + ); + + let mut expected = UNIX_HEADER.to_vec(); + expected.extend_from_slice(b"print('cli ok')\n"); + assert_eq!(fs::read(&out_path).unwrap(), expected); + + let Some(bin_rel) = env::var_os("SHRUBBERY_BIN") else { + let _ = fs::remove_dir_all(&temp_dir); + return; + }; + let bin_path = PathBuf::from(bin_rel); + if !bin_path.exists() { + let _ = fs::remove_dir_all(&temp_dir); + return; + } + + let bin_out_path = temp_dir.join("bin_cli_out"); + let status = Command::new(&bin_path) + .arg("venv_shebang_rewriter") + .arg(&in_path) + .arg(&bin_out_path) + .arg("unix") + .status() + .unwrap(); + assert!(status.success()); + assert_eq!(fs::read(&bin_out_path).unwrap(), expected); + + // Fewer than 3 args should exit with non-zero status. + let bad_output = Command::new(&bin_path) + .arg("venv_shebang_rewriter") + .arg(&in_path) + .output() + .unwrap(); + assert!(!bad_output.status.success()); + let stderr = String::from_utf8_lossy(&bad_output.stderr); + assert!(stderr.contains("Usage:")); + + let _ = fs::remove_dir_all(&temp_dir); +}