refactor(entry_points): convert py_console_script_gen build tool to Rust (#4512)

Generating console script entry points via Python requires executing a
full Python binary during `py_console_script_gen` actions.

Add `//crates/py_console_script_gen:py_console_script_gen_lib` with an
`entry_points.txt` reader, register `py_console_script_gen` on
`shrubbery`, and wire the rule to `get_shrubbery_tool`.

Work towards #4250
diff --git a/.agents/rules/rust.md b/.agents/rules/rust.md
index 05e0af9..96d5e5a 100644
--- a/.agents/rules/rust.md
+++ b/.agents/rules/rust.md
@@ -12,10 +12,10 @@
   scratch.
 * Never hand-roll CLI argument parsers (`lexopt` or `clap`), `@flagfile`
   response-file readers (`argfile`), CSV/INI/JSON/TOML format parsers (`csv`,
-  etc.), base64/hex codecs (`base64`), language or packaging-spec parsers
-  (`ruff_python_parser`, `pep440_rs`, `pep508_rs`), regex engines (`regex`),
-  archive/compression codecs (`zip`, `flate2`), or cryptographic hashes
-  (`sha2`).
+  `configparser`, etc.), base64/hex codecs (`base64`), language or
+  packaging-spec parsers (`ruff_python_parser`, `pep440_rs`, `pep508_rs`),
+  regex engines (`regex`), archive/compression codecs (`zip`, `flate2`), or
+  cryptographic hashes (`sha2`).
 
 ## Dependency Vetting & Versioning
 When adding or updating a Rust crate dependency:
@@ -46,11 +46,13 @@
 * **Edition & control flow**: Use `edition = "2024"`. Flatten nested
   conditionals with early `continue`/`return` guards and `let`-chains
   (`if let Some(ext) = path.extension() && ext == "whl"`).
-* **String & line processing**: Prefer `str` pattern methods (`split_once`,
-  `rsplit_once`, `strip_prefix`, `strip_suffix`) over manual index slicing.
-  Iterate lines directly with `str::lines()` (`.map(str::trim).filter(...)`)
-  instead of pre-allocating `.replace("\r\n", "\n")` (`str::lines()` strips both
-  `\n` and `\r\n`).
+* **String & line processing**: Prefer raw string literals (`r#"..."#`) when a
+  string contains embedded quotes or backslashes instead of backslash-escaping
+  them. Prefer `str` pattern methods (`split_once`, `rsplit_once`,
+  `strip_prefix`, `strip_suffix`) over manual index slicing. Iterate lines
+  directly with `str::lines()` (`.map(str::trim).filter(...)`) instead of
+  pre-allocating `.replace("\r\n", "\n")` (`str::lines()` strips both `\n` and
+  `\r\n`).
 * **Filesystem parent directories**: Pass `parent` directly to
   `fs::create_dir_all(parent)` without `!parent.as_os_str().is_empty()` (`""` is
   already a no-op).
diff --git a/crates/Cargo.Bazel.lock b/crates/Cargo.Bazel.lock
index f713074..b9f23f7 100644
--- a/crates/Cargo.Bazel.lock
+++ b/crates/Cargo.Bazel.lock
@@ -1,5 +1,5 @@
 {
-  "checksum": "2d0ce215f26718cc18a9b0d2ec186981b34870f61dd4e7fbe3e24330778493bc",
+  "checksum": "261e46aa4944be2809c1b6c1cbcb64ddc3822f55e7e4cdc8dba510b778fa7c23",
   "crates": {
     "aho-corasick 1.1.5": {
       "name": "aho-corasick",
@@ -478,6 +478,45 @@
       ],
       "license_file": "LICENSE"
     },
+    "configparser 3.3.0": {
+      "name": "configparser",
+      "version": "3.3.0",
+      "package_url": "https://github.com/QEDK/configparser-rs",
+      "repository": {
+        "Http": {
+          "url": "https://static.crates.io/crates/configparser/3.3.0/download",
+          "sha256": "031ad3d167622974ed636505ae4556267ed4aa2aea0464122fa6bc9698a32825"
+        }
+      },
+      "targets": [
+        {
+          "Library": {
+            "crate_name": "configparser",
+            "crate_root": "src/lib.rs",
+            "srcs": {
+              "allow_empty": true,
+              "include": [
+                "**/*.rs"
+              ]
+            }
+          }
+        }
+      ],
+      "library_target_name": "configparser",
+      "common_attrs": {
+        "compile_data_glob": [
+          "**"
+        ],
+        "edition": "2024",
+        "version": "3.3.0"
+      },
+      "license": "MIT OR LGPL-3.0-or-later",
+      "license_ids": [
+        "LGPL-3.0",
+        "MIT"
+      ],
+      "license_file": "LICENSE-LGPL"
+    },
     "const-oid 0.10.2": {
       "name": "const-oid",
       "version": "0.10.2",
@@ -3213,6 +3252,10 @@
               "target": "base64"
             },
             {
+              "id": "configparser 3.3.0",
+              "target": "configparser"
+            },
+            {
               "id": "csv 1.4.0",
               "target": "csv"
             },
@@ -5248,6 +5291,7 @@
     "anyhow 1.0.104",
     "argfile 1.0.0",
     "base64 0.23.1",
+    "configparser 3.3.0",
     "csv 1.4.0",
     "flate2 1.1.11",
     "lexopt 0.3.2",
diff --git a/crates/Cargo.lock b/crates/Cargo.lock
index 1b43554..6ff1d9d 100644
--- a/crates/Cargo.lock
+++ b/crates/Cargo.lock
@@ -73,6 +73,12 @@
 checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
 
 [[package]]
+name = "configparser"
+version = "3.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031ad3d167622974ed636505ae4556267ed4aa2aea0464122fa6bc9698a32825"
+
+[[package]]
 name = "const-oid"
 version = "0.10.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -487,6 +493,7 @@
  "anyhow",
  "argfile",
  "base64",
+ "configparser",
  "csv",
  "flate2",
  "lexopt",
diff --git a/crates/Cargo.toml b/crates/Cargo.toml
index d11365a..7421b9e 100644
--- a/crates/Cargo.toml
+++ b/crates/Cargo.toml
@@ -17,6 +17,7 @@
 anyhow = "1.0.104"
 argfile = "1.0.0"
 base64 = "0.23.1"
+configparser = "3.3.0"
 csv = "1.4.0"
 # Transitive dep of zip: disable default features (`rust_backend` pulls in
 # unused `miniz_oxide`) and enable `runtime_detection` so `zlib-rs` enables
diff --git a/crates/py_console_script_gen/BUILD.bazel b/crates/py_console_script_gen/BUILD.bazel
new file mode 100644
index 0000000..8c4f7eb
--- /dev/null
+++ b/crates/py_console_script_gen/BUILD.bazel
@@ -0,0 +1,22 @@
+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 = "py_console_script_gen_lib",
+    srcs = ["src/lib.rs"],
+    edition = "2024",
+    deps = [
+        "@crates//:anyhow",
+        "@crates//:argfile",
+        "@crates//:configparser",
+        "@crates//:lexopt",
+    ],
+)
+
+distribution_filegroup(
+    name = "distribution",
+)
diff --git a/crates/py_console_script_gen/src/lib.rs b/crates/py_console_script_gen/src/lib.rs
new file mode 100644
index 0000000..97f0e83
--- /dev/null
+++ b/crates/py_console_script_gen/src/lib.rs
@@ -0,0 +1,305 @@
+//! Library for generating console_script entrypoint Python files from `entry_points.txt`.
+//!
+//! Parses the `[console_scripts]` section of a wheel's `entry_points.txt`, selects the
+//! requested (or guessed) entry point, and expands a Python entrypoint template to `OUT`.
+//!
+//! The default template (`//python/private:console_script_template.txt`) trims `sys.path[0]`
+//! when it points outside the runfiles tree. For Python versions earlier than 3.11 and Bazel
+//! versions earlier than 7.0, `sys.path[0]` escapes the runfiles tree (see
+//! <https://github.com/bazel-contrib/rules_python/issues/382> and
+//! <https://github.com/bazelbuild/bazel/pull/15701>), so a `py_binary` named like the program
+//! it wraps (`flake8`, `pylint`, `pytest`, ...) ends up importing its own internals from the
+//! Bazel entrypoint script. Dropping the first `sys.path` entry when it lacks `.runfiles` fixes
+//! console_scripts under `bazel run`; binaries defined at the root of an external repository
+//! (e.g. `@pypi_pylint//`) are unaffected because that path is already inside runfiles.
+
+// Errors must be returned, not panicked; see the `rust-lint` config in .bazelrc.
+#![deny(clippy::expect_used, clippy::unwrap_used)]
+
+use std::collections::HashMap;
+use std::ffi::OsString;
+use std::fs;
+use std::path::PathBuf;
+use std::process::ExitCode;
+
+use anyhow::{Context, Result, anyhow, bail};
+use configparser::ini::Ini;
+use lexopt::prelude::*;
+
+mod flags {
+    // keep-sorted start
+    pub const CONSOLE_SCRIPT: &str = "console-script";
+    pub const CONSOLE_SCRIPT_GUESS: &str = "console-script-guess";
+    pub const HELP: &str = "help";
+    pub const HELP_SHORT: char = 'h';
+    pub const SHEBANG: &str = "shebang";
+    pub const TEMPLATE: &str = "template";
+    // keep-sorted end
+}
+
+mod placeholders {
+    // keep-sorted start
+    pub const ATTR: &str = "%attr%";
+    pub const ENTRY_POINT: &str = "%entry_point%";
+    pub const MODULE: &str = "%module%";
+    pub const SHEBANG: &str = "%shebang%";
+    // keep-sorted end
+}
+
+/// Usage text for `--help`. `lexopt` does not generate help, so this is maintained by hand.
+const USAGE: &str = "\
+Usage: py_console_script_gen [OPTIONS] --template <PATH> --console-script-guess <NAME> <ENTRY_POINTS_TXT> <OUT>
+
+Generate a console_script entrypoint Python file from a wheel's entry_points.txt.
+
+Arguments:
+  <ENTRY_POINTS_TXT>             The entry_points.txt within the dist-info of a PyPI wheel
+  <OUT>                          The output file
+
+Options:
+  --template <PATH>              Path to the Python entrypoint template file
+  --console-script <NAME>        The console_script to generate the entry_point template for
+  --console-script-guess <NAME>  The string used for guessing the console_script if it is not provided
+  --shebang <SHEBANG>            The shebang to use for the entry point python file
+  @<FLAGFILE>                    Read newline-delimited arguments from <FLAGFILE>
+  -h, --help                     Print this help";
+
+/// Parses the `[console_scripts]` section from an `entry_points.txt` INI string.
+///
+/// Matches Python's `configparser.ConfigParser` with `optionxform = str` (case-sensitive keys,
+/// `=` and `:` delimiters, `#` and `;` full-line comments, no inline comment stripping, and
+/// indented continuation lines). Returns `Ok(None)` if `[console_scripts]` is absent or has no
+/// non-empty entries.
+///
+/// # Errors
+///
+/// Returns `Err` if `content` contains malformed INI syntax (such as an unclosed `[section`
+/// header or an empty option key).
+pub fn parse_console_scripts(content: &str) -> Result<Option<HashMap<String, String>>> {
+    let mut defaults = Ini::new_cs().defaults();
+    defaults.enable_inline_comments = false;
+    defaults.multiline = true;
+    let mut ini = Ini::new_from_defaults(defaults);
+    let mut sections = ini
+        .read(content.to_owned())
+        .map_err(|err| anyhow!("parsing entry_points.txt: {err}"))?;
+    let Some(section) = sections.remove("console_scripts") else {
+        return Ok(None);
+    };
+    let console_scripts: HashMap<String, String> = section
+        .into_iter()
+        .filter_map(|(key, val)| val.filter(|v| !v.is_empty()).map(|v| (key, v)))
+        .collect();
+    Ok((!console_scripts.is_empty()).then_some(console_scripts))
+}
+
+/// Substitutes `%shebang%`, `%module%`, `%attr%`, and `%entry_point%` placeholders in `template`.
+pub fn render_template(
+    template: &str,
+    shebang: &str,
+    module: &str,
+    attr: &str,
+    entry_point: &str,
+) -> String {
+    let shebang_prefix = if shebang.is_empty() {
+        String::new()
+    } else {
+        format!("{shebang}\n")
+    };
+
+    template
+        .replace(placeholders::SHEBANG, &shebang_prefix)
+        .replace(placeholders::MODULE, module)
+        .replace(placeholders::ATTR, attr)
+        .replace(placeholders::ENTRY_POINT, entry_point)
+}
+
+/// Generates the console script Python file described by `options`.
+///
+/// # Errors
+///
+/// Returns `Err` if `entry_points` or `template` cannot be read, `entry_points` contains invalid
+/// INI syntax or provides no `[console_scripts]`, the requested (or guessed) console script is
+/// missing, or `out` cannot be written.
+pub fn run(options: &Options) -> Result<()> {
+    let content = fs::read_to_string(&options.entry_points)
+        .with_context(|| format!("reading {}", options.entry_points.display()))?;
+
+    let console_scripts = parse_console_scripts(&content)?
+        .context("The package does not provide any console_scripts in its entry_points.txt")?;
+
+    let available = || {
+        let mut names: Vec<_> = console_scripts.keys().cloned().collect();
+        names.sort_unstable();
+        names.join(", ")
+    };
+
+    let entry_point = match &options.console_script {
+        Some(name) => console_scripts.get(name).with_context(|| {
+            format!(
+                "The console_script '{name}' was not found, only the following are available: {}",
+                available()
+            )
+        })?,
+        None => {
+            let guess = &options.console_script_guess;
+            console_scripts.get(guess).with_context(|| {
+                format!(
+                    "Tried to guess that you wanted '{guess}', but could not find it. Please select one of the following console scripts: {}",
+                    available()
+                )
+            })?
+        }
+    };
+
+    let (module, entry_point_callable) = entry_point.rsplit_once(':').unwrap_or(("", entry_point));
+    let attr = entry_point_callable
+        .split_once('.')
+        .map_or(entry_point_callable, |(first, _)| first);
+    // TODO: handle 'extras' in entry_point generation
+    // See https://github.com/bazel-contrib/rules_python/issues/1383
+    // See https://packaging.python.org/en/latest/specifications/entry-points/
+
+    let template = fs::read_to_string(&options.template)
+        .with_context(|| format!("reading template {}", options.template.display()))?;
+    let rendered = render_template(
+        &template,
+        &options.shebang,
+        module,
+        attr,
+        entry_point_callable,
+    );
+    fs::write(&options.out, rendered)
+        .with_context(|| format!("writing {}", options.out.display()))?;
+
+    Ok(())
+}
+
+/// Parses command-line arguments (excluding `argv[0]` and subcommand name) into [`ParsedArgs`].
+///
+/// # Errors
+///
+/// Returns `Err` if an `@flagfile` cannot be read, an unknown flag is given, a flag is missing its
+/// value, `--template` or `--console-script-guess` is absent, or there are not exactly two
+/// positional arguments.
+pub fn parse_args<I, T>(args: I) -> Result<ParsedArgs>
+where
+    I: IntoIterator<Item = T>,
+    T: Into<OsString>,
+{
+    let expanded = argfile::expand_args_from(
+        args.into_iter().map(Into::into),
+        argfile::parse_fromfile,
+        argfile::PREFIX,
+    )
+    .context("reading @flagfile")?;
+
+    let mut positional: Vec<PathBuf> = Vec::with_capacity(2);
+    let mut template: Option<PathBuf> = None;
+    let mut console_script: Option<String> = None;
+    let mut console_script_guess: Option<String> = None;
+    let mut shebang = String::new();
+
+    let mut parser = lexopt::Parser::from_args(expanded);
+    while let Some(arg) = parser.next()? {
+        match arg {
+            Short(flags::HELP_SHORT) | Long(flags::HELP) => return Ok(ParsedArgs::Help),
+            Long(flags::TEMPLATE) => {
+                template = Some(PathBuf::from(parser.value()?));
+            }
+            Long(flags::CONSOLE_SCRIPT) => {
+                let val = parser.value()?.string()?;
+                console_script = (!val.is_empty()).then_some(val);
+            }
+            Long(flags::CONSOLE_SCRIPT_GUESS) => {
+                console_script_guess = Some(parser.value()?.string()?);
+            }
+            Long(flags::SHEBANG) => {
+                shebang = parser.value()?.string()?;
+            }
+            Value(val) => positional.push(PathBuf::from(val)),
+            _ => bail!("{}", arg.unexpected()),
+        }
+    }
+
+    let template =
+        template.with_context(|| format!("missing required argument: --{}", flags::TEMPLATE))?;
+    let console_script_guess = console_script_guess.with_context(|| {
+        format!(
+            "missing required argument: --{}",
+            flags::CONSOLE_SCRIPT_GUESS
+        )
+    })?;
+
+    if positional.len() != 2 {
+        bail!(
+            "expected 2 positional arguments (ENTRY_POINTS_TXT OUT), got {}",
+            positional.len()
+        );
+    }
+    let out = positional.remove(1);
+    let entry_points = positional.remove(0);
+
+    Ok(ParsedArgs::Options(Options {
+        template,
+        entry_points,
+        out,
+        console_script,
+        console_script_guess,
+        shebang,
+    }))
+}
+
+/// Parses CLI arguments (excluding `argv[0]` and subcommand name), generates the console script,
+/// 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!("py_console_script_gen: error: {err:#}");
+            return ExitCode::FAILURE;
+        }
+    };
+    if let Err(err) = run(&options) {
+        eprintln!("py_console_script_gen: 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 `py_console_script_gen`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Options {
+    /// Path to the Python entrypoint template file, relative to the current working directory or
+    /// absolute.
+    pub template: PathBuf,
+    /// Path to the `entry_points.txt` file to parse, relative to the current working directory or
+    /// absolute.
+    pub entry_points: PathBuf,
+    /// Path of the Python entrypoint script to write, relative to the current working directory
+    /// or absolute.
+    pub out: PathBuf,
+    /// Explicitly requested console script name; `None` when absent or empty.
+    pub console_script: Option<String>,
+    /// Name to look up when `console_script` is `None`.
+    pub console_script_guess: String,
+    /// Shebang line to prepend to the script; empty for none.
+    pub shebang: String,
+}
diff --git a/crates/shrubbery/BUILD.bazel b/crates/shrubbery/BUILD.bazel
index 1c37ddd..682ec24 100644
--- a/crates/shrubbery/BUILD.bazel
+++ b/crates/shrubbery/BUILD.bazel
@@ -11,6 +11,7 @@
     edition = "2024",
     deps = [
         "//crates/exe_zip_maker:exe_zip_maker_lib",
+        "//crates/py_console_script_gen:py_console_script_gen_lib",
         "//crates/py_wheel_dist:py_wheel_dist_lib",
         "//crates/wheelmaker:wheelmaker_lib",
         "//crates/zip_main_maker:zip_main_maker_lib",
diff --git a/crates/shrubbery/src/lib.rs b/crates/shrubbery/src/lib.rs
index 1ed3656..5116fe9 100644
--- a/crates/shrubbery/src/lib.rs
+++ b/crates/shrubbery/src/lib.rs
@@ -11,6 +11,7 @@
 pub mod subcommands {
     // keep-sorted start case=no
     pub const EXE_ZIP_MAKER: &str = "exe_zip_maker";
+    pub const PY_CONSOLE_SCRIPT_GEN: &str = "py_console_script_gen";
     pub const PY_WHEEL_DIST: &str = "py_wheel_dist";
     pub const WHEELMAKER: &str = "wheelmaker";
     pub const ZIP_MAIN_MAKER: &str = "zip_main_maker";
@@ -22,6 +23,7 @@
 pub const SUBCOMMANDS: &[&str] = &[
     // keep-sorted start case=no
     subcommands::EXE_ZIP_MAKER,
+    subcommands::PY_CONSOLE_SCRIPT_GEN,
     subcommands::PY_WHEEL_DIST,
     subcommands::WHEELMAKER,
     subcommands::ZIP_MAIN_MAKER,
@@ -68,6 +70,7 @@
     match sub_raw.as_ref() {
         // keep-sorted start case=no
         subcommands::EXE_ZIP_MAKER => exe_zip_maker_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::WHEELMAKER => wheelmaker_lib::run_cli(iter),
         subcommands::ZIP_MAIN_MAKER => zip_main_maker_lib::run_cli(iter),
diff --git a/python/private/BUILD.bazel b/python/private/BUILD.bazel
index 45ae983..78e4c48 100644
--- a/python/private/BUILD.bazel
+++ b/python/private/BUILD.bazel
@@ -120,6 +120,14 @@
     visibility = NOT_ACTUALLY_PUBLIC,
 )
 
+filegroup(
+    name = "console_script_template",
+    srcs = ["console_script_template.txt"],
+    # Not actually public. Only public because it's an implicit dependency of
+    # py_console_script_gen.
+    visibility = NOT_ACTUALLY_PUBLIC,
+)
+
 # NOTE: Windows builds don't use this bootstrap. Instead, a native Windows
 # program locates some Python exe and runs `python.exe foo.zip` which
 # runs the __main__.py in the zip file.
@@ -950,6 +958,15 @@
 )
 
 bzl_library(
+    name = "py_console_script_gen",
+    srcs = ["py_console_script_gen.bzl"],
+    deps = [
+        ":toolchain_types",
+        "//python/private/toolchains:shrubbery_toolchain",
+    ],
+)
+
+bzl_library(
     name = "artifacts_manifest",
     srcs = ["artifacts_manifest.bzl"],
 )
@@ -1005,11 +1022,6 @@
 )
 
 bzl_library(
-    name = "py_console_script_gen",
-    srcs = ["py_console_script_gen.bzl"],
-)
-
-bzl_library(
     name = "py_exec_tools_info",
     srcs = ["py_exec_tools_info.bzl"],
 )
diff --git a/python/private/console_script_template.txt b/python/private/console_script_template.txt
new file mode 100644
index 0000000..42e6767
--- /dev/null
+++ b/python/private/console_script_template.txt
@@ -0,0 +1,19 @@
+%shebang%import sys
+
+# See @rules_python//crates/py_console_script_gen for explanation
+if getattr(sys.flags, "safe_path", False):
+    # We are running on Python 3.11 and we don't need this workaround
+    pass
+elif ".runfiles" not in sys.path[0]:
+    sys.path = sys.path[1:]
+
+try:
+    from %module% import %attr%
+except ImportError:
+    entries = "\n".join(sys.path)
+    print("Printing sys.path entries for easier debugging:", file=sys.stderr)
+    print(f"sys.path is:\n{entries}", file=sys.stderr)
+    raise
+
+if __name__ == "__main__":
+    sys.exit(%entry_point%())  # pyrefly: ignore[not-callable]
diff --git a/python/private/py_console_script_gen.bzl b/python/private/py_console_script_gen.bzl
index 091193d..8b343c2 100644
--- a/python/private/py_console_script_gen.bzl
+++ b/python/private/py_console_script_gen.bzl
@@ -23,6 +23,9 @@
 https://github.com/bazelbuild/bazel/issues/14744
 """
 
+load("//python/private/toolchains:shrubbery_toolchain.bzl", "get_shrubbery_tool")
+load(":toolchain_types.bzl", "SHRUBBERY_TOOLCHAIN_TYPE")
+
 _ENTRY_POINTS_TXT = "entry_points.txt"
 
 def _get_entry_points_txt(entry_points_txt):
@@ -39,7 +42,14 @@
 def _py_console_script_gen_impl(ctx):
     entry_points_txt = _get_entry_points_txt(ctx.attr.entry_points_txt)
 
+    tool = get_shrubbery_tool(
+        ctx,
+        "py_console_script_gen",
+        ctx.attr._tool,
+    )
     args = ctx.actions.args()
+    args.add_all(tool.prefix_args)
+    args.add("--template", ctx.file._template)
     args.add("--console-script", ctx.attr.console_script)
     args.add("--console-script-guess", ctx.attr.console_script_guess)
     args.add("--shebang", ctx.attr.shebang)
@@ -48,13 +58,15 @@
 
     ctx.actions.run(
         inputs = [
+            ctx.file._template,
             entry_points_txt,
         ],
         outputs = [ctx.outputs.out],
         arguments = [args],
         mnemonic = "PyConsoleScriptBinaryGen",
         progress_message = "Generating py_console_script_binary main: %{label}",
-        executable = ctx.executable._tool,
+        executable = tool.executable[DefaultInfo].files_to_run,
+        toolchain = tool.toolchain,
     )
 
     return [DefaultInfo(
@@ -87,13 +99,21 @@
             doc = "The shebang to use for the entry point python file.",
             default = "",
         ),
+        "_template": attr.label(
+            default = ":console_script_template",
+            allow_single_file = True,
+            doc = "The template file used to generate the entry point python file.",
+        ),
         "_tool": attr.label(
             default = ":py_console_script_gen_py",
             executable = True,
             cfg = "exec",
         ),
     },
-    doc = """\
+    toolchains = [
+        config_common.toolchain_type(SHRUBBERY_TOOLCHAIN_TYPE, mandatory = False),
+    ],
+    doc = """
 Builds an entry_point script from an entry_points.txt file.
 """,
 )
diff --git a/python/private/py_console_script_gen.py b/python/private/py_console_script_gen.py
index 887441c..e5b4fd0 100644
--- a/python/private/py_console_script_gen.py
+++ b/python/private/py_console_script_gen.py
@@ -86,6 +86,7 @@
     console_script: str | None,
     console_script_guess: str,
     shebang: str,
+    template: pathlib.Path | None = None,
 ):
     """Run the generator
 
@@ -95,6 +96,8 @@
         console_script: The console_script entry in the entry_points.txt file.
         console_script_guess: The string used for guessing the console_script if it is not provided.
         shebang: The shebang to use for the entry point python file. Defaults to empty string (no shebang).
+        template: Optional path to the template file using `%shebang%`, `%module%`, `%attr%`, and
+            `%entry_point%` placeholders.
     """
     config = EntryPointsParser()
     config.read(entry_points)
@@ -134,20 +137,35 @@
     # See https://github.com/bazel-contrib/rules_python/issues/1383
     # See https://packaging.python.org/en/latest/specifications/entry-points/
 
-    with open(out, "w") as f:
-        f.write(
-            _TEMPLATE.format(
-                shebang=f"{shebang}\n" if shebang else "",
-                module=module,
-                attr=attr,
-                entry_point=entry_point,
-            ),
+    shebang_prefix = f"{shebang}\n" if shebang else ""
+    if template is not None:
+        rendered = (
+            template.read_text(encoding="utf-8")
+            .replace("%shebang%", shebang_prefix)
+            .replace("%module%", module)
+            .replace("%attr%", attr)
+            .replace("%entry_point%", entry_point)
         )
+    else:
+        rendered = _TEMPLATE.format(
+            shebang=shebang_prefix,
+            module=module,
+            attr=attr,
+            entry_point=entry_point,
+        )
+    with open(out, "w", encoding="utf-8") as f:
+        f.write(rendered)
 
 
 def main():
     parser = argparse.ArgumentParser(description="console_script generator")
     parser.add_argument(
+        "--template",
+        type=pathlib.Path,
+        default=None,
+        help="Path to the Python entrypoint template file.",
+    )
+    parser.add_argument(
         "--console-script",
         help="The console_script to generate the entry_point template for.",
     )
@@ -180,6 +198,7 @@
         console_script=args.console_script,
         console_script_guess=args.console_script_guess,
         shebang=args.shebang,
+        template=args.template,
     )
 
 
diff --git a/tests/integration/bzlmod_lockfile_runner_test.py b/tests/integration/bzlmod_lockfile_runner_test.py
index 5375d11..45d8f7e 100644
--- a/tests/integration/bzlmod_lockfile_runner_test.py
+++ b/tests/integration/bzlmod_lockfile_runner_test.py
@@ -96,7 +96,7 @@
         args: Sequence[str], **_kwargs: object
     ) -> subprocess.CompletedProcess[str]:
         cmd_list = list(args)
-        subcommand = cmd_list[1]
+        subcommand = next(a for a in cmd_list[1:] if not a.startswith("-"))
         if subcommand == "test":
             if force_test_failure_stderr is not None:
                 return subprocess.CompletedProcess(
@@ -199,7 +199,8 @@
         args: Sequence[str], **_kwargs: object
     ) -> subprocess.CompletedProcess[str]:
         cmd_list = list(args)
-        if cmd_list[1] == "test":
+        subcommand = next(a for a in cmd_list[1:] if not a.startswith("-"))
+        if subcommand == "test":
             return subprocess.CompletedProcess(cmd_list, 1, stdout="", stderr="")
         lockfile_path.write_bytes(_UPDATED_LOCKFILE)
         raise OSError("simulated bazel crash after partial lockfile write")
@@ -211,3 +212,24 @@
             _run_case()
 
     _assert_lockfile_preserved(lockfile_path, _STALE_LOCKFILE)
+
+
+def test_windows_short_base_dir_shortens_execroot_path() -> None:
+    outer_output_base = pathlib.Path("/b/bg4v2njf")
+    long_test_tmpdir = (
+        outer_output_base
+        / "execroot"
+        / "_main"
+        / "_tmp"
+        / "2b67879734a8223e62fed43efa249f19"
+    )
+    short_base = bzlmod_lockfile_test.runner._windows_short_base_dir(long_test_tmpdir)
+    assert short_base is not None
+    assert short_base.parent == outer_output_base
+    assert len(short_base.name) == 8
+    assert (
+        bzlmod_lockfile_test.runner._windows_short_base_dir(
+            pathlib.Path("/b/bg4v2njf/no_execroot")
+        )
+        is None
+    )
diff --git a/tests/integration/runner.py b/tests/integration/runner.py
index fc85edf..131058d 100644
--- a/tests/integration/runner.py
+++ b/tests/integration/runner.py
@@ -12,6 +12,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import hashlib
 import logging
 import os
 import os.path
@@ -24,6 +25,23 @@
 _logger = logging.getLogger(__name__)
 
 
+def _windows_short_base_dir(outer_test_tmpdir: pathlib.Path) -> pathlib.Path | None:
+    """Returns a short base directory under the outer `output_base` on Windows.
+
+    On Windows, `TEST_TMPDIR` is nested deep inside the outer Bazel `execroot`
+    (e.g. `C:\\b\\<base>\\execroot\\_main\\_tmp\\<32-char-hash>`). If the inner
+    Bazel places its `output_user_root` inside `TEST_TMPDIR`, the inner
+    `execroot` prefix exceeds 110 characters and Rust tool builds (such as
+    `@rules_rust//util/process_wrapper` and `cargo_toml_variable_extractor`)
+    exceed the 260-character Windows `MAX_PATH` limit in `link.exe` (`LNK1181`).
+    """
+    for parent in outer_test_tmpdir.parents:
+        if parent.name == "execroot":
+            digest = hashlib.sha256(str(outer_test_tmpdir).encode()).hexdigest()[:8]
+            return parent.parent / digest
+    return None
+
+
 class ExecuteError(Exception):
     def __init__(self, result):
         self.result = result
@@ -84,12 +102,21 @@
                 interpreter = first_line[2:].decode().split()
                 if interpreter and interpreter[0].endswith("/env"):
                     interpreter = interpreter[1:]
-        self.bazel_cmd = (*interpreter, str(bazel))
         outer_test_tmpdir = pathlib.Path(os.environ["TEST_TMPDIR"])
-        self.test_tmp_dir = outer_test_tmpdir / "bit_test_tmp"
-        # Put the global tmp not under the test tmp to better match how a real
-        # execution has entirely different directories for these.
-        self.tmp_dir = outer_test_tmpdir / "bit_tmp"
+        short_base = (
+            _windows_short_base_dir(outer_test_tmpdir) if os.name == "nt" else None
+        )
+        if short_base is not None:
+            self.test_tmp_dir = short_base / "t"
+            self.tmp_dir = short_base / "g"
+            startup_flags = (f"--output_base={short_base / 'b'}",)
+        else:
+            self.test_tmp_dir = outer_test_tmpdir / "bit_test_tmp"
+            # Put the global tmp not under the test tmp to better match how a real
+            # execution has entirely different directories for these.
+            self.tmp_dir = outer_test_tmpdir / "bit_tmp"
+            startup_flags = ()
+        self.bazel_cmd = (*interpreter, str(bazel), *startup_flags)
         self.test_tmp_dir.mkdir(parents=True, exist_ok=True)
         self.tmp_dir.mkdir(parents=True, exist_ok=True)
         self.bazel_env = {
diff --git a/tests/py_console_script_gen/BUILD.bazel b/tests/py_console_script_gen/BUILD.bazel
new file mode 100644
index 0000000..6ebf5e6
--- /dev/null
+++ b/tests/py_console_script_gen/BUILD.bazel
@@ -0,0 +1,21 @@
+load("@rules_rust//rust:defs.bzl", "rust_test")
+
+package(default_visibility = ["//:__subpackages__"])
+
+licenses(["notice"])
+
+rust_test(
+    name = "py_console_script_gen_test",
+    size = "small",
+    srcs = ["py_console_script_gen_test.rs"],
+    data = [
+        "//python/private:console_script_template",
+    ],
+    edition = "2024",
+    env = {
+        "CONSOLE_SCRIPT_TEMPLATE": "$(rootpath //python/private:console_script_template)",
+    },
+    deps = [
+        "//crates/py_console_script_gen:py_console_script_gen_lib",
+    ],
+)
diff --git a/tests/py_console_script_gen/py_console_script_gen_test.rs b/tests/py_console_script_gen/py_console_script_gen_test.rs
new file mode 100644
index 0000000..08b3c1a
--- /dev/null
+++ b/tests/py_console_script_gen/py_console_script_gen_test.rs
@@ -0,0 +1,502 @@
+use std::env;
+use std::ffi::OsString;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::ExitCode;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use py_console_script_gen_lib::{
+    Options, ParsedArgs, parse_args, parse_console_scripts, run, run_cli,
+};
+
+static TEST_COUNTER: AtomicUsize = AtomicUsize::new(0);
+
+fn default_template_path() -> PathBuf {
+    PathBuf::from(
+        env::var_os("CONSOLE_SCRIPT_TEMPLATE")
+            .expect("CONSOLE_SCRIPT_TEMPLATE env var should be set by Bazel"),
+    )
+}
+
+/// Builds `Options` for direct `run` invocations using the repository's console script template.
+fn options(
+    entry_points: &Path,
+    out: &Path,
+    console_script: Option<&str>,
+    console_script_guess: &str,
+    shebang: &str,
+) -> Options {
+    Options {
+        template: default_template_path(),
+        entry_points: entry_points.to_path_buf(),
+        out: out.to_path_buf(),
+        console_script: console_script.map(str::to_owned),
+        console_script_guess: console_script_guess.to_owned(),
+        shebang: shebang.to_owned(),
+    }
+}
+
+/// Parses `args` and unwraps the `ParsedArgs::Options` variant.
+fn parse_options<I, T>(args: I) -> Options
+where
+    I: IntoIterator<Item = T>,
+    T: Into<OsString>,
+{
+    match parse_args(args).expect("arguments should parse") {
+        ParsedArgs::Options(opts) => opts,
+        ParsedArgs::Help => panic!("expected ParsedArgs::Options, got ParsedArgs::Help"),
+    }
+}
+
+#[test]
+fn test_no_console_scripts_error() {
+    let tmp = TempDir::new("no_console_scripts");
+    let outfile = tmp.path().join("out.py");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[non_console_scripts]\nfoo = foo.bar:fizz\n").unwrap();
+
+    let err = run(&options(&entry_points, &outfile, None, "", "")).unwrap_err();
+    assert_eq!(
+        err.to_string(),
+        "The package does not provide any console_scripts in its entry_points.txt"
+    );
+}
+
+#[test]
+fn test_empty_console_scripts_section_error() {
+    let tmp = TempDir::new("empty_console_scripts");
+    let outfile = tmp.path().join("out.py");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\n# only a comment\n").unwrap();
+
+    let err = run(&options(&entry_points, &outfile, None, "foo", "")).unwrap_err();
+    assert_eq!(
+        err.to_string(),
+        "The package does not provide any console_scripts in its entry_points.txt"
+    );
+}
+
+#[test]
+fn test_no_entry_point_selected_error() {
+    let tmp = TempDir::new("no_entry_point_selected");
+    let outfile = tmp.path().join("out.py");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\nfoo = foo.bar:fizz\n").unwrap();
+
+    let err = run(&options(&entry_points, &outfile, None, "bar-baz", "")).unwrap_err();
+    assert_eq!(
+        err.to_string(),
+        "Tried to guess that you wanted 'bar-baz', but could not find it. Please select one of the following console scripts: foo"
+    );
+}
+
+#[test]
+fn test_incorrect_entry_point() {
+    let tmp = TempDir::new("incorrect_entry_point");
+    let outfile = tmp.path().join("out.py");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(
+        &entry_points,
+        "[console_scripts]\nfoo = foo.bar:fizz\nbar = foo.bar:buzz\n",
+    )
+    .unwrap();
+
+    let err = run(&options(&entry_points, &outfile, Some("baz"), "", "")).unwrap_err();
+    assert_eq!(
+        err.to_string(),
+        "The console_script 'baz' was not found, only the following are available: bar, foo"
+    );
+}
+
+#[test]
+fn test_a_single_entry_point() {
+    let tmp = TempDir::new("single_entry_point");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\nfoo = foo.bar:baz\n").unwrap();
+    let out = tmp.path().join("foo.py");
+
+    run(&options(&entry_points, &out, None, "foo", "")).expect("script should be generated");
+
+    let got = fs::read_to_string(&out).unwrap();
+    let want = r#"import sys
+
+# See @rules_python//crates/py_console_script_gen for explanation
+if getattr(sys.flags, "safe_path", False):
+    # We are running on Python 3.11 and we don't need this workaround
+    pass
+elif ".runfiles" not in sys.path[0]:
+    sys.path = sys.path[1:]
+
+try:
+    from foo.bar import baz
+except ImportError:
+    entries = "\n".join(sys.path)
+    print("Printing sys.path entries for easier debugging:", file=sys.stderr)
+    print(f"sys.path is:\n{entries}", file=sys.stderr)
+    raise
+
+if __name__ == "__main__":
+    sys.exit(baz())  # pyrefly: ignore[not-callable]
+"#;
+    assert_eq!(got, want);
+}
+
+#[test]
+fn test_custom_template_file() {
+    let tmp = TempDir::new("custom_template");
+    let template = tmp.path().join("custom_template.txt");
+    fs::write(
+        &template,
+        "%shebang%# custom\nfrom %module% import %attr% as _ep\n_ep_call = %entry_point%\n",
+    )
+    .unwrap();
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\nfoo = pkg.sub:Cls.run\n").unwrap();
+    let out = tmp.path().join("out.py");
+
+    let mut opts = options(
+        &entry_points,
+        &out,
+        Some("foo"),
+        "",
+        "#!/usr/bin/env python3",
+    );
+    opts.template = template;
+    run(&opts).expect("custom template should render");
+
+    let got = fs::read_to_string(&out).unwrap();
+    assert_eq!(
+        got,
+        "#!/usr/bin/env python3\n# custom\nfrom pkg.sub import Cls as _ep\n_ep_call = Cls.run\n"
+    );
+}
+
+#[test]
+fn test_a_second_entry_point_class_method() {
+    let tmp = TempDir::new("second_entry_point");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(
+        &entry_points,
+        "[console_scripts]\nfoo = foo.bar:Bar.baz\nbar = foo.baz:Bar.baz\n",
+    )
+    .unwrap();
+    let out = tmp.path().join("out.py");
+
+    run(&options(&entry_points, &out, Some("bar"), "", "")).expect("script should be generated");
+
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.contains("from foo.baz import Bar\n"));
+    assert!(got.contains("sys.exit(Bar.baz())  # pyrefly: ignore[not-callable]\n"));
+}
+
+#[test]
+fn test_shebang_included() {
+    let tmp = TempDir::new("shebang_included");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\nfoo = foo.bar:baz\n").unwrap();
+    let out = tmp.path().join("foo.py");
+
+    let shebang = "#!/usr/bin/env python3";
+    run(&options(&entry_points, &out, None, "foo", shebang)).expect("script should be generated");
+
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.starts_with("#!/usr/bin/env python3\nimport sys\n"));
+}
+
+#[test]
+fn test_empty_console_script_flag_falls_back_to_guess() {
+    let tmp = TempDir::new("empty_console_script_flag");
+    let template = default_template_path();
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\nmy-tool = pkg.mod:main\n").unwrap();
+    let out = tmp.path().join("out.py");
+
+    let args: Vec<OsString> = vec![
+        OsString::from("--template"),
+        template.as_os_str().to_owned(),
+        OsString::from("--console-script"),
+        OsString::from(""),
+        OsString::from("--console-script-guess"),
+        OsString::from("my-tool"),
+        OsString::from("--shebang"),
+        OsString::from(""),
+        entry_points.as_os_str().to_owned(),
+        out.as_os_str().to_owned(),
+    ];
+    let opts = parse_options(&args);
+    assert_eq!(opts.template, template);
+    assert_eq!(opts.console_script, None);
+    assert_eq!(opts.console_script_guess, "my-tool");
+    assert_eq!(opts.shebang, "");
+
+    run(&opts).expect("script should be generated");
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.contains("from pkg.mod import main\n"));
+    assert!(got.contains("sys.exit(main())"));
+}
+
+#[test]
+fn test_equals_flag_syntax_and_flagfile() {
+    let tmp = TempDir::new("flagfile");
+    let template = default_template_path();
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\ncli = pkg.cli:run\n").unwrap();
+    let out = tmp.path().join("out.py");
+    let flagfile = tmp.path().join("args.params");
+    fs::write(
+        &flagfile,
+        format!(
+            "--template={}\n--console-script\n\n--console-script-guess=cli\n--shebang=#!/usr/bin/python3\n{}\n{}\n",
+            template.display(),
+            entry_points.display(),
+            out.display()
+        ),
+    )
+    .unwrap();
+
+    let opts = parse_options([format!("@{}", flagfile.display())]);
+    assert_eq!(opts.console_script, None);
+    run(&opts).expect("script should be generated");
+
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.starts_with("#!/usr/bin/python3\nimport sys\n"));
+    assert!(got.contains("from pkg.cli import run\n"));
+}
+
+#[test]
+fn test_ini_colon_delimiter_comments_and_case_sensitivity() {
+    let tmp = TempDir::new("ini_features");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(
+        &entry_points,
+        "\
+# Leading comment
+; Semicolon comment
+
+[other_section]
+MyTool = wrong.mod:func
+
+  [console_scripts]  
+# Comment inside console_scripts
+MyTool : correct.mod:Class.method
+mytool = lower.mod:func
+
+[trailing_section]
+MyTool = trailing.mod:func
+",
+    )
+    .unwrap();
+    let out = tmp.path().join("out.py");
+
+    run(&options(&entry_points, &out, Some("MyTool"), "", "")).expect("script should be generated");
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.contains("from correct.mod import Class\n"));
+    assert!(got.contains("sys.exit(Class.method())"));
+
+    // Verify case-sensitive lookup fails for wrong case
+    let err = run(&options(&entry_points, &out, Some("MYTOOL"), "", "")).unwrap_err();
+    assert_eq!(
+        err.to_string(),
+        "The console_script 'MYTOOL' was not found, only the following are available: MyTool, mytool"
+    );
+}
+
+#[test]
+fn test_multiple_sections_with_non_console_scripts_last() {
+    let tmp = TempDir::new("multiple_sections_trailing");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(
+        &entry_points,
+        "\
+[gui_scripts]
+gui_before = pkg.gui:before
+
+[console_scripts]
+cli_one = pkg.cli:one
+cli_two = pkg.cli:two
+
+[pytest11]
+my_plugin = pkg.plugin
+
+[flake8.extension]
+F99 = pkg.flake8:Checker
+",
+    )
+    .unwrap();
+    let out = tmp.path().join("out.py");
+
+    run(&options(&entry_points, &out, Some("cli_two"), "", ""))
+        .expect("console_scripts entry before trailing sections should resolve");
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.contains("from pkg.cli import two\n"));
+
+    let err = run(&options(&entry_points, &out, Some("F99"), "", "")).unwrap_err();
+    assert_eq!(
+        err.to_string(),
+        "The console_script 'F99' was not found, only the following are available: cli_one, cli_two"
+    );
+}
+
+#[test]
+fn test_parse_console_scripts_edge_cases() {
+    assert_eq!(parse_console_scripts("").expect("empty INI is valid"), None);
+    assert_eq!(
+        parse_console_scripts("[console_scripts]\nempty_val = \nno_delim_key\n")
+            .expect("empty values should parse"),
+        None
+    );
+
+    let parsed = parse_console_scripts(
+        "\
+[ console_scripts ]
+alpha = pkg.a:first
+  continuation_line
+alpha = pkg.a:override
+beta : pkg.b:run
+empty_ignored =   
+",
+    )
+    .expect("INI should parse")
+    .expect("console_scripts section should be non-empty");
+
+    assert_eq!(parsed.len(), 2);
+    assert_eq!(
+        parsed.get("alpha").map(String::as_str),
+        Some("pkg.a:override")
+    );
+    assert_eq!(parsed.get("beta").map(String::as_str), Some("pkg.b:run"));
+
+    assert!(
+        parse_console_scripts("[unclosed_section\nfoo = bar:baz\n").is_err(),
+        "unclosed section header should fail"
+    );
+}
+
+#[test]
+fn test_nested_class_attribute_entry_point() {
+    let tmp = TempDir::new("nested_attr");
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(
+        &entry_points,
+        "[console_scripts]\nrunner = pkg.sub.mod:Outer.Inner.execute\n",
+    )
+    .unwrap();
+    let out = tmp.path().join("out.py");
+
+    run(&options(&entry_points, &out, Some("runner"), "", "")).expect("script should be generated");
+    let got = fs::read_to_string(&out).unwrap();
+    assert!(got.contains("from pkg.sub.mod import Outer\n"));
+    assert!(got.contains("sys.exit(Outer.Inner.execute())  # pyrefly: ignore[not-callable]\n"));
+}
+
+#[test]
+fn test_help() {
+    assert_eq!(
+        parse_args(["--help"]).expect("--help should parse"),
+        ParsedArgs::Help
+    );
+    assert_eq!(
+        parse_args(["-h"]).expect("-h should parse"),
+        ParsedArgs::Help
+    );
+    assert_eq!(run_cli(["--help"]), ExitCode::SUCCESS);
+}
+
+#[test]
+fn test_cli_parse_errors_and_double_dash() {
+    assert!(parse_args(["entry_points.txt", "out.py"]).is_err());
+    assert!(parse_args(["--console-script-guess=foo", "a", "b"]).is_err());
+    assert!(parse_args(["--template=tmpl.txt", "a", "b"]).is_err());
+    assert!(
+        parse_args([
+            "--template=tmpl.txt",
+            "--console-script-guess=foo",
+            "only_one"
+        ])
+        .is_err()
+    );
+    assert!(
+        parse_args([
+            "--template=tmpl.txt",
+            "--console-script-guess=foo",
+            "--unknown-flag",
+            "a",
+            "b"
+        ])
+        .is_err()
+    );
+    assert!(
+        parse_args([
+            "--template=tmpl.txt",
+            "--console-script-guess=foo",
+            "-x",
+            "a",
+            "b"
+        ])
+        .is_err()
+    );
+    assert!(parse_args(["--template"]).is_err());
+    assert!(parse_args(["--console-script"]).is_err());
+    assert!(parse_args(["--console-script-guess"]).is_err());
+    assert!(parse_args(["--shebang"]).is_err());
+
+    let opts = parse_options([
+        "--template=tmpl.txt",
+        "--console-script-guess=foo",
+        "--",
+        "-dash_entry_points.txt",
+        "-dash_out.py",
+    ]);
+    assert_eq!(opts.template, PathBuf::from("tmpl.txt"));
+    assert_eq!(opts.entry_points, PathBuf::from("-dash_entry_points.txt"));
+    assert_eq!(opts.out, PathBuf::from("-dash_out.py"));
+}
+
+#[test]
+fn test_run_cli_exit_codes() {
+    let tmp = TempDir::new("run_cli");
+    let template = default_template_path();
+    let entry_points = tmp.path().join("entry_points.txt");
+    fs::write(&entry_points, "[console_scripts]\ncli = pkg.cli:main\n").unwrap();
+    let out = tmp.path().join("cli_out.py");
+
+    let code_ok = run_cli([
+        OsString::from("--template"),
+        template.as_os_str().to_owned(),
+        OsString::from("--console-script-guess=cli"),
+        entry_points.as_os_str().to_owned(),
+        out.as_os_str().to_owned(),
+    ]);
+    assert_eq!(code_ok, ExitCode::SUCCESS);
+    assert!(out.exists());
+
+    let code_err = run_cli(["--unknown-flag"]);
+    assert_eq!(code_err, ExitCode::FAILURE);
+}
+
+struct TempDir {
+    path: PathBuf,
+}
+
+impl TempDir {
+    fn new(prefix: &str) -> Self {
+        let id = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
+        let path = env::temp_dir().join(format!(
+            "py_console_script_gen_test_{prefix}_{}_{id}",
+            std::process::id(),
+        ));
+        let _ = fs::remove_dir_all(&path);
+        fs::create_dir_all(&path).unwrap();
+        Self { path }
+    }
+
+    fn path(&self) -> &Path {
+        &self.path
+    }
+}
+
+impl Drop for TempDir {
+    fn drop(&mut self) {
+        let _ = fs::remove_dir_all(&self.path);
+    }
+}
diff --git a/tests/shrubbery/shrubbery_test.rs b/tests/shrubbery/shrubbery_test.rs
index 7127746..595f02a 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(), 5);
+    assert_eq!(SUBCOMMANDS.len(), 6);
     let mut sorted = SUBCOMMANDS.to_vec();
     sorted.sort_unstable();
     assert_eq!(SUBCOMMANDS, sorted.as_slice());