Skip to main content

lux_cli/
path.rs

1use clap::Subcommand;
2use lux_lib::{
3    config::Config,
4    lua,
5    path::{BinPath, PackagePath, Paths},
6    tree::InstallTree,
7};
8use miette::{miette, Result};
9use strum_macros::{Display, EnumString, VariantNames};
10
11use clap::{Args, ValueEnum};
12
13use crate::workspace::current_workspace_or_user_tree;
14
15#[derive(Args)]
16pub struct Path {
17    #[command(subcommand)]
18    cmd: Option<PathCmd>,
19
20    /// Prepend the rocks tree paths to the system paths.
21    #[clap(default_value_t = false)]
22    #[arg(long)]
23    prepend: bool,
24}
25
26#[derive(Subcommand, PartialEq, Eq, Debug, Clone)]
27#[clap(rename_all = "kebab_case")]
28enum PathCmd {
29    /// Generate an export statement for all paths
30    /// (formatted as a shell command). [Default]
31    Full(FullArgs),
32    /// Generate a `LUA_PATH` expression for `lua` libraries in the lux tree.
33    /// (not formatted as a shell command)
34    Lua,
35    /// Generate a `LUA_CPATH` expression for native `lib` libraries in the lux tree.
36    /// (not formatted as a shell command)
37    C,
38    /// Generate a `PATH` expression for `bin` executables in the lux tree.
39    /// (not formatted as a shell command)
40    Bin,
41    /// Generate a `LUA_INIT` expression for the lux loader.
42    /// (not formatted as a shell command)
43    Init,
44}
45
46impl Default for PathCmd {
47    fn default() -> Self {
48        Self::Full(FullArgs::default())
49    }
50}
51
52#[derive(Args, PartialEq, Eq, Debug, Clone, Default)]
53struct FullArgs {
54    /// Do not export `PATH` (`bin` paths).
55    #[clap(default_value_t = false)]
56    #[arg(long)]
57    no_bin: bool,
58
59    /// Do not add `require('lux').loader()` to `LUA_INIT`.
60    /// If a rock has conflicting transitive dependencies,
61    /// disabling the Lux loader may result in the wrong modules being loaded.
62    #[clap(default_value_t = false)]
63    #[arg(long)]
64    no_loader: bool,
65
66    /// The shell to format for.
67    #[clap(default_value_t = Shell::default())]
68    #[arg(long)]
69    shell: Shell,
70}
71
72#[derive(EnumString, VariantNames, Display, ValueEnum, PartialEq, Eq, Debug, Clone)]
73#[strum(serialize_all = "lowercase")]
74#[derive(Default)]
75enum Shell {
76    #[default]
77    Posix,
78    Fish,
79    Nu,
80}
81
82impl PathCmd {
83    fn name(&self) -> &'static str {
84        match self {
85            PathCmd::Full(_) => "full",
86            PathCmd::Lua => "lua",
87            PathCmd::C => "c",
88            PathCmd::Bin => "bin",
89            PathCmd::Init => "init",
90        }
91    }
92}
93
94pub async fn path(path_data: Path, config: Config) -> Result<()> {
95    let tree = current_workspace_or_user_tree(&config)?;
96    let cmd = path_data.cmd.unwrap_or_default();
97    let prepend = path_data.prepend;
98    if tree.version() == &lua::Version::Luau {
99        return match cmd {
100            PathCmd::Full(args) => {
101                let paths = Paths::new(&tree)?;
102                let mut result = String::new();
103                if !args.no_bin {
104                    let path = mk_bin_path(&paths, prepend)?;
105                    if !path.is_empty() {
106                        result.push_str(format_export(&args.shell, "PATH", &path).as_str());
107                        result.push('\n');
108                    }
109                }
110                println!("{}", result.trim_end());
111                Ok(())
112            }
113            PathCmd::Bin => {
114                let paths = Paths::new(&tree)?;
115                println!("{}", mk_bin_path(&paths, prepend)?);
116                Ok(())
117            }
118            PathCmd::Lua | PathCmd::C | PathCmd::Init => Err(miette!(
119                help = "Luau uses the `.luaurc` (generated by Lux) for module resolution",
120                "`lx path {}` is not supported under Luau",
121                cmd.name()
122            )),
123        };
124    }
125    let paths = Paths::new(&tree)?;
126    match cmd {
127        PathCmd::Full(args) => {
128            let mut result = String::new();
129            let no_loader = args.no_loader || {
130                if tree.version().lux_lib_dir().is_none() {
131                    tracing::warn!(
132                        r#"lux-lua library not found.
133Cannot use the `lux.loader`.
134To suppress this warning, run `lx path full --no-loader`."#
135                    );
136                    true
137                } else {
138                    false
139                }
140            };
141            let shell = args.shell;
142            let package_path = mk_package_path(&paths, prepend);
143            if !package_path.is_empty() {
144                result.push_str(format_export(&shell, "LUA_PATH", &package_path).as_str());
145                result.push('\n')
146            }
147            let package_cpath = mk_package_cpath(&paths, prepend);
148            if !package_cpath.is_empty() {
149                result.push_str(format_export(&shell, "LUA_CPATH", &package_cpath).as_str());
150                result.push('\n')
151            }
152            if !args.no_bin {
153                let path = mk_bin_path(&paths, prepend)?;
154                if !path.is_empty() {
155                    result.push_str(format_export(&shell, "PATH", &path).as_str());
156                    result.push('\n')
157                }
158            }
159            if !no_loader {
160                result.push_str(format_export(&shell, "LUA_INIT", &paths.init()).as_str());
161                result.push('\n')
162            }
163            println!("{}", result);
164        }
165        PathCmd::Lua => println!("{}", mk_package_path(&paths, prepend)),
166        PathCmd::C => println!("{}", mk_package_cpath(&paths, prepend)),
167        PathCmd::Bin => println!("{}", mk_bin_path(&paths, prepend)?),
168        PathCmd::Init => println!("{}", paths.init()),
169    }
170    Ok(())
171}
172
173fn mk_package_path(paths: &Paths, prepend: bool) -> PackagePath {
174    if prepend {
175        paths.package_path_prepended()
176    } else {
177        paths.package_path().clone()
178    }
179}
180
181fn mk_package_cpath(paths: &Paths, prepend: bool) -> PackagePath {
182    if prepend {
183        paths.package_cpath_prepended()
184    } else {
185        paths.package_cpath().clone()
186    }
187}
188
189fn mk_bin_path(paths: &Paths, prepend: bool) -> Result<BinPath> {
190    let mut result = if prepend {
191        BinPath::from_env()
192    } else {
193        BinPath::default()
194    };
195    result.prepend(paths.path());
196    Ok(result)
197}
198
199fn format_export<D>(shell: &Shell, var_name: &str, var: &D) -> String
200where
201    D: std::fmt::Display,
202{
203    match shell {
204        Shell::Posix => format!("export {var_name}='{var}';"),
205        Shell::Fish => format!("set -x {var_name} \"{var}\";"),
206        Shell::Nu => format!("$env.{var_name} = \"{var}\";"),
207    }
208}