Skip to main content

scoop_fsearch/
lib.rs

1//! `scoop search` alternative.
2
3#![warn(missing_docs)]
4
5#[cfg(test)]
6mod tests;
7#[cfg(windows)]
8mod windows;
9
10use serde_json::Value;
11
12// Number of worker threads if an optimal one cannot be determined.
13const DEFAULT_THREADS: usize = 2;
14/// Maximum number of worker threads.
15const MAX_THREADS: usize = 12;
16
17/// Marker for where/how a match is found.
18///
19/// This enum is specifically written to also be usable as a line prefix
20/// character to make the lines sort nicely (exact matches first, and so on).
21#[derive(Clone, Copy)]
22#[repr(u8)]
23enum MatchMarker {
24    /// Exact package name match: `!`.
25    Exact = b'!',
26    /// Package name match: `"`.
27    Name,
28    /// Description match: `#`.
29    Desc,
30    /// Executable filename match: `$`.
31    Bin,
32}
33
34/// Terminal escape strings to format the output text.
35#[derive(Clone)]
36struct Color {
37    /// Formatting reset.
38    default: &'static str,
39    /// Highlighting formats, corresponding to [`MatchMarker`] members.
40    highlight: [&'static str; 4],
41    /// Underline start.
42    underline: &'static str,
43    /// Underline end.
44    underline_off: &'static str,
45}
46impl Color {
47    /// Gets the highlighting format that matches a marker.
48    fn highlight(&self, marker: MatchMarker) -> &'static str {
49        self.highlight[marker as usize - MatchMarker::Exact as usize]
50    }
51}
52/// Normal color strings.
53const COLOR: Color = Color {
54    // https://man7.org/linux/man-pages/man4/console_codes.4.html
55    // (search for SGR)
56    default: "\x1B[m",
57    highlight: ["\x1B[92m", "\x1B[93m", "\x1B[96m", "\x1B[97m"],
58    underline: "\x1B[4m",
59    underline_off: "\x1B[24m",
60};
61/// Empty color strings.
62const NO_COLOR: Color = Color {
63    default: "",
64    highlight: ["", "", "", ""],
65    underline: "",
66    underline_off: "",
67};
68
69/// Reads a file and parses it as JSON.
70fn parse_json_file(path: impl AsRef<std::path::Path>) -> Option<Value> {
71    // We expect the file to be small, so slurping it first makes this faster.
72    // In particular, do not use serde_json::from_reader here; see
73    // https://github.com/serde-rs/json/issues/160
74    let buf = std::fs::read(path).ok()?;
75    serde_json::from_slice(&buf).ok()
76}
77
78/// Checks whether a JSON node contains a "bin" that matches a keyword.
79///
80/// `keyword` must have already gone through [`str::to_uppercase`].
81///
82/// The value of "bin" is a shim definition, which can either be:
83/// * the executable path, or
84/// * an array, where each item is either:
85///   * an executable path,
86///   * an executable path inside a single-element array (not recommended; this
87///     form is not used in the core and extras buckets), or
88///   * a renamed shim definition, which is an array containing:
89///     * the original executable path (not searched, unlike `scoop search`),
90///     * the file stem of the shim, and
91///     * optionally, arguments to the executable (not searched).
92///
93/// In TypeScript, the type would be
94/// ```typescript
95/// | string
96/// | (
97///   | string
98///   | [string]
99///   | [string, string, ...string[]]
100///   )[]
101/// ```
102fn 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() // This was originally a string
110                .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 this is an array, first value is shim target, (optional)
129                // second value is shim name.
130                // TODO: This code may not be quite right; shim name should not
131                // be stemmed.
132                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
143/// Checks whether any "bin" in a package JSON matches a keyword.
144fn 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
156/// Underlines (case-insensitive) occurences of `needle` within `haystack`.
157///
158/// `needle` must have already gone through [`str::to_uppercase`].
159///
160/// Returns `None` if there is no match.
161/// Otherwise, returns `Some((underlined_string, is_exact_match))`.
162fn 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        // Too hard, so don't bother underlining
171        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    // Allocate result assuming that usually there is at most one match
179    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
200/// Finds match in a package JSON object.
201///
202/// Returns `Some((marker, package_name, version, description))` if found,
203/// otherwise `None`.
204fn 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
252/// Reads, parses, and finds match in a file.
253fn 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    // Make sure the output is parsable
267    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
294/// Enumerates files in a bucket directory and runs [`process_file`] on each.
295///
296/// If the directory contains a readable subdirectory named "bucket", it is used
297/// as the bucket directory instead of the original.
298///
299/// IO errors on individual files are ignored.
300/// The only time this function returns an error is when the initial directory
301/// read fails.
302fn 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        // The unwrap is ensured by the extension filter
319        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
338/// Gets the Scoop directory.
339pub 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            // NOTE: Scoop 0.3.0 (2022-10-10) changed this from rootPath to
352            // root_path
353            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
364/// Runs the program.
365pub 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    // https://no-color.org/
371    let color = if get_env("NO_COLOR").is_none() {
372        // NOTE: enable_vt fails if stdout is not a terminal, but it doesn't
373        // matter; we still need to output colors
374        #[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}