terminal-info 1.3.1

An extensible terminal information CLI and developer toolbox
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use std::collections::BTreeMap;

use serde::Serialize;

use crate::plugin::{
    PluginSearchEntry, installed_plugin_search_entries, registry_plugin_search_entries,
};

#[derive(Clone)]
struct BuiltinEntry {
    command: &'static str,
    description: &'static str,
    category: &'static str,
}

#[derive(Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SearchResultKind {
    Builtin,
    Plugin,
}

#[derive(Clone, Serialize)]
pub struct SearchResult {
    pub kind: SearchResultKind,
    pub command: String,
    pub title: String,
    pub description: String,
    pub source: String,
    pub category: String,
    pub installed: bool,
    pub trusted: bool,
    pub score: i32,
}

#[derive(Serialize)]
struct SearchOutput {
    query: String,
    results: Vec<SearchResult>,
}

const BUILTIN_COMMANDS: &[BuiltinEntry] = &[
    BuiltinEntry {
        command: "weather",
        description: "Weather tools and location-aware forecasts",
        category: "weather",
    },
    BuiltinEntry {
        command: "weather now",
        description: "Show current weather for the configured location or a city",
        category: "weather",
    },
    BuiltinEntry {
        command: "weather forecast",
        description: "Show a short forecast",
        category: "weather",
    },
    BuiltinEntry {
        command: "weather hourly",
        description: "Show hourly weather",
        category: "weather",
    },
    BuiltinEntry {
        command: "weather alerts",
        description: "Show active weather alerts",
        category: "weather",
    },
    BuiltinEntry {
        command: "weather location",
        description: "Show or set the default weather location",
        category: "weather",
    },
    BuiltinEntry {
        command: "ping",
        description: "Test network latency to a host",
        category: "network",
    },
    BuiltinEntry {
        command: "latency",
        description: "Run the latency probes used by ping",
        category: "network",
    },
    BuiltinEntry {
        command: "network",
        description: "Show local network information",
        category: "network",
    },
    BuiltinEntry {
        command: "network speed",
        description: "Measure network download speed",
        category: "network",
    },
    BuiltinEntry {
        command: "system",
        description: "Show system information",
        category: "system",
    },
    BuiltinEntry {
        command: "system hardware",
        description: "Show detailed hardware inventory",
        category: "system",
    },
    BuiltinEntry {
        command: "disk",
        description: "Inspect disk health and reliability",
        category: "storage",
    },
    BuiltinEntry {
        command: "storage",
        description: "Analyze filesystem usage and cleanup opportunities",
        category: "storage",
    },
    BuiltinEntry {
        command: "ps",
        description: "Inspect running processes",
        category: "process",
    },
    BuiltinEntry {
        command: "top",
        description: "Alias for ps sorted process inspection",
        category: "process",
    },
    BuiltinEntry {
        command: "time",
        description: "Show local or global times",
        category: "time",
    },
    BuiltinEntry {
        command: "diagnostic",
        description: "Run system, network, and plugin diagnostics",
        category: "diagnostic",
    },
    BuiltinEntry {
        command: "config",
        description: "Manage configuration and first-run setup",
        category: "config",
    },
    BuiltinEntry {
        command: "profile",
        description: "Manage configuration profiles",
        category: "config",
    },
    BuiltinEntry {
        command: "completion",
        description: "Generate or install shell completions",
        category: "shell",
    },
    BuiltinEntry {
        command: "dashboard",
        description: "Inspect or reset dashboard settings",
        category: "dashboard",
    },
    BuiltinEntry {
        command: "plugin",
        description: "Manage plugins and plugin development workflows",
        category: "plugin",
    },
    BuiltinEntry {
        command: "search",
        description: "Search built-ins and plugins",
        category: "search",
    },
    BuiltinEntry {
        command: "install",
        description: "Install optional modules such as the AI dashboard",
        category: "maintenance",
    },
    BuiltinEntry {
        command: "list",
        description: "List optional modules",
        category: "maintenance",
    },
    BuiltinEntry {
        command: "update",
        description: "Update the core CLI or an optional module",
        category: "maintenance",
    },
    BuiltinEntry {
        command: "self-repair",
        description: "Repair the current installation",
        category: "maintenance",
    },
    BuiltinEntry {
        command: "reinstall",
        description: "Reinstall the latest release",
        category: "maintenance",
    },
    BuiltinEntry {
        command: "uninstall",
        description: "Remove the core CLI or an optional module",
        category: "maintenance",
    },
];

pub fn run_search(query_parts: &[String]) -> Result<(), String> {
    let query = query_parts.join(" ").trim().to_string();
    if query.is_empty() {
        return Err("Search query cannot be empty.".to_string());
    }

    let results = collect_results(&query)?;
    if crate::output::json_output() {
        println!(
            "{}",
            serde_json::to_string_pretty(&SearchOutput { query, results })
                .unwrap_or_else(|_| "{\"query\":\"\",\"results\":[]}".to_string())
        );
        return Ok(());
    }

    print_terminal_results(&query, &results);
    Ok(())
}

fn collect_results(query: &str) -> Result<Vec<SearchResult>, String> {
    let mut results = builtin_results(query);
    results.extend(plugin_results(query)?);
    results.sort_by(|a, b| {
        b.score
            .cmp(&a.score)
            .then_with(|| a.kind_rank().cmp(&b.kind_rank()))
            .then_with(|| a.command.cmp(&b.command))
    });
    results.truncate(12);
    Ok(results)
}

fn builtin_results(query: &str) -> Vec<SearchResult> {
    BUILTIN_COMMANDS
        .iter()
        .filter_map(|entry| {
            let score = score_match(query, entry.command, entry.description);
            (score > 0).then(|| SearchResult {
                kind: SearchResultKind::Builtin,
                command: entry.command.to_string(),
                title: entry.command.to_string(),
                description: entry.description.to_string(),
                source: "built-in".to_string(),
                category: entry.category.to_string(),
                installed: true,
                trusted: true,
                score: score + 8,
            })
        })
        .collect()
}

fn plugin_results(query: &str) -> Result<Vec<SearchResult>, String> {
    let mut merged: BTreeMap<String, SearchResult> = BTreeMap::new();

    for plugin in registry_plugin_search_entries()? {
        let score = score_match(query, &plugin.name, &plugin.description);
        if score <= 0 {
            continue;
        }
        merged.insert(
            plugin.name.clone(),
            SearchResult {
                kind: SearchResultKind::Plugin,
                command: plugin.name.clone(),
                title: plugin.name.clone(),
                description: plugin.description.clone(),
                source: "registry".to_string(),
                category: "plugin".to_string(),
                installed: false,
                trusted: false,
                score,
            },
        );
    }

    for plugin in installed_plugin_search_entries()? {
        let score = score_match(query, &plugin.name, &plugin.description);
        if score <= 0 {
            continue;
        }
        merge_plugin_result(&mut merged, plugin, score);
    }

    Ok(merged.into_values().collect())
}

fn merge_plugin_result(
    merged: &mut BTreeMap<String, SearchResult>,
    plugin: PluginSearchEntry,
    score: i32,
) {
    let mut combined_score = score + 18;
    if plugin.trusted {
        combined_score += 4;
    }

    if let Some(existing) = merged.get_mut(&plugin.name) {
        existing.installed = true;
        existing.trusted = plugin.trusted;
        existing.source = "installed, registry".to_string();
        existing.score = existing.score.max(combined_score);
        if !plugin.description.trim().is_empty() {
            existing.description = plugin.description;
        }
        return;
    }

    merged.insert(
        plugin.name.clone(),
        SearchResult {
            kind: SearchResultKind::Plugin,
            command: plugin.name.clone(),
            title: plugin.name,
            description: plugin.description,
            source: "installed".to_string(),
            category: "plugin".to_string(),
            installed: true,
            trusted: plugin.trusted,
            score: combined_score,
        },
    );
}

fn score_match(query: &str, primary: &str, description: &str) -> i32 {
    let query = query.trim().to_ascii_lowercase();
    if query.is_empty() {
        return 0;
    }

    let primary = primary.to_ascii_lowercase();
    let description = description.to_ascii_lowercase();
    let tokens = query.split_whitespace().collect::<Vec<_>>();

    let mut score = 0;
    if primary == query {
        score += 120;
    } else if primary.starts_with(&query) {
        score += 95;
    } else if primary.contains(&query) {
        score += 70;
    } else if description.contains(&query) {
        score += 30;
    }

    for token in tokens {
        if primary == token {
            score += 50;
        } else if primary.starts_with(token) {
            score += 30;
        } else if primary.contains(token) {
            score += 18;
        } else if description.contains(token) {
            score += 8;
        }
    }

    score
}

fn print_terminal_results(query: &str, results: &[SearchResult]) {
    if results.is_empty() {
        println!("No matches for \"{query}\".");
        println!("Try a broader term such as `network`, `disk`, or `plugin`.");
        return;
    }

    println!("Search results for \"{query}\"");
    println!();

    let builtin = results
        .iter()
        .filter(|item| matches!(item.kind, SearchResultKind::Builtin))
        .collect::<Vec<_>>();
    let plugins = results
        .iter()
        .filter(|item| matches!(item.kind, SearchResultKind::Plugin))
        .collect::<Vec<_>>();

    if !builtin.is_empty() {
        println!("Built-in commands");
        for item in builtin {
            println!("  {:<20} {}", item.command, item.description);
        }
        println!();
    }

    if !plugins.is_empty() {
        println!("Plugins");
        for item in plugins {
            let mut flags = vec![item.source.clone()];
            if item.installed {
                flags.push("installed".to_string());
            }
            if item.trusted {
                flags.push("trusted".to_string());
            }
            println!(
                "  {:<20} {} [{}]",
                item.command,
                item.description,
                flags.join(", ")
            );
        }
    }
}

impl SearchResult {
    fn kind_rank(&self) -> i32 {
        match self.kind {
            SearchResultKind::Builtin => 0,
            SearchResultKind::Plugin => 1,
        }
    }
}

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

    #[test]
    fn exact_match_scores_above_description_match() {
        let exact = score_match("network", "network", "Show local network information");
        let description = score_match("network", "diagnostic", "Run network diagnostics");
        assert!(exact > description);
    }
}