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 #[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 Full(FullArgs),
32 Lua,
35 C,
38 Bin,
41 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 #[clap(default_value_t = false)]
56 #[arg(long)]
57 no_bin: bool,
58
59 #[clap(default_value_t = false)]
63 #[arg(long)]
64 no_loader: bool,
65
66 #[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}