diff --git a/crates/py_console_script_gen/BUILD.bazel b/crates/py_console_script_gen/BUILD.bazel new file mode 100644 index 0000000000..c1f672a8ec --- /dev/null +++ b/crates/py_console_script_gen/BUILD.bazel @@ -0,0 +1,21 @@ +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//: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 0000000000..4daf314c7e --- /dev/null +++ b/crates/py_console_script_gen/src/lib.rs @@ -0,0 +1,283 @@ +//! 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 renders a Python entrypoint script to `OUT`. +//! +//! The rendered script 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 and +//! ), 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, bail}; +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"; + // 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] --console-script-guess + +Generate a console_script entrypoint Python file from a wheel's entry_points.txt. + +Arguments: + The entry_points.txt within the dist-info of a PyPI wheel + The output file + +Options: + --console-script The console_script to generate the entry_point template for + --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 + @ Read newline-delimited arguments from + -h, --help Print this help"; + +/// Parses the `[console_scripts]` section from an `entry_points.txt` INI string. +/// +/// Preserves case-sensitivity of keys (`optionxform = str`). +/// Returns `None` if `[console_scripts]` is absent or empty. +pub fn parse_console_scripts(content: &str) -> Option> { + let mut in_console_scripts = false; + let mut console_scripts: HashMap = HashMap::new(); + + let lines = content + .lines() + .map(|raw_line| (raw_line, raw_line.trim())) + .filter(|(_, trimmed)| !trimmed.is_empty() && !trimmed.starts_with(['#', ';'])); + for (raw_line, trimmed) in lines { + if let Some(section) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { + in_console_scripts = section.trim() == "console_scripts"; + continue; + } + + if !in_console_scripts || raw_line.starts_with([' ', '\t']) { + continue; + } + + if let Some((raw_key, raw_val)) = raw_line.split_once(['=', ':']) { + let key = raw_key.trim(); + let val = raw_val.trim(); + if !key.is_empty() && !val.is_empty() { + console_scripts.insert(key.to_owned(), val.to_owned()); + } + } + } + + (!console_scripts.is_empty()).then_some(console_scripts) +} + +/// Renders the console script template for the given module, imported attribute, entry point, and shebang. +pub fn render_template(shebang: &str, module: &str, attr: &str, entry_point: &str) -> String { + let shebang_prefix = if shebang.is_empty() { + String::new() + } else { + format!("{shebang}\n") + }; + + format!( + "{shebang_prefix}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] +" + ) +} + +/// Generates the console script Python file described by `options`. +/// +/// # Errors +/// +/// Returns `Err` if `entry_points` cannot be read, provides no `[console_scripts]`, does not +/// contain the requested (or guessed) console script, or if `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); + + let rendered = render_template(&options.shebang, module, attr, entry_point_callable); + fs::write(&options.out, rendered) + .with_context(|| format!("writing {}", options.out.display()))?; + + Ok(()) +} + +/// Parsed command-line options for `py_console_script_gen`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Options { + /// Path to the `entry_points.txt` file to parse. + pub entry_points: PathBuf, + /// Path of the Python entrypoint script to write. + pub out: PathBuf, + /// Explicitly requested console script name; `None` when absent or empty. + pub console_script: Option, + /// 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, +} + +/// Result of parsing the command line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Cli { + /// `--help` was requested. + Help, + /// Generate the console script with the given options. + Run(Options), +} + +/// Parses command-line arguments (excluding `argv[0]` and subcommand name) into [`Cli`]. +/// +/// # Errors +/// +/// Returns `Err` if an `@flagfile` cannot be read, an unknown flag is given, a flag is missing its +/// value, `--console-script-guess` is absent, or there are not exactly two positional arguments. +pub fn parse_args(args: I) -> Result +where + I: IntoIterator, + T: Into, +{ + let expanded = argfile::expand_args_from( + args.into_iter().map(Into::into), + argfile::parse_fromfile, + argfile::PREFIX, + ) + .context("reading @flagfile")?; + + let mut positional: Vec = Vec::with_capacity(2); + let mut console_script: Option = None; + let mut console_script_guess: Option = 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(Cli::Help), + 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 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(Cli::Run(Options { + 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(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!("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 +} diff --git a/crates/shrubbery/BUILD.bazel b/crates/shrubbery/BUILD.bazel index 1c37ddd5d6..682ec241ce 100644 --- a/crates/shrubbery/BUILD.bazel +++ b/crates/shrubbery/BUILD.bazel @@ -11,6 +11,7 @@ rust_library( 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 1ed3656642..5116fe98ea 100644 --- a/crates/shrubbery/src/lib.rs +++ b/crates/shrubbery/src/lib.rs @@ -11,6 +11,7 @@ use std::process::ExitCode; 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 mod subcommands { 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 @@ where 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 45ae9831eb..cec8f76a75 100644 --- a/python/private/BUILD.bazel +++ b/python/private/BUILD.bazel @@ -949,6 +949,15 @@ bzl_library( deps = [":py_info"], ) +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"], @@ -1004,11 +1013,6 @@ bzl_library( srcs = ["py_cc_toolchain_info.bzl"], ) -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/py_console_script_gen.bzl b/python/private/py_console_script_gen.bzl index 091193d410..02dae6cfb5 100644 --- a/python/private/py_console_script_gen.bzl +++ b/python/private/py_console_script_gen.bzl @@ -23,6 +23,9 @@ which cannot be done in pure starlark according to 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): @@ -46,15 +49,21 @@ def _py_console_script_gen_impl(ctx): args.add(entry_points_txt) args.add(ctx.outputs.out) + tool = get_shrubbery_tool( + ctx, + "py_console_script_gen", + ctx.attr._tool, + ) ctx.actions.run( inputs = [ entry_points_txt, ], outputs = [ctx.outputs.out], - arguments = [args], + arguments = tool.prefix_args + [args], mnemonic = "PyConsoleScriptBinaryGen", progress_message = "Generating py_console_script_binary main: %{label}", - executable = ctx.executable._tool, + executable = tool.files_to_run, + toolchain = tool.toolchain, ) return [DefaultInfo( @@ -93,7 +102,10 @@ py_console_script_gen = rule( 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/tests/py_console_script_gen/BUILD.bazel b/tests/py_console_script_gen/BUILD.bazel new file mode 100644 index 0000000000..e31a9ebe82 --- /dev/null +++ b/tests/py_console_script_gen/BUILD.bazel @@ -0,0 +1,15 @@ +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"], + edition = "2024", + 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 0000000000..91885b95b0 --- /dev/null +++ b/tests/py_console_script_gen/py_console_script_gen_test.rs @@ -0,0 +1,378 @@ +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::{Cli, Options, parse_args, parse_console_scripts, run, run_cli}; + +static TEST_COUNTER: AtomicUsize = AtomicUsize::new(0); + +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); + } +} + +/// Builds `Options` for direct `run` invocations. +fn options( + entry_points: &Path, + out: &Path, + console_script: Option<&str>, + console_script_guess: &str, + shebang: &str, +) -> Options { + Options { + 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 `Cli::Run` variant. +fn parse_run(args: I) -> Options +where + I: IntoIterator, + T: Into, +{ + match parse_args(args).expect("arguments should parse") { + Cli::Run(opts) => opts, + Cli::Help => panic!("expected Cli::Run, got Cli::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 = "\ +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_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 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 = vec![ + 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_run(&args); + 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 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!( + "--console-script\n\n--console-script-guess=cli\n--shebang=#!/usr/bin/python3\n{}\n{}\n", + entry_points.display(), + out.display() + ), + ) + .unwrap(); + + let opts = parse_run([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_parse_console_scripts_edge_cases() { + assert_eq!(parse_console_scripts(""), None); + assert_eq!( + parse_console_scripts("[console_scripts]\nempty_val = \n indented = ignored:fn\n"), + None + ); + + let parsed = parse_console_scripts( + "\ +[ console_scripts ] +alpha = pkg.a:first + continuation_line_ignored +alpha = pkg.a:override +beta : pkg.b:run +empty_ignored = +", + ) + .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")); +} + +#[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"), + Cli::Help + ); + assert_eq!(parse_args(["-h"]).expect("-h should parse"), Cli::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", "only_one_positional"]).is_err()); + assert!(parse_args(["--console-script-guess=foo", "--unknown-flag", "a", "b"]).is_err()); + assert!(parse_args(["--console-script-guess=foo", "-x", "a", "b"]).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_run([ + "--console-script-guess=foo", + "--", + "-dash_entry_points.txt", + "-dash_out.py", + ]); + 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 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("--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); +} diff --git a/tests/shrubbery/shrubbery_test.rs b/tests/shrubbery/shrubbery_test.rs index 7127746284..595f02abf3 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(), 5); + assert_eq!(SUBCOMMANDS.len(), 6); let mut sorted = SUBCOMMANDS.to_vec(); sorted.sort_unstable(); assert_eq!(SUBCOMMANDS, sorted.as_slice());