lux_cli/
path.rs

1use std::{env, str::FromStr as _};
2
3use clap::Subcommand;
4use eyre::Result;
5use lux_lib::{
6    config::Config,
7    path::{BinPath, PackagePath, Paths},
8};
9use strum_macros::{Display, EnumString, VariantNames};
10
11use clap::{Args, ValueEnum};
12
13use crate::utils::project::current_project_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 export `LUA_INIT` (`require('lux').loader()`).
60    #[clap(default_value_t = false)]
61    #[arg(long)]
62    no_init: bool,
63
64    /// The shell to format for.
65    #[clap(default_value_t = Shell::default())]
66    #[arg(long)]
67    shell: Shell,
68}
69
70#[derive(EnumString, VariantNames, Display, ValueEnum, PartialEq, Eq, Debug, Clone)]
71#[strum(serialize_all = "lowercase")]
72enum Shell {
73    Posix,
74    Fish,
75    Nu,
76}
77
78impl Default for Shell {
79    fn default() -> Self {
80        Self::Posix
81    }
82}
83
84pub async fn path(path_data: Path, config: Config) -> Result<()> {
85    let tree = current_project_or_user_tree(&config)?;
86    let paths = Paths::new(&tree)?;
87    let cmd = path_data.cmd.unwrap_or_default();
88    let prepend = path_data.prepend;
89    match cmd {
90        PathCmd::Full(args) => {
91            let mut result = String::new();
92            let no_init = args.no_init || {
93                if tree.version().lux_lib_dir().is_none() {
94                    eprintln!(
95                        "⚠️ WARNING: lux-lua library not found.
96Cannot use the `lux.loader`.
97To suppress this warning, run `lx path full --no-init`.
98                "
99                    );
100                    true
101                } else {
102                    false
103                }
104            };
105            let shell = args.shell;
106            let package_path = mk_package_path(&paths, prepend)?;
107            if !package_path.is_empty() {
108                result.push_str(format_export(&shell, "LUA_PATH", &package_path).as_str());
109                result.push('\n')
110            }
111            let package_cpath = mk_package_cpath(&paths, prepend)?;
112            if !package_cpath.is_empty() {
113                result.push_str(format_export(&shell, "LUA_CPATH", &package_cpath).as_str());
114                result.push('\n')
115            }
116            if !args.no_bin {
117                let path = mk_bin_path(&paths, prepend)?;
118                if !path.is_empty() {
119                    result.push_str(format_export(&shell, "PATH", &path).as_str());
120                    result.push('\n')
121                }
122            }
123            if !no_init {
124                result.push_str(format_export(&shell, "LUA_INIT", &paths.init()).as_str());
125                result.push('\n')
126            }
127            println!("{}", &result);
128        }
129        PathCmd::Lua => println!("{}", &mk_package_path(&paths, prepend)?),
130        PathCmd::C => println!("{}", &mk_package_cpath(&paths, prepend)?),
131        PathCmd::Bin => println!("{}", &mk_bin_path(&paths, prepend)?),
132        PathCmd::Init => println!("{}", paths.init()),
133    }
134    Ok(())
135}
136
137fn mk_package_path(paths: &Paths, prepend: bool) -> Result<PackagePath> {
138    let mut result = if prepend {
139        PackagePath::from_str(env::var("LUA_PATH").unwrap_or_default().as_str()).unwrap_or_default()
140    } else {
141        PackagePath::default()
142    };
143    result.prepend(paths.package_path());
144    Ok(result)
145}
146
147fn mk_package_cpath(paths: &Paths, prepend: bool) -> Result<PackagePath> {
148    let mut result = if prepend {
149        PackagePath::from_str(env::var("LUA_CPATH").unwrap_or_default().as_str())
150            .unwrap_or_default()
151    } else {
152        PackagePath::default()
153    };
154    result.prepend(paths.package_cpath());
155    Ok(result)
156}
157
158fn mk_bin_path(paths: &Paths, prepend: bool) -> Result<BinPath> {
159    let mut result = if prepend {
160        BinPath::from_env()
161    } else {
162        BinPath::default()
163    };
164    result.prepend(paths.path());
165    Ok(result)
166}
167
168fn format_export<D>(shell: &Shell, var_name: &str, var: &D) -> String
169where
170    D: std::fmt::Display,
171{
172    match shell {
173        Shell::Posix => format!("export {}='{}';", var_name, var),
174        Shell::Fish => format!("set -x {} \"{}\";", var_name, var),
175        Shell::Nu => format!("$env.{} = \"{}\";", var_name, var),
176    }
177}