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