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