1#![warn(missing_docs)]
4
5#[cfg(test)]
6mod tests;
7#[cfg(windows)]
8mod windows;
9
10use serde_json::Value;
11
12const DEFAULT_THREADS: usize = 2;
14const MAX_THREADS: usize = 12;
16
17#[derive(Clone, Copy)]
22#[repr(u8)]
23enum MatchMarker {
24 Exact = b'!',
26 Name,
28 Desc,
30 Bin,
32}
33
34#[derive(Clone)]
36struct Color {
37 default: &'static str,
39 highlight: [&'static str; 4],
41 underline: &'static str,
43 underline_off: &'static str,
45}
46impl Color {
47 fn highlight(&self, marker: MatchMarker) -> &'static str {
49 self.highlight[marker as usize - MatchMarker::Exact as usize]
50 }
51}
52const COLOR: Color = Color {
54 default: "\x1B[m",
57 highlight: ["\x1B[92m", "\x1B[93m", "\x1B[96m", "\x1B[97m"],
58 underline: "\x1B[4m",
59 underline_off: "\x1B[24m",
60};
61const NO_COLOR: Color = Color {
63 default: "",
64 highlight: ["", "", "", ""],
65 underline: "",
66 underline_off: "",
67};
68
69fn parse_json_file(path: impl AsRef<std::path::Path>) -> Option<Value> {
71 let buf = std::fs::read(path).ok()?;
75 serde_json::from_slice(&buf).ok()
76}
77
78fn match_bin_inner(node: &Value, keyword: &str) -> bool {
103 debug_assert_eq!(keyword.to_uppercase(), keyword);
104 fn get_bin_name(path: &str) -> Option<String> {
105 Some(
106 std::path::PathBuf::from(path)
107 .file_stem()?
108 .to_str()
109 .unwrap() .to_uppercase(),
111 )
112 }
113 fn bin_match(keyword: &str, bin: &Value) -> bool {
114 bin.as_str()
115 .and_then(get_bin_name)
116 .map(|bin| bin.contains(keyword))
117 .unwrap_or(false)
118 }
119 if let Some(bin) = node.get("bin") {
120 if bin_match(keyword, bin) {
121 return true;
122 }
123 if let Some(bin) = bin.as_array() {
124 for bin in bin {
125 if bin_match(keyword, bin) {
126 return true;
127 }
128 if let Some([_, bin, ..] | [bin]) = bin.as_array().map(Vec::as_slice) {
133 if bin_match(keyword, bin) {
134 return true;
135 }
136 }
137 }
138 }
139 }
140 false
141}
142
143fn match_bin(pkg: &Value, keyword: &str) -> bool {
145 if match_bin_inner(pkg, keyword) {
146 return true;
147 }
148 pkg.get("architecture")
149 .and_then(Value::as_object)
150 .is_some_and(|arch| {
151 arch.values()
152 .any(|arch_val| match_bin_inner(arch_val, keyword))
153 })
154}
155
156fn find_and_underline(haystack: &str, needle: &str, color: &Color) -> Option<(String, bool)> {
163 debug_assert_eq!(needle.to_uppercase(), needle);
164 if needle.is_empty() {
165 return Some((haystack.to_owned(), false));
166 }
167 let haystack_upper = haystack.to_uppercase();
168
169 if haystack_upper.len() != haystack.len() {
170 if haystack_upper.contains(needle) {
172 return Some((haystack.to_owned(), haystack_upper.len() == needle.len()));
173 } else {
174 return None;
175 };
176 }
177
178 let mut result =
180 String::with_capacity(haystack.len() + color.underline.len() + color.underline_off.len());
181 let mut first: usize = 0;
182 let mut last: usize = 0;
183 for (i, _) in haystack_upper.match_indices(needle) {
184 result.push_str(&haystack[last..i]);
185 result.push_str(color.underline);
186 result.push_str(&haystack[i..i + needle.len()]);
187 result.push_str(color.underline_off);
188 last = i + needle.len();
189 if first == 0 {
190 first = i;
191 }
192 }
193 if last == 0 {
194 return None;
195 }
196 result.push_str(&haystack[last..]);
197 Some((result, first == 0 && last == haystack.len()))
198}
199
200fn match_pkg<'a>(
205 pkg: Option<&'a Value>,
206 pkg_name: String,
207 keyword: &str,
208 color: &Color,
209) -> Option<(MatchMarker, String, Option<&'a str>, Option<String>)> {
210 let (ver, desc) = pkg
211 .map(|pkg| {
212 (
213 pkg.get("version").and_then(Value::as_str),
214 pkg.get("description").and_then(Value::as_str),
215 )
216 })
217 .unwrap_or_default();
218 if keyword.is_empty() {
219 return Some((
220 MatchMarker::Name,
221 pkg_name,
222 ver,
223 desc.map(ToOwned::to_owned),
224 ));
225 }
226 if let Some((pkg_name, exact)) = find_and_underline(&pkg_name, keyword, color) {
227 let marker = if exact {
228 MatchMarker::Exact
229 } else {
230 MatchMarker::Name
231 };
232 let desc = desc.map(|desc| match find_and_underline(desc, keyword, color) {
233 Some((desc, _)) => desc,
234 None => desc.to_owned(),
235 });
236 Some((marker, pkg_name, ver, desc))
237 } else {
238 if let Some(desc) = desc.as_ref() {
239 if let Some((desc, _)) = find_and_underline(desc, keyword, color) {
240 return Some((MatchMarker::Desc, pkg_name, ver, Some(desc)));
241 }
242 }
243 if let Some(pkg) = pkg {
244 if match_bin(pkg, keyword) {
245 return Some((MatchMarker::Bin, pkg_name, ver, desc.map(ToOwned::to_owned)));
246 }
247 }
248 None
249 }
250}
251
252fn process_file(
254 path: &std::path::Path,
255 pkg_name: String,
256 keyword: &str,
257 color: &Color,
258 out_buf: Option<&std::sync::Arc<std::sync::Mutex<String>>>,
259) {
260 let pkg = parse_json_file(path);
261 let Some((marker, pkg_name, ver, desc)) = match_pkg(pkg.as_ref(), pkg_name, keyword, color)
262 else {
263 return;
264 };
265
266 if pkg_name.bytes().any(|c| matches!(c, b'\n' | b' ')) {
268 return;
269 }
270 let ver = ver
271 .and_then(|s| s.bytes().all(|c| !matches!(c, b'\n' | b']')).then_some(s))
272 .unwrap_or_default();
273 let desc = desc.map_or_else(
274 || "".to_owned(),
275 |s| s.chars().map(|c| if c == '\n' { ' ' } else { c }).collect(),
276 );
277
278 let line = format!(
279 "{marker} {highlight}{pkg_name}{default} [{ver}]: {desc}\n",
280 marker = marker as u8 as char,
281 highlight = color.highlight(marker),
282 default = color.default,
283 );
284 if let Some(out_buf) = out_buf {
285 if let Ok(mut s) = out_buf.lock() {
286 s.push_str(&line);
287 }
288 } else {
289 use std::io::Write;
290 let _ = std::io::stdout().write_all(line.as_bytes());
291 }
292}
293
294fn process_bucket(
303 pool: Option<&threadpool::ThreadPool>,
304 pkg_dir: &std::path::Path,
305 keyword: &str,
306 color: &Color,
307 out_buf: Option<&std::sync::Arc<std::sync::Mutex<String>>>,
308) -> std::io::Result<()> {
309 let pkg_files = pkg_dir
310 .join("bucket")
311 .read_dir()
312 .or_else(|_| pkg_dir.read_dir())?;
313 let pkg_files = pkg_files
314 .filter_map(Result::ok)
315 .map(|f| f.path())
316 .filter(|f| f.extension() == Some(std::ffi::OsStr::new("json")));
317 for pkg_file in pkg_files {
318 let pkg_name = pkg_file.file_stem().unwrap();
320 let pkg_name = match pkg_name.to_str() {
321 Some(s) => s.to_owned(),
322 None => continue,
323 };
324 if let Some(pool) = pool {
325 let keyword = keyword.to_owned();
326 let color = color.to_owned();
327 let out_buf = out_buf.map(std::clone::Clone::clone);
328 pool.execute(move || {
329 process_file(&pkg_file, pkg_name, &keyword, &color, out_buf.as_ref());
330 });
331 } else {
332 process_file(&pkg_file, pkg_name, keyword, color, out_buf);
333 }
334 }
335 Ok(())
336}
337
338pub fn get_scoop_dir(
340 get_env: fn(&str) -> Option<std::ffi::OsString>,
341) -> Result<std::path::PathBuf, String> {
342 let get_env = |k| get_env(k).filter(|v| !v.is_empty());
343 if let Some(scoop_dir) = get_env("SCOOP") {
344 return Ok(scoop_dir.into());
345 }
346 if let Some(home_dir) = get_env("USERPROFILE") {
347 let home_dir = std::path::PathBuf::from(home_dir);
348 if let Some(Value::Object(config)) =
349 parse_json_file(home_dir.join(".config/scoop/config.json"))
350 {
351 if let Some(Value::String(scoop_dir)) =
354 config.get("root_path").or_else(|| config.get("rootPath"))
355 {
356 return Ok(scoop_dir.into());
357 }
358 }
359 return Ok(home_dir.join("scoop"));
360 }
361 Err("The SCOOP or USERPROFILE environment variable must be set and not empty\n".to_owned())
362}
363
364pub fn main(
366 mut args: impl Iterator<Item = std::ffi::OsString>,
367 get_env: fn(&str) -> Option<std::ffi::OsString>,
368 out_buf: Option<&std::sync::Arc<std::sync::Mutex<String>>>,
369) -> Result<(), String> {
370 let color = if get_env("NO_COLOR").is_none() {
372 #[cfg(windows)]
375 let _ = self::windows::enable_vt();
376 &COLOR
377 } else {
378 &NO_COLOR
379 };
380
381 let keyword = {
382 let arg = args.nth(1);
383 match arg {
384 Some(arg) if args.next().is_none() => arg,
385 _ => {
386 return Err(format!(
387 r#"{pkg_name} {pkg_version}
388
389Syntax: {pkg_name} STRING
390
391Output legend: (if you sort the output, they will be in this order)
392 ! {hl_exact}exact package name match{default}
393 " {hl_name}package name match{default}
394 # {hl_desc}description match{default}
395 $ {hl_bin}executable filename match{default}
396
397Run with NO_COLOR set if you don't want colors.
398"#,
399 pkg_name = env!("CARGO_PKG_NAME"),
400 pkg_version = env!("CARGO_PKG_VERSION"),
401 hl_exact = color.highlight(MatchMarker::Exact),
402 hl_name = color.highlight(MatchMarker::Name),
403 hl_desc = color.highlight(MatchMarker::Desc),
404 hl_bin = color.highlight(MatchMarker::Bin),
405 default = color.default,
406 ));
407 }
408 }
409 };
410 let keyword = keyword
411 .to_str()
412 .ok_or("Search string must be valid Unicode\n")?
413 .to_uppercase();
414
415 let scoop_dir = get_scoop_dir(get_env)?;
416 let buckets_dir = scoop_dir.join("buckets");
417
418 #[allow(clippy::assertions_on_constants)]
419 const _: () = debug_assert!(DEFAULT_THREADS <= MAX_THREADS);
420 let n_threads =
421 std::thread::available_parallelism().map_or(DEFAULT_THREADS, |n| n.get().min(MAX_THREADS));
422
423 let pool = threadpool::ThreadPool::with_name("worker".to_owned(), n_threads);
424
425 let pkg_dirs = buckets_dir
426 .read_dir()
427 .map_err(|_| "Error reading Scoop buckets directory\n")?
428 .filter_map(Result::ok)
429 .map(|d| d.path());
430 for pkg_dir in pkg_dirs {
431 let pool1 = pool.clone();
432 let keyword = keyword.clone();
433 let out_buf = out_buf.map(std::clone::Clone::clone);
434 pool.execute(move || {
435 let _ = process_bucket(Some(&pool1), &pkg_dir, &keyword, color, out_buf.as_ref());
436 });
437 }
438
439 pool.join();
440 Ok(())
441}