1use crate::package;
2use std::{io, path::PathBuf};
3
4use crate::{
5 config::Config,
6 lua, rockspec,
7 tree::{self, InstallTree},
8};
9use bon::Builder;
10use itertools::Itertools;
11use miette::Diagnostic;
12use thiserror::Error;
13
14#[derive(Builder)]
16#[builder(start_fn = new, finish_fn(name = _build, vis = ""))]
17pub struct Which<'a> {
18 #[builder(start_fn)]
19 module: rockspec::build::backend::Module,
20 #[builder(start_fn)]
21 config: &'a Config,
22 #[builder(field)]
23 packages: Vec<package::Req>,
24}
25
26impl<State> WhichBuilder<'_, State>
27where
28 State: which_builder::State,
29{
30 pub fn package(mut self, package: package::Req) -> Self {
31 self.packages.push(package);
32 self
33 }
34
35 pub fn packages(mut self, packages: impl IntoIterator<Item = package::Req>) -> Self {
36 self.packages.extend(packages);
37 self
38 }
39
40 #[tracing::instrument(level = "trace", skip_all)]
41 pub fn search(self) -> Result<PathBuf, Error>
42 where
43 State: which_builder::IsComplete,
44 {
45 do_search(self._build())
46 }
47}
48
49#[derive(Error, Debug, Diagnostic)]
50#[non_exhaustive]
51pub enum Error {
52 #[error(transparent)]
53 Io(#[from] io::Error),
54 #[error(transparent)]
55 #[diagnostic(transparent)]
56 Tree(#[from] tree::Error),
57 #[error(transparent)]
58 #[diagnostic(transparent)]
59 LuaVersion(#[from] lua::version::Error),
60 #[error("lua module {0} not found.")]
61 ModuleNotFound(rockspec::build::backend::Module),
62}
63
64fn do_search(which: Which<'_>) -> Result<PathBuf, Error> {
65 let config = which.config;
66 let lua_version = lua::Version::from(config)?;
67 let tree = config.user_tree(lua_version.clone())?;
68 let lockfile = tree.lockfile()?;
69 let local_packages = if which.packages.is_empty() {
70 lockfile.list().into_values().flatten().collect_vec()
71 } else {
72 which
73 .packages
74 .iter()
75 .flat_map(|req| {
76 lockfile
77 .find_rocks(req)
78 .into_iter()
79 .filter_map(|id| lockfile.get(&id))
80 .cloned()
81 .collect_vec()
82 })
83 .collect_vec()
84 };
85 local_packages
86 .into_iter()
87 .filter_map(|pkg| {
88 let layout = tree.layout_for(&pkg.spec);
89 let lib_path = layout.lib.join(which.module.to_lib_path());
90 if lib_path.is_file() {
91 return Some(lib_path);
92 }
93 let lua_path = layout.src.join(which.module.to_lua_path());
94 if lua_path.is_file() {
95 return Some(lua_path);
96 }
97 let lua_path = layout.src.join(which.module.to_lua_init_path());
98 if lua_path.is_file() {
99 return Some(lua_path);
100 }
101 let luau_path = layout.src.join(which.module.to_luau_path());
102 if luau_path.is_file() {
103 return Some(luau_path);
104 }
105 let luau_init_path = layout.src.join(which.module.to_luau_init_path());
106 if luau_init_path.is_file() {
107 return Some(luau_init_path);
108 }
109 None
110 })
111 .next()
112 .ok_or(Error::ModuleNotFound(which.module))
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use crate::config;
119 use assert_fs::prelude::PathCopy;
120 use std::{path::PathBuf, str::FromStr};
121
122 #[tokio::test]
123 async fn test_which() {
124 let tree_path =
125 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("resources/test/sample-tree");
126 let temp = assert_fs::TempDir::new().unwrap();
127 temp.copy_from(&tree_path, &["**"]).unwrap();
128 let tree_path = temp.to_path_buf();
129 let config = config::Builder::new()
130 .unwrap()
131 .user_tree(Some(tree_path.clone()))
132 .lua_version(Some(lua::Version::Lua51))
133 .build()
134 .unwrap();
135
136 let result = Which::new(
137 rockspec::build::backend::Module::from_str("foo.bar").unwrap(),
138 &config,
139 )
140 .search()
141 .unwrap();
142 assert_eq!(result.file_name().unwrap().to_string_lossy(), "bar.lua");
143 assert_eq!(
144 result
145 .parent()
146 .unwrap()
147 .file_name()
148 .unwrap()
149 .to_string_lossy(),
150 "foo"
151 );
152 let result = Which::new(
153 rockspec::build::backend::Module::from_str("bat.baz").unwrap(),
154 &config,
155 )
156 .search()
157 .unwrap();
158 assert_eq!(result.file_name().unwrap().to_string_lossy(), "baz.so");
159 assert_eq!(
160 result
161 .parent()
162 .unwrap()
163 .file_name()
164 .unwrap()
165 .to_string_lossy(),
166 "bat"
167 );
168 let result = Which::new(
169 rockspec::build::backend::Module::from_str("hello").unwrap(),
170 &config,
171 )
172 .search()
173 .unwrap();
174 assert_eq!(result.file_name().unwrap().to_string_lossy(), "hello.luau");
175 let result = Which::new(
176 rockspec::build::backend::Module::from_str("extra").unwrap(),
177 &config,
178 )
179 .search()
180 .unwrap();
181 assert_eq!(result.file_name().unwrap().to_string_lossy(), "init.luau");
182 let result = Which::new(
183 rockspec::build::backend::Module::from_str("foo.bar").unwrap(),
184 &config,
185 )
186 .package("lua-cjson".parse().unwrap())
187 .search();
188 assert!(matches!(result, Err(Error::ModuleNotFound(_))));
189 let result = Which::new(
190 rockspec::build::backend::Module::from_str("foo.bar").unwrap(),
191 &config,
192 )
193 .package("neorg@8.1.1-1".parse().unwrap())
194 .search();
195 assert!(matches!(result, Err(Error::ModuleNotFound(_))));
196 }
197}