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 /// A build backend for running busted tests with Neovim as the Lua interpreter.
303 /// Used for testing Neovim plugins.
304 /// {n}
305 /// Example:{n}
306 /// {n}
307 /// ```toml{n}
308 /// [test]{n}
309 /// type = "busted-nlua"{n}
310 /// flags = [ ] # Optional CLI flags to pass to busted{n}
311 /// ```{n}
312 /// {n}
313 /// `lx test` will default to using `busted-nlua` if no test backend is specified and:{n}
314 /// * there is a `.busted` file in the project root{n}
315 /// * or `busted` and `nlua` are `test_dependencies`.{n}
316 /// {n}
317 /// - command:{n}
318 /// {n}
319 /// Name/file name of a shell command that will run the test suite.{n}
320 /// Example:{n}
321 /// {n}
322 /// ```toml{n}
323 /// [test]{n}
324 /// type = "command"{n}
325 /// command = "make"{n}
326 /// flags = [ "test" ]{n}
327 /// ```{n}
328 /// {n}
329 /// - script:{n}
330 /// {n}
331 /// Relative path to a Lua script that will run the test suite.{n}
332 /// Example:{n}
333 /// {n}
334 /// ```toml{n}
335 /// [test]{n}
336 /// type = "script"{n}
337 /// script = "tests.lua" # Expects a tests.lua file in the project root{n}
338 /// flags = [ ] # Optional arguments passed to the test script{n}
339 /// ```{n}
340 Test(Test),
341 /// Uninstall a rock from the system.
342 Uninstall(Uninstall),
343 /// Unpins an existing rock, allowing updates to alter the package.
344 Unpin(ChangePin),
345 /// Updates all rocks in a project.
346 Update(Update),
347 /// Generate a Lua rockspec for a Lux project and upload it to the public luarocks repository.{n}
348 /// You can specify a source template for release and dev packages in the lux.toml.{n}
349 /// {n}
350 /// Example:{n}
351 /// {n}
352 /// ```toml{n}
353 /// [source]{n}
354 /// url = "https://host.com/owner/$(PACKAGE)/refs/tags/$(REF).zip"{n}
355 /// dev = "git+https://host.com/owner/$(PACKAGE).git"{n}
356 /// ```{n}
357 /// {n}
358 /// You can use the following variables in the source template:{n}
359 /// {n}
360 /// - $(PACKAGE): The package name.{n}
361 /// - $(VERSION): The package version.{n}
362 /// - $(REF): The git tag or revision (if in a git repository).{n}
363 /// - You may also specify environment variables with `$(<VAR_NAME>)`.{n}
364 /// {n}
365 /// If the `version` is not set in the lux.toml, lux will search the current
366 /// commit for SemVer tags and if found, will use it to generate the package version.
367 Upload(Upload),
368 /// Infrequently used commands such as for generating shell completions and man pages.
369 #[command(subcommand, arg_required_else_help = true)]
370 Util(Util),
371 /// Vendor the dependencies of a project or RockSpec locally.
372 /// When building or installing a package with the `--vendor-dir` option{n}
373 /// or the `[vendor_dir]` config option, Lux will fetch sources from the <vendor-dir>{n}
374 /// instead of from a remote server.
375 Vendor(Vendor),
376 /// Tell which file corresponds to a given module name.
377 Which(Which),
378 /// Spawns an interactive shell with PATH, LUA_PATH, LUA_CPATH and LUA_INIT set.
379 Shell(Shell),
380 /// Synchronize the project tree with the current lux.toml,{n}
381 /// ensuring all packages are installed correctly.
382 Sync(SyncProject),
383}
384
385impl Commands {
386 /// For workspace commands, try to determine the project's Lua version.
387 ///
388 /// Returns [`None`]:
389 /// - if the project does not have an exact Lua version
390 /// - if there is more than one project an no `--package` has been specified
391 /// - if the command is not a project command
392 /// - if the workspace cannot be loaded
393 pub fn lua_version(&self) -> Option<LuaVersion> {
394 match self {
395 Self::Add(Add { package, .. })
396 | Self::Build(Build { package, .. })
397 | Self::Fmt(Fmt { package, .. })
398 | Self::Upload(Upload { package, .. })
399 | Self::GenerateRockspec(GenerateRockspec { package, .. })
400 | Self::Pin(ChangePin { package, .. })
401 | Self::Unpin(ChangePin { package, .. })
402 | Self::Remove(Remove { package, .. })
403 | Self::Test(Test { package, .. })
404 | Self::Update(Update { package, .. })
405 | Self::Run(Run {
406 build: Build { package, .. },
407 ..
408 }) => project_lua_version(package),
409 Self::Dist(d) => match d {
410 Dist::Bin(Bin { package, .. }) => project_lua_version(package),
411 Dist::FlatArchive(FlatArchive {
412 package_or_rockspec,
413 ..
414 }) => match package_or_rockspec {
415 Some(PackageOrRockspec::Package(p)) => {
416 project_lua_version(&Some(p.name().clone()))
417 }
418 Some(PackageOrRockspec::RockSpec(_)) => None,
419 None => project_lua_version(&None),
420 },
421 },
422 Self::Pack(Pack {
423 package_or_rockspec,
424 }) => match package_or_rockspec {
425 Some(PackageOrRockspec::Package(p)) => project_lua_version(&Some(p.name().clone())),
426 Some(PackageOrRockspec::RockSpec(_)) => None,
427 None => project_lua_version(&None),
428 },
429 | Self::Debug(Debug::Project(_)) => project_lua_version(&None),
430 // workspace commands without a --package flag
431 Self::Check(_)
432 | Self::Exec(_)
433 | Self::Info(_)
434 | Self::Lua(_)
435 | Self::Lint(_)
436 | Self::Outdated(_)
437 | Self::Path(_)
438 | Self::Shell(_)
439 | Self::Sync(_)
440 | Self::Vendor(_) => {
441 project_lua_version(&None)
442 },
443 | Self::New(_)
444 // non-project commands
445 | Self::Config(_)
446 | Self::Util(_)
447 | Self::Debug(Debug::Unpack(_))
448 | Self::Debug(Debug::FetchRemote(_))
449 | Self::Debug(Debug::UnpackRemote(_))
450 | Self::Debug(Debug::Toolchains(_))
451 | Self::Doc(_)
452 | Self::Download(_)
453 | Self::Install(_)
454 | Self::InstallRockspec(_)
455 | Self::InstallLua
456 | Self::List(_)
457 | Self::Purge
458 | Self::Search(_)
459 | Self::Uninstall(_)
460 | Self::Which(_) => None,
461 }
462 }
463
464 /// Load the user [`ConfigBuilder`], merged with the workspace-local [`ConfigBuilder`],
465 /// if present and running a workspace command.
466 pub fn config(&self) -> Result<ConfigBuilder> {
467 let config = ConfigBuilder::new()?;
468 if let Some(workspace) = self.workspace()? {
469 let config = if let Some(workspace_config) = workspace.config()? {
470 config.merge(workspace_config)
471 } else {
472 config
473 };
474 if let Self::Dist(_) = self {
475 Ok(config)
476 } else {
477 Ok(config.default_build_profile(lux_lib::config::build::Profile::Dev))
478 }
479 } else {
480 Ok(config)
481 }
482 }
483
484 /// For commands that can operate on a workspace, load the current workspace, if present.
485 fn workspace(&self) -> Result<Option<Workspace>> {
486 match self {
487 Self::Add(_)
488 | Self::Build(_)
489 | Self::Fmt(_)
490 | Self::Upload(_)
491 | Self::GenerateRockspec(_)
492 | Self::Pin(_)
493 | Self::Unpin(_)
494 | Self::Remove(_)
495 | Self::Test(_)
496 | Self::Update(_)
497 | Self::Check(_)
498 | Self::Exec(_)
499 | Self::Info(_)
500 | Self::Lua(_)
501 | Self::Lint(_)
502 | Self::Outdated(_)
503 | Self::Path(_)
504 | Self::Shell(_)
505 | Self::Sync(_)
506 | Self::Config(_)
507 | Self::Vendor(_)
508 | Self::New(_)
509 | Self::Run(_)
510 | Self::Dist(Dist::Bin(_))
511 | Self::Dist(Dist::FlatArchive(FlatArchive {
512 package_or_rockspec: Some(PackageOrRockspec::Package(_)),
513 ..
514 }))
515 | Self::Dist(Dist::FlatArchive(FlatArchive {
516 package_or_rockspec: None,
517 ..
518 }))
519 | Self::Pack(Pack {
520 package_or_rockspec: Some(PackageOrRockspec::Package(_)),
521 })
522 | Self::Pack(Pack {
523 package_or_rockspec: None,
524 })
525 | Self::Debug(Debug::Project(_)) => Workspace::current().into_diagnostic(),
526 // non-project commands
527 Self::Debug(Debug::Unpack(_))
528 | Self::Debug(Debug::FetchRemote(_))
529 | Self::Debug(Debug::UnpackRemote(_))
530 | Self::Debug(Debug::Toolchains(_))
531 | Self::Dist(Dist::FlatArchive(FlatArchive {
532 package_or_rockspec: Some(PackageOrRockspec::RockSpec(_)),
533 ..
534 }))
535 | Self::Pack(Pack {
536 package_or_rockspec: Some(PackageOrRockspec::RockSpec(_)),
537 })
538 | Self::Util(_)
539 | Self::Doc(_)
540 | Self::Download(_)
541 | Self::Install(_)
542 | Self::InstallRockspec(_)
543 | Self::InstallLua
544 | Self::List(_)
545 | Self::Purge
546 | Self::Search(_)
547 | Self::Uninstall(_)
548 | Self::Which(_) => Ok(None),
549 }
550 }
551}
552
553/// Parse a key=value pair.
554fn parse_key_val<T, U>(s: &str) -> Result<(T, U), Box<dyn Error + Send + Sync + 'static>>
555where
556 T: std::str::FromStr,
557 T::Err: Error + Send + Sync + 'static,
558 U: std::str::FromStr,
559 U::Err: Error + Send + Sync + 'static,
560{
561 let pos = s
562 .find('=')
563 .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?;
564 Ok((s[..pos].parse()?, s[pos + 1..].parse()?))
565}
566
567fn project_lua_version(pkg: &Option<PackageName>) -> Option<LuaVersion> {
568 let current_workspace = Workspace::current().ok().flatten()?;
569 let project = current_workspace.single_member_or_select(pkg).ok()?;
570 let lua = project.toml().lua()?;
571 let mut matches = LuaVersion::iter().filter(|v| {
572 !matches!(v, LuaVersion::LuaJIT | LuaVersion::LuaJIT52) && lua.matches(&v.as_version())
573 });
574 let version = matches.next()?;
575 if matches.next().is_none() {
576 Some(version)
577 } else {
578 None
579 }
580}