Skip to main content

lux_cli/
lib.rs

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