Skip to main content

lux_cli/
lib.rs

1use crate::{completion::Completion, format::Fmt, project::NewProject};
2use std::error::Error;
3use std::path::PathBuf;
4
5use add::Add;
6use build::Build;
7use check::Check;
8use clap::{Parser, Subcommand};
9use config::ConfigCmd;
10use debug::Debug;
11use doc::Doc;
12use download::Download;
13use exec::Exec;
14use generate_rockspec::GenerateRockspec;
15use info::Info;
16use install::Install;
17use install_rockspec::InstallRockspec;
18use lint::Lint;
19use list::ListCmd;
20use lux_lib::lua_version::LuaVersion;
21use outdated::Outdated;
22use pack::Pack;
23use path::Path;
24use pin::ChangePin;
25use remove::Remove;
26use run::Run;
27use run_lua::RunLua;
28use search::Search;
29use shell::Shell;
30use sync::SyncProject;
31use test::Test;
32use uninstall::Uninstall;
33use update::Update;
34use upload::Upload;
35use url::Url;
36use vendor::Vendor;
37use which::Which;
38
39pub mod add;
40pub mod build;
41pub mod check;
42pub mod completion;
43pub mod config;
44pub mod debug;
45pub mod doc;
46pub mod download;
47pub mod exec;
48pub mod fetch;
49pub mod format;
50pub mod generate_rockspec;
51pub mod info;
52pub mod install;
53pub mod install_lua;
54pub mod install_rockspec;
55pub mod lint;
56pub mod list;
57pub mod outdated;
58pub mod pack;
59pub mod path;
60pub mod pin;
61pub mod project;
62pub mod purge;
63pub mod remove;
64pub mod run;
65pub mod run_lua;
66pub mod search;
67pub mod shell;
68pub mod sync;
69pub mod test;
70pub mod uninstall;
71pub mod unpack;
72pub mod update;
73pub mod upload;
74pub mod utils;
75pub mod vendor;
76pub mod which;
77
78/// A luxurious package manager for Lua.
79#[derive(Parser)]
80#[command(author, version, about, long_about = None, arg_required_else_help = true)]
81pub struct Cli {
82    /// Enable the sub-repositories in luarocks servers for rockspecs of in-development versions.
83    #[arg(long)]
84    pub dev: bool,
85
86    /// Fetch rocks/rockspecs from this server (takes priority over config file).
87    #[arg(long, value_name = "server")]
88    pub server: Option<Url>,
89
90    /// Fetch rocks/rockspecs from this server in addition to the main server{n}
91    /// (overrides any entries in the config file).
92    #[arg(long, value_name = "extra-server")]
93    pub extra_servers: Option<Vec<Url>>,
94
95    /// Restrict downloads to paths matching the given URL.
96    #[arg(long, value_name = "url")]
97    pub only_sources: Option<String>,
98
99    /// Specify the luarocks server namespace to use.
100    #[arg(long, value_name = "namespace")]
101    pub namespace: Option<String>,
102
103    /// Specify the directory in which to install Lua{n}
104    /// if not found.
105    #[arg(long, value_name = "prefix")]
106    pub lua_dir: Option<PathBuf>,
107
108    /// Which Lua installation to use.{n}
109    /// Valid versions are: '5.1', '5.2', '5.3', '5.4', 'jit' and 'jit52'.
110    #[arg(long, value_name = "ver")]
111    pub lua_version: Option<LuaVersion>,
112
113    /// Which tree to operate on.
114    #[arg(long, value_name = "tree")]
115    pub tree: Option<PathBuf>,
116
117    /// Specifies the cache directory for e.g. luarocks manifests.
118    #[arg(long, value_name = "cache-dir")]
119    pub cache_dir: Option<PathBuf>,
120
121    /// Specifies the data directory (e.g. ~/.local/share/lux).
122    #[arg(long, value_name = "data-dir")]
123    pub data_dir: Option<PathBuf>,
124
125    /// Specifies a directory with locally vendored sources and RockSpecs.{n}
126    /// When building or installing a package with this flag,{n}
127    /// Lux will fetch sources from the <vendor-dir> instead of from a remote server.
128    #[arg(long, value_name = "vendor-dir")]
129    pub vendor_dir: Option<PathBuf>,
130
131    /// Override config variables.{n}
132    /// Example: `lx -v "LUA=/path/to/lua" ...`
133    #[arg(long, value_name = "variable", visible_short_alias = 'v', value_parser = parse_key_val::<String, String>)]
134    pub variables: Option<Vec<(String, String)>>,
135
136    /// Display verbose output of commands executed.
137    #[arg(long)]
138    pub verbose: bool,
139
140    /// Don't print any progress bars or spinners.
141    #[arg(long)]
142    pub no_progress: bool,
143
144    /// Configure lux for installing Neovim packages.
145    #[arg(long)]
146    pub nvim: bool,
147
148    /// Timeout on network operations, in seconds.{n}
149    /// 0 means no timeout (wait forever). Default is 30.
150    #[arg(long, value_name = "seconds")]
151    pub timeout: Option<usize>,
152
153    /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
154    /// 0 means no limit. Default is 0.
155    #[arg(long, visible_short_alias = 'j')]
156    pub max_jobs: Option<usize>,
157
158    /// Do not generate or update a `.luarc.json` file when building{n}
159    /// a project.
160    #[arg(long)]
161    pub no_luarc: bool,
162
163    #[command(subcommand)]
164    pub command: Commands,
165}
166
167#[derive(Subcommand)]
168pub enum Commands {
169    /// Add a dependency to the current project.
170    Add(Add),
171    /// Build/compile a project.
172    Build(Build),
173    /// [EXPERIMENTAL]{n}
174    /// Type check the current project based on EmmyLua/LuaCATS annotations.{n}
175    /// Respects `.emmyrc.json` and `.luarc.json` files in the project directory.
176    Check(Check),
177    /// Interact with the lux configuration.
178    #[command(subcommand, arg_required_else_help = true)]
179    Config(ConfigCmd),
180    /// Generate autocompletion scripts for the shell.{n}
181    /// Example: `lx completion zsh > ~/.zsh/completions/_lx`
182    Completion(Completion),
183    /// Internal commands for debugging Lux itself.
184    #[command(subcommand, arg_required_else_help = true)]
185    Debug(Debug),
186    /// Show documentation for an installed rock.
187    Doc(Doc),
188    /// Download a specific rock file from a luarocks server.
189    #[command(arg_required_else_help = true)]
190    Download(Download),
191    /// Formats the codebase with stylua.
192    Fmt(Fmt),
193    /// Generate a rockspec file from a project.
194    GenerateRockspec(GenerateRockspec),
195    /// Show metadata for any rock.
196    Info(Info),
197    /// Install a rock for use on the system.
198    #[command(arg_required_else_help = true)]
199    Install(Install),
200    /// Install a local rockspec for use on the system.
201    #[command(arg_required_else_help = true)]
202    InstallRockspec(InstallRockspec),
203    /// Manually install and manage Lua headers for various Lua versions.
204    InstallLua,
205    /// Lint the current project using `luacheck`.
206    Lint(Lint),
207    /// List currently installed rocks.
208    List(ListCmd),
209    /// Run lua, with the `LUA_PATH` and `LUA_CPATH` set to the specified lux tree.
210    Lua(RunLua),
211    /// Create a new Lua project.
212    New(NewProject),
213    /// List outdated rocks.
214    Outdated(Outdated),
215    /// Create a packed rock for distribution, packing sources or binaries.
216    Pack(Pack),
217    /// Return the currently configured package path.
218    Path(Path),
219    /// Pin an existing rock, preventing any updates to the package.
220    Pin(ChangePin),
221    /// Remove all installed rocks from a tree.
222    Purge,
223    /// Remove a rock from the current project's lux.toml dependencies.
224    Remove(Remove),
225    /// Run the current project with the provided arguments.
226    Run(Run),
227    /// Execute a command that has been installed with lux.
228    /// If the command is not found, a package named after the command
229    /// will be installed.
230    Exec(Exec),
231    /// Query the luarocks servers.
232    #[command(arg_required_else_help = true)]
233    Search(Search),
234    /// Run the test suite in the current project directory.{n}
235    /// Lux supports the following test backends, specified by the `[test]` table in the lux.toml:{n}
236    /// {n}
237    ///   - busted:{n}
238    ///     {n}
239    ///     https://lunarmodules.github.io/busted/{n}
240    ///     {n}
241    ///     Example:{n}
242    ///     {n}
243    ///     ```toml{n}
244    ///     [test]{n}
245    ///     type = "busted"{n}
246    ///     flags = [ ] # Optional CLI flags to pass to busted{n}
247    ///     ```{n}
248    ///     {n}
249    ///     `lx test` will default to using `busted` if no test backend is specified and:{n}
250    ///         * there is a `.busted` file in the project root{n}
251    ///         * or `busted` is one of the `test_dependencies`).{n}
252    /// {n}
253    ///   - busted-nlua:{n}:
254    ///     {n}
255    ///     [currently broken on Windows]{n}
256    ///     A build backend for running busted tests with Neovim as the Lua interpreter.
257    ///     Used for testing Neovim plugins.
258    ///     {n}
259    ///     Example:{n}
260    ///     {n}
261    ///     ```toml{n}
262    ///     [test]{n}
263    ///     type = "busted-nlua"{n}
264    ///     flags = [ ] # Optional CLI flags to pass to busted{n}
265    ///     ```{n}
266    ///     {n}
267    ///     `lx test` will default to using `busted-nlua` if no test backend is specified and:{n}
268    ///         * there is a `.busted` file in the project root{n}
269    ///         * or `busted` and `nlua` are `test_dependencies`.{n}
270    /// {n}
271    ///   - command:{n}
272    ///     {n}
273    ///     Name/file name of a shell command that will run the test suite.{n}
274    ///     Example:{n}
275    ///     {n}
276    ///     ```toml{n}
277    ///     [test]{n}
278    ///     type = "command"{n}
279    ///     command = "make"{n}
280    ///     flags = [ "test" ]{n}
281    ///     ```{n}
282    ///     {n}
283    ///   - script:{n}
284    ///     {n}
285    ///     Relative path to a Lua script that will run the test suite.{n}
286    ///     Example:{n}
287    ///     {n}
288    ///     ```toml{n}
289    ///     [test]{n}
290    ///     type = "script"{n}
291    ///     script = "tests.lua" # Expects a tests.lua file in the project root{n}
292    ///     flags = [ ] # Optional arguments passed to the test script{n}
293    ///     ```{n}
294    Test(Test),
295    /// Uninstall a rock from the system.
296    Uninstall(Uninstall),
297    /// Unpins an existing rock, allowing updates to alter the package.
298    Unpin(ChangePin),
299    /// Updates all rocks in a project.
300    Update(Update),
301    /// Generate a Lua rockspec for a Lux project and upload it to the public luarocks repository.{n}
302    /// You can specify a source template for release and dev packages in the lux.toml.{n}
303    /// {n}
304    /// Example:{n}
305    /// {n}
306    /// ```toml{n}
307    /// [source]{n}
308    /// url = "https://host.com/owner/$(PACKAGE)/refs/tags/$(REF).zip"{n}
309    /// dev = "git+https://host.com/owner/$(PACKAGE).git"{n}
310    /// ```{n}
311    /// {n}
312    /// You can use the following variables in the source template:{n}
313    /// {n}
314    ///  - $(PACKAGE): The package name.{n}
315    ///  - $(VERSION): The package version.{n}
316    ///  - $(REF): The git tag or revision (if in a git repository).{n}
317    ///  - You may also specify environment variables with `$(<VAR_NAME>)`.{n}
318    /// {n}
319    /// If the `version` is not set in the lux.toml, lux will search the current
320    /// commit for SemVer tags and if found, will use it to generate the package version.
321    Upload(Upload),
322    /// Vendor the dependencies of a project or RockSpec locally.
323    /// When building or installing a package with the `--vendor-dir` option{n}
324    /// or the `[vendor_dir]` config option, Lux will fetch sources from the <vendor-dir>{n}
325    /// instead of from a remote server.
326    Vendor(Vendor),
327    /// Tell which file corresponds to a given module name.
328    Which(Which),
329    /// Spawns an interactive shell with PATH, LUA_PATH, LUA_CPATH and LUA_INIT set.
330    Shell(Shell),
331    /// Synchronize the project tree with the current lux.toml,{n}
332    /// ensuring all packages are installed correctly.
333    Sync(SyncProject),
334}
335
336/// Parse a key=value pair.
337fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
338where
339    T: std::str::FromStr,
340    T::Err: Error + Send + Sync + 'static,
341    U: std::str::FromStr,
342    U::Err: Error + Send + Sync + 'static,
343{
344    let pos = s
345        .find('=')
346        .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
347    Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
348}