aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart/src/commands/search.rs
blob: 7259e6c72956019c9951131b6af15c82e9f3c07e (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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use clap::Args;
use mozart_core::console::{IoInterface, hyperlink};
use mozart_core::console_format;
use mozart_core::console_writeln;
use mozart_core::repository::packagist::SearchResult;
use mozart_core::repository::repository::{RepositorySet, SearchMode};
use serde::Serialize;

/// JSON output structure matching Composer's search result schema.
///
/// Composer outputs only `name`, `description`, `url`, and optionally `abandoned`.
#[derive(Serialize)]
struct SearchResultOutput {
    name: String,
    description: String,
    url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    abandoned: Option<serde_json::Value>,
}

impl From<&SearchResult> for SearchResultOutput {
    fn from(r: &SearchResult) -> Self {
        Self {
            name: r.name.clone(),
            description: r.description.clone(),
            url: r.url.clone(),
            abandoned: r.abandoned.clone(),
        }
    }
}

#[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>,
}

/// Returns true if the search result represents an abandoned package.
///
/// The `abandoned` field from the Packagist API can be:
/// - absent (`None`) — not abandoned
/// - a non-empty string — abandoned, with a replacement package name
/// - `true` — abandoned, no replacement
/// - an empty string or `false` — not abandoned
fn is_abandoned(result: &SearchResult) -> bool {
    match &result.abandoned {
        None => false,
        Some(serde_json::Value::Bool(b)) => *b,
        Some(serde_json::Value::String(s)) => !s.is_empty(),
        Some(_) => true,
    }
}

pub async fn execute(
    args: &SearchArgs,
    cli: &super::Cli,
    io: std::sync::Arc<std::sync::Mutex<Box<dyn IoInterface>>>,
) -> anyhow::Result<()> {
    // 1. Format check first — matches Composer's `SearchCommand::execute`
    //    L61-66 ordering.
    let format = args.format.as_deref().unwrap_or("text");
    if !matches!(format, "text" | "json") {
        io.lock().unwrap().error(&console_format!(
            "<error>Unsupported format \"{format}\". See help for supported formats.</error>"
        ));
        return Err(mozart_core::exit_code::bail_silent(
            mozart_core::exit_code::GENERAL_ERROR,
        ));
    }

    // 2. Mutex check on the two scoping flags. Composer's
    //    `RepositoryFactory::generateRepositoryManager` precedes this with
    //    `tryComposer`; we skip until configured-repos support lands.
    if args.only_name && args.only_vendor {
        anyhow::bail!("--only-name and --only-vendor cannot be used together");
    }

    // 3. Mode resolution. Composer checks `--only-vendor` before `--only-name`
    //    (`SearchCommand::execute` L78-86), so vendor wins if both are set —
    //    but the mutex check above already guards that.
    let mode = if args.only_vendor {
        SearchMode::Vendor
    } else if args.only_name {
        SearchMode::Name
    } else {
        SearchMode::Fulltext
    };

    // 4. Build the query string. Composer joins tokens with a single space
    //    and `preg_quote`s the result for non-fulltext modes so that user
    //    input like `c++` is matched literally rather than as regex
    //    metacharacters.
    let mut query = args.tokens.join(" ");
    if !matches!(mode, SearchMode::Fulltext) {
        query = regex::escape(&query);
    }

    // 5. Build the repository set. Configured remote repositories from
    //    `composer.json` are not yet wired up; this is a known divergence
    //    from Composer's full `CompositeRepository`.
    let cache_config = mozart_core::repository::cache::build_cache_config(cli.no_cache);
    let repo_cache = mozart_core::repository::cache::Cache::repo(&cache_config);
    let repos = RepositorySet::with_packagist(repo_cache);

    // 6. Dispatch.
    let results = repos.search(&query, mode, args.r#type.as_deref()).await?;

    // 7. Render. Empty results emit nothing in text mode (matches Composer)
    //    and `[]` in JSON mode.
    match format {
        "json" => render_json(&results, io.clone())?,
        _ => render_text(&results, io.clone()),
    }

    Ok(())
}

/// Render results as JSON with 4-space indent, matching Composer's
/// `JsonFile::encode` output (`JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES |
/// JSON_UNESCAPED_UNICODE`). `serde_json` does not escape forward slashes
/// or non-ASCII Unicode by default, so the encoder configuration alone
/// covers the latter two flags.
fn render_json(
    results: &[SearchResult],
    io: std::sync::Arc<std::sync::Mutex<Box<dyn IoInterface>>>,
) -> anyhow::Result<()> {
    let output: Vec<SearchResultOutput> = results.iter().map(SearchResultOutput::from).collect();
    let buf = Vec::new();
    let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
    let mut ser = serde_json::Serializer::with_formatter(buf, formatter);
    output.serialize(&mut ser)?;
    console_writeln!(io, "{}", &String::from_utf8(ser.into_inner())?);
    Ok(())
}

/// Render results in Composer's text format. For each row:
/// - `<href=URL>name</>` (terminal hyperlink) when `url` is non-empty,
///   else plain `name`, padded to the longest-name column.
/// - `<warning>! Abandoned !</warning> ` prefix when abandoned.
/// - Description, truncated with `...` to fit the terminal width.
fn render_text(
    results: &[SearchResult],
    io: std::sync::Arc<std::sync::Mutex<Box<dyn IoInterface>>>,
) {
    if results.is_empty() {
        return;
    }

    let width = terminal_size::terminal_size()
        .map(|(w, _)| w.0 as usize)
        .unwrap_or(80);
    let name_length = results.iter().map(|r| r.name.len()).max().unwrap_or(0) + 1;

    for result in results {
        let warning = if is_abandoned(result) {
            console_format!("<warning>! Abandoned !</warning> ")
        } else {
            String::new()
        };

        // Composer uses `Console::strlen` on the warning fragment which
        // strips formatter tags before measuring; here we count the visible
        // chars manually since the styled string contains ANSI bytes.
        let visible_warning_len = if warning.is_empty() { 0 } else { 14 };
        let remaining = width.saturating_sub(name_length + visible_warning_len);
        let description = result.description.as_str();
        let desc_display = if description.chars().count() > remaining && remaining > 3 {
            let cutoff: String = description.chars().take(remaining - 3).collect();
            format!("{cutoff}...")
        } else {
            description.to_string()
        };

        let padding_width = name_length.saturating_sub(result.name.len());
        let padded_name = if !result.url.is_empty() {
            format!(
                "{}{}",
                hyperlink(&result.url, &result.name, io.lock().unwrap().is_decorated()),
                " ".repeat(padding_width)
            )
        } else {
            format!("{}{}", result.name, " ".repeat(padding_width))
        };

        console_writeln!(io, "{padded_name}{warning}{desc_display}");
    }
}

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

    #[test]
    fn test_parse_search_response() {
        use mozart_core::repository::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_abandoned() {
        use mozart_core::repository::packagist::SearchResponse;

        let json = r#"{
            "results": [
                {
                    "name": "old/abandoned-pkg",
                    "description": "An abandoned package",
                    "url": "https://packagist.org/packages/old/abandoned-pkg",
                    "repository": "https://github.com/old/abandoned-pkg",
                    "downloads": 1000,
                    "favers": 10,
                    "abandoned": "new/replacement-pkg"
                },
                {
                    "name": "active/pkg",
                    "description": "An active package",
                    "url": "https://packagist.org/packages/active/pkg",
                    "repository": null,
                    "downloads": 5000,
                    "favers": 100
                }
            ],
            "total": 2,
            "next": null
        }"#;

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

        let first = &response.results[0];
        assert_eq!(first.name, "old/abandoned-pkg");
        assert_eq!(
            first.abandoned.as_ref().and_then(|v| v.as_str()),
            Some("new/replacement-pkg")
        );

        let second = &response.results[1];
        assert_eq!(second.name, "active/pkg");
        assert!(second.abandoned.is_none());
    }

    #[test]
    fn test_parse_search_response_with_next() {
        use mozart_core::repository::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")
        );
    }

    #[test]
    fn test_is_abandoned_none() {
        let result = make_result("vendor/pkg");
        assert!(!is_abandoned(&result));
    }

    #[test]
    fn test_is_abandoned_true() {
        let mut result = make_result("vendor/pkg");
        result.abandoned = Some(serde_json::Value::Bool(true));
        assert!(is_abandoned(&result));
    }

    #[test]
    fn test_is_abandoned_false() {
        let mut result = make_result("vendor/pkg");
        result.abandoned = Some(serde_json::Value::Bool(false));
        assert!(!is_abandoned(&result));
    }

    #[test]
    fn test_is_abandoned_replacement_string() {
        let mut result = make_result("vendor/pkg");
        result.abandoned = Some(serde_json::Value::String("other/pkg".to_string()));
        assert!(is_abandoned(&result));
    }

    #[test]
    fn test_is_abandoned_empty_string() {
        let mut result = make_result("vendor/pkg");
        result.abandoned = Some(serde_json::Value::String(String::new()));
        assert!(!is_abandoned(&result));
    }

    #[test]
    fn test_search_result_output_matches_composer_schema() {
        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,
            abandoned: None,
        };

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

        assert_eq!(parsed["name"], "test/pkg");
        assert_eq!(parsed["description"], "A test package");
        assert_eq!(parsed["url"], "https://packagist.org/packages/test/pkg");
        // Composer schema does not include repository, downloads, or favers
        assert!(parsed.get("repository").is_none());
        assert!(parsed.get("downloads").is_none());
        assert!(parsed.get("favers").is_none());
        // abandoned is skipped when None
        assert!(parsed.get("abandoned").is_none());
    }

    #[test]
    fn test_search_result_output_with_abandoned() {
        let result = SearchResult {
            name: "old/pkg".to_string(),
            description: "Old package".to_string(),
            url: "https://packagist.org/packages/old/pkg".to_string(),
            repository: None,
            downloads: 0,
            favers: 0,
            abandoned: Some(serde_json::Value::String("new/pkg".to_string())),
        };

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

        assert_eq!(parsed["abandoned"], "new/pkg");
    }

    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,
            abandoned: None,
        }
    }
}