1use itertools::Itertools;
2use path_slash::PathBufExt;
3use serde::Serialize;
4use std::{env, fmt::Display, path::PathBuf, str::FromStr};
5use thiserror::Error;
6
7use crate::{
8 build::utils::c_dylib_extension,
9 config::LuaVersion,
10 tree::{Tree, TreeError},
11};
12
13const LUA_PATH_SEPARATOR: &str = ";";
14const LUA_INIT: &str = "require('lux').loader()";
15
16#[derive(PartialEq, Eq, Debug, Serialize)]
17pub struct Paths {
18 src: PackagePath,
20 lib: PackagePath,
22 bin: BinPath,
24
25 version: LuaVersion,
26}
27
28#[derive(Debug, Error)]
29pub enum PathsError {
30 #[error(transparent)]
31 Tree(#[from] TreeError),
32}
33
34impl Paths {
35 fn default(tree: &Tree) -> Self {
36 Self {
37 src: <_>::default(),
38 lib: <_>::default(),
39 bin: <_>::default(),
40 version: tree.version().clone(),
41 }
42 }
43
44 pub fn new(tree: &Tree) -> Result<Self, PathsError> {
45 let mut paths = tree
46 .list()?
47 .into_iter()
48 .flat_map(|(_, packages)| {
49 packages
50 .into_iter()
51 .map(|package| tree.installed_rock_layout(&package))
52 .collect_vec()
53 })
54 .try_fold(Self::default(tree), |mut paths, package| {
55 let package = package?;
56 paths.src.0.push(package.src.join("?.lua"));
57 paths.src.0.push(package.src.join("?").join("init.lua"));
58 paths
59 .lib
60 .0
61 .push(package.lib.join(format!("?.{}", c_dylib_extension())));
62 paths.bin.0.push(package.bin);
63 Ok::<Paths, TreeError>(paths)
64 })?;
65
66 if let Some(lib_path) = tree.version().lux_lib_dir() {
67 paths.prepend(&Paths {
68 version: tree.version().clone(),
69 src: <_>::default(),
70 bin: <_>::default(),
71 lib: PackagePath(vec![lib_path.join(".so")]),
72 });
73 }
74
75 Ok(paths)
76 }
77
78 pub fn package_path(&self) -> &PackagePath {
80 &self.src
81 }
82
83 pub fn package_cpath(&self) -> &PackagePath {
85 &self.lib
86 }
87
88 pub fn path(&self) -> &BinPath {
90 &self.bin
91 }
92
93 pub fn init(&self) -> String {
95 format!("if _VERSION:find('{}') then {LUA_INIT} end", self.version)
96 }
97
98 pub fn path_prepended(&self) -> BinPath {
100 let mut path = BinPath::from_env();
101 path.prepend(self.path());
102 path
103 }
104
105 pub fn prepend(&mut self, other: &Self) {
106 self.src.prepend(&other.src);
107 self.lib.prepend(&other.lib);
108 self.bin.prepend(&other.bin);
109 }
110}
111
112#[derive(PartialEq, Eq, Debug, Default, Serialize)]
113pub struct PackagePath(Vec<PathBuf>);
114
115impl PackagePath {
116 pub fn prepend(&mut self, other: &Self) {
117 let mut new_vec = other.0.to_owned();
118 new_vec.append(&mut self.0);
119 self.0 = new_vec;
120 }
121 pub fn is_empty(&self) -> bool {
122 self.0.is_empty()
123 }
124 pub fn joined(&self) -> String {
125 self.0
126 .iter()
127 .unique()
128 .map(|path| path.to_slash_lossy())
129 .join(LUA_PATH_SEPARATOR)
130 }
131}
132
133impl FromStr for PackagePath {
134 type Err = &'static str;
135
136 fn from_str(s: &str) -> Result<Self, Self::Err> {
137 let paths = s
138 .trim_start_matches(LUA_PATH_SEPARATOR)
139 .trim_end_matches(LUA_PATH_SEPARATOR)
140 .split(LUA_PATH_SEPARATOR)
141 .map(PathBuf::from)
142 .collect();
143 Ok(PackagePath(paths))
144 }
145}
146
147impl Display for PackagePath {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 self.joined().fmt(f)
150 }
151}
152
153#[derive(PartialEq, Eq, Debug, Default, Serialize)]
154pub struct BinPath(Vec<PathBuf>);
155
156impl BinPath {
157 pub fn from_env() -> Self {
158 Self::from_str(env::var("PATH").unwrap_or_default().as_str()).unwrap_or_default()
159 }
160 pub fn prepend(&mut self, other: &Self) {
161 let mut new_vec = other.0.to_owned();
162 new_vec.append(&mut self.0);
163 self.0 = new_vec;
164 }
165 pub fn is_empty(&self) -> bool {
166 self.0.is_empty()
167 }
168 pub fn joined(&self) -> String {
169 env::join_paths(self.0.iter().unique())
170 .expect("Failed to join bin paths.")
171 .to_string_lossy()
172 .to_string()
173 }
174}
175
176impl FromStr for BinPath {
177 type Err = &'static str;
178
179 fn from_str(s: &str) -> Result<Self, Self::Err> {
180 let paths = env::split_paths(s).collect();
181 Ok(BinPath(paths))
182 }
183}
184
185impl Display for BinPath {
186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187 self.joined().fmt(f)
188 }
189}
190
191#[cfg(test)]
192mod test {
193 use super::*;
194
195 #[test]
196 fn package_path_leading_trailing_delimiters() {
197 let path = PackagePath::from_str(
198 ";;/path/to/some/lib/lua/5.1/?.so;/path/to/another/lib/lua/5.1/?.so;;;",
199 )
200 .unwrap();
201 assert_eq!(
202 path,
203 PackagePath(vec![
204 "/path/to/some/lib/lua/5.1/?.so".into(),
205 "/path/to/another/lib/lua/5.1/?.so".into(),
206 ])
207 );
208 assert_eq!(
209 format!("{}", path),
210 "/path/to/some/lib/lua/5.1/?.so;/path/to/another/lib/lua/5.1/?.so"
211 );
212 }
213}