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