refactor(pypi): convert venv_shebang_rewriter build tool to Rust (#4515)

Rewriting virtualenv script shebangs uses separate shell and PowerShell
scripts across Unix and Windows hosts.

Add `//crates/venv_shebang_rewriter:venv_shebang_rewriter_lib`, register
`venv_shebang_rewriter` on `shrubbery`, and route `PyVenvRewriteBin`
through `get_shrubbery_tool` with the platform scripts as fallback.

Work towards #4250
diff --git a/crates/shrubbery/BUILD.bazel b/crates/shrubbery/BUILD.bazel
index 7819849..aa3fb6d 100644
--- a/crates/shrubbery/BUILD.bazel
+++ b/crates/shrubbery/BUILD.bazel
@@ -14,6 +14,7 @@
         "//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 1ef313a..d29a710 100644
--- a/crates/shrubbery/src/lib.rs
+++ b/crates/shrubbery/src/lib.rs
@@ -14,6 +14,7 @@
     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 @@
     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 @@
         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 0000000..ea0c02e
--- /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 0000000..342059a
--- /dev/null
+++ b/crates/venv_shebang_rewriter/src/lib.rs
@@ -0,0 +1,254 @@
+//! Rewrites a `console_script` wrapper's shebang into a batch/shell-Python polyglot.
+//!
+//! Reads `<in_path>`, replaces its first line with a platform-specific polyglot header for
+//! `<target_os>`, writes the result to `<out_path>`, 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 <IN_PATH> <OUT_PATH> <TARGET_OS>
+
+Rewrite a console_script wrapper's shebang into a batch/shell-Python polyglot.
+
+Arguments:
+  <IN_PATH>     Path to the input script
+  <OUT_PATH>    Path to write the rewritten script to
+  <TARGET_OS>   Target OS family: 'unix' or 'windows'
+
+Options:
+  -h, --help    Print this help";
+
+// Wheel `.data/scripts/*` and `console_scripts` wrappers start with a `#!python` (or `#!pythonw`)
+// placeholder shebang. Because Bazel venvs are relocatable across sandboxes and runfiles trees,
+// their absolute location is not known at build time, and OS `#!` shebangs cannot resolve an
+// interpreter relative to the script's own directory. Instead, we prepend a polyglot header that
+// invokes the sibling interpreter in the venv's `bin/` / `Scripts/` directory and is ignored when
+// Python subsequently parses the same file.
+
+/// Shell-Python polyglot header for Unix-like platforms:
+///
+/// ```text
+/// #!/bin/sh
+/// '''exec' "$(dirname "$0")/python3" "$0" "$@"
+/// ' '''
+/// ```
+///
+/// * **As `/bin/sh`**: `''` (an empty single-quoted string) concatenates onto `'exec'` to run
+///   `exec`, replacing the shell process with `python3` from the script's directory and forwarding
+///   the script path (`"$0"`) and arguments (`"$@"`). Because `exec` does not return, `/bin/sh`
+///   never reads line 3 or the Python body below.
+/// * **As Python**: Line 1 (`#!/bin/sh`) is a `#` comment, and lines 2–3 (`'''exec' ... \n' '''`)
+///   form a single triple-quoted string literal that Python evaluates and discards before running
+///   the rest of the file.
+pub const UNIX_HEADER: &[u8] = br#"#!/bin/sh
+'''exec' "$(dirname "$0")/python3" "$0" "$@"
+' '''
+"#;
+
+/// Batch-Python polyglot header for Windows (`python.exe`, CRLF-terminated for `.bat`/`.cmd`):
+///
+/// * **As `cmd.exe`**: `@` suppresses command echo; `setlocal enabledelayedexpansion` lets
+///   `!ERRORLEVEL!` expand *after* Python finishes (whereas `%ERRORLEVEL%` would expand when
+///   `cmd.exe` parses the `&`-joined line); `"%~dp0python.exe" -x "%~f0" %*` runs `python.exe` in
+///   the script's directory (`%~dp0`) on the script's full path (`%~f0`) with all arguments
+///   (`%*`); and `exit /b !ERRORLEVEL!` exits batch execution with Python's exit code before
+///   `cmd.exe` reaches the Python body on line 2.
+/// * **As Python**: `-x` instructs CPython to skip the first line of the source file, ignoring the
+///   batch command and executing the remaining Python code starting at line 2.
+pub const WINDOWS_PYTHON_HEADER: &[u8] = concat!(
+    r#"@setlocal enabledelayedexpansion & "%~dp0python.exe" -x "%~f0" %* & exit /b !ERRORLEVEL!"#,
+    "\r\n",
+)
+.as_bytes();
+
+/// Batch-Python polyglot header for Windows GUI scripts (`pythonw.exe`); works identically to
+/// [`WINDOWS_PYTHON_HEADER`] when the input script's shebang starts with `#!pythonw`.
+pub const WINDOWS_PYTHONW_HEADER: &[u8] = concat!(
+    r#"@setlocal enabledelayedexpansion & "%~dp0pythonw.exe" -x "%~f0" %* & exit /b !ERRORLEVEL!"#,
+    "\r\n",
+)
+.as_bytes();
+
+/// 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<u8> {
+    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(())
+}
+
+/// Parses command-line arguments (excluding `argv[0]` and subcommand name) into [`ParsedArgs`].
+///
+/// Expects exactly three positionals: `<in_path> <out_path> <target_os>`.
+///
+/// # Errors
+///
+/// Returns an error if an unknown flag is given, positional argument count is not 3, or
+/// `<target_os>` is not `"unix"` or `"windows"`.
+pub fn parse_args<I, T>(args: I) -> Result<ParsedArgs>
+where
+    I: IntoIterator<Item = T>,
+    T: Into<OsString>,
+{
+    let mut positional: Vec<OsString> = 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(ParsedArgs::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 <IN_PATH>")?);
+    let out_path = PathBuf::from(positional.next().context("missing <OUT_PATH>")?);
+    let target_os = positional.next().context("missing <TARGET_OS>")?;
+    let target_os = target_os
+        .to_str()
+        .with_context(|| format!("target_os is not valid UTF-8: {target_os:?}"))?
+        .parse::<TargetOs>()?;
+
+    Ok(ParsedArgs::Options(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<I, T>(args: I) -> ExitCode
+where
+    I: IntoIterator<Item = T>,
+    T: Into<OsString>,
+{
+    let options = match parse_args(args) {
+        Ok(ParsedArgs::Help) => {
+            println!("{USAGE}");
+            return ExitCode::SUCCESS;
+        }
+        Ok(ParsedArgs::Options(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
+}
+
+/// Result of parsing command-line arguments.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ParsedArgs {
+    /// `--help` was requested.
+    Help,
+    /// Parsed command-line options.
+    Options(Options),
+}
+
+/// Parsed command-line options for `venv_shebang_rewriter`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Options {
+    /// Path to the input script, relative to the current working directory or absolute.
+    pub in_path: PathBuf,
+    /// Path to write the rewritten script to, relative to the current working directory or
+    /// absolute.
+    pub out_path: PathBuf,
+    /// Target OS family selecting the polyglot header.
+    pub target_os: TargetOs,
+}
+
+/// 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<Self> {
+        match s {
+            "unix" => Ok(Self::Unix),
+            "windows" => Ok(Self::Windows),
+            other => bail!("unsupported target_os '{other}': expected 'unix' or 'windows'"),
+        }
+    }
+}
diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel
index e43ea3b..065c6b9 100644
--- a/python/private/pypi/BUILD.bazel
+++ b/python/private/pypi/BUILD.bazel
@@ -466,6 +466,8 @@
         "//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 c653211..fccc6f0 100644
--- a/python/private/pypi/venv_rewrite_shebang.bzl
+++ b/python/private/pypi/venv_rewrite_shebang.bzl
@@ -4,6 +4,8 @@
 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 @@
     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.from_shrubbery_toolchain:
+        inputs = depset([in_file])
+        action_exe = tool.executable[DefaultInfo].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.executable[DefaultInfo].files_to_run
 
     action_args.add(in_file)
     action_args.add(out_file)
@@ -42,7 +55,7 @@
         arguments = [action_args],
         mnemonic = "PyVenvRewriteBin",
         progress_message = "Rewriting venv bin script %{input}",
-        toolchain = None,
+        toolchain = action_toolchain,
     )
 
     symlink = VenvSymlinkEntry(
@@ -66,6 +79,9 @@
 _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 6078a5a..0aab936 100644
--- a/tests/shrubbery/shrubbery_test.rs
+++ b/tests/shrubbery/shrubbery_test.rs
@@ -17,7 +17,7 @@
 
 #[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 0000000..2641ff6
--- /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 0000000..4542df5
--- /dev/null
+++ b/tests/venv_shebang_rewriter/venv_shebang_rewriter_test.rs
@@ -0,0 +1,338 @@
+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::{
+    Options, ParsedArgs, 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_options<const N: usize>(args: [&str; N]) -> Options {
+    match parse_args(args).expect("arguments should parse successfully") {
+        ParsedArgs::Options(options) => options,
+        ParsedArgs::Help => panic!("expected ParsedArgs::Options, got ParsedArgs::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(
+            concat!(
+                r#"@setlocal enabledelayedexpansion & "%~dp0python.exe" -x "%~f0" %* & exit /b !ERRORLEVEL!"#,
+                "\r\n",
+            )
+            .as_bytes()
+        )
+    );
+
+    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(
+            concat!(
+                r#"@setlocal enabledelayedexpansion & "%~dp0pythonw.exe" -x "%~f0" %* & exit /b !ERRORLEVEL!"#,
+                "\r\n",
+            )
+            .as_bytes()
+        )
+    );
+
+    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_options(["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_options(["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"),
+        ParsedArgs::Help
+    );
+    assert_eq!(
+        parse_args(["-h"]).expect("-h should parse successfully"),
+        ParsedArgs::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);
+}