Skip to main content

lux_cli/
search.rs

1use std::collections::HashMap;
2
3use clap::Args;
4use itertools::Itertools;
5use miette::{IntoDiagnostic, Result};
6use text_trees::{FormatCharacters, StringTreeNode, TreeFormatting};
7
8use lux_lib::{
9    config::Config,
10    package::{PackageName, PackageReq, PackageVersion},
11    progress::MultiProgress,
12    remote_package_db::RemotePackageDB,
13};
14
15use crate::args::OutputFormat;
16
17#[derive(Args)]
18pub struct Search {
19    lua_package_req: PackageReq,
20    // TODO(vhyrro): Add options.
21    #[arg(long, default_value = "text", value_enum, ignore_case = true)]
22    output_format: OutputFormat,
23}
24
25pub async fn search(data: Search, config: Config) -> Result<()> {
26    let progress = MultiProgress::new(&config);
27    let bar = progress.map(MultiProgress::new_bar);
28    let formatting = TreeFormatting::dir_tree(FormatCharacters::box_chars());
29
30    let package_db = RemotePackageDB::from_config(&config, &bar).await?;
31
32    bar.map(|b| b.set_message(format!("🔎 Searching for `{}`...", data.lua_package_req)));
33
34    let lua_package_req = data.lua_package_req;
35
36    let result = package_db.search(&lua_package_req);
37
38    bar.map(|b| b.finish_and_clear());
39
40    match data.output_format {
41        OutputFormat::Json => {
42            let rock_to_version_map: HashMap<&PackageName, Vec<&PackageVersion>> =
43                HashMap::from_iter(result);
44            println!(
45                "{}",
46                serde_json::to_string(&rock_to_version_map).into_diagnostic()?
47            );
48        }
49        OutputFormat::Text => {
50            for (key, versions) in result.into_iter().sorted() {
51                let mut tree = StringTreeNode::new(key.to_string().to_owned());
52
53                for version in versions {
54                    tree.push(version.to_string());
55                }
56
57                println!(
58                    "{}",
59                    tree.to_string_with_format(&formatting).into_diagnostic()?
60                );
61            }
62        }
63    }
64
65    Ok(())
66}