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', 'rojo'.
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
186 /// Disable prompts for two-factor authentication (2FA) codes.{n}
187 /// It is strongly recommended to enable 2FA instead
188 /// see (https://luarocks.org/settings/two-factor-auth).
189 #[arg(long, global = true)]
190 pub no_tfa: bool,
191
192 /// Allow Lux to run as root (linux) or Administrator (windows).
193 #[arg(long, global = true)]
194 pub allow_root: bool,
195
196 /// Timeout on network operations, in seconds.{n}
197 /// 0 means no timeout (wait forever). Default is 30.
198 #[arg(long, global = true, value_name = "seconds")]
199 pub timeout: Option<usize>,
200
201 /// Maximum buffer size for parallel jobs, such as downloading rockspecs and installing rocks.
202 /// 0 means no limit. Default is 0.
203 #[arg(long, global = true, visible_short_alias = 'j')]
204 pub max_jobs: Option<usize>,
205
206 /// Do not generate or update a `.luarc.json` file when building{n}
207 /// a project.
208 #[arg(long, global = true)]
209 pub no_luarc: bool,
210
211 /// Do not wrap Lua `bin` scripts.
212 #[arg(long, global = true)]
213 pub no_wrap_bin: bool,
214
215 /// The user agent to set when making web requests.
216 /// Default is "lux/<version>"
217 #[arg(long, global = true)]
218 pub user_agent: Option<String>,
219
220 #[command(subcommand)]
221 pub command: Commands,
222}
223
224#[derive(Subcommand)]
225pub enum Commands {
226 /// Add a dependency to the current project.
227 Add(Add),
228 /// Build/compile a project.
229 Build(Build),
230 /// [EXPERIMENTAL]{n}
231 /// Type check the current project based on EmmyLua/LuaCATS annotations.{n}
232 /// Respects `.emmyrc.json` and `.luarc.json` files in the project directory.
233 Check(Check),
234 /// Interact with the lux configuration.
235 #[command(subcommand, arg_required_else_help = true)]
236 Config(ConfigCmd),
237 /// Internal commands for debugging Lux itself.
238 #[command(subcommand, arg_required_else_help = true)]
239 Debug(Debug),
240 /// Distribute a Lux project.
241 #[command(subcommand, arg_required_else_help = true)]
242 Dist(Dist),
243 /// Show documentation for an installed rock.
244 Doc(Doc),
245 /// Download a specific rock file from a luarocks server.
246 #[command(arg_required_else_help = true)]
247 Download(Download),
248 /// Formats the codebase with stylua.
249 Fmt(Fmt),
250 /// Generate a rockspec file from a project.
251 GenerateRockspec(GenerateRockspec),
252 /// Generate a lockfile for the current project without installing its dependencies.
253 GenerateLockfile,
254 /// Show metadata for any rock.
255 Info(Info),
256 /// Install a rock for use on the system.
257 #[command(arg_required_else_help = true)]
258 Install(Install),
259 /// Install a local rockspec for use on the system.
260 #[command(arg_required_else_help = true)]
261 InstallRockspec(InstallRockspec),
262 /// Manually install and manage Lua headers for various Lua versions.
263 InstallLua,
264 /// Lint the current project using `luacheck`.
265 Lint(Lint),
266 /// List currently installed rocks.
267 List(ListCmd),
268 /// Run lua, with the `LUA_PATH` and `LUA_CPATH` set to the specified lux tree.
269 Lua(RunLua),
270 /// Create a new Lua project.
271 New(NewProject),
272 /// List outdated rocks.
273 Outdated(Outdated),
274 /// Create a packed rock for distribution, packing sources or binaries.
275 Pack(Pack),
276 /// Return the currently configured package path.
277 Path(Path),
278 /// Pin an existing rock, preventing any updates to the package.
279 Pin(ChangePin),
280 /// Remove all installed rocks from a tree.
281 Purge,
282 /// Remove a rock from the current project's lux.toml dependencies.
283 Remove(Remove),
284 /// Run the current project with the provided arguments.
285 Run(Run),
286 /// Execute a command that has been installed with lux.
287 /// If the command is not found, a package named after the command
288 /// will be installed.
289 Exec(Exec),
290 /// Query the luarocks servers.
291 #[command(arg_required_else_help = true)]
292 Search(Search),
293 /// Run the test suite in the current project directory.{n}
294 /// Lux supports the following test backends, specified by the `[test]` table in the lux.toml:{n}
295 /// {n}
296 /// - busted:{n}
297 /// {n}
298 /// https://lunarmodules.github.io/busted/{n}
299 /// {n}
300 /// Example:{n}
301 /// {n}
302 /// ```toml{n}
303 /// [test]{n}
304 /// type = "busted"{n}
305 /// flags = [ ] # Optional CLI flags to pass to busted{n}
306 /// ```{n}
307 /// {n}
308 /// `lx test` will default to using `busted` if no test backend is specified and:{n}
309 /// * there is a `.busted` file in the project root{n}
310 /// * or `busted` is one of the `test_dependencies`).{n}
311 /// {n}
312 /// - busted-nlua:{n}:
313 /// {n}
314 /// A build backend for running busted tests with Neovim as the Lua interpreter.
315 /// Used for testing Neovim plugins.
316 /// {n}
317 /// Example:{n}
318 /// {n}
319 /// ```toml{n}
320 /// [test]{n}
321 /// type = "busted-nlua"{n}
322 /// flags = [ ] # Optional CLI flags to pass to busted{n}
323 /// ```{n}
324 /// {n}
325 /// `lx test` will default to using `busted-nlua` if no test backend is specified and:{n}
326 /// * there is a `.busted` file in the project root{n}
327 /// * or `busted` and `nlua` are `test_dependencies`.{n}
328 /// {n}
329 /// - command:{n}
330 /// {n}
331 /// Name/file name of a shell command that will run the test suite.{n}
332 /// Example:{n}
333 /// {n}
334 /// ```toml{n}
335 /// [test]{n}
336 /// type = "command"{n}
337 /// command = "make"{n}
338 /// flags = [ "test" ]{n}
339 /// ```{n}
340 /// {n}
341 /// - script:{n}
342 /// {n}
343 /// Relative path to a Lua script that will run the test suite.{n}
344 /// Example:{n}
345 /// {n}
346 /// ```toml{n}
347 /// [test]{n}
348 /// type = "script"{n}
349 /// script = "tests.lua" # Expects a tests.lua file in the project root{n}
350 /// flags = [ ] # Optional arguments passed to the test script{n}
351 /// ```{n}
352 Test(Test),
353 /// Uninstall a rock from the system.
354 Uninstall(Uninstall),
355 /// Unpins an existing rock, allowing updates to alter the package.
356 Unpin(ChangePin),
357 /// Updates all rocks in a project.
358 Update(Update),
359 /// Generate a Lua rockspec for a Lux project and upload it to the public luarocks repository.{n}
360 /// You can specify a source template for release and dev packages in the lux.toml.{n}
361 /// {n}
362 /// Example:{n}
363 /// {n}
364 /// ```toml{n}
365 /// [source]{n}
366 /// url = "https://host.com/owner/$(PACKAGE)/refs/tags/$(REF).zip"{n}
367 /// dev = "git+https://host.com/owner/$(PACKAGE).git"{n}
368 /// ```{n}
369 /// {n}
370 /// You can use the following variables in the source template:{n}
371 /// {n}
372 /// - $(PACKAGE): The package name.{n}
373 /// - $(VERSION): The package version.{n}
374 /// - $(REF): The git tag or revision (if in a git repository).{n}
375 /// - You may also specify environment variables with `$(<VAR_NAME>)`.{n}
376 /// {n}
377 /// If the `version` is not set in the lux.toml, lux will search the current
378 /// commit for SemVer tags and if found, will use it to generate the package version.
379 Upload(Upload),
380 /// Infrequently used commands such as for generating shell completions and man pages.
381 #[command(subcommand, arg_required_else_help = true)]
382 Util(Util),
383 /// Vendor the dependencies of a project or RockSpec locally.
384 /// When building or installing a package with the `--vendor-dir` option{n}
385 /// or the `[vendor_dir]` config option, Lux will fetch sources from the <vendor-dir>{n}
386 /// instead of from a remote server.
387 Vendor(Vendor),
388 /// Tell which file corresponds to a given module name.
389 Which(Which),
390 /// Spawns an interactive shell with PATH, LUA_PATH, LUA_CPATH and LUA_INIT set.
391 Shell(Shell),
392 /// Synchronize the project tree with the current lux.toml,{n}
393 /// ensuring all packages are installed correctly.
394 Sync(SyncProject),
395}
396
397impl Commands {
398 /// For workspace commands, try to determine the project's Lua version.
399 ///
400 /// Returns [`None`]:
401 /// - if the project does not have an exact Lua version
402 /// - if there is more than one project an no `--package` has been specified
403 /// - if the command is not a project command
404 /// - if the workspace cannot be loaded
405 pub fn lua_version(&self) -> Option<LuaVersion> {
406 match self {
407 Self::Add(Add { package, .. })
408 | Self::Build(Build { package, .. })
409 | Self::Fmt(Fmt { package, .. })
410 | Self::Upload(Upload { package, .. })
411 | Self::GenerateRockspec(GenerateRockspec { package, .. })
412 | Self::Pin(ChangePin { package, .. })
413 | Self::Unpin(ChangePin { package, .. })
414 | Self::Remove(Remove { package, .. })
415 | Self::Test(Test { package, .. })
416 | Self::Update(Update { package, .. })
417 | Self::Run(Run {
418 build: Build { package, .. },
419 ..
420 }) => project_lua_version(package),
421 Self::Dist(d) => match d {
422 Dist::Bin(Bin { package, .. }) => project_lua_version(package),
423 Dist::FlatArchive(FlatArchive {
424 package_or_rockspec,
425 ..
426 }) => match package_or_rockspec {
427 Some(PackageOrRockspec::Package(p)) => {
428 project_lua_version(&Some(p.name().clone()))
429 }
430 Some(PackageOrRockspec::RockSpec(_)) => None,
431 None => project_lua_version(&None),
432 },
433 },
434 Self::Pack(Pack {
435 package_or_rockspec,
436 }) => match package_or_rockspec {
437 Some(PackageOrRockspec::Package(p)) => project_lua_version(&Some(p.name().clone())),
438 Some(PackageOrRockspec::RockSpec(_)) => None,
439 None => project_lua_version(&None),
440 },
441 | Self::Debug(Debug::Project(_)) => project_lua_version(&None),
442 // workspace commands without a --package flag
443 Self::Check(_)
444 | Self::Exec(_)
445 | Self::Info(_)
446 | Self::Lua(_)
447 | Self::Lint(_)
448 | Self::Outdated(_)
449 | Self::Path(_)
450 | Self::Shell(_)
451 | Self::GenerateLockfile
452 | Self::Sync(_)
453 | Self::Vendor(_) => {
454 project_lua_version(&None)
455 },
456 | Self::New(_)
457 // non-project commands
458 | Self::Config(_)
459 | Self::Util(_)
460 | Self::Debug(Debug::Unpack(_))
461 | Self::Debug(Debug::FetchRemote(_))
462 | Self::Debug(Debug::UnpackRemote(_))
463 | Self::Debug(Debug::Toolchains(_))
464 | Self::Doc(_)
465 | Self::Download(_)
466 | Self::Install(_)
467 | Self::InstallRockspec(_)
468 | Self::InstallLua
469 | Self::List(_)
470 | Self::Purge
471 | Self::Search(_)
472 | Self::Uninstall(_)
473 | Self::Which(_) => None,
474 }
475 }
476
477 /// Load the user [`ConfigBuilder`], merged with the workspace-local [`ConfigBuilder`],
478 /// if present and running a workspace command.
479 pub fn config(&self) -> Result<ConfigBuilder> {
480 let config = ConfigBuilder::new()?;
481 if let Some(workspace) = self.workspace()? {
482 let config = if let Some(workspace_config) = workspace.config()? {
483 config.merge(workspace_config)
484 } else {
485 config
486 };
487 if let Self::Dist(_) = self {
488 Ok(config)
489 } else {
490 Ok(config.default_build_profile(lux_lib::config::build::Profile::Dev))
491 }
492 } else {
493 Ok(config)
494 }
495 }
496
497 /// For commands that can operate on a workspace, load the current workspace, if present.
498 fn workspace(&self) -> Result<Option<Workspace>> {
499 match self {
500 Self::Add(_)
501 | Self::Build(_)
502 | Self::Fmt(_)
503 | Self::Upload(_)
504 | Self::GenerateRockspec(_)
505 | Self::Pin(_)
506 | Self::Unpin(_)
507 | Self::Remove(_)
508 | Self::Test(_)
509 | Self::Update(_)
510 | Self::Check(_)
511 | Self::Exec(_)
512 | Self::Info(_)
513 | Self::Lua(_)
514 | Self::Lint(_)
515 | Self::Outdated(_)
516 | Self::Path(_)
517 | Self::Shell(_)
518 | Self::GenerateLockfile
519 | Self::Sync(_)
520 | Self::Config(_)
521 | Self::Vendor(_)
522 | Self::New(_)
523 | Self::Run(_)
524 | Self::Dist(Dist::Bin(_))
525 | Self::Dist(Dist::FlatArchive(FlatArchive {
526 package_or_rockspec: Some(PackageOrRockspec::Package(_)),
527 ..
528 }))
529 | Self::Dist(Dist::FlatArchive(FlatArchive {
530 package_or_rockspec: None,
531 ..
532 }))
533 | Self::Pack(Pack {
534 package_or_rockspec: Some(PackageOrRockspec::Package(_)),
535 })
536 | Self::Pack(Pack {
537 package_or_rockspec: None,
538 })
539 | Self::Debug(Debug::Project(_)) => Workspace::current().into_diagnostic(),
540 // non-project commands
541 Self::Debug(Debug::Unpack(_))
542 | Self::Debug(Debug::FetchRemote(_))
543 | Self::Debug(Debug::UnpackRemote(_))
544 | Self::Debug(Debug::Toolchains(_))
545 | Self::Dist(Dist::FlatArchive(FlatArchive {
546 package_or_rockspec: Some(PackageOrRockspec::RockSpec(_)),
547 ..
548 }))
549 | Self::Pack(Pack {
550 package_or_rockspec: Some(PackageOrRockspec::RockSpec(_)),
551 })
552 | Self::Util(_)
553 | Self::Doc(_)
554 | Self::Download(_)
555 | Self::Install(_)
556 | Self::InstallRockspec(_)
557 | Self::InstallLua
558 | Self::List(_)
559 | Self::Purge
560 | Self::Search(_)
561 | Self::Uninstall(_)
562 | Self::Which(_) => Ok(None),
563 }
564 }
565}
566
567/// Parse a key=value pair.
568fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
569where
570 T: std::str::FromStr,
571 T::Err: Error + Send + Sync + 'static,
572 U: std::str::FromStr,
573 U::Err: Error + Send + Sync + 'static,
574{
575 let pos = s
576 .find('=')
577 .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
578 Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
579}
580
581fn project_lua_version(pkg: &Option<PackageName>) -> Option<LuaVersion> {
582 let current_workspace = Workspace::current().ok().flatten()?;
583 let project = current_workspace.single_member_or_select(pkg).ok()?;
584 let lua = project.toml().lua()?;
585 let mut matches = LuaVersion::iter().filter(|v| {
586 !matches!(v, LuaVersion::LuaJIT | LuaVersion::LuaJIT52) && lua.matches(&v.as_version())
587 });
588 let version = matches.next()?;
589 if matches.next().is_none() {
590 Some(version)
591 } else {
592 None
593 }
594}