1use std::collections::HashMap;
9use std::path::Path;
10use std::process::Command;
11
12use crate::models::{CheckStatus, DiagnosticResult, ProjectStack};
13
14pub fn check_dependencies(repo_path: &str, stack: &ProjectStack) -> DiagnosticResult {
20 match stack {
21 ProjectStack::Node { .. } => check_node_deps(repo_path),
22 ProjectStack::Python { .. } => check_python_deps(repo_path),
23 ProjectStack::Rust { .. } => check_rust_deps(repo_path),
24 ProjectStack::Go { .. } | ProjectStack::Java { .. } | ProjectStack::Docker | ProjectStack::Unknown => DiagnosticResult::new(
25 "Dependencies",
26 CheckStatus::Pass,
27 "no dependency audit needed for this stack",
28 ),
29 }
30}
31
32pub fn run_npm_list(repo_path: &str) -> Option<serde_json::Value> {
38 let output = Command::new("npm")
39 .args(["list", "--depth=0", "--json"])
40 .current_dir(repo_path)
41 .output()
42 .ok()?;
43 if !output.status.success() && output.stdout.is_empty() {
44 return None;
45 }
46 serde_json::from_slice(&output.stdout).ok()
47}
48
49pub fn run_pip_list() -> Option<Vec<(String, String)>> {
51 let output = Command::new("pip")
52 .args(["list", "--format=json"])
53 .output()
54 .ok()?;
55 if !output.status.success() {
56 return None;
57 }
58 let parsed: Vec<HashMap<String, String>> = serde_json::from_slice(&output.stdout).ok()?;
59 Some(
60 parsed
61 .into_iter()
62 .filter_map(|p| {
63 let name = p.get("name")?.to_lowercase();
64 let version = p.get("version")?.clone();
65 Some((name, version))
66 })
67 .collect(),
68 )
69}
70
71pub fn run_cargo_tree(repo_path: &str) -> Option<Vec<String>> {
74 let output = Command::new("cargo")
75 .args(["tree", "--depth=1", "--prefix=depth"])
76 .current_dir(repo_path)
77 .output()
78 .ok()?;
79 if !output.status.success() {
80 return None;
81 }
82 let text = String::from_utf8_lossy(&output.stdout);
83 Some(
84 text.lines()
85 .filter_map(|line| {
86 let trimmed = line.trim_start();
88 let rest = trimmed
90 .split_whitespace()
91 .skip(1) .collect::<Vec<_>>()
93 .join(" ");
94 if rest.is_empty() || rest.starts_with('(') || rest.contains("proc-macro") {
95 None
96 } else {
97 Some(rest)
98 }
99 })
100 .collect(),
101 )
102}
103
104fn read_package_json(repo_path: &str) -> (Vec<String>, Vec<String>) {
110 let path = Path::new(repo_path).join("package.json");
111 let Ok(text) = std::fs::read_to_string(&path) else {
112 return (Vec::new(), Vec::new());
113 };
114 let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
115 return (Vec::new(), Vec::new());
116 };
117 let deps = extract_dep_keys(&value, "dependencies");
118 let dev_deps = extract_dep_keys(&value, "devDependencies");
119 (deps, dev_deps)
120}
121
122fn extract_dep_keys(value: &serde_json::Value, field: &str) -> Vec<String> {
123 value
124 .get(field)
125 .and_then(|v| v.as_object())
126 .map(|obj| obj.keys().cloned().collect())
127 .unwrap_or_default()
128}
129
130fn parse_npm_list(value: &serde_json::Value) -> HashMap<String, String> {
133 let mut installed = HashMap::new();
134 if let Some(deps) = value.get("dependencies").and_then(|v| v.as_object()) {
135 for (name, info) in deps {
136 let status = if info.get("missing").and_then(|v| v.as_bool()) == Some(true) {
137 "missing".to_string()
138 } else if info.get("invalid").and_then(|v| v.as_bool()) == Some(true) {
139 let ver = info.get("version").and_then(|v| v.as_str()).unwrap_or("?");
140 format!("invalid({ver})")
141 } else {
142 info.get("version")
143 .and_then(|v| v.as_str())
144 .unwrap_or("?")
145 .to_string()
146 };
147 installed.insert(name.to_lowercase(), status);
148 }
149 }
150 installed
151}
152
153fn check_node_deps(repo_path: &str) -> DiagnosticResult {
154 let root = Path::new(repo_path);
155 let has_modules = root.join("node_modules").is_dir();
156 let has_package_json = root.join("package.json").is_file();
157
158 if !has_package_json {
159 return DiagnosticResult::new(
160 "Dependencies",
161 CheckStatus::Pass,
162 "no package.json found; nothing to audit",
163 );
164 }
165
166 if !has_modules {
167 return DiagnosticResult::new(
168 "Dependencies",
169 CheckStatus::Fail,
170 "node_modules/ is missing",
171 )
172 .with_remediation("Run `npm install` to install dependencies");
173 }
174
175 let (all_deps, dev_deps) = read_package_json(repo_path);
176 let total_expected = all_deps.len() + dev_deps.len();
177
178 match run_npm_list(repo_path) {
179 None => DiagnosticResult::new(
180 "Dependencies",
181 CheckStatus::Warn,
182 "node_modules/ exists but npm is not available to audit",
183 )
184 .with_remediation("Install npm and run `npm list` to check dependency health"),
185 Some(value) => {
186 let installed = parse_npm_list(&value);
187
188 let missing: Vec<&String> = all_deps
189 .iter()
190 .chain(dev_deps.iter())
191 .filter(|name| installed.get(name.as_str()) == Some(&"missing".to_string()))
192 .collect();
193
194 let invalid: Vec<(&String, &String)> = all_deps
195 .iter()
196 .chain(dev_deps.iter())
197 .filter_map(|name| {
198 let status = installed.get(name.as_str())?;
199 if status.starts_with("invalid(") {
200 Some((name, status))
201 } else {
202 None
203 }
204 })
205 .collect();
206
207 if !missing.is_empty() {
208 let names: Vec<&str> = missing.iter().map(|n| n.as_str()).collect();
209 return DiagnosticResult::new(
210 "Dependencies",
211 CheckStatus::Fail,
212 format!("{} dependencies missing from node_modules", missing.len()),
213 )
214 .with_remediation(format!(
215 "Run `npm install` to install: {}",
216 names.join(", ")
217 ));
218 }
219
220 if !invalid.is_empty() {
221 let details: Vec<String> = invalid
222 .iter()
223 .map(|(name, status)| format!("{name} ({status})"))
224 .collect();
225 return DiagnosticResult::new(
226 "Dependencies",
227 CheckStatus::Warn,
228 format!("{} dependencies have version mismatches", invalid.len()),
229 )
230 .with_remediation(format!("Run `npm install` to fix: {}", details.join(", ")));
231 }
232
233 DiagnosticResult::new(
234 "Dependencies",
235 CheckStatus::Pass,
236 format!(
237 "node_modules present and consistent with package.json ({total_expected} deps)"
238 ),
239 )
240 }
241 }
242}
243
244pub fn parse_requirements(content: &str) -> Vec<(String, String)> {
250 content
251 .lines()
252 .filter_map(|line| {
253 let line = line.trim();
254 if line.is_empty() || line.starts_with('#') || line.starts_with('-') {
255 return None;
256 }
257 let (name, spec) = if let Some(pos) = line.find(|c: char| "><=!~".contains(c)) {
259 (&line[..pos], line[pos..].trim_end())
260 } else {
261 (line, "")
262 };
263 let name = name.trim().to_lowercase();
264 if name.is_empty() {
265 None
266 } else {
267 Some((name, spec.to_string()))
268 }
269 })
270 .collect()
271}
272
273fn check_python_deps(repo_path: &str) -> DiagnosticResult {
274 check_python_deps_impl(repo_path, run_pip_list())
275}
276
277fn check_python_deps_impl(
278 repo_path: &str,
279 pip_output: Option<Vec<(String, String)>>,
280) -> DiagnosticResult {
281 let root = Path::new(repo_path);
282 let has_requirements = root.join("requirements.txt").is_file();
283 let has_pyproject = root.join("pyproject.toml").is_file();
284
285 if !has_requirements && !has_pyproject {
286 return DiagnosticResult::new(
287 "Dependencies",
288 CheckStatus::Pass,
289 "no requirements.txt or pyproject.toml found",
290 );
291 }
292
293 match pip_output {
294 None => DiagnosticResult::new(
295 "Dependencies",
296 CheckStatus::Warn,
297 "requirements file found but pip is not available to audit",
298 )
299 .with_remediation("Activate a virtual environment and run `pip list` to check"),
300 Some(installed) => {
301 if !has_requirements {
302 return DiagnosticResult::new(
303 "Dependencies",
304 CheckStatus::Pass,
305 format!(
306 "pyproject.toml present; {} packages installed via pip",
307 installed.len()
308 ),
309 );
310 }
311
312 let reqs = std::fs::read_to_string(root.join("requirements.txt")).unwrap_or_default();
313 let required = parse_requirements(&reqs);
314 let installed_map: HashMap<&str, &str> = installed
315 .iter()
316 .map(|(n, v)| (n.as_str(), v.as_str()))
317 .collect();
318
319 let missing: Vec<&str> = required
320 .iter()
321 .filter(|(name, _)| !installed_map.contains_key(name.as_str()))
322 .map(|(name, _)| name.as_str())
323 .collect();
324
325 if !missing.is_empty() {
326 return DiagnosticResult::new(
327 "Dependencies",
328 CheckStatus::Fail,
329 format!(
330 "{} packages from requirements.txt are not installed",
331 missing.len()
332 ),
333 )
334 .with_remediation(format!(
335 "Run `pip install -r requirements.txt` to install: {}",
336 missing.join(", ")
337 ));
338 }
339
340 DiagnosticResult::new(
341 "Dependencies",
342 CheckStatus::Pass,
343 format!(
344 "all {} required packages are installed ({} packages total)",
345 required.len(),
346 installed.len()
347 ),
348 )
349 }
350 }
351}
352
353fn check_rust_deps(repo_path: &str) -> DiagnosticResult {
358 let root = Path::new(repo_path);
359 let has_cargo_toml = root.join("Cargo.toml").is_file();
360 let has_cargo_lock = root.join("Cargo.lock").is_file();
361
362 if !has_cargo_toml {
363 return DiagnosticResult::new(
364 "Dependencies",
365 CheckStatus::Pass,
366 "no Cargo.toml found; nothing to audit",
367 );
368 }
369
370 if !has_cargo_lock {
371 return DiagnosticResult::new(
372 "Dependencies",
373 CheckStatus::Warn,
374 "Cargo.toml present but Cargo.lock is missing",
375 )
376 .with_remediation("Run `cargo build` to generate Cargo.lock (required for binaries)");
377 }
378
379 match run_cargo_tree(repo_path) {
380 None => DiagnosticResult::new(
381 "Dependencies",
382 CheckStatus::Warn,
383 "Cargo.lock exists but cargo is not available to audit",
384 )
385 .with_remediation("Install rustup and run `cargo tree` to check dependency health"),
386 Some(tree) => {
387 if tree.is_empty() {
388 return DiagnosticResult::new(
389 "Dependencies",
390 CheckStatus::Warn,
391 "cargo tree returned no dependencies",
392 )
393 .with_remediation("Run `cargo check` to resolve dependency issues");
394 }
395
396 DiagnosticResult::new(
397 "Dependencies",
398 CheckStatus::Pass,
399 format!(
400 "Cargo.lock present; {} direct dependencies resolved",
401 tree.len()
402 ),
403 )
404 }
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use std::fs;
412 use std::path::PathBuf;
413 use std::time::{SystemTime, UNIX_EPOCH};
414
415 struct TempDir {
416 path: PathBuf,
417 }
418
419 impl TempDir {
420 fn new(label: &str) -> Self {
421 let stamp = SystemTime::now()
422 .duration_since(UNIX_EPOCH)
423 .expect("system clock")
424 .as_nanos();
425 let path = std::env::temp_dir().join(format!("limitless_dep_{label}_{stamp}"));
426 fs::create_dir_all(&path).expect("create temp dir");
427 TempDir { path }
428 }
429
430 fn path(&self) -> &Path {
431 &self.path
432 }
433
434 fn write(self, relative: &str, content: &str) -> Self {
435 let full = self.path.join(relative);
436 if let Some(parent) = full.parent() {
437 fs::create_dir_all(parent).expect("create parent dirs");
438 }
439 fs::write(full, content).expect("write fixture file");
440 self
441 }
442 }
443
444 impl Drop for TempDir {
445 fn drop(&mut self) {
446 let _ = fs::remove_dir_all(&self.path);
447 }
448 }
449
450 #[test]
453 fn parse_npm_list_extracts_versions_and_flags() {
454 let json = serde_json::json!({
455 "dependencies": {
456 "react": { "version": "18.2.0" },
457 "lodash": { "version": "4.17.21", "missing": true },
458 "axios": { "version": "1.6.0", "invalid": true }
459 }
460 });
461 let installed = parse_npm_list(&json);
462
463 assert_eq!(installed.get("react").unwrap(), "18.2.0");
464 assert_eq!(installed.get("lodash").unwrap(), "missing");
465 assert!(installed.get("axios").unwrap().starts_with("invalid("));
466 }
467
468 #[test]
469 fn parse_npm_list_handles_empty() {
470 let json = serde_json::json!({ "dependencies": {} });
471 assert!(parse_npm_list(&json).is_empty());
472 }
473
474 #[test]
477 fn parse_requirements_captures_packages_and_specs() {
478 let content = "flask>=3.0\nrequests\n# commented\nurllib3~=2.1\n";
479 let reqs = parse_requirements(content);
480
481 assert_eq!(reqs.len(), 3);
482 assert_eq!(reqs[0].0, "flask");
483 assert_eq!(reqs[0].1, ">=3.0");
484 assert_eq!(reqs[1].0, "requests");
485 assert!(reqs[1].1.is_empty());
486 assert_eq!(reqs[2].0, "urllib3");
487 assert_eq!(reqs[2].1, "~=2.1");
488 }
489
490 #[test]
491 fn parse_requirements_skips_empty_and_options() {
492 let content = "\n\n-r constraints.txt\n--index-url https://example.com\nflask\n";
493 let reqs = parse_requirements(content);
494 assert_eq!(reqs.len(), 1);
495 assert_eq!(reqs[0].0, "flask");
496 }
497
498 #[test]
501 fn node_no_package_json_passes() {
502 let dir = TempDir::new("node_empty");
503 let result = check_dependencies(dir.path().to_str().unwrap(), &node_stack());
504 assert_eq!(result.status, CheckStatus::Pass);
505 assert!(result.message.contains("no package.json"));
506 }
507
508 #[test]
509 fn node_missing_node_modules_fails() {
510 let dir = TempDir::new("node_no_modules").write("package.json", r#"{ "name": "web" }"#);
511 let result = check_dependencies(dir.path().to_str().unwrap(), &node_stack());
512 assert_eq!(result.status, CheckStatus::Fail);
513 assert!(result.message.contains("node_modules"));
514 assert!(result.remediation.unwrap().contains("npm install"));
515 }
516
517 #[test]
518 fn node_with_modules_but_no_npm_warns() {
519 let dir = TempDir::new("node_modules_no_npm")
520 .write("package.json", r#"{ "name": "web", "dependencies": {} }"#);
521 fs::create_dir_all(dir.path().join("node_modules")).expect("create node_modules");
522 let result = check_dependencies(dir.path().to_str().unwrap(), &node_stack());
523 assert_eq!(result.status, CheckStatus::Warn);
524 assert!(result.message.contains("npm"));
525 }
526
527 #[test]
530 fn python_no_manifest_passes() {
531 let dir = TempDir::new("python_empty");
532 let result = check_dependencies(dir.path().to_str().unwrap(), &python_stack());
533 assert_eq!(result.status, CheckStatus::Pass);
534 assert!(result.message.contains("no requirements"));
535 }
536
537 #[test]
538 fn python_with_requirements_but_no_pip_warns() {
539 let dir =
540 TempDir::new("python_reqs_no_pip").write("requirements.txt", "flask>=3.0\nrequests\n");
541 let result = check_python_deps_impl(dir.path().to_str().unwrap(), None);
542 assert_eq!(result.status, CheckStatus::Warn);
543 assert!(result.message.contains("pip"));
544 }
545
546 #[test]
547 fn python_missing_required_packages_fails() {
548 let dir =
549 TempDir::new("python_missing").write("requirements.txt", "flask>=3.0\nrequests\n");
550 let pip = vec![
551 ("requests".to_string(), "2.32.3".to_string()),
552 ("urllib3".to_string(), "2.2.2".to_string()),
553 ];
554 let result = check_python_deps_impl(dir.path().to_str().unwrap(), Some(pip));
555 assert_eq!(result.status, CheckStatus::Fail);
556 assert!(result.message.contains("not installed"));
557 assert!(result.remediation.unwrap().contains("flask"));
558 }
559
560 #[test]
563 fn rust_no_cargo_toml_passes() {
564 let dir = TempDir::new("rust_empty");
565 let result = check_dependencies(dir.path().to_str().unwrap(), &rust_stack());
566 assert_eq!(result.status, CheckStatus::Pass);
567 assert!(result.message.contains("no Cargo.toml"));
568 }
569
570 #[test]
571 fn rust_no_cargo_lock_warns() {
572 let dir = TempDir::new("rust_no_lock").write(
573 "Cargo.toml",
574 "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
575 );
576 let result = check_dependencies(dir.path().to_str().unwrap(), &rust_stack());
577 assert_eq!(result.status, CheckStatus::Warn);
578 assert!(result.message.contains("Cargo.lock"));
579 }
580
581 #[test]
582 fn rust_with_lock_but_no_cargo_warns() {
583 let dir = TempDir::new("rust_lock_no_cargo")
584 .write(
585 "Cargo.toml",
586 "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n",
587 )
588 .write("Cargo.lock", "[metadata]\n\"checksum\"");
589 let result = check_dependencies(dir.path().to_str().unwrap(), &rust_stack());
590 assert_eq!(result.status, CheckStatus::Warn);
592 }
593
594 #[test]
597 fn unknown_stack_passes() {
598 let result = check_dependencies("/tmp", &ProjectStack::Unknown);
599 assert_eq!(result.status, CheckStatus::Pass);
600 }
601
602 fn node_stack() -> ProjectStack {
605 ProjectStack::Node {
606 version: String::new(),
607 package_manager: "npm".to_string(),
608 }
609 }
610
611 fn python_stack() -> ProjectStack {
612 ProjectStack::Python {
613 version: String::new(),
614 }
615 }
616
617 fn rust_stack() -> ProjectStack {
618 ProjectStack::Rust {
619 version: String::new(),
620 }
621 }
622}