Skip to main content

pkl_cli/
lib.rs

1//! Product `pkl` CLI library for Apple Pkl 0.32.0.
2//!
3//! Dispatches all Apple Pkl 0.32.0 subcommands (`eval`, `repl`, `server`, `test`,
4//! `project resolve`, `project package`, `download-package`, `analyze imports`,
5//! `format`, `run`, `shell-completion`) with byte-exact help, errors, and honest
6//! native-flavor `--version` output.
7
8mod env;
9mod eval_cmd;
10mod format_cmd;
11mod help;
12mod options;
13mod repl_cmd;
14mod run_cmd;
15mod test_cmd;
16
17use crate::help::{
18    COMPLETION_BASH, COMPLETION_FISH, COMPLETION_ZSH, HELP_ANALYZE, HELP_PROJECT, HELP_ROOT,
19    HELP_SERVER, HELP_SHELL_COMPLETION,
20};
21use crate::options::CliError;
22use std::io::{self, Write};
23
24const ROOT_USAGE: &str = "Usage: pkl [<options>] <command> [<args>]...";
25const ROOT_SUBCOMMANDS: &str =
26    "eval, repl, server, test, project, download-package, analyze, format, run, shell-completion";
27
28/// Main entry point for the `pkl` product CLI binary (arguments after `argv[0]`).
29pub fn run_cli(args: &[String]) -> i32 {
30    let outcome = dispatch(args);
31    match outcome {
32        Ok(code) => code,
33        Err(CliError::Silent(code)) => code,
34        Err(CliError::Message { text, exit_code }) => {
35            let mut stderr = io::stderr().lock();
36            let _ = stderr.write_all(text.as_bytes());
37            if !text.ends_with('\n') {
38                let _ = stderr.write_all(b"\n");
39            }
40            let _ = stderr.flush();
41            exit_code
42        }
43    }
44}
45
46fn dispatch(args: &[String]) -> Result<i32, CliError> {
47    let Some(first) = args.first().map(String::as_str) else {
48        write_help(HELP_ROOT);
49        return Ok(0);
50    };
51
52    match first {
53        "-v" | "--version" => {
54            let banner = pkl::Release::current().version_info();
55            write_stdout(&format!("{banner}\n"));
56            Ok(0)
57        }
58        "-h" | "--help" => {
59            write_help(HELP_ROOT);
60            Ok(0)
61        }
62        "eval" => eval_cmd::cmd_eval(&args[1..]),
63        "repl" => repl_cmd::cmd_repl(&args[1..]),
64        "server" => cmd_server(&args[1..]),
65        "test" => test_cmd::cmd_test(&args[1..]),
66        "project" => cmd_project(&args[1..]),
67        "download-package" => eval_cmd::cmd_download_package(&args[1..]),
68        "analyze" => cmd_analyze(&args[1..]),
69        "format" => format_cmd::cmd_format(&args[1..]),
70        "run" => run_cmd::cmd_run(&args[1..]),
71        "shell-completion" => cmd_shell_completion(&args[1..]),
72        other if other.starts_with('-') => Err(CliError::usage(
73            ROOT_USAGE,
74            &format!("no such option {other}. (Possible options: -v, --version, -h, --help)"),
75        )),
76        other => Err(CliError::usage(
77            ROOT_USAGE,
78            &format!("no such subcommand {other}. (Possible subcommands: {ROOT_SUBCOMMANDS})"),
79        )),
80    }
81}
82
83fn cmd_server(args: &[String]) -> Result<i32, CliError> {
84    const USAGE: &str = "Usage: pkl server [<options>]";
85    if args.iter().any(|a| a == "-h" || a == "--help") {
86        write_help(HELP_SERVER);
87        return Ok(0);
88    }
89    if let Some(arg) = args.first() {
90        return if arg.starts_with('-') {
91            Err(CliError::usage(USAGE, &format!("no such option {arg}")))
92        } else {
93            Err(CliError::usage(
94                USAGE,
95                &format!("got unexpected extra argument ({arg})"),
96            ))
97        };
98    }
99    Ok(pkl_server::run_cli_server())
100}
101
102fn cmd_project(args: &[String]) -> Result<i32, CliError> {
103    const USAGE: &str = "Usage: pkl project [<options>] <command> [<args>]...";
104    let Some(first) = args.first().map(String::as_str) else {
105        write_help(HELP_PROJECT);
106        return Ok(0);
107    };
108    match first {
109        "-h" | "--help" => {
110            write_help(HELP_PROJECT);
111            Ok(0)
112        }
113        "resolve" => eval_cmd::cmd_project_resolve(&args[1..]),
114        "package" => eval_cmd::cmd_project_package(&args[1..]),
115        other if other.starts_with('-') => {
116            Err(CliError::usage(USAGE, &format!("no such option {other}")))
117        }
118        other => Err(CliError::usage(
119            USAGE,
120            &format!("no such subcommand {other}. (Possible subcommands: resolve, package)"),
121        )),
122    }
123}
124
125fn cmd_analyze(args: &[String]) -> Result<i32, CliError> {
126    const USAGE: &str = "Usage: pkl analyze [<options>] <command> [<args>]...";
127    let Some(first) = args.first().map(String::as_str) else {
128        write_help(HELP_ANALYZE);
129        return Ok(0);
130    };
131    match first {
132        "-h" | "--help" => {
133            write_help(HELP_ANALYZE);
134            Ok(0)
135        }
136        "imports" => eval_cmd::cmd_analyze_imports(&args[1..]),
137        other if other.starts_with('-') => {
138            Err(CliError::usage(USAGE, &format!("no such option {other}")))
139        }
140        other => Err(CliError::usage(
141            USAGE,
142            &format!("no such subcommand {other}. (Possible subcommands: imports)"),
143        )),
144    }
145}
146
147fn cmd_shell_completion(args: &[String]) -> Result<i32, CliError> {
148    const USAGE: &str = "Usage: pkl shell-completion [<options>] <shell>";
149    let mut positionals = Vec::new();
150    let mut end_of_flags = false;
151    for arg in args {
152        if !end_of_flags && arg == "--" {
153            end_of_flags = true;
154            continue;
155        }
156        if !end_of_flags && (arg == "-h" || arg == "--help") {
157            write_help(HELP_SHELL_COMPLETION);
158            return Ok(0);
159        }
160        if !end_of_flags && arg.starts_with('-') && arg != "-" {
161            return Err(CliError::usage(USAGE, &format!("no such option {arg}")));
162        }
163        positionals.push(arg.as_str());
164    }
165    let Some(&shell) = positionals.first() else {
166        return Err(CliError::usage(USAGE, "missing argument <shell>"));
167    };
168    if positionals.len() > 1 {
169        let extra = &positionals[1..];
170        let msg = if extra.len() == 1 {
171            format!("got unexpected extra argument ({})", extra[0])
172        } else {
173            format!("got unexpected extra arguments ({})", extra.join(" "))
174        };
175        return Err(CliError::usage(USAGE, &msg));
176    }
177    match shell {
178        "bash" => {
179            write_stdout(COMPLETION_BASH);
180            Ok(0)
181        }
182        "zsh" => {
183            write_stdout(COMPLETION_ZSH);
184            Ok(0)
185        }
186        "fish" => {
187            write_stdout(COMPLETION_FISH);
188            Ok(0)
189        }
190        other => Err(CliError::usage(
191            USAGE,
192            &format!(
193                "invalid value for <shell>: invalid choice: {other}. (choose from bash, zsh, fish)"
194            ),
195        )),
196    }
197}
198
199pub(crate) fn write_help(plain_help: &str) {
200    let level = pkl_runtime::diagnostic::mordant::detect_ansi_level();
201    let rendered = pkl_runtime::diagnostic::mordant::colorize_clikt_help(plain_help, level);
202    write_stdout(&rendered);
203}
204
205fn write_stdout(text: &str) {
206    let mut stdout = io::stdout().lock();
207    let _ = stdout.write_all(text.as_bytes());
208    let _ = stdout.flush();
209}