aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart/src/commands/search.rs
blob: f1454602d2e3623e3ae110935f47119bc8cf1b68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use clap::Args;
use mozart_registry::packagist::SearchResult;

#[derive(Args)]
pub struct SearchArgs {
    /// Search tokens
    #[arg(required = true)]
    pub tokens: Vec<String>,

    /// Search only in name
    #[arg(short = 'N', long)]
    pub only_name: bool,

    /// Search only for vendor / organization
    #[arg(short = 'O', long)]
    pub only_vendor: bool,

    /// Filter by package type
    #[arg(short, long, value_name = "TYPE")]
    pub r#type: Option<String>,

    /// Output format (text, json)
    #[arg(short, long)]
    pub format: Option<String>,
}

/// Format a large count as a human-readable string (e.g. 1500 -> "1.5K", 2500000 -> "2.5M").
fn format_count(n: u64) -> String {
    if n >= 1_000_000 {
        let m = n as f64 / 1_000_000.0;
        // Show one decimal place only when needed
        if (m - m.floor()).abs() < 0.05 {
            format!("{}M", m.floor() as u64)
        } else {
            format!("{:.1}M", m)
        }
    } else if n >= 1_000 {
        let k = n as f64 / 1_000.0;
        if (k - k.floor()).abs() < 0.05 {
            format!("{}K", k.floor() as u64)
        } else {
            format!("{:.1}K", k)
        }
    } else {
        n.to_string()
    }
}

/// Returns true if the result passes the `--only-name` filter: the package name must contain
/// the query string (case-insensitive).
fn passes_only_name(result: &SearchResult, query: &str) -> bool {
    result.name.to_lowercase().contains(&query.to_lowercase())
}

/// Returns true if the result passes the `--only-vendor` filter: the vendor portion of the
/// package name (before the `/`) must equal the query (case-insensitive).
fn passes_only_vendor(result: &SearchResult, query: &str) -> bool {
    let vendor = result.name.split('/').next().unwrap_or("");
    vendor.eq_ignore_ascii_case(query)
}

pub async fn execute(
    args: &SearchArgs,
    _cli: &super::Cli,
    _console: &mozart_core::console::Console,
) -> anyhow::Result<()> {
    if args.only_name && args.only_vendor {
        anyhow::bail!("--only-name and --only-vendor cannot be used together");
    }

    let query = args.tokens.join(" ");

    let format = args.format.as_deref().unwrap_or("text");

    if !matches!(format, "text" | "json") {
        eprintln!(
            "{}",
            mozart_core::console::error(&format!(
                "Unsupported format \"{format}\". See help for supported formats."
            ))
        );
        std::process::exit(1);
    }

    let (all_results, total) =
        mozart_registry::packagist::search_packages(&query, args.r#type.as_deref()).await?;

    // Apply client-side filters
    let mut results: Vec<&SearchResult> = all_results.iter().collect();

    if args.only_name {
        results.retain(|r| passes_only_name(r, &query));
    }

    if args.only_vendor {
        results.retain(|r| passes_only_vendor(r, &query));
    }

    // Output
    match format {
        "json" => {
            let owned: Vec<SearchResult> = results.into_iter().cloned().collect();
            let json = serde_json::to_string_pretty(&owned)?;
            println!("{json}");
        }
        _ => {
            if results.is_empty() {
                eprintln!(
                    "{}",
                    mozart_core::console::warning(&format!("No packages found for \"{query}\""))
                );
                return Ok(());
            }

            eprintln!(
                "Found {} packages matching \"{}\" (showing {} result{})",
                total,
                query,
                results.len(),
                if results.len() == 1 { "" } else { "s" }
            );
            eprintln!();

            // Calculate alignment widths
            let name_width = results.iter().map(|r| r.name.len()).max().unwrap_or(0);

            for result in &results {
                let dl_str = format!("Downloads: {}", format_count(result.downloads));
                let fav_str = format!("Favers: {}", format_count(result.favers));

                println!(
                    "{} {}  {}",
                    mozart_core::console::info(&format!(
                        "{:<width$}",
                        result.name,
                        width = name_width
                    )),
                    mozart_core::console::comment(&dl_str),
                    mozart_core::console::comment(&fav_str),
                );
                if !result.description.is_empty() {
                    println!("  {}", result.description);
                }
            }
        }
    }

    Ok(())
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── format_count ────────────────────────────────────────────────────────

    #[test]
    fn test_format_count_small() {
        assert_eq!(format_count(0), "0");
        assert_eq!(format_count(42), "42");
        assert_eq!(format_count(999), "999");
    }

    #[test]
    fn test_format_count_thousands() {
        assert_eq!(format_count(1_000), "1K");
        assert_eq!(format_count(1_500), "1.5K");
        assert_eq!(format_count(2_500), "2.5K");
        assert_eq!(format_count(10_000), "10K");
    }

    #[test]
    fn test_format_count_millions() {
        assert_eq!(format_count(1_000_000), "1M");
        assert_eq!(format_count(1_500_000), "1.5M");
        assert_eq!(format_count(2_500_000), "2.5M");
    }

    // ── SearchResponse parsing ───────────────────────────────────────────────

    #[test]
    fn test_parse_search_response() {
        use mozart_registry::packagist::SearchResponse;

        let json = r#"{
            "results": [
                {
                    "name": "monolog/monolog",
                    "description": "Sends your logs to files, sockets, inboxes, databases and various web services",
                    "url": "https://packagist.org/packages/monolog/monolog",
                    "repository": "https://github.com/Seldaek/monolog",
                    "downloads": 500000000,
                    "favers": 20000
                },
                {
                    "name": "psr/log",
                    "description": "Common interface for logging libraries",
                    "url": "https://packagist.org/packages/psr/log",
                    "repository": null,
                    "downloads": 800000000,
                    "favers": 10000
                }
            ],
            "total": 2,
            "next": null
        }"#;

        let response: SearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.results.len(), 2);
        assert_eq!(response.total, 2);
        assert!(response.next.is_none());

        let first = &response.results[0];
        assert_eq!(first.name, "monolog/monolog");
        assert_eq!(first.downloads, 500_000_000);
        assert_eq!(first.favers, 20_000);
        assert_eq!(
            first.repository.as_deref(),
            Some("https://github.com/Seldaek/monolog")
        );

        let second = &response.results[1];
        assert_eq!(second.name, "psr/log");
        assert!(second.repository.is_none());
    }

    #[test]
    fn test_parse_search_response_with_next() {
        use mozart_registry::packagist::SearchResponse;

        let json = r#"{
            "results": [],
            "total": 100,
            "next": "https://packagist.org/search.json?q=monolog&page=2"
        }"#;

        let response: SearchResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.total, 100);
        assert_eq!(
            response.next.as_deref(),
            Some("https://packagist.org/search.json?q=monolog&page=2")
        );
    }

    // ── only_name filter ─────────────────────────────────────────────────────

    #[test]
    fn test_passes_only_name_match() {
        let result = make_result("monolog/monolog");
        assert!(passes_only_name(&result, "monolog"));
    }

    #[test]
    fn test_passes_only_name_partial_match() {
        let result = make_result("monolog/monolog");
        assert!(passes_only_name(&result, "mono"));
    }

    #[test]
    fn test_passes_only_name_case_insensitive() {
        let result = make_result("Monolog/Monolog");
        assert!(passes_only_name(&result, "monolog"));
    }

    #[test]
    fn test_passes_only_name_no_match() {
        let result = make_result("symfony/console");
        assert!(!passes_only_name(&result, "monolog"));
    }

    #[test]
    fn test_passes_only_name_vendor_part_matches() {
        let result = make_result("monolog/handler");
        assert!(passes_only_name(&result, "monolog"));
    }

    // ── only_vendor filter ───────────────────────────────────────────────────

    #[test]
    fn test_passes_only_vendor_match() {
        let result = make_result("monolog/monolog");
        assert!(passes_only_vendor(&result, "monolog"));
    }

    #[test]
    fn test_passes_only_vendor_case_insensitive() {
        let result = make_result("Monolog/SomePackage");
        assert!(passes_only_vendor(&result, "monolog"));
    }

    #[test]
    fn test_passes_only_vendor_no_match() {
        // query "monolog" as vendor but package vendor is "symfony"
        let result = make_result("symfony/console");
        assert!(!passes_only_vendor(&result, "monolog"));
    }

    #[test]
    fn test_passes_only_vendor_partial_does_not_match() {
        // only_vendor requires exact vendor match, not substring
        let result = make_result("monolog/monolog");
        assert!(!passes_only_vendor(&result, "mono"));
    }

    // ── serialization ────────────────────────────────────────────────────────

    #[test]
    fn test_search_result_serializes_to_json() {
        let result = SearchResult {
            name: "test/pkg".to_string(),
            description: "A test package".to_string(),
            url: "https://packagist.org/packages/test/pkg".to_string(),
            repository: Some("https://github.com/test/pkg".to_string()),
            downloads: 1000,
            favers: 50,
        };

        let json = serde_json::to_string(&result).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["name"], "test/pkg");
        assert_eq!(parsed["downloads"], 1000);
        assert_eq!(parsed["favers"], 50);
    }

    // ── helper ───────────────────────────────────────────────────────────────

    fn make_result(name: &str) -> SearchResult {
        SearchResult {
            name: name.to_string(),
            description: String::new(),
            url: format!("https://packagist.org/packages/{name}"),
            repository: None,
            downloads: 0,
            favers: 0,
        }
    }
}