Skip to main content

lux_cli/
lib.rs

1use crate::{
2    args::{PackageOrRockspec, Preset},
3    dist::{Bin, Dist, FlatArchive},
4    format::Fmt,
5    project::NewProject,
6    util::Util,
7};
8use lux_lib::package;
9use miette::Result;
10use std::error::Error;
11use std::path::PathBuf;
12
13use add::Add;
14use build::Build;
15use check::Check;
16use clap::{Parser, Subcommand};
17use config::ConfigCmd;
18use debug::Debug;
19use doc::Doc;
20use download::Download;
21use exec::Exec;
22use generate_rockspec::GenerateRockspec;
23use info::Info;
24use install::Install;
25use install_rockspec::InstallRockspec;
26use lint::Lint;
27use list::ListCmd;
28use lux_lib::{config::ConfigBuilder, lua_version::LuaVersion, workspace::Workspace};
29use miette::IntoDiagnostic;
30use outdated::Outdated;
31use pack::Pack;
32use path::Path;
33use pin::ChangePin;
34use remove::Remove;
35use run::Run;
36use run_lua::RunLua;
37use search::Search;
38use shell::Shell;
39use strum::IntoEnumIterator;
40use sync::SyncProject;
41use test::Test;
42use uninstall::Uninstall;
43use update::Update;
44use upload::Upload;
45use url::Url;
46use vendor::Vendor;
47use which::Which;
48
49pub mod add;
50pub mod args;
51pub mod build;
52pub mod check;
53pub mod config;
54pub mod debug;
55pub mod dist;
56pub mod doc;
57pub mod download;
58pub mod exec;
59pub mod fetch;
60pub mod format;
61pub mod generate_lockfile;
62pub mod generate_rockspec;
63pub mod info;
64pub mod install;
65pub mod install_lua;
66pub mod install_rockspec;
67pub mod lint;
68pub mod list;
69pub mod outdated;
70pub mod pack;
71pub mod path;
72pub mod pin;
73pub mod progress;
74pub mod project;
75pub mod purge;
76pub mod remove;
77pub mod run;
78pub mod run_lua;
79pub mod search;
80pub mod shell;
81pub mod sync;
82pub mod test;
83pub mod uninstall;
84pub mod unpack;
85pub mod update;
86pub mod upload;
87pub mod util;
88pub mod utils;
89pub mod vendor;
90pub mod which;
91pub mod workspace;
92
93/// A luxurious package manager for Lua.
94#[derive(Parser)]
95#[command(author, version, about, long_about = None, arg_required_else_help = true)]
96pub struct Cli {
97    /// Enable the sub-repositories in luarocks servers for rockspecs of in-development versions.
98    #[arg(long)]
99    pub dev: bool,
100
101    /// Fetch rocks/rockspecs from this server (takes priority over config file).
102    #[arg(long, global = true, value_name = "server")]
103    pub server: Option<Url>,
104
105    /// Fetch rocks/rockspecs from these servers in addition to the main server{n}
106    /// (overrides any entries in the config file).
107    #[arg(long, global = true, value_name = "extra-server")]
108    pub extra_servers: Option<Vec<Url>>,
109
110    /// Specify the luarocks server namespace to use.
111    #[arg(long, global = true, value_name = "namespace")]
112    pub namespace: Option<String>,
113
114    /// Specify the directory in which to install Lua if not found.
115    #[arg(long, global = true, value_name = "prefix")]
116    pub lua_dir: Option<PathBuf>,
117
118    /// Which Lua installation to use.{n}
119    /// Valid versions are: '5.1', '5.2', '5.3', '5.4', '5.5', 'jit' and 'jit52'.{n}
120    /// If not set, Lux will attempt to detect the Lua version:{n}
121    ///   - From the current project, if it has an exact Lua version requirement.{n}
122    ///   - From the Lua installation that is available on the PATH.
123    #[arg(long, global = true, value_name = "ver")]
124    pub lua_version: Option<LuaVersion>,
125
126    /// Which tree to operate on.{n}
127    /// In a workspace, this can be used to specify a detached workspace tree.
128    #[arg(long, global = true, value_name = "tree")]
129    pub tree: Option<PathBuf>,
130
131    /// Specifies the cache directory, e.g. for luarocks manifests.
132    #[arg(long, global = true, value_name = "cache-dir")]
133    pub cache_dir: Option<PathBuf>,
134
135    /// Disable the precomputed manifest cache.
136    #[arg(long)]
137    pub no_manifest_cache: bool,
138
139    /// Specifies the data directory,{n}
140    /// in which the default user install tree resides{n}
141    /// (e.g. ~/.local/share/lux).
142    #[arg(long, global = true, value_name = "data-dir")]
143    pub data_dir: Option<PathBuf>,
144
145    /// Specifies a directory with locally vendored sources and RockSpecs.{n}
146    /// When building or installing a package with this flag,{n}
147    /// Lux will fetch sources from the <vendor-dir> instead of from a remote server.
148    #[arg(long, value_name = "vendor-dir")]
149    pub vendor_dir: Option<PathBuf>,
150
151    /// Override config variables.{n}
152    /// Example: `lx -v "LUA=/path/to/lua" ...`
153    #[arg(long, global = true, value_name = "variable", visible_short_alias = 'v', value_parser = parse_key_val::<String, String>)]
154    pub variables: Option<Vec<(String, String)>>,
155
156    /// The build profile to use when compiling packages.{n}
157    /// Default: `release`.
158    #[arg(long, global = true, value_enum, value_name = "profile")]
159    pub profile: Option<lux_lib::config::build::Profile>,
160
161    /// Display verbose output of commands executed, enabling DEBUG logs.{n}
162    /// To enable TRACE logs, set RUST_LOG=trace.
163    #[arg(long, global = true)]
164    pub verbose: bool,
165
166    /// Don't print any progress bars or spinners.
167    #[arg(long, global = true)]
168    pub no_progress: bool,
169
170    /// Skip prompts, selecting the default option.{n}
171    /// Prompting is enabled by default in terminal/TTY environments.
172    #[arg(long, global = true)]
173    pub no_prompt: Option<bool>,
174
175    /// Configure Lux for a specific environment.{n}
176    /// Valid presets are: 'nvim', 'rojo'.
177    #[arg(long, global = true, value_enum, value_name = "preset")]
178    pub preset: Option<Preset>,
179
180    /// [DEPRECATED] Configure lux for installing Neovim packages.{n}
181    /// Use `--preset nvim` instead.
182    #[arg(long, global = true, conflicts_with = "preset")]
183    pub nvim: bool,
184
185    /// Disable prompts for two-factor authentication (2FA) codes.{n}
186    /// It is strongly recommended to enable 2FA instead
187    /// see (https://luarocks.org/settings/two-factor-auth).
188    #[arg(long, global = true)]
189    pub no_tfa: bool,
190
191    /// Allow Lux to run as root (linux) or Administrator (windows).
192    #[arg(long, global = true)]
193    pub allow_root: bool,
194
195    /// Timeout on network operations, in seconds.{n}
196    /// 0 means no timeout (wait forever). Default is 30.
197    #[arg(long, global = true, value_name = "seconds")]
198    pub timeout: Option<usize>,
199
200    /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
201    /// 0 means no limit. Default is 0.
202    #[arg(long, global = true, visible_short_alias = 'j')]
203    pub max_jobs: Option<usize>,
204
205    /// Do not generate or update a `.luarc.json` file when building{n}
206    /// a project.
207    #[arg(long, global = true)]
208    pub no_luarc: bool,
209
210    /// Do not wrap Lua `bin` scripts.
211    #[arg(long, global = true)]
212    pub no_wrap_bin: bool,
213
214    /// The user agent to set when making web requests.
215    /// Default is "lux/<version>"
216    #[arg(long, global = true)]
217    pub user_agent: Option<String>,
218
219    #[command(subcommand)]
220    pub command: Commands,
221}
222
223#[derive(Subcommand)]
224pub enum Commands {
225    /// Add a dependency to the current project.
226    Add(Add),
227    /// Build/compile a project.
228    Build(Build),
229    /// [EXPERIMENTAL]{n}
230    /// Type check the current project based on EmmyLua/LuaCATS annotations.{n}
231    /// Respects `.emmyrc.json` and `.luarc.json` files in the project directory.
232    Check(Check),
233    /// Interact with the lux configuration.
234    #[command(subcommand, arg_required_else_help = true)]
235    Config(ConfigCmd),
236    /// Internal commands for debugging Lux itself.
237    #[command(subcommand, arg_required_else_help = true)]
238    Debug(Debug),
239    /// Distribute a Lux project.
240    #[command(subcommand, arg_required_else_help = true)]
241    Dist(Dist),
242    /// Show documentation for an installed rock.
243    Doc(Doc),
244    /// Download a specific rock file from a luarocks server.
245    #[command(arg_required_else_help = true)]
246    Download(Download),
247    /// Formats the codebase with stylua.
248    Fmt(Fmt),
249    /// Generate a rockspec file from a project.
250    GenerateRockspec(GenerateRockspec),
251    /// Generate a lockfile for the current project without installing its dependencies.
252    GenerateLockfile,
253    /// Show metadata for any rock.
254    Info(Info),
255    /// Install a rock for use on the system.
256    #[command(arg_required_else_help = true)]
257    Install(Install),
258    /// Install a local rockspec for use on the system.
259    #[command(arg_required_else_help = true)]
260    InstallRockspec(InstallRockspec),
261    /// Manually install and manage Lua headers for various Lua versions.
262    InstallLua,
263    /// Lint the current project using `luacheck`.
264    Lint(Lint),
265    /// List currently installed rocks.
266    List(ListCmd),
267    /// Run lua, with the `LUA_PATH` and `LUA_CPATH` set to the specified lux tree.
268    Lua(RunLua),
269    /// Create a new Lua project.
270    New(NewProject),
271    /// List outdated rocks.
272    Outdated(Outdated),
273    /// Create a packed rock for distribution, packing sources or binaries.
274    Pack(Pack),
275    /// Return the currently configured package path.
276    Path(Path),
277    /// Pin an existing rock, preventing any updates to the package.
278    Pin(ChangePin),
279    /// Remove all installed rocks from a tree.
280    Purge,
281    /// Remove a rock from the current project's lux.toml dependencies.
282    Remove(Remove),
283    /// Run the current project with the provided arguments.
284    Run(Run),
285    /// Execute a command that has been installed with lux.
286    /// If the command is not found, a package named after the command
287    /// will be installed.
288    Exec(Exec),
289    /// Query the luarocks servers.
290    #[command(arg_required_else_help = true)]
291    Search(Search),
292    /// Run the test suite in the current project directory.{n}
293    /// Lux supports the following test backends, specified by the `[test]` table in the lux.toml:{n}
294    /// {n}
295    ///   - busted:{n}
296    ///     {n}
297    ///     https://lunarmodules.github.io/busted/{n}
298    ///     {n}
299    ///     Example:{n}
300    ///     {n}
301    ///     ```toml{n}
302    ///     [test]{n}
303    ///     type = "busted"{n}
304    ///     flags = [ ] # Optional CLI flags to pass to busted{n}
305    ///     ```{n}
306    ///     {n}
307    ///     `lx test` will default to using `busted` if no test backend is specified and:{n}
308    ///         * there is a `.busted` file in the project root{n}
309    ///         * or `busted` is one of the `test_dependencies`).{n}
310    /// {n}
311    ///   - busted-nlua:{n}:
312    ///     {n}
313    ///     A build backend for running busted tests with Neovim as the Lua interpreter.
314    ///     Used for testing Neovim plugins.
315    ///     {n}
316    ///     Example:{n}
317    ///     {n}
318    ///     ```toml{n}
319    ///     [test]{n}
320    ///     type = "busted-nlua"{n}
321    ///     flags = [ ] # Optional CLI flags to pass to busted{n}
322    ///     ```{n}
323    ///     {n}
324    ///     `lx test` will default to using `busted-nlua` if no test backend is specified and:{n}
325    ///         * there is a `.busted` file in the project root{n}
326    ///         * or `busted` and `nlua` are `test_dependencies`.{n}
327    /// {n}
328    ///   - command:{n}
329    ///     {n}
330    ///     Name/file name of a shell command that will run the test suite.{n}
331    ///     Example:{n}
332    ///     {n}
333    ///     ```toml{n}
334    ///     [test]{n}
335    ///     type = "command"{n}
336    ///     command = "make"{n}
337    ///     flags = [ "test" ]{n}
338    ///     ```{n}
339    ///     {n}
340    ///   - script:{n}
341    ///     {n}
342    ///     Relative path to a Lua script that will run the test suite.{n}
343    ///     Example:{n}
344    ///     {n}
345    ///     ```toml{n}
346    ///     [test]{n}
347    ///     type = "script"{n}
348    ///     script = "tests.lua" # Expects a tests.lua file in the project root{n}
349    ///     flags = [ ] # Optional arguments passed to the test script{n}
350    ///     ```{n}
351    Test(Test),
352    /// Uninstall a rock from the system.
353    Uninstall(Uninstall),
354    /// Unpins an existing rock, allowing updates to alter the package.
355    Unpin(ChangePin),
356    /// Updates all rocks in a project.
357    Update(Update),
358    /// Generate a Lua rockspec for a Lux project and upload it to the public luarocks repository.{n}
359    /// You can specify a source template for release and dev packages in the lux.toml.{n}
360    /// {n}
361    /// Example:{n}
362    /// {n}
363    /// ```toml{n}
364    /// [source]{n}
365    /// url = "https://host.com/owner/$(PACKAGE)/refs/tags/$(REF).zip"{n}
366    /// dev = "git+https://host.com/owner/$(PACKAGE).git"{n}
367    /// ```{n}
368    /// {n}
369    /// You can use the following variables in the source template:{n}
370    /// {n}
371    ///  - $(PACKAGE): The package name.{n}
372    ///  - $(VERSION): The package version.{n}
373    ///  - $(REF): The git tag or revision (if in a git repository).{n}
374    ///  - You may also specify environment variables with `$(<VAR_NAME>)`.{n}
375    /// {n}
376    /// If the `version` is not set in the lux.toml, lux will search the current
377    /// commit for SemVer tags and if found, will use it to generate the package version.
378    Upload(Upload),
379    /// Infrequently used commands such as for generating shell completions and man pages.
380    #[command(subcommand, arg_required_else_help = true)]
381    Util(Util),
382    /// Vendor the dependencies of a project or RockSpec locally.
383    /// When building or installing a package with the `--vendor-dir` option{n}
384    /// or the `[vendor_dir]` config option, Lux will fetch sources from the <vendor-dir>{n}
385    /// instead of from a remote server.
386    Vendor(Vendor),
387    /// Tell which file corresponds to a given module name.
388    Which(Which),
389    /// Spawns an interactive shell with PATH, LUA_PATH, LUA_CPATH and LUA_INIT set.
390    Shell(Shell),
391    /// Synchronize the project tree with the current lux.toml,{n}
392    /// ensuring all packages are installed correctly.
393    Sync(SyncProject),
394}
395
396impl Commands {
397    /// For workspace commands, try to determine the project's Lua version.
398    ///
399    /// Returns [`None`]:
400    /// - if the project does not have an exact Lua version
401    /// - if there is more than one project an no `--package` has been specified
402    /// - if the command is not a project command
403    /// - if the workspace cannot be loaded
404    pub fn lua_version(&self) -> Option<LuaVersion> {
405        match self {
406            Self::Add(Add { package, .. })
407            | Self::Build(Build { package, .. })
408            | Self::Fmt(Fmt { package, .. })
409            | Self::Upload(Upload { package, .. })
410            | Self::GenerateRockspec(GenerateRockspec { package, .. })
411            | Self::Pin(ChangePin { package, .. })
412            | Self::Unpin(ChangePin { package, .. })
413            | Self::Remove(Remove { package, .. })
414            | Self::Test(Test { package, .. })
415            | Self::Update(Update { package, .. })
416            | Self::Run(Run {
417                build: Build { package, .. },
418                ..
419            }) => project_lua_version(package),
420            Self::Dist(d) => match d {
421                Dist::Bin(Bin { package, .. }) => project_lua_version(package),
422                Dist::FlatArchive(FlatArchive {
423                    package_or_rockspec,
424                    ..
425                }) => match package_or_rockspec {
426                    Some(PackageOrRockspec::Package(p)) => {
427                        project_lua_version(&Some(p.name().clone()))
428                    }
429                    Some(PackageOrRockspec::RockSpec(_)) => None,
430                    None => project_lua_version(&None),
431                },
432            },
433            Self::Pack(Pack {
434                package_or_rockspec,
435            }) => match package_or_rockspec {
436                Some(PackageOrRockspec::Package(p)) => project_lua_version(&Some(p.name().clone())),
437                Some(PackageOrRockspec::RockSpec(_)) => None,
438                None => project_lua_version(&None),
439            },
440            | Self::Debug(Debug::Project(_)) => project_lua_version(&None),
441            // workspace commands without a --package flag
442            Self::Check(_)
443            | Self::Exec(_)
444            | Self::Info(_)
445            | Self::Lua(_)
446            | Self::Lint(_)
447            | Self::Outdated(_)
448            | Self::Path(_)
449            | Self::Shell(_)
450            | Self::GenerateLockfile
451            | Self::Sync(_)
452            | Self::Vendor(_) => {
453                project_lua_version(&None)
454            },
455            | Self::New(_)
456            // non-project commands
457            | Self::Config(_)
458            | Self::Util(_)
459            | Self::Debug(Debug::Unpack(_))
460            | Self::Debug(Debug::FetchRemote(_))
461            | Self::Debug(Debug::UnpackRemote(_))
462            | Self::Debug(Debug::Toolchains(_))
463            | Self::Doc(_)
464            | Self::Download(_)
465            | Self::Install(_)
466            | Self::InstallRockspec(_)
467            | Self::InstallLua
468            | Self::List(_)
469            | Self::Purge
470            | Self::Search(_)
471            | Self::Uninstall(_)
472            | Self::Which(_) => None,
473        }
474    }
475
476    /// Load the user [`ConfigBuilder`], merged with the workspace-local [`ConfigBuilder`],
477    /// if present and running a workspace command.
478    pub fn config(&self) -> Result<ConfigBuilder> {
479        let config = ConfigBuilder::new()?;
480        if let Some(workspace) = self.workspace()? {
481            let config = if let Some(workspace_config) = workspace.config()? {
482                config.merge(workspace_config)
483            } else {
484                config
485            };
486            if let Self::Dist(_) = self {
487                Ok(config)
488            } else {
489                Ok(config.default_build_profile(lux_lib::config::build::Profile::Dev))
490            }
491        } else {
492            Ok(config)
493        }
494    }
495
496    /// For commands that can operate on a workspace, load the current workspace, if present.
497    fn workspace(&self) -> Result<Option<Workspace>> {
498        match self {
499            Self::Add(_)
500            | Self::Build(_)
501            | Self::Fmt(_)
502            | Self::Upload(_)
503            | Self::GenerateRockspec(_)
504            | Self::Pin(_)
505            | Self::Unpin(_)
506            | Self::Remove(_)
507            | Self::Test(_)
508            | Self::Update(_)
509            | Self::Check(_)
510            | Self::Exec(_)
511            | Self::Info(_)
512            | Self::Lua(_)
513            | Self::Lint(_)
514            | Self::Outdated(_)
515            | Self::Path(_)
516            | Self::Shell(_)
517            | Self::GenerateLockfile
518            | Self::Sync(_)
519            | Self::Config(_)
520            | Self::Vendor(_)
521            | Self::New(_)
522            | Self::Run(_)
523            | Self::Dist(Dist::Bin(_))
524            | Self::Dist(Dist::FlatArchive(FlatArchive {
525                package_or_rockspec: Some(PackageOrRockspec::Package(_)),
526                ..
527            }))
528            | Self::Dist(Dist::FlatArchive(FlatArchive {
529                package_or_rockspec: None,
530                ..
531            }))
532            | Self::Pack(Pack {
533                package_or_rockspec: Some(PackageOrRockspec::Package(_)),
534            })
535            | Self::Pack(Pack {
536                package_or_rockspec: None,
537            })
538            | Self::Debug(Debug::Project(_)) => Workspace::current().into_diagnostic(),
539            // non-project commands
540            Self::Debug(Debug::Unpack(_))
541            | Self::Debug(Debug::FetchRemote(_))
542            | Self::Debug(Debug::UnpackRemote(_))
543            | Self::Debug(Debug::Toolchains(_))
544            | Self::Dist(Dist::FlatArchive(FlatArchive {
545                package_or_rockspec: Some(PackageOrRockspec::RockSpec(_)),
546                ..
547            }))
548            | Self::Pack(Pack {
549                package_or_rockspec: Some(PackageOrRockspec::RockSpec(_)),
550            })
551            | Self::Util(_)
552            | Self::Doc(_)
553            | Self::Download(_)
554            | Self::Install(_)
555            | Self::InstallRockspec(_)
556            | Self::InstallLua
557            | Self::List(_)
558            | Self::Purge
559            | Self::Search(_)
560            | Self::Uninstall(_)
561            | Self::Which(_) => Ok(None),
562        }
563    }
564}
565
566/// Parse a key=value pair.
567fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
568where
569    T: std::str::FromStr,
570    T::Err: Error + Send + Sync + 'static,
571    U: std::str::FromStr,
572    U::Err: Error + Send + Sync + 'static,
573{
574    let pos = s
575        .find('=')
576        .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
577    Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
578}
579
580fn project_lua_version(pkg: &Option<package::Name>) -> Option<LuaVersion> {
581    let current_workspace = Workspace::current().ok().flatten()?;
582    let project = current_workspace.single_member_or_select(pkg).ok()?;
583    let lua = project.toml().lua()?;
584    let mut matches = LuaVersion::iter().filter(|v| {
585        !matches!(v, LuaVersion::LuaJIT | LuaVersion::LuaJIT52) && lua.matches(&v.as_version())
586    });
587    let version = matches.next()?;
588    if matches.next().is_none() {
589        Some(version)
590    } else {
591        None
592    }
593}