Skip to main content

runner/
lib.rs

1//! # Runner (`runner-run` crate)
2//!
3//! ## Overview
4//!
5//! Universal project task runner.
6//!
7//! `runner` auto-detects your project's toolchain (package managers, task
8//! runners, version constraints) and provides a unified interface to run
9//! tasks, install dependencies, clean artifacts, and execute ad-hoc commands.
10//!
11//! ## Supported Ecosystems
12//!
13//! **Package managers/ecosystems:** [npm], [yarn], [pnpm], [bun], [cargo],
14//! [deno], [uv], [poetry], [pipenv], [go], [bundler], [composer]
15//!
16//! **Task runners:** [turbo], [nx], [make], [just], [go-task], [mise], [bacon]
17//!
18//! [npm]: https://www.npmjs.com/
19//! [yarn]: https://yarnpkg.com/
20//! [pnpm]: https://pnpm.io/
21//! [bun]: https://bun.sh/
22//! [cargo]: https://doc.rust-lang.org/cargo/
23//! [deno]: https://deno.land/
24//! [uv]: https://github.com/astral-sh/uv/
25//! [poetry]: https://python-poetry.org/
26//! [pipenv]: https://pipenv.pypa.io/
27//! [go]: https://go.dev/
28//! [bundler]: https://bundler.io/
29//! [composer]: https://getcomposer.org/
30//! [turbo]: https://turborepo.dev/
31//! [nx]: https://nx.dev/
32//! [make]: https://www.gnu.org/software/make/
33//! [just]: https://just.systems/
34//! [go-task]: https://taskfile.dev/
35//! [mise]: https://mise.jdx.dev/
36//! [bacon]: https://dystroy.org/bacon/
37//!
38//! ## Library API
39//!
40//! - [`run_from_env`] parses process args and dispatches in current dir.
41//! - [`run_from_args`] parses explicit args and dispatches in current dir.
42//! - [`run_in_dir`] parses explicit args and dispatches against a given dir.
43//!
44//! ## CLI Usage
45//!
46//! ```bash
47//! runner              # show detected project info
48//! runner <task>       # run a task (falls back to package-manager exec)
49//! run <task>          # alias binary: a same-named task wins, else the
50//!                     #   built-in default (install/clean/list/info/
51//!                     #   completions), else PM exec
52//! runner run <target> # explicit unified run: task → built-in → PM exec
53//! runner install      # ALWAYS the built-in (deps); a task named `install`
54//!                     #   is reached via `run install`
55//! runner clean        # remove caches and build artifacts (always built-in)
56//! runner list         # list available tasks from all sources (always built-in)
57//! ```
58// Generate docs with `cargo doc --document-private-items --open`.
59
60#![doc(
61    html_logo_url = "https://raw.githubusercontent.com/kjanat/runner/d876a0b9716806d92e07f5d5560b022b6158ecd5/branding/icon.svg",
62    html_favicon_url = "https://raw.githubusercontent.com/kjanat/runner/d876a0b9716806d92e07f5d5560b022b6158ecd5/branding/icon.svg"
63)]
64
65pub(crate) mod chain;
66mod cli;
67mod cmd;
68mod complete;
69mod config;
70mod detect;
71mod resolver;
72mod schema;
73mod tool;
74mod types;
75
76use std::ffi::OsString;
77use std::io::IsTerminal;
78use std::path::{Path, PathBuf};
79
80use anyhow::{Result, bail};
81use clap::{CommandFactory, FromArgMatches};
82use colored::Colorize;
83
84use resolver::ResolveError;
85
86/// JSON Schema for `runner.toml`. Built under the `schema` feature;
87/// `runner schema` renders it.
88#[cfg(feature = "schema")]
89#[must_use]
90pub fn config_schema() -> schemars::Schema {
91    schemars::schema_for!(config::RunnerConfig)
92}
93
94/// Exit code semantics:
95/// - `0`, success
96/// - `1`, generic failure (I/O, detection, child-process non-zero)
97/// - `2`, resolver could not satisfy intent (typed resolver error)
98///
99/// `main` and `bin/run.rs` use this to map an [`anyhow::Error`] to the
100/// right code: anything that downcasts to the internal resolver-error
101/// type is 2, everything else is 1. The resolver-error type itself is
102/// crate-private; only the exit-code projection is part of the
103/// library's public surface.
104#[must_use]
105pub fn exit_code_for_error(err: &anyhow::Error) -> i32 {
106    if err.downcast_ref::<ResolveError>().is_some() {
107        2
108    } else {
109        1
110    }
111}
112
113const REPOSITORY_URL: &str = env!("CARGO_PKG_REPOSITORY");
114const VERSION: &str = clap::crate_version!();
115
116/// Parse process args, detect current dir, dispatch, return exit code.
117///
118/// When the `COMPLETE` environment variable is set (e.g. `COMPLETE=zsh`),
119/// this function writes shell completions to stdout and exits without
120/// running the normal command dispatch.
121///
122/// # Errors
123///
124/// Returns an error when reading current dir fails, project detection fails,
125/// command execution fails, or writing clap output fails.
126///
127/// Argument parsing/help/version flows are rendered by clap and returned as an
128/// exit code instead of terminating the host process.
129pub fn run_from_env() -> Result<i32> {
130    let bin = bin_name_from_arg0(&std::env::args_os().next().unwrap_or_default())
131        .unwrap_or_else(|| "runner".to_string());
132    clap_complete::CompleteEnv::with_factory(move || {
133        configure_cli_command(cli::Cli::command(), true)
134            .name(bin.clone())
135            .bin_name(bin.clone())
136    })
137    .shells(complete::SHELLS)
138    .complete();
139    run_from_args(std::env::args_os())
140}
141
142/// Parse explicit args, detect current dir, dispatch, return exit code.
143///
144/// `args` must include `argv[0]` as first item.
145///
146/// # Errors
147///
148/// Returns an error when reading current dir fails, project detection fails,
149/// command execution fails, or writing clap output fails.
150///
151/// Argument parsing/help/version flows are rendered by clap and returned as an
152/// exit code instead of terminating the host process.
153pub fn run_from_args<I, T>(args: I) -> Result<i32>
154where
155    I: IntoIterator<Item = T>,
156    T: Into<OsString> + Clone,
157{
158    let cwd = std::env::current_dir()?;
159    run_in_dir(args, &cwd)
160}
161
162/// Parse explicit args and run against `dir`.
163///
164/// `args` must include `argv[0]` as first item.
165///
166/// # Errors
167///
168/// Returns an error when project detection fails, command execution fails, or
169/// writing clap output fails.
170///
171/// Argument parsing/help/version flows are rendered by clap and returned as an
172/// exit code instead of terminating the host process.
173pub fn run_in_dir<I, T>(args: I, dir: &Path) -> Result<i32>
174where
175    I: IntoIterator<Item = T>,
176    T: Into<OsString> + Clone,
177{
178    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
179
180    if requests_version(&args) {
181        println!("{}", version_line(&args, std::io::stdout().is_terminal()));
182        return Ok(0);
183    }
184
185    let cli = match parse_cli(args) {
186        Ok(cli) => cli,
187        Err(err) => return render_clap_error(&err),
188    };
189    // The language server parses each editor buffer itself and needs neither a
190    // resolved project dir nor detection; handle it before either can bail.
191    #[cfg(feature = "lsp")]
192    if matches!(cli.command.as_ref(), Some(cli::Command::Lsp)) {
193        return cmd::lsp::run();
194    }
195    let project_dir = resolve_project_dir(
196        configured_project_dir(
197            cli.global.project_dir.as_deref(),
198            std::env::var_os("RUNNER_DIR").as_deref(),
199        )
200        .as_deref(),
201        dir,
202    )?;
203    dispatch(cli, &project_dir)
204}
205
206fn parse_cli<I, T>(args: I) -> Result<cli::Cli, clap::Error>
207where
208    I: IntoIterator<Item = T>,
209    T: Into<OsString> + Clone,
210{
211    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
212
213    let mut command = configure_cli_command(cli::Cli::command(), std::io::stdout().is_terminal());
214    if let Some(bin_name) = args.first().and_then(bin_name_from_arg0) {
215        command = command.name(bin_name.clone()).bin_name(bin_name);
216    }
217    command = shorten_help_subcommand(command);
218
219    let matches = command.try_get_matches_from(args)?;
220    cli::Cli::from_arg_matches(&matches)
221}
222
223/// Replace clap's verbose default `help` subcommand description
224/// (`"Print this message or the help of the given subcommand(s)"`) with a terse
225/// one. clap only injects the implicit `help` subcommand during `Command::build`,
226/// so force the build first; the `Built` flag makes the later parse-time build a
227/// no-op. Guarded with `find_subcommand` because a flat command without
228/// subcommands (the `run` alias) never gets a `help` entry, and `mut_subcommand`
229/// panics on a missing name. Must run after `name`/`bin_name` are set, since
230/// `build` snapshots bin names.
231fn shorten_help_subcommand(mut command: clap::Command) -> clap::Command {
232    command.build();
233    if command.find_subcommand("help").is_some() {
234        command.mut_subcommand("help", |help| help.about("Print help for a subcommand"))
235    } else {
236        command
237    }
238}
239
240/// Parse process args as the `run` alias binary, detect the current dir,
241/// dispatch, and return the exit code.
242///
243/// Always treats positional arguments as a task or command (routed through
244/// `cmd::run`); built-in subcommand names are never parsed specially, so
245/// `run clean`, `run install`, etc. run a same-named project task when one
246/// exists. When no such task exists, a bare run token naming a built-in verb
247/// (`install`/`clean`/`list`/`info`/`completions`) falls back to that
248/// built-in's default form rather than the package-manager exec path.
249///
250/// When the `COMPLETE` environment variable is set, writes shell completions
251/// to stdout and exits without running the normal command dispatch.
252///
253/// # Errors
254///
255/// Returns an error when reading current dir fails, project detection fails,
256/// command execution fails, or writing clap output fails.
257///
258/// Argument parsing/help/version flows are rendered by clap and returned as an
259/// exit code instead of terminating the host process.
260pub fn run_alias_from_env() -> Result<i32> {
261    let bin = bin_name_from_arg0(&std::env::args_os().next().unwrap_or_default())
262        .unwrap_or_else(|| "run".to_string());
263    clap_complete::CompleteEnv::with_factory(move || {
264        configure_cli_command(cli::RunAliasCli::command(), true)
265            .name(bin.clone())
266            .bin_name(bin.clone())
267    })
268    .shells(complete::SHELLS)
269    .complete();
270    run_alias_from_args(std::env::args_os())
271}
272
273/// Parse explicit args as the `run` alias binary, detect current dir,
274/// dispatch, and return the exit code. See [`run_alias_from_env`].
275///
276/// `args` must include `argv[0]` as first item.
277///
278/// # Errors
279///
280/// Returns an error when reading current dir fails, project detection fails,
281/// command execution fails, or writing clap output fails.
282pub fn run_alias_from_args<I, T>(args: I) -> Result<i32>
283where
284    I: IntoIterator<Item = T>,
285    T: Into<OsString> + Clone,
286{
287    let cwd = std::env::current_dir()?;
288    run_alias_in_dir(args, &cwd)
289}
290
291/// Parse explicit args as the `run` alias binary against `dir`.\
292/// See [`run_alias_from_env`].
293///
294/// `args` must include `argv[0]` as first item.
295///
296/// # Errors
297///
298/// Returns an error when project detection fails, command execution fails, or
299/// writing clap output fails.
300pub fn run_alias_in_dir<I, T>(args: I, dir: &Path) -> Result<i32>
301where
302    I: IntoIterator<Item = T>,
303    T: Into<OsString> + Clone,
304{
305    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
306
307    if requests_version(&args) {
308        println!("{}", version_line(&args, std::io::stdout().is_terminal()));
309        return Ok(0);
310    }
311
312    let cli = match parse_run_alias_cli(args.clone()) {
313        Ok(cli) => cli,
314        // A `--help`/`--version` *before* any task is this binary's own:
315        // clap's built-ins are disabled and the flag is undefined, so it
316        // can't fill the hyphen-rejecting `task` positional and surfaces as
317        // `UnknownArgument`. (A *trailing* one is swallowed by `args` and
318        // forwarded instead, see `cli::RunAliasCli`.) Covers the bare
319        // `run --help` as well as `run --pm npm --help`, `run --dir … -V`.
320        Err(err) => {
321            return match alias_builtin_request(&err) {
322                Some(AliasBuiltin::Help) => print_run_alias_help(&args),
323                Some(AliasBuiltin::Version) => {
324                    println!("{}", version_line(&args, std::io::stdout().is_terminal()));
325                    Ok(0)
326                }
327                None => render_clap_error(&err),
328            };
329        }
330    };
331
332    let project_dir = resolve_project_dir(
333        configured_project_dir(
334            cli.global.project_dir.as_deref(),
335            std::env::var_os("RUNNER_DIR").as_deref(),
336        )
337        .as_deref(),
338        dir,
339    )?;
340    dispatch_run_alias(cli, &project_dir)
341}
342
343/// This binary's own help/version, requested *before* any task.
344enum AliasBuiltin {
345    Help,
346    Version,
347}
348
349/// Classify a `run`-alias parse failure as a request for this binary's own
350/// help/version, or `None` for an unrelated error to surface verbatim.
351///
352/// With clap's built-in `--help`/`--version` disabled and undefined, a
353/// leading `-h`/`--help`/`-V`/`--version` cannot fill the hyphen-rejecting
354/// `task` positional, so clap reports [`ErrorKind::UnknownArgument`] naming
355/// the offending flag. A *trailing* one never reaches here; it is captured
356/// by `args` and forwarded, so an `UnknownArgument` naming a help/version
357/// flag unambiguously means "before any task", i.e. ours to handle.
358fn alias_builtin_request(err: &clap::Error) -> Option<AliasBuiltin> {
359    use clap::error::{ContextKind, ContextValue, ErrorKind};
360
361    if err.kind() != ErrorKind::UnknownArgument {
362        return None;
363    }
364    match err.get(ContextKind::InvalidArg) {
365        Some(ContextValue::String(arg)) => match arg.as_str() {
366            "--help" | "-h" => Some(AliasBuiltin::Help),
367            "--version" | "-V" => Some(AliasBuiltin::Version),
368            _ => None,
369        },
370        _ => None,
371    }
372}
373
374/// Render the `run` alias binary's own help to stdout, returning exit 0.
375///
376/// Invoked when `-h`/`--help` precedes any task. A help flag that *follows*
377/// a task is forwarded to that task instead (see [`cli::RunAliasCli`]), so
378/// this path is only reached for `run`'s own help. The bin name is taken
379/// from `argv[0]` so the `Usage:` line reads `run`, matching how clap's
380/// built-in help rendered before it was disabled.
381fn print_run_alias_help(args: &[OsString]) -> Result<i32> {
382    let mut command =
383        configure_cli_command(cli::RunAliasCli::command(), std::io::stdout().is_terminal());
384    if let Some(bin_name) = args.first().and_then(bin_name_from_arg0) {
385        command = command.name(bin_name.clone()).bin_name(bin_name);
386    }
387    command.print_help()?;
388    Ok(0)
389}
390
391fn parse_run_alias_cli<I, T>(args: I) -> Result<cli::RunAliasCli, clap::Error>
392where
393    I: IntoIterator<Item = T>,
394    T: Into<OsString> + Clone,
395{
396    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
397
398    let mut command =
399        configure_cli_command(cli::RunAliasCli::command(), std::io::stdout().is_terminal());
400    if let Some(bin_name) = args.first().and_then(bin_name_from_arg0) {
401        command = command.name(bin_name.clone()).bin_name(bin_name);
402    }
403
404    let matches = command.try_get_matches_from(args)?;
405    cli::RunAliasCli::from_arg_matches(&matches)
406}
407
408/// Dispatch a parsed `run`-alias CLI by funnelling it through the same
409/// [`dispatch`] entry point the `runner` binary uses, so both share a
410/// single resolver-override + command-dispatch implementation rather than
411/// keeping a second copy in sync.
412///
413/// The alias is a thin shortcut for `runner run <task>`, so a parsed
414/// [`cli::RunAliasCli`] maps onto [`cli::Cli`] one-to-one:
415/// - a bare invocation (no task and no `-s`/`-p` mode flag) becomes
416///   `command: None`, reproducing the bare-`runner` project dashboard.
417///   A lone `-k`/`-K` does not defeat this: the chain-failure flags are
418///   inert on the dashboard (which never reads the failure policy) and are
419///   dropped before override building, so, unlike the old eager builder,
420///   a bare `run -k`/`-K` no longer conflicts with an opposite-polarity
421///   `RUNNER_KILL_ON_FAIL`/`RUNNER_KEEP_GOING` or `[chain]` config;
422/// - everything else becomes [`cli::Command::Run`] carrying the alias's
423///   task, forwarded args, and chain flags.
424///
425/// Building a typed [`cli::Cli`] here, rather than rewriting argv to
426/// `["runner", "run", …]` and re-parsing through clap, keeps the mapping
427/// total and compiler-checked and, crucially, leaves the alias's bespoke
428/// help/version forwarding untouched. That forwarding lives in the parse
429/// layer ([`cli::RunAliasCli`] disables clap's `--help`/`--version` so a
430/// *trailing* one reaches the task); re-parsing through [`cli::Command::Run`],
431/// which inherits the `runner` binary's enabled global help/version, would
432/// short-circuit and print clap help instead of forwarding it.
433fn dispatch_run_alias(cli: cli::RunAliasCli, dir: &Path) -> Result<i32> {
434    let bare = cli.task.is_none() && !cli.mode.sequential && !cli.mode.parallel;
435    let command = if bare {
436        None
437    } else {
438        Some(cli::Command::Run {
439            task: cli.task,
440            args: cli.args,
441            mode: cli.mode,
442            failure: cli.failure,
443        })
444    };
445    dispatch(
446        cli::Cli {
447            global: cli.global,
448            command,
449        },
450        dir,
451    )
452}
453
454/// Extracts the filename portion from an `argv[0]`-style `OsString`, returning it when non-empty.
455///
456/// Returns `Some(String)` with the file name if `arg0` has a non-empty file-name segment, `None` otherwise.
457///
458/// Strips a trailing `.exe` suffix (case-insensitive) so Windows builds present the
459/// same `runner` / `run` identifier in `--version`, `--help`, and the `Usage:` line
460/// as Unix builds. Without this, clap's bin-name plumbing surfaces the raw
461/// `runner.exe` from `argv[0]`, leaking the platform-specific extension into UX.
462///
463/// # Examples
464///
465/// ```rust
466/// use std::ffi::OsString;
467/// let name = runner::bin_name_from_arg0(&OsString::from("/usr/bin/runner"));
468/// assert_eq!(name.as_deref(), Some("runner"));
469///
470/// let win = runner::bin_name_from_arg0(&OsString::from("runner.exe"));
471/// assert_eq!(win.as_deref(), Some("runner"));
472/// ```
473#[must_use]
474pub fn bin_name_from_arg0(arg0: &OsString) -> Option<String> {
475    let name = Path::new(arg0)
476        .file_name()
477        .map(|segment| segment.to_string_lossy().into_owned())?;
478
479    let trimmed = strip_exe_suffix(&name);
480    (!trimmed.is_empty()).then(|| trimmed.to_string())
481}
482
483/// Strip a trailing `.exe` extension (ASCII case-insensitive) from a file name.
484///
485/// Returns the input unchanged if no such suffix is present. The match is
486/// ASCII-only because Windows treats `.EXE`, `.Exe`, `.exe` etc. as the same
487/// extension, and that case-fold is bounded to ASCII regardless of the active
488/// code page.
489fn strip_exe_suffix(name: &str) -> &str {
490    const SUFFIX: &str = ".exe";
491    if name.len() > SUFFIX.len()
492        && name.is_char_boundary(name.len() - SUFFIX.len())
493        && name[name.len() - SUFFIX.len()..].eq_ignore_ascii_case(SUFFIX)
494    {
495        &name[..name.len() - SUFFIX.len()]
496    } else {
497        name
498    }
499}
500
501/// Attaches the generated help byline to a clap command.
502///
503/// The byline text is produced by `help_byline` using `stdout_is_terminal` and is
504/// applied via `Command::before_help`.
505///
506/// # Examples
507///
508/// ```rust
509/// let cmd = clap::Command::new("app");
510/// let cmd = runner::configure_cli_command(cmd, true);
511/// assert!(cmd.get_before_help().is_some());
512/// ```
513#[must_use]
514pub fn configure_cli_command(command: clap::Command, stdout_is_terminal: bool) -> clap::Command {
515    command.before_help(help_byline(stdout_is_terminal))
516}
517
518/// Render the CLI help byline using the build-time author metadata.
519///
520/// When `stdout_is_terminal` is true and `RUNNER_AUTHOR_EMAIL` is set, the
521/// author name is wrapped in an OSC-8 `mailto:` hyperlink; otherwise the plain
522/// author name is used. The returned string is prefixed with `"by "`.
523///
524/// # Examples
525///
526/// ```rust
527/// // Without a terminal, output is plain "by <name>" using the build-time author.
528/// let s = runner::help_byline(false);
529/// assert!(s.starts_with("by "));
530///
531/// // With a terminal, the name may be wrapped in an OSC-8 mailto: hyperlink,
532/// // but the byline still begins with "by ".
533/// let t = runner::help_byline(true);
534/// assert!(t.starts_with("by "));
535/// ```
536#[must_use]
537pub fn help_byline(stdout_is_terminal: bool) -> String {
538    let name = env!("RUNNER_AUTHOR_NAME");
539    let rendered = if stdout_is_terminal {
540        option_env!("RUNNER_AUTHOR_EMAIL").map_or_else(
541            || name.to_string(),
542            |mail| osc8_link(name, &format!("mailto:{mail}")),
543        )
544    } else {
545        name.to_string()
546    };
547    format!("by {rendered}")
548}
549
550/// Detects whether the provided argv-style slice specifically requests the program version.
551///
552/// # Returns
553///
554/// `true` if `args` has exactly two elements and the second element is `--version` or `-V`, `false` otherwise.
555///
556/// # Examples
557///
558/// ```rust
559/// use std::ffi::OsString;
560///
561/// let args = vec![OsString::from("runner"), OsString::from("--version")];
562/// assert!(runner::requests_version(&args));
563///
564/// let args2 = vec![OsString::from("runner"), OsString::from("-V")];
565/// assert!(runner::requests_version(&args2));
566///
567/// let args3 = vec![OsString::from("runner")];
568/// assert!(!runner::requests_version(&args3));
569///
570/// let args4 = vec![OsString::from("runner"), OsString::from("--version"), OsString::from("extra")];
571/// assert!(!runner::requests_version(&args4));
572/// ```
573#[must_use]
574pub fn requests_version(args: &[OsString]) -> bool {
575    if args.len() != 2 {
576        return false;
577    }
578
579    let flag = args[1].to_string_lossy();
580    flag == "--version" || flag == "-V"
581}
582
583fn version_line(args: &[OsString], stdout_is_terminal: bool) -> String {
584    let bin = args
585        .first()
586        .and_then(bin_name_from_arg0)
587        .unwrap_or_else(|| "runner".to_string());
588
589    if !stdout_is_terminal {
590        return format!("{bin} {VERSION}");
591    }
592
593    format!(
594        "{} {}",
595        osc8_link(&bin, REPOSITORY_URL),
596        osc8_link(VERSION, &release_url(VERSION))
597    )
598}
599
600fn release_url(version: &str) -> String {
601    format!("{REPOSITORY_URL}/releases/tag/v{version}")
602}
603
604fn osc8_link(label: &str, url: &str) -> String {
605    format!("\u{1b}]8;;{url}\u{1b}\\{label}\u{1b}]8;;\u{1b}\\")
606}
607
608fn configured_project_dir(
609    project_dir: Option<&Path>,
610    env_dir: Option<&std::ffi::OsStr>,
611) -> Option<PathBuf> {
612    project_dir
613        .map(Path::to_path_buf)
614        .or_else(|| env_dir.map(PathBuf::from))
615}
616
617/// Expand a leading `~` (or `~/`) in a path to the user's home directory.
618///
619/// Shells only expand an unquoted tilde when it is the first character of a
620/// word, so forms like `--dir=~/foo` arrive here unexpanded. We mirror the
621/// common shell behaviour for the bare `~` and `~/` cases; any other form
622/// (including `~user`) is returned unchanged.
623pub(crate) fn expand_tilde(path: &Path) -> PathBuf {
624    expand_tilde_with(path, home_dir().as_deref())
625}
626
627fn expand_tilde_with(path: &Path, home: Option<&Path>) -> PathBuf {
628    let Some(home) = home else {
629        return path.to_path_buf();
630    };
631
632    match path.strip_prefix("~") {
633        // `~` on its own.
634        Ok(rest) if rest.as_os_str().is_empty() => home.to_path_buf(),
635        // `~/rest` (`strip_prefix` consumes the separator).
636        Ok(rest) => home.join(rest),
637        // Not a tilde path, or a form we don't expand (e.g. `~user`).
638        Err(_) => path.to_path_buf(),
639    }
640}
641
642fn home_dir() -> Option<PathBuf> {
643    let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
644    std::env::var_os(var)
645        .filter(|v| !v.is_empty())
646        .map(PathBuf::from)
647}
648
649fn resolve_project_dir(project_dir: Option<&Path>, cwd: &Path) -> Result<PathBuf> {
650    let project_dir = project_dir.map(expand_tilde);
651    let dir = match project_dir.as_deref() {
652        Some(path) if path.is_absolute() => path.to_path_buf(),
653        Some(path) => cwd.join(path),
654        None => cwd.to_path_buf(),
655    };
656
657    if !dir.exists() {
658        bail!("project dir does not exist: {}", dir.display());
659    }
660    if !dir.is_dir() {
661        bail!("project dir is not a directory: {}", dir.display());
662    }
663
664    Ok(dir)
665}
666
667fn render_clap_error(err: &clap::Error) -> Result<i32> {
668    let exit_code = err.exit_code();
669    err.print()?;
670    Ok(exit_code)
671}
672
673fn dispatch_install_chain(
674    ctx: &types::ProjectContext,
675    overrides: &resolver::ResolutionOverrides,
676    frozen: bool,
677    mode: cli::ChainModeFlags,
678    tasks: &[String],
679) -> Result<i32> {
680    let items = chain::parse::parse_task_list(tasks)?;
681
682    if !mode.parallel {
683        // Sequential (default): install is the chain head, then tasks run in
684        // order. `run_chain` pre-flights the task tokens *before* install, so
685        // a typo'd task name aborts ahead of the slow install step.
686        let mut all = vec![chain::ChainItem::install(frozen)];
687        all.extend(items);
688        return chain::exec::run_chain(
689            ctx,
690            overrides,
691            &chain::Chain {
692                mode: chain::ChainMode::Sequential,
693                items: all,
694                failure: overrides.failure_policy,
695            },
696        );
697    }
698
699    // Parallel post-install: install must finish first (it's the prerequisite,
700    // and the parallel executor refuses an install item as a sibling). So run
701    // install as the sequential head, then fan the tasks out in parallel.
702    // Pre-flight the task tokens up front to preserve the "typo aborts before
703    // install" guarantee the sequential path gets for free. `run_chain` below
704    // re-prechecks (it can't assume a caller did), but that pass runs after
705    // install; this loop is what gates the slow install. precheck_task is
706    // side-effect-free, so the redundant second pass is harmless.
707    for task in tasks {
708        cmd::run::precheck_task(ctx, overrides, task)?;
709    }
710    // Time the install step the same way the sequential path's synthetic
711    // install head is (run_chain -> emit_task_timing). Without this the
712    // imperative parallel pre-install bypasses the timing path, so
713    // `runner install -p ...` would print per-task timing but none for install
714    // while `-s` does. "install" matches ChainItem::install(..).display_name();
715    // emit_task_timing self-gates via timing_enabled (--quiet/--no-warnings).
716    let started = std::time::Instant::now();
717    let install_code = cmd::install(ctx, overrides, frozen)?;
718    cmd::emit_task_timing(overrides, "install", started.elapsed(), install_code);
719    let keep_going = matches!(overrides.failure_policy, chain::FailurePolicy::KeepGoing);
720    if install_code != 0 && !keep_going {
721        return Ok(install_code);
722    }
723    let task_code = chain::exec::run_chain(
724        ctx,
725        overrides,
726        &chain::Chain {
727            mode: chain::ChainMode::Parallel,
728            items,
729            failure: overrides.failure_policy,
730        },
731    )?;
732    // First failure wins, mirroring chain semantics: a failed install is the
733    // first failure even if a later task also fails.
734    Ok(if install_code != 0 {
735        install_code
736    } else {
737        task_code
738    })
739}
740
741fn dispatch_run(
742    ctx: &types::ProjectContext,
743    overrides: &resolver::ResolutionOverrides,
744    task: Option<String>,
745    args: Vec<String>,
746    mode: cli::ChainModeFlags,
747) -> Result<i32> {
748    if mode.sequential || mode.parallel {
749        let chain_mode = if mode.parallel {
750            chain::ChainMode::Parallel
751        } else {
752            chain::ChainMode::Sequential
753        };
754        let mut positionals: Vec<String> = Vec::new();
755        if let Some(t) = task {
756            positionals.push(t);
757        }
758        positionals.extend(args);
759        let items = chain::parse::parse_task_list(&positionals)?;
760        let c = chain::Chain {
761            mode: chain_mode,
762            items,
763            failure: overrides.failure_policy,
764        };
765        return chain::exec::run_chain(ctx, overrides, &c);
766    }
767    let Some(task) = task.as_deref() else {
768        bail!(
769            "task name required (drop -s/-p for single-task mode or supply at least one task name)"
770        );
771    };
772    if args.is_empty()
773        && let Some(code) = run_path_builtin_fallback(ctx, overrides, task)?
774    {
775        return Ok(code);
776    }
777    cmd::run(ctx, overrides, task, &args, None)
778}
779
780/// Run-path fallback for builtin verbs.
781///
782/// When a bare, arg-less `run`/`runner run` token names a built-in verb and
783/// no same-named task exists, run that built-in's default (no-flag) form,
784/// the same behavior the explicit `runner <verb>` subcommand provides. A
785/// project task of the same name takes precedence (handled by the early
786/// `has_task` return → falls through to `cmd::run`).
787///
788/// Returns `Ok(Some(code))` when the fallback handled the token, `Ok(None)`
789/// to fall through to `cmd::run` (task dispatch / PM-exec).
790///
791/// Qualified tokens (`source:verb`) carry the `source:` prefix, so they never
792/// match a bare verb arm and fall through untouched, no qualifier parsing
793/// needed here. `info` maps to a plain `list` (no deprecation warning): the
794/// deprecation is specific to the explicit `runner info` subcommand, and
795/// emitting it on the run path, where the user typed `run info`, would be
796/// misleading and would spuriously fire the GitHub Actions annotation.
797fn run_path_builtin_fallback(
798    ctx: &types::ProjectContext,
799    overrides: &resolver::ResolutionOverrides,
800    name: &str,
801) -> Result<Option<i32>> {
802    if has_task(ctx, name) {
803        return Ok(None);
804    }
805    let code = match name {
806        "install" => cmd::install(ctx, overrides, false)?,
807        "clean" => {
808            cmd::clean(ctx, false, false)?;
809            0
810        }
811        // `info` maps to a plain `list`: the deprecation warning is specific
812        // to the explicit `runner info` subcommand, not the run path.
813        "list" | "info" => {
814            cmd::list(ctx, overrides, false, false, None)?;
815            0
816        }
817        "completions" => {
818            cmd::completions(None, None)?;
819            0
820        }
821        _ => return Ok(None),
822    };
823    Ok(Some(code))
824}
825
826/// Validate `--schema-version=N` for schema-aware (`--json`) output.
827/// `clap` already bounds the flag to [`schema::SCHEMA_VERSION`]; this is a
828/// defensive second check so a future non-CLI caller can't slip an
829/// unsupported version past the JSON-producing commands.
830fn schema_version_for_json(json: bool, requested: Option<u32>) -> Result<u32> {
831    if json {
832        schema::validate_schema_version(requested.unwrap_or(schema::SCHEMA_VERSION))
833    } else {
834        Ok(schema::SCHEMA_VERSION)
835    }
836}
837
838/// Build [`resolver::ResolutionOverrides`] from a parsed CLI + loaded config.
839/// Lifted out of [`dispatch`] so the latter stays under clippy's
840/// `too_many_lines` budget; the chain-failure inputs come from whichever
841/// subcommand carries them (`Run` / `Install`), with `false` defaults for
842/// subcommands that don't.
843fn build_overrides(
844    cli: &cli::Cli,
845    loaded_config: Option<&config::LoadedConfig>,
846) -> Result<resolver::ResolutionOverrides> {
847    let (cli_keep_going, cli_kill_on_fail) = match cli.command.as_ref() {
848        Some(cli::Command::Run { failure, .. } | cli::Command::Install { failure, .. }) => {
849            (failure.keep_going, failure.kill_on_fail)
850        }
851        _ => (false, false),
852    };
853    let mut overrides = resolver::ResolutionOverrides::from_cli_and_env(
854        cli.global.pm_override.as_deref(),
855        cli.global.runner_override.as_deref(),
856        cli.global.fallback.as_deref(),
857        cli.global.on_mismatch.as_deref(),
858        resolver::DiagnosticFlags {
859            no_warnings: cli.global.no_warnings,
860            quiet: cli.global.quiet,
861            explain: cli.global.explain,
862        },
863        cli::ChainFailureFlags {
864            keep_going: cli_keep_going,
865            kill_on_fail: cli_kill_on_fail,
866        },
867        loaded_config,
868    )?;
869    apply_script_policy_flags(cli, &mut overrides);
870    Ok(overrides)
871}
872
873/// Layer the install-only `--no-scripts` / `--scripts` CLI flags onto the
874/// resolved [`resolver::ScriptPolicy`]. These flags are the top precedence
875/// level (CLI > env > config): `--no-scripts` forces
876/// [`resolver::ScriptPolicy::Deny`] and `--scripts` forces
877/// [`resolver::ScriptPolicy::Allow`], while neither leaves the env/config
878/// resolution untouched. clap marks the two mutually exclusive, so at most one
879/// is set. Threading them here (rather than as more `from_cli_and_env`
880/// arguments) keeps that constructor's signature stable.
881const fn apply_script_policy_flags(cli: &cli::Cli, overrides: &mut resolver::ResolutionOverrides) {
882    if let Some(cli::Command::Install {
883        no_scripts,
884        scripts,
885        ..
886    }) = cli.command.as_ref()
887    {
888        if *no_scripts {
889            overrides.script_policy = resolver::ScriptPolicy::Deny;
890        } else if *scripts {
891            overrides.script_policy = resolver::ScriptPolicy::Allow;
892        }
893    }
894}
895
896/// Lenient sibling of [`build_overrides`] used when strict parsing
897/// failed and the command is `doctor`: invalid env-sourced override
898/// values degrade to [`types::DetectionWarning`]s instead of killing
899/// the one command whose job is to report a broken environment.
900fn build_overrides_lenient(
901    cli: &cli::Cli,
902    loaded_config: Option<&config::LoadedConfig>,
903) -> Result<(resolver::ResolutionOverrides, Vec<types::DetectionWarning>)> {
904    let (cli_keep_going, cli_kill_on_fail) = match cli.command.as_ref() {
905        Some(cli::Command::Run { failure, .. } | cli::Command::Install { failure, .. }) => {
906            (failure.keep_going, failure.kill_on_fail)
907        }
908        _ => (false, false),
909    };
910    resolver::ResolutionOverrides::from_cli_and_env_lenient(
911        cli.global.pm_override.as_deref(),
912        cli.global.runner_override.as_deref(),
913        cli.global.fallback.as_deref(),
914        cli.global.on_mismatch.as_deref(),
915        resolver::DiagnosticFlags {
916            no_warnings: cli.global.no_warnings,
917            quiet: cli.global.quiet,
918            explain: cli.global.explain,
919        },
920        cli::ChainFailureFlags {
921            keep_going: cli_keep_going,
922            kill_on_fail: cli_kill_on_fail,
923        },
924        loaded_config,
925    )
926}
927
928/// Resolve overrides for [`dispatch`]. Strict for every command;
929/// `doctor` retries leniently on failure because it must survive the
930/// misconfigured environment it exists to diagnose; env garbage
931/// degrades to warnings appended to `ctx`, while CLI flag garbage
932/// re-raises from the lenient pass and stays fatal.
933fn dispatch_overrides(
934    cli: &cli::Cli,
935    loaded_config: Option<&config::LoadedConfig>,
936    ctx: &mut types::ProjectContext,
937) -> Result<resolver::ResolutionOverrides> {
938    match build_overrides(cli, loaded_config) {
939        Ok(overrides) => Ok(overrides),
940        Err(_) if matches!(cli.command, Some(cli::Command::Doctor { .. })) => {
941            let (overrides, env_warnings) = build_overrides_lenient(cli, loaded_config)?;
942            ctx.warnings.extend(env_warnings);
943            Ok(overrides)
944        }
945        Err(e) => Err(e),
946    }
947}
948
949fn dispatch(cli: cli::Cli, dir: &Path) -> Result<i32> {
950    let mut ctx = detect::detect(dir);
951    // A malformed `runner.toml` must not abort the `config` subcommand;
952    // `config validate`/`show` exist to inspect and repair exactly that
953    // file, and they re-load it with their own error handling. Unknown
954    // sections/fields are tolerated everywhere (forward compat) and surface
955    // as warnings; only an unreadable/syntactically-broken file or a
956    // wrong-typed known field still fails the parse here.
957    let loaded_config = match config::load(dir) {
958        Ok(loaded) => loaded,
959        Err(_) if matches!(cli.command, Some(cli::Command::Config { .. })) => None,
960        Err(e) => return Err(e),
961    };
962    if let Some(loaded) = &loaded_config {
963        ctx.warnings.extend(loaded.warnings.iter().cloned());
964    }
965    let mut overrides = dispatch_overrides(&cli, loaded_config.as_ref(), &mut ctx)?;
966    // The first point where a resolved root and the inherited marker are both
967    // in hand, so it is where the nesting question gets answered.
968    overrides.parent_warned = cmd::parent_warned_about(&ctx.root);
969
970    match cli.command {
971        None => cmd::info(&ctx, &overrides, false).map(|()| 0),
972        // `info` is a deprecated alias for `list`. Bare `runner` (the
973        // `None` arm above) keeps the dashboard; only the explicit verb
974        // is deprecated.
975        Some(cli::Command::Info { json }) => {
976            eprintln!(
977                "{} `runner info` is deprecated; use `runner list`",
978                "warn:".yellow().bold(),
979            );
980            // Under GitHub Actions, also emit a workflow-command
981            // annotation so the deprecation surfaces in the run summary
982            // / inline, not just buried in the step log. Kept on stderr
983            // so `runner info --json` stdout stays a clean pipe; the
984            // runner scans both streams for `::` commands.
985            if actions_rs::env::is_github_actions() {
986                eprintln!(
987                    "::warning title=Deprecation::`runner info` is deprecated; use `runner list`"
988                );
989            }
990            schema_version_for_json(json, cli.global.schema_version)?;
991            cmd::list(&ctx, &overrides, false, json, None)?;
992            Ok(0)
993        }
994        Some(cli::Command::Run {
995            task, args, mode, ..
996        }) => dispatch_run(&ctx, &overrides, task, args, mode),
997        Some(cli::Command::External(args)) => {
998            if args.is_empty() {
999                cmd::info(&ctx, &overrides, false)?;
1000                Ok(0)
1001            } else {
1002                cmd::run(&ctx, &overrides, &args[0], &args[1..], None)
1003            }
1004        }
1005        Some(cli::Command::Install {
1006            frozen,
1007            tasks,
1008            mode,
1009            ..
1010        }) if !tasks.is_empty() => dispatch_install_chain(&ctx, &overrides, frozen, mode, &tasks),
1011        Some(cli::Command::Install {
1012            frozen,
1013            mode,
1014            failure,
1015            ..
1016        }) => {
1017            // No post-install tasks, so the chain flags govern nothing; say so
1018            // rather than silently swallowing a `-p`/`-k` the user expected to
1019            // matter.
1020            if mode.sequential || mode.parallel || failure.keep_going || failure.kill_on_fail {
1021                eprintln!(
1022                    "{} chain flags (-s/-p/-k/-K) have no effect without post-install task names",
1023                    "note:".dimmed(),
1024                );
1025            }
1026            cmd::install(&ctx, &overrides, frozen)
1027        }
1028        Some(cli::Command::Clean {
1029            yes,
1030            include_framework,
1031        }) => {
1032            cmd::clean(&ctx, yes, include_framework)?;
1033            Ok(0)
1034        }
1035        Some(cli::Command::List { raw, json, source }) => {
1036            schema_version_for_json(json, cli.global.schema_version)?;
1037            cmd::list(&ctx, &overrides, raw, json, source.as_deref())?;
1038            Ok(0)
1039        }
1040        Some(cli::Command::Completions { shell, output }) => {
1041            cmd::completions(shell, output.as_deref())?;
1042            Ok(0)
1043        }
1044        #[cfg(feature = "man")]
1045        Some(cli::Command::Man { output }) => dispatch_man(output.as_deref()),
1046        #[cfg(feature = "schema")]
1047        Some(cli::Command::Schema { all, output }) => dispatch_schema(all, output.as_deref()),
1048        #[cfg(feature = "lsp")]
1049        Some(cli::Command::Lsp) => cmd::lsp::run(), // intercepted pre-detection
1050        Some(cli::Command::Doctor { json }) => {
1051            schema_version_for_json(json, cli.global.schema_version)?;
1052            cmd::doctor(&ctx, &overrides, json)?;
1053            Ok(0)
1054        }
1055        Some(cli::Command::Config { action }) => cmd::config(dir, action),
1056        Some(cli::Command::Why { task, json }) => {
1057            schema_version_for_json(json, cli.global.schema_version)?;
1058            cmd::why(&ctx, &overrides, &task, json)?;
1059            Ok(0)
1060        }
1061    }
1062}
1063
1064#[cfg(feature = "man")]
1065fn dispatch_man(output: Option<&Path>) -> Result<i32> {
1066    match output {
1067        Some(dir) => cmd::write_man_pages(dir)?,
1068        None => cmd::write_runner_page_to_stdout()?,
1069    }
1070    Ok(0)
1071}
1072
1073#[cfg(feature = "schema")]
1074fn dispatch_schema(all: bool, output: Option<&Path>) -> Result<i32> {
1075    cmd::write_schema(all, output)?;
1076    Ok(0)
1077}
1078
1079/// Whether the detected project defines a task with the given name.
1080fn has_task(ctx: &types::ProjectContext, name: &str) -> bool {
1081    ctx.tasks.iter().any(|task| task.name == name)
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086    use std::ffi::OsString;
1087    use std::fs;
1088    use std::path::{Path, PathBuf};
1089
1090    use super::{
1091        AliasBuiltin, VERSION, alias_builtin_request, bin_name_from_arg0, configured_project_dir,
1092        exit_code_for_error, expand_tilde_with, has_task, parse_cli, parse_run_alias_cli,
1093        release_url, requests_version, resolve_project_dir, run_alias_in_dir, run_in_dir,
1094        version_line,
1095    };
1096    use crate::cli;
1097    use crate::resolver::ResolveError;
1098    use crate::tool::test_support::TempDir;
1099    use crate::types::{Ecosystem, ProjectContext, Task, TaskSource};
1100
1101    #[test]
1102    fn exit_code_for_resolve_error_is_two() {
1103        let err: anyhow::Error = ResolveError::NoSignalsFound {
1104            ecosystem: Ecosystem::Node,
1105            soft: false,
1106        }
1107        .into();
1108
1109        assert_eq!(exit_code_for_error(&err), 2);
1110    }
1111
1112    #[test]
1113    fn exit_code_for_generic_error_is_one() {
1114        let err = anyhow::anyhow!("generic boom");
1115
1116        assert_eq!(exit_code_for_error(&err), 1);
1117    }
1118
1119    #[test]
1120    fn help_returns_zero_instead_of_exiting() {
1121        let code = run_in_dir(["runner", "--help"], Path::new("."))
1122            .expect("help should return an exit code");
1123
1124        assert_eq!(code, 0);
1125    }
1126
1127    #[test]
1128    fn invalid_args_return_non_zero_instead_of_exiting() {
1129        let code = run_in_dir(["runner", "--definitely-invalid"], Path::new("."))
1130            .expect("parse errors should return an exit code");
1131
1132        assert_ne!(code, 0);
1133    }
1134
1135    #[test]
1136    fn version_returns_zero_instead_of_exiting() {
1137        let code = run_in_dir(["runner", "--version"], Path::new("."))
1138            .expect("version should return an exit code");
1139
1140        assert_eq!(code, 0);
1141    }
1142
1143    #[test]
1144    fn requests_version_detects_top_level_version_flags() {
1145        assert!(requests_version(&[
1146            OsString::from("runner"),
1147            OsString::from("--version")
1148        ]));
1149        assert!(requests_version(&[
1150            OsString::from("runner"),
1151            OsString::from("-V")
1152        ]));
1153        assert!(!requests_version(&[
1154            OsString::from("runner"),
1155            OsString::from("info"),
1156            OsString::from("--version"),
1157        ]));
1158    }
1159
1160    #[test]
1161    fn release_url_points_to_version_tag() {
1162        assert_eq!(
1163            release_url(VERSION),
1164            format!("https://github.com/kjanat/runner/releases/tag/v{VERSION}")
1165        );
1166    }
1167
1168    #[test]
1169    fn version_line_wraps_bin_and_version_with_separate_links() {
1170        let line = version_line(&[OsString::from("runner")], true);
1171
1172        assert!(line.contains(
1173            "\u{1b}]8;;https://github.com/kjanat/runner\u{1b}\\runner\u{1b}]8;;\u{1b}\\"
1174        ));
1175        assert!(line.contains(&format!(
1176            "\u{1b}]8;;https://github.com/kjanat/runner/releases/tag/v{VERSION}\u{1b}\\{VERSION}\u{1b}]8;;\u{1b}\\"
1177        )));
1178    }
1179
1180    #[test]
1181    fn resolve_project_dir_uses_cwd_when_not_overridden() {
1182        let cwd = TempDir::new("runner-project-dir-default");
1183
1184        assert_eq!(
1185            resolve_project_dir(None, cwd.path()).expect("cwd should be accepted"),
1186            cwd.path()
1187        );
1188    }
1189
1190    #[test]
1191    fn resolve_project_dir_resolves_relative_paths_from_cwd() {
1192        let cwd = TempDir::new("runner-project-dir-cwd");
1193        fs::create_dir(cwd.path().join("child")).expect("child dir should be created");
1194
1195        let resolved = resolve_project_dir(Some(Path::new("child")), cwd.path())
1196            .expect("relative dir should resolve");
1197
1198        assert_eq!(resolved, cwd.path().join("child"));
1199    }
1200
1201    #[test]
1202    fn resolve_project_dir_rejects_missing_directories() {
1203        let cwd = TempDir::new("runner-project-dir-missing");
1204        let err = resolve_project_dir(Some(Path::new("missing")), cwd.path())
1205            .expect_err("missing dir should error");
1206
1207        assert!(err.to_string().contains("project dir does not exist"));
1208    }
1209
1210    #[test]
1211    fn expand_tilde_expands_leading_tilde_slash() {
1212        let home = Path::new("/home/example");
1213        assert_eq!(
1214            expand_tilde_with(Path::new("~/projects/recipe"), Some(home)),
1215            home.join("projects/recipe"),
1216        );
1217    }
1218
1219    #[test]
1220    fn expand_tilde_expands_bare_tilde() {
1221        let home = Path::new("/home/example");
1222        assert_eq!(expand_tilde_with(Path::new("~"), Some(home)), home);
1223    }
1224
1225    #[test]
1226    fn expand_tilde_leaves_other_paths_untouched() {
1227        let home = Path::new("/home/example");
1228        for raw in ["/abs/path", "relative/path", "~user/projects", "./~/foo"] {
1229            assert_eq!(
1230                expand_tilde_with(Path::new(raw), Some(home)),
1231                PathBuf::from(raw),
1232                "path {raw} should be unchanged",
1233            );
1234        }
1235    }
1236
1237    #[test]
1238    fn expand_tilde_without_home_is_noop() {
1239        assert_eq!(
1240            expand_tilde_with(Path::new("~/projects"), None),
1241            PathBuf::from("~/projects"),
1242        );
1243    }
1244
1245    #[test]
1246    fn resolve_project_dir_does_not_join_tilde_onto_cwd() {
1247        // Regression: `--dir=~/foo` arrives unexpanded, and previously the
1248        // tilde path was treated as relative and joined onto the cwd, yielding
1249        // a bogus `<cwd>/~/foo`. The cwd exists but `<cwd>/~/foo` must not, so
1250        // a non-expanding implementation would fail with a path containing the
1251        // literal tilde segment.
1252        let home_var = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1253        if std::env::var_os(home_var).is_none_or(|v| v.is_empty()) {
1254            // Without a home directory there is nothing to expand to; the pure
1255            // `expand_tilde_with` tests cover the no-home path instead.
1256            return;
1257        }
1258
1259        let cwd = TempDir::new("runner-project-dir-tilde");
1260        let err = resolve_project_dir(Some(Path::new("~/definitely-missing")), cwd.path())
1261            .expect_err("tilde dir should not resolve against cwd");
1262
1263        let message = err.to_string();
1264        assert!(message.contains("project dir does not exist"));
1265        // Use `join` rather than a hardcoded `/` so the guard is
1266        // path-separator agnostic (e.g. `\` on Windows).
1267        let joined_tilde = cwd.path().join("~");
1268        assert!(
1269            !message.contains(&joined_tilde.display().to_string()),
1270            "tilde must not be joined onto cwd: {message}",
1271        );
1272    }
1273
1274    #[test]
1275    fn configured_project_dir_prefers_flag_over_env() {
1276        let dir = configured_project_dir(
1277            Some(Path::new("flag-dir")),
1278            Some(std::ffi::OsStr::new("env-dir")),
1279        )
1280        .expect("dir should be selected");
1281
1282        assert_eq!(dir, PathBuf::from("flag-dir"));
1283    }
1284
1285    #[test]
1286    fn configured_project_dir_falls_back_to_env() {
1287        let dir = configured_project_dir(None, Some(std::ffi::OsStr::new("env-dir")))
1288            .expect("env dir should be selected");
1289
1290        assert_eq!(dir, PathBuf::from("env-dir"));
1291    }
1292
1293    #[test]
1294    fn bin_name_from_arg0_uses_path_file_name() {
1295        let name = bin_name_from_arg0(&OsString::from("/tmp/run"));
1296
1297        assert_eq!(name.as_deref(), Some("run"));
1298    }
1299
1300    #[test]
1301    fn bin_name_from_arg0_strips_windows_exe_suffix() {
1302        // Windows builds inherit `runner.exe` / `run.exe` from argv[0]; clap
1303        // pipes that straight into `--version` / `--help` / Usage unless we
1304        // normalize it here. We feed bare file names rather than full Windows
1305        // paths because `Path::file_name` is host-OS-aware and won't split on
1306        // `\` when the tests run on Unix.
1307        let runner = bin_name_from_arg0(&OsString::from("runner.exe"));
1308        assert_eq!(runner.as_deref(), Some("runner"));
1309
1310        let run = bin_name_from_arg0(&OsString::from("run.exe"));
1311        assert_eq!(run.as_deref(), Some("run"));
1312    }
1313
1314    #[test]
1315    fn bin_name_from_arg0_strips_exe_case_insensitive() {
1316        let upper = bin_name_from_arg0(&OsString::from("RUNNER.EXE"));
1317        assert_eq!(upper.as_deref(), Some("RUNNER"));
1318
1319        let mixed = bin_name_from_arg0(&OsString::from("Run.Exe"));
1320        assert_eq!(mixed.as_deref(), Some("Run"));
1321    }
1322
1323    #[test]
1324    fn bin_name_from_arg0_preserves_unrelated_extensions() {
1325        // `.exe` only, names that happen to embed those characters in other
1326        // positions, or carry different extensions, pass through unchanged.
1327        let dotted = bin_name_from_arg0(&OsString::from("/tmp/runner.exe.bak"));
1328        assert_eq!(dotted.as_deref(), Some("runner.exe.bak"));
1329
1330        let other = bin_name_from_arg0(&OsString::from("/tmp/runner.sh"));
1331        assert_eq!(other.as_deref(), Some("runner.sh"));
1332    }
1333
1334    #[test]
1335    fn bin_name_from_arg0_handles_bare_dot_exe() {
1336        // `.exe` alone shouldn't strip to an empty name; the suffix length
1337        // guard keeps the input intact.
1338        let bare = bin_name_from_arg0(&OsString::from(".exe"));
1339        assert_eq!(bare.as_deref(), Some(".exe"));
1340    }
1341
1342    fn stub_context(tasks: &[&str]) -> ProjectContext {
1343        ProjectContext {
1344            root: PathBuf::from("."),
1345            package_managers: Vec::new(),
1346            task_runners: Vec::new(),
1347            tasks: tasks
1348                .iter()
1349                .map(|name| Task {
1350                    name: (*name).to_string(),
1351                    source: TaskSource::PackageJson,
1352                    run_target: None,
1353                    description: None,
1354                    alias_of: None,
1355                    passthrough_to: None,
1356                })
1357                .collect(),
1358            node_version: None,
1359            current_node: None,
1360            is_monorepo: false,
1361            install_dirs: Vec::new(),
1362            warnings: Vec::new(),
1363        }
1364    }
1365
1366    #[test]
1367    fn has_task_returns_true_for_existing_task() {
1368        let ctx = stub_context(&["clean", "install"]);
1369
1370        assert!(has_task(&ctx, "clean"));
1371        assert!(has_task(&ctx, "install"));
1372        assert!(!has_task(&ctx, "build"));
1373    }
1374
1375    #[test]
1376    fn run_alias_parses_builtin_names_as_tasks() {
1377        for name in [
1378            "clean",
1379            "install",
1380            "list",
1381            "exec",
1382            "info",
1383            "completions",
1384            "run",
1385        ] {
1386            let cli = parse_run_alias_cli(["run", name])
1387                .unwrap_or_else(|e| panic!("run {name} should parse: {e}"));
1388
1389            assert_eq!(cli.task.as_deref(), Some(name));
1390            assert!(cli.args.is_empty());
1391        }
1392    }
1393
1394    #[test]
1395    fn run_alias_forwards_trailing_args() {
1396        let cli = parse_run_alias_cli(["run", "test", "--watch", "--reporter=verbose"])
1397            .expect("run test --watch --reporter=verbose should parse");
1398
1399        assert_eq!(cli.task.as_deref(), Some("test"));
1400        assert_eq!(cli.args, vec!["--watch", "--reporter=verbose"]);
1401    }
1402
1403    #[test]
1404    fn run_alias_bare_has_no_task() {
1405        let cli = parse_run_alias_cli(["run"]).expect("bare run should parse");
1406
1407        assert!(cli.task.is_none());
1408        assert!(cli.args.is_empty());
1409    }
1410
1411    #[test]
1412    fn run_alias_honours_dir_flag() {
1413        let cli = parse_run_alias_cli(["run", "--dir=other", "build"])
1414            .expect("run --dir=other build should parse");
1415
1416        assert_eq!(cli.global.project_dir, Some(PathBuf::from("other")));
1417        assert_eq!(cli.task.as_deref(), Some("build"));
1418    }
1419
1420    #[test]
1421    fn run_alias_bare_shows_info() {
1422        let dir = TempDir::new("runner-run-bare");
1423
1424        let code =
1425            run_alias_in_dir(["run"], dir.path()).expect("bare run should succeed on empty dir");
1426
1427        assert_eq!(code, 0);
1428    }
1429
1430    #[test]
1431    fn run_alias_dispatch_shares_override_building_with_runner() {
1432        // The alias now funnels through the same `dispatch` path as the
1433        // `runner` binary, so an invalid `--pm` surfaces the resolver's
1434        // "unknown package manager" error from the single shared override
1435        // builder instead of a second copy that could drift.
1436        let dir = TempDir::new("runner-run-alias-bad-pm");
1437        let err = run_alias_in_dir(["run", "--pm", "zoot", "build"], dir.path())
1438            .expect_err("unknown --pm should error through the shared dispatch path");
1439        assert!(
1440            format!("{err}").contains("unknown package manager"),
1441            "alias must reuse the runner override builder: {err}",
1442        );
1443    }
1444
1445    #[test]
1446    fn run_alias_bare_matches_bare_runner_dashboard() {
1447        // A bare `run` maps to `command: None`, the same project-dashboard
1448        // path bare `runner` takes; both succeed identically on an empty
1449        // directory.
1450        let dir = TempDir::new("runner-run-alias-bare-eq");
1451        let alias = run_alias_in_dir(["run"], dir.path()).expect("bare run should succeed");
1452        let runner = run_in_dir(["runner"], dir.path()).expect("bare runner should succeed");
1453        assert_eq!(alias, runner, "alias bare dispatch must match bare runner");
1454        assert_eq!(alias, 0);
1455    }
1456
1457    #[test]
1458    fn run_alias_bare_drops_chain_failure_flag() {
1459        // A bare `run -k` (chain-failure flag, no task, no `-s`/`-p`) is
1460        // classified bare -> `command: None`, so the inert chain-failure
1461        // flag is dropped before override building. With an opposite-polarity
1462        // `[chain].kill_on_fail = true` in config, the old eager builder kept
1463        // the CLI `-k` and resolve_failure_policy hit the cross-source
1464        // (keep+kill) conflict, erroring out. Dropping the flag avoids that:
1465        // the dashboard never reads the failure policy, so a clean exit 0 is
1466        // the correct outcome. Config-driven (not env) to stay parallel-safe.
1467        let dir = TempDir::new("runner-run-alias-bare-drop-flag");
1468        fs::write(
1469            dir.path().join(crate::config::CONFIG_FILENAME),
1470            "[chain]\nkill_on_fail = true\n",
1471        )
1472        .expect("write runner.toml");
1473
1474        let code = run_alias_in_dir(["run", "-k"], dir.path())
1475            .expect("bare `run -k` must not error on an opposite-polarity [chain] config");
1476        assert_eq!(code, 0, "bare dashboard ignores the dropped failure flag");
1477    }
1478
1479    #[test]
1480    fn run_alias_forwards_help_and_version_after_task() {
1481        // `run <task> --help/--version` must reach the task, not print
1482        // run's own help/version. The flag is an undefined hyphen token
1483        // after the first positional, so `args` (trailing_var_arg) keeps it.
1484        for flag in ["--help", "-h", "--version", "-V"] {
1485            let cli = parse_run_alias_cli(["run", "build", flag])
1486                .unwrap_or_else(|e| panic!("run build {flag} should parse: {e}"));
1487            assert_eq!(cli.task.as_deref(), Some("build"));
1488            assert_eq!(cli.args, vec![flag.to_string()]);
1489        }
1490    }
1491
1492    #[test]
1493    fn run_alias_forwards_interleaved_help_flag() {
1494        // A forwarded help flag keeps its position among the task's args.
1495        let cli = parse_run_alias_cli(["run", "build", "--foo", "--help", "--bar"])
1496            .expect("interleaved --help should parse and forward");
1497        assert_eq!(cli.task.as_deref(), Some("build"));
1498        assert_eq!(cli.args, vec!["--foo", "--help", "--bar"]);
1499    }
1500
1501    #[test]
1502    fn run_alias_double_dash_forwards_help_literally() {
1503        // `run <task> -- --help` keeps forwarding the literal flag (the `--`
1504        // separator itself is consumed by clap).
1505        let cli = parse_run_alias_cli(["run", "build", "--", "--help"])
1506            .expect("run build -- --help should parse");
1507        assert_eq!(cli.task.as_deref(), Some("build"));
1508        assert_eq!(cli.args, vec!["--help"]);
1509    }
1510
1511    #[test]
1512    fn run_alias_leading_builtins_classified_as_own_request() {
1513        // Before any task, a help/version flag can't fill the
1514        // hyphen-rejecting `task` positional (clap built-ins are disabled),
1515        // so it surfaces as UnknownArgument and is recognised as ours.
1516        for flag in ["--help", "-h"] {
1517            let err = parse_run_alias_cli(["run", flag])
1518                .expect_err("leading help flag should not parse as a task");
1519            assert!(
1520                matches!(alias_builtin_request(&err), Some(AliasBuiltin::Help)),
1521                "{flag} before a task should be classified as a help request",
1522            );
1523        }
1524        for flag in ["--version", "-V"] {
1525            let err = parse_run_alias_cli(["run", flag])
1526                .expect_err("leading version flag should not parse as a task");
1527            assert!(
1528                matches!(alias_builtin_request(&err), Some(AliasBuiltin::Version)),
1529                "{flag} before a task should be classified as a version request",
1530            );
1531        }
1532    }
1533
1534    #[test]
1535    fn run_alias_global_flag_before_help_still_classified_as_help() {
1536        // `run --pm npm --help`: the value-taking global flag is consumed,
1537        // then --help still lands before any task → run's own help.
1538        let err = parse_run_alias_cli(["run", "--pm", "npm", "--help"])
1539            .expect_err("--pm npm --help should not parse as a task");
1540        assert!(matches!(
1541            alias_builtin_request(&err),
1542            Some(AliasBuiltin::Help)
1543        ));
1544    }
1545
1546    #[test]
1547    fn run_alias_unknown_flag_is_not_a_builtin_request() {
1548        // A genuine unknown flag must surface as an error, never be
1549        // mistaken for a help/version request.
1550        let err = parse_run_alias_cli(["run", "--bogus"])
1551            .expect_err("unknown leading flag should not parse");
1552        assert!(alias_builtin_request(&err).is_none());
1553    }
1554
1555    #[test]
1556    fn run_alias_own_help_and_version_return_zero() {
1557        // End-to-end through dispatch: own help/version exit 0 without
1558        // needing a real project. `--pm npm --version` is len > 2 so it
1559        // bypasses the `requests_version` fast-path and exercises the
1560        // parse-error classification.
1561        let dir = TempDir::new("runner-run-builtin");
1562        assert_eq!(
1563            run_alias_in_dir(["run", "--help"], dir.path()).expect("run --help should succeed"),
1564            0,
1565        );
1566        assert_eq!(
1567            run_alias_in_dir(["run", "--pm", "npm", "--version"], dir.path())
1568                .expect("run --pm npm --version should succeed"),
1569            0,
1570        );
1571    }
1572
1573    #[test]
1574    fn runner_cli_still_parses_install_as_builtin_when_flag_set() {
1575        let cli = parse_cli(["runner", "install", "--frozen"]).expect("should parse");
1576
1577        match cli.command {
1578            Some(cli::Command::Install { frozen: true, .. }) => {}
1579            other => panic!("expected Install {{ frozen: true }}, got {other:?}"),
1580        }
1581    }
1582
1583    #[test]
1584    fn runner_cli_parses_install_frozen_short_flag() {
1585        let cli = parse_cli(["runner", "install", "-f"]).expect("should parse");
1586
1587        match cli.command {
1588            Some(cli::Command::Install { frozen: true, .. }) => {}
1589            other => panic!("expected Install {{ frozen: true }}, got {other:?}"),
1590        }
1591    }
1592
1593    #[test]
1594    fn runner_cli_parses_install_chain_flags_after_task_names() {
1595        // `runner install build test --kill-on-fail` must parse
1596        // `--kill-on-fail` as a chain-failure flag, not as a task name.
1597        // Regression for the `trailing_var_arg` consumption bug.
1598        let cli = parse_cli(["runner", "install", "build", "test", "-K"]).expect("parses");
1599        match cli.command {
1600            Some(cli::Command::Install {
1601                tasks,
1602                failure:
1603                    cli::ChainFailureFlags {
1604                        kill_on_fail: true, ..
1605                    },
1606                ..
1607            }) => assert_eq!(tasks, vec!["build".to_string(), "test".to_string()]),
1608            other => {
1609                panic!("expected Install with kill_on_fail=true and clean task list, got {other:?}")
1610            }
1611        }
1612    }
1613
1614    #[test]
1615    fn runner_cli_parses_clean_as_builtin_when_flag_set() {
1616        let cli = parse_cli(["runner", "clean", "-y"]).expect("should parse");
1617
1618        match cli.command {
1619            Some(cli::Command::Clean { yes: true, .. }) => {}
1620            other => panic!("expected Clean {{ yes: true, .. }}, got {other:?}"),
1621        }
1622    }
1623
1624    #[test]
1625    fn runner_cli_routes_unknown_name_to_external() {
1626        let cli = parse_cli(["runner", "no-such-builtin"]).expect("should parse");
1627
1628        match cli.command {
1629            Some(cli::Command::External(args)) => {
1630                assert_eq!(args, vec!["no-such-builtin"]);
1631            }
1632            other => panic!("expected External, got {other:?}"),
1633        }
1634    }
1635
1636    #[test]
1637    fn runner_cli_parses_pm_and_runner_overrides_globally() {
1638        let cli = parse_cli(["runner", "--pm", "pnpm", "--runner", "just", "run", "build"])
1639            .expect("global --pm/--runner should parse on the run subcommand");
1640
1641        assert_eq!(cli.global.pm_override.as_deref(), Some("pnpm"));
1642        assert_eq!(cli.global.runner_override.as_deref(), Some("just"));
1643        match cli.command {
1644            Some(cli::Command::Run { task, args, .. }) => {
1645                assert_eq!(task.as_deref(), Some("build"));
1646                assert!(args.is_empty());
1647            }
1648            other => panic!("expected Run, got {other:?}"),
1649        }
1650    }
1651
1652    #[test]
1653    fn run_alias_parses_pm_override() {
1654        let cli =
1655            parse_run_alias_cli(["run", "--pm=bun", "test"]).expect("--pm=bun test should parse");
1656
1657        assert_eq!(cli.global.pm_override.as_deref(), Some("bun"));
1658        assert_eq!(cli.task.as_deref(), Some("test"));
1659    }
1660
1661    #[test]
1662    fn invalid_pm_override_value_returns_error() {
1663        // Bad PM name should not crash the binary; it should surface as an
1664        // error exit code so the user sees the message from `from_cli_and_env`.
1665        let dir = TempDir::new("runner-bad-pm");
1666        let result = run_in_dir(["runner", "--pm", "zoot", "info"], dir.path());
1667
1668        let err = result.expect_err("unknown --pm should error");
1669        assert!(format!("{err}").contains("unknown package manager"));
1670    }
1671
1672    #[test]
1673    fn install_with_undetected_pm_override_exits_2() {
1674        // A cargo-only project with `--pm npm`: the override can't be
1675        // honored, so install must refuse with a ResolveError (exit 2)
1676        // before spawning anything.
1677        let dir = TempDir::new("runner-install-undetected-pm");
1678        fs::write(
1679            dir.path().join("Cargo.toml"),
1680            "[package]\nname = \"fixture\"\nversion = \"0.0.0\"\n",
1681        )
1682        .expect("write Cargo.toml");
1683
1684        let err = run_in_dir(["runner", "--pm", "npm", "install"], dir.path())
1685            .expect_err("undetected --pm should refuse the install");
1686
1687        assert_eq!(
1688            exit_code_for_error(&err),
1689            2,
1690            "ResolveError must map to exit 2"
1691        );
1692        let msg = format!("{err}");
1693        assert!(msg.contains("--pm"), "should name the source: {msg}");
1694        assert!(msg.contains("cargo"), "should list detected PMs: {msg}");
1695    }
1696
1697    #[test]
1698    fn install_chain_with_undetected_pm_override_exits_2() {
1699        // Same refusal through the chain path (`runner install <task>`).
1700        let dir = TempDir::new("runner-install-chain-undetected-pm");
1701        fs::write(
1702            dir.path().join("Cargo.toml"),
1703            "[package]\nname = \"fixture\"\nversion = \"0.0.0\"\n",
1704        )
1705        .expect("write Cargo.toml");
1706
1707        let err = run_in_dir(["runner", "--pm", "npm", "install", "build"], dir.path())
1708            .expect_err("undetected --pm should refuse the install chain");
1709
1710        assert_eq!(
1711            exit_code_for_error(&err),
1712            2,
1713            "ResolveError must map to exit 2"
1714        );
1715    }
1716
1717    #[test]
1718    fn schema_version_rejects_invalid_for_non_json_commands() {
1719        let dir = TempDir::new("runner-schema-invalid-completions");
1720
1721        let code = run_in_dir(
1722            ["runner", "--schema-version", "99", "completions", "bash"],
1723            dir.path(),
1724        )
1725        .expect("parse errors should return an exit code");
1726
1727        assert_ne!(code, 0);
1728    }
1729
1730    #[test]
1731    fn schema_version_rejects_invalid_for_run_alias_bare_info() {
1732        let dir = TempDir::new("runner-schema-invalid-run-alias");
1733
1734        let code = run_alias_in_dir(["run", "--schema-version", "99"], dir.path())
1735            .expect("parse errors should return an exit code");
1736
1737        assert_ne!(code, 0);
1738    }
1739
1740    #[test]
1741    fn schema_version_rejects_invalid_for_json_output() {
1742        let dir = TempDir::new("runner-schema-json-invalid");
1743
1744        let code = run_in_dir(
1745            ["runner", "--schema-version", "99", "info", "--json"],
1746            dir.path(),
1747        )
1748        .expect("parse errors should return an exit code");
1749
1750        assert_ne!(code, 0);
1751    }
1752
1753    #[test]
1754    fn runner_cli_parses_completions_output_long() {
1755        let cli = parse_cli(["runner", "completions", "--output", "/tmp/runner.zsh"])
1756            .expect("should parse");
1757
1758        match cli.command {
1759            Some(cli::Command::Completions {
1760                shell: None,
1761                output: Some(path),
1762            }) => assert_eq!(path, PathBuf::from("/tmp/runner.zsh")),
1763            other => panic!("expected Completions with --output long form, got {other:?}"),
1764        }
1765    }
1766
1767    #[test]
1768    fn runner_cli_parses_completions_output_short() {
1769        let cli =
1770            parse_cli(["runner", "completions", "-o", "/tmp/runner.zsh"]).expect("should parse");
1771
1772        match cli.command {
1773            Some(cli::Command::Completions {
1774                shell: None,
1775                output: Some(path),
1776            }) => assert_eq!(path, PathBuf::from("/tmp/runner.zsh")),
1777            other => panic!("expected Completions with -o short form, got {other:?}"),
1778        }
1779    }
1780
1781    #[test]
1782    fn runner_cli_parses_completions_shell_and_output() {
1783        let cli = parse_cli([
1784            "runner",
1785            "completions",
1786            "zsh",
1787            "--output",
1788            "/tmp/runner.zsh",
1789        ])
1790        .expect("should parse");
1791
1792        match cli.command {
1793            Some(cli::Command::Completions {
1794                shell: Some(_),
1795                output: Some(path),
1796            }) => assert_eq!(path, PathBuf::from("/tmp/runner.zsh")),
1797            other => panic!("expected Completions with both shell and output set, got {other:?}"),
1798        }
1799    }
1800}