jarvy 0.4.0

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Detection rule engine for `jarvy discover`.
//!
//! Each `DetectionRule` declares marker files / directories that indicate
//! a technology is in use, where to extract its version, and what
//! companion tools to recommend. The bundled `default_rules()` set covers
//! the main ecosystems jarvy supports today (rust, node, python, go,
//! docker, kubectl, terraform, pre-commit). Adding a new ecosystem is one
//! entry in the array — no other code changes needed.

use serde::{Deserialize, Serialize};
use std::path::Path;

use super::scanner::find_first_match;
use super::version::extract_version;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectionRule {
    pub name: String,
    pub detect: Vec<DetectionPattern>,
    #[serde(default)]
    pub version_from: Option<VersionSource>,
    #[serde(default)]
    pub suggests: Vec<String>,
    pub category: ToolCategory,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DetectionPattern {
    File {
        file: String,
    },
    Dir {
        dir: String,
    },
    /// Match a file whose contents contain a literal substring. Used
    /// for ecosystems where the marker file is generic (`*.yaml`) but
    /// the content is distinctive (`kind: Deployment` for Kubernetes,
    /// `engines.node` for Node package manifests, etc.). Bounded
    /// reads — only the first MAX_CONTAINING_BYTES (4 KiB) are
    /// scanned per file, which is more than enough for header lines.
    FileContaining {
        file: String,
        containing: String,
    },
}

/// Cap how much of a file we inspect for `FileContaining`. Most
/// markers we care about live in the first few lines; reading 4 KiB
/// is plenty and bounds the cost of a malicious giant marker file.
pub const MAX_CONTAINING_BYTES: usize = 4 * 1024;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionSource {
    pub file: String,
    #[serde(default)]
    pub pattern: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolCategory {
    Runtime,
    Build,
    Dev,
    Ops,
}

/// One technology successfully detected in the project tree. The
/// `source` field is human-readable (e.g. "Cargo.toml") and surfaces in
/// the `--format pretty` output so users can see why a tool was
/// suggested.
#[derive(Debug, Clone, Serialize)]
pub struct Detection {
    pub tool: String,
    pub version: Option<String>,
    pub source: String,
    pub suggests: Vec<String>,
    pub category: ToolCategory,
}

/// Walk every rule against `project_dir` and return one `Detection` per
/// matched rule. Stable iteration order matches `rules` for
/// deterministic output.
pub fn run(project_dir: &Path, rules: &[DetectionRule]) -> Vec<Detection> {
    let mut out = Vec::new();
    for rule in rules {
        if let Some(matched_source) = rule_match_source(project_dir, rule) {
            let version = rule
                .version_from
                .as_ref()
                .and_then(|vs| extract_version(project_dir, vs));
            out.push(Detection {
                tool: rule.name.clone(),
                version,
                source: matched_source,
                suggests: rule.suggests.clone(),
                category: rule.category,
            });
        }
    }
    out
}

/// First matching pattern wins; we return its source string so the
/// suggestion explainer can cite a real file ("detected from Cargo.toml").
///
/// The source string flows into the rendered `# detected from ...`
/// comment in `discover/generator.rs`. For pattern-supplied filenames
/// (`Cargo.toml`, `package.json`, ...) that's a trusted rule-author
/// literal. For `*.ext` glob matches the on-disk filename is
/// attacker-controllable (POSIX filenames may contain newlines, `"`,
/// and control bytes). We strict-allowlist the matched filename to
/// printable ASCII without quotes/backslashes so a hostile filename
/// like `x.tf\n[packages]\nallow_remote = true\n# .tf` can't inject
/// a TOML section through the rendered comment (review item P0 #2).
fn rule_match_source(project_dir: &Path, rule: &DetectionRule) -> Option<String> {
    for pattern in &rule.detect {
        match pattern {
            DetectionPattern::File { file } => {
                if let Some(p) = find_first_match(project_dir, file) {
                    let name = p.file_name()?.to_string_lossy().into_owned();
                    if let Some(safe) = sanitize_source(&name) {
                        return Some(safe);
                    }
                    // Hostile filename — skip this pattern but still try
                    // siblings so a `*.tf` rule isn't defeated by one
                    // poisoned filename.
                    continue;
                }
            }
            DetectionPattern::Dir { dir } => {
                if project_dir.join(dir).is_dir() {
                    if let Some(safe) = sanitize_source(dir) {
                        return Some(safe);
                    }
                }
            }
            DetectionPattern::FileContaining { file, containing } => {
                if let Some(p) = find_first_match(project_dir, file) {
                    if let Ok(content) = read_bounded(&p, MAX_CONTAINING_BYTES) {
                        if content.contains(containing) {
                            let name = p.file_name()?.to_string_lossy().into_owned();
                            if let Some(safe) = sanitize_source(&name) {
                                return Some(safe);
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Read at most `cap` bytes of `path` and return as a UTF-8 string.
/// Lossy decoding so a stray non-UTF8 byte doesn't kill the scan.
fn read_bounded(path: &Path, cap: usize) -> std::io::Result<String> {
    use std::io::Read;
    let mut file = std::fs::File::open(path)?;
    let mut buf = vec![0u8; cap];
    let n = file.read(&mut buf)?;
    buf.truncate(n);
    Ok(String::from_utf8_lossy(&buf).into_owned())
}

/// Accept only ASCII-graphic + space — every other byte (newline,
/// CR, NUL, ESC, DEL, `"`, `\`) is refused. Returning `None` on a
/// hostile filename means the rule doesn't fire at all rather than
/// allowing partial / sanitized attribution.
fn sanitize_source(name: &str) -> Option<String> {
    if name.is_empty() || name.len() > 255 {
        return None;
    }
    if !name
        .chars()
        .all(|c| (c.is_ascii_graphic() && c != '"' && c != '\\') || c == ' ')
    {
        return None;
    }
    Some(name.to_string())
}

/// Built-in detection rules covering the ecosystems jarvy ships handlers
/// for today. Names match the canonical jarvy tool name (lowercase,
/// dash-separated) so `analyze()` can validate suggestions against
/// `tools::registry::registered_tool_names()` without aliasing logic.
///
/// Cached behind a `OnceLock` (review item P2 #22) — the ~50 String
/// allocations are paid once per process, not per `analyze()` call.
pub fn default_rules() -> &'static [DetectionRule] {
    use std::sync::OnceLock;
    static RULES: OnceLock<Vec<DetectionRule>> = OnceLock::new();
    RULES.get_or_init(build_default_rules)
}

fn build_default_rules() -> Vec<DetectionRule> {
    vec![
        DetectionRule {
            name: "rust".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "Cargo.toml".into(),
                },
                DetectionPattern::File {
                    file: "Cargo.lock".into(),
                },
                DetectionPattern::File {
                    file: "rust-toolchain.toml".into(),
                },
                DetectionPattern::File {
                    file: "rust-toolchain".into(),
                },
            ],
            version_from: Some(VersionSource {
                file: "rust-toolchain.toml".into(),
                pattern: Some(r#"channel\s*=\s*"([^"]+)""#.into()),
            }),
            suggests: vec!["cargo-watch".into(), "cargo-nextest".into()],
            category: ToolCategory::Runtime,
        },
        DetectionRule {
            name: "node".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "package.json".into(),
                },
                DetectionPattern::File {
                    file: "package-lock.json".into(),
                },
                DetectionPattern::File {
                    file: "yarn.lock".into(),
                },
                DetectionPattern::File {
                    file: "pnpm-lock.yaml".into(),
                },
                DetectionPattern::File {
                    file: ".nvmrc".into(),
                },
            ],
            version_from: Some(VersionSource {
                file: ".nvmrc".into(),
                pattern: Some(r"v?(\d+(?:\.\d+(?:\.\d+)?)?)".into()),
            }),
            suggests: vec!["pnpm".into(), "yarn".into()],
            category: ToolCategory::Runtime,
        },
        DetectionRule {
            name: "python".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "pyproject.toml".into(),
                },
                DetectionPattern::File {
                    file: "requirements.txt".into(),
                },
                DetectionPattern::File {
                    file: "Pipfile".into(),
                },
                DetectionPattern::File {
                    file: "setup.py".into(),
                },
                DetectionPattern::File {
                    file: ".python-version".into(),
                },
            ],
            version_from: Some(VersionSource {
                file: ".python-version".into(),
                pattern: None,
            }),
            suggests: vec!["uv".into(), "poetry".into(), "pipx".into()],
            category: ToolCategory::Runtime,
        },
        DetectionRule {
            name: "go".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "go.mod".into(),
                },
                DetectionPattern::File {
                    file: "go.sum".into(),
                },
            ],
            version_from: Some(VersionSource {
                file: "go.mod".into(),
                pattern: Some(r"^go\s+(\d+\.\d+(?:\.\d+)?)".into()),
            }),
            suggests: vec![],
            category: ToolCategory::Runtime,
        },
        DetectionRule {
            name: "ruby".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "Gemfile".into(),
                },
                DetectionPattern::File {
                    file: "Gemfile.lock".into(),
                },
                DetectionPattern::File {
                    file: ".ruby-version".into(),
                },
            ],
            version_from: Some(VersionSource {
                file: ".ruby-version".into(),
                pattern: None,
            }),
            suggests: vec![],
            category: ToolCategory::Runtime,
        },
        DetectionRule {
            name: "docker".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "Dockerfile".into(),
                },
                DetectionPattern::File {
                    file: "docker-compose.yml".into(),
                },
                DetectionPattern::File {
                    file: "docker-compose.yaml".into(),
                },
                DetectionPattern::File {
                    file: "compose.yml".into(),
                },
                DetectionPattern::File {
                    file: "compose.yaml".into(),
                },
            ],
            version_from: None,
            suggests: vec!["docker-compose".into(), "lazydocker".into()],
            category: ToolCategory::Ops,
        },
        DetectionRule {
            name: "kubectl".into(),
            detect: vec![
                DetectionPattern::Dir { dir: "k8s".into() },
                DetectionPattern::Dir {
                    dir: "kubernetes".into(),
                },
                DetectionPattern::Dir {
                    dir: "manifests".into(),
                },
                // Catch repos that scatter k8s manifests at the root
                // (no k8s/ dir) by looking for the marker fields inside
                // a bare `*.yaml`. FileContaining is bounded to the
                // first 4 KiB so it stays fast on large repos.
                DetectionPattern::FileContaining {
                    file: "*.yaml".into(),
                    containing: "kind: Deployment".into(),
                },
                DetectionPattern::FileContaining {
                    file: "*.yaml".into(),
                    containing: "apiVersion: apps/v1".into(),
                },
            ],
            version_from: None,
            suggests: vec!["helm".into(), "kustomize".into(), "k9s".into()],
            category: ToolCategory::Ops,
        },
        DetectionRule {
            name: "helm".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "Chart.yaml".into(),
                },
                DetectionPattern::Dir {
                    dir: "charts".into(),
                },
            ],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Ops,
        },
        DetectionRule {
            name: "terraform".into(),
            detect: vec![
                DetectionPattern::File {
                    file: ".terraform.lock.hcl".into(),
                },
                DetectionPattern::File {
                    file: "main.tf".into(),
                },
                DetectionPattern::File {
                    file: "*.tf".into(),
                },
            ],
            version_from: None,
            suggests: vec!["tflint".into(), "terraform-docs".into()],
            category: ToolCategory::Ops,
        },
        DetectionRule {
            name: "pre-commit".into(),
            detect: vec![DetectionPattern::File {
                file: ".pre-commit-config.yaml".into(),
            }],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Dev,
        },
        DetectionRule {
            name: "make".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "Makefile".into(),
                },
                DetectionPattern::File {
                    file: "makefile".into(),
                },
                DetectionPattern::File {
                    file: "GNUmakefile".into(),
                },
            ],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Build,
        },
        DetectionRule {
            name: "just".into(),
            detect: vec![DetectionPattern::File {
                file: "Justfile".into(),
            }],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Build,
        },
        // The following ecosystems trigger detection but typically
        // land in the `uninstallable` bucket because jarvy doesn't
        // ship first-party handlers yet. We still surface them so
        // contributors see "jarvy noticed you have Java but can't
        // install it for you" rather than silently doing nothing.
        DetectionRule {
            name: "maven".into(),
            detect: vec![DetectionPattern::File {
                file: "pom.xml".into(),
            }],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Build,
        },
        DetectionRule {
            name: "gradle".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "build.gradle".into(),
                },
                DetectionPattern::File {
                    file: "build.gradle.kts".into(),
                },
                DetectionPattern::File {
                    file: "settings.gradle".into(),
                },
            ],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Build,
        },
        DetectionRule {
            name: "dotnet".into(),
            detect: vec![
                DetectionPattern::File {
                    file: "*.csproj".into(),
                },
                DetectionPattern::File {
                    file: "*.fsproj".into(),
                },
                DetectionPattern::File {
                    file: "global.json".into(),
                },
            ],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Runtime,
        },
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    /// Review P0 #2 — hostile filename with newline + `[section]` must
    /// not become a detection source string. The file-glob path is the
    /// only attacker-controllable detection input; rule-author literals
    /// are trusted.
    #[test]
    fn rejects_hostile_glob_match_filename() {
        let tmp = tempdir().unwrap();
        // Filename literally containing newline + section header.
        fs::write(tmp.path().join("x.tf\n[packages]\nbad = true\n.tf"), "").unwrap();
        let rule = DetectionRule {
            name: "terraform".into(),
            detect: vec![DetectionPattern::File {
                file: "*.tf".into(),
            }],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Ops,
        };
        // Source MUST be None (no fallback to partial sanitization).
        assert!(rule_match_source(tmp.path(), &rule).is_none());
    }

    #[test]
    fn accepts_well_formed_filename_glob() {
        let tmp = tempdir().unwrap();
        fs::write(tmp.path().join("main.tf"), "").unwrap();
        let rule = DetectionRule {
            name: "terraform".into(),
            detect: vec![DetectionPattern::File {
                file: "*.tf".into(),
            }],
            version_from: None,
            suggests: vec![],
            category: ToolCategory::Ops,
        };
        assert_eq!(
            rule_match_source(tmp.path(), &rule).as_deref(),
            Some("main.tf")
        );
    }

    #[test]
    fn sanitize_source_table() {
        assert_eq!(sanitize_source("Cargo.toml").as_deref(), Some("Cargo.toml"));
        assert_eq!(sanitize_source("k8s").as_deref(), Some("k8s"));
        assert!(sanitize_source("").is_none());
        assert!(sanitize_source("x\nbad").is_none());
        assert!(sanitize_source("has\"quote").is_none());
        assert!(sanitize_source("back\\slash").is_none());
        assert!(sanitize_source("nul\0byte").is_none());
        assert!(sanitize_source(&"x".repeat(256)).is_none());
    }
}