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