|
| 1 | +use std::fs; |
| 2 | +use std::io::ErrorKind; |
| 3 | +use std::path::Path; |
| 4 | +use std::process::Command; |
| 5 | +use std::time::Duration; |
| 6 | + |
| 7 | +use anyhow::Result; |
| 8 | +use clap::{Args, ValueEnum}; |
| 9 | +use strum::EnumIter; |
| 10 | + |
| 11 | +use crate::command; |
| 12 | + |
| 13 | +#[derive(Args)] |
| 14 | +pub struct Audit { |
| 15 | + #[arg(long, value_delimiter = ',', default_value = AuditTools::default_arg())] |
| 16 | + tools: Vec<AuditTools>, |
| 17 | +} |
| 18 | + |
| 19 | +enum_with_all!(pub enum AuditTools, Tool(AuditTool), "tools"); |
| 20 | + |
| 21 | +#[derive(Clone, Copy, Default, EnumIter, Eq, PartialEq, ValueEnum)] |
| 22 | +pub enum AuditTool { |
| 23 | + #[default] |
| 24 | + RustSec, |
| 25 | + Npm, |
| 26 | +} |
| 27 | + |
| 28 | +impl Audit { |
| 29 | + pub fn new(tools: Vec<AuditTools>) -> Self { |
| 30 | + Self { tools } |
| 31 | + } |
| 32 | + |
| 33 | + pub fn execute(self, verbose: bool) -> Result<()> { |
| 34 | + let tools = AuditTool::from_tools(self.tools)?; |
| 35 | + let mut duration = Duration::ZERO; |
| 36 | + |
| 37 | + for tool in tools { |
| 38 | + match tool { |
| 39 | + AuditTool::RustSec => { |
| 40 | + let mut command = Command::new("cargo"); |
| 41 | + command.arg("audit"); |
| 42 | + duration += command::run("RustSec", command, verbose)?; |
| 43 | + } |
| 44 | + AuditTool::Npm => { |
| 45 | + duration += Self::npm("js-bindgen-ld", "ld/src/js", verbose)?; |
| 46 | + duration += Self::npm("js-bindgen-runner", "runner/src/js", verbose)?; |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + println!("-------------------------"); |
| 52 | + println!("Total Time: {:.2}s", duration.as_secs_f32()); |
| 53 | + |
| 54 | + Ok(()) |
| 55 | + } |
| 56 | + |
| 57 | + fn npm(package: &str, path: &str, verbose: bool) -> Result<Duration> { |
| 58 | + let needs_install = match fs::metadata(Path::new(path).join("package-lock.json")) { |
| 59 | + Ok(meta) => { |
| 60 | + let lock_mtime = meta.modified()?; |
| 61 | + let pkg_mtime = fs::metadata(Path::new(path).join("package.json"))?.modified()?; |
| 62 | + |
| 63 | + lock_mtime < pkg_mtime |
| 64 | + } |
| 65 | + Err(error) if error.kind() == ErrorKind::NotFound => true, |
| 66 | + Err(error) => return Err(error.into()), |
| 67 | + }; |
| 68 | + |
| 69 | + if needs_install { |
| 70 | + let mut command = Command::new("npm"); |
| 71 | + command |
| 72 | + .current_dir(path) |
| 73 | + .arg("install") |
| 74 | + .arg("--package-lock-only") |
| 75 | + .arg("--no-audit") |
| 76 | + .arg("--no-fund"); |
| 77 | + |
| 78 | + command::run(&format!("NPM Install `{package}`"), command, verbose)?; |
| 79 | + } |
| 80 | + |
| 81 | + let mut command = Command::new("npm"); |
| 82 | + command.current_dir(path).arg("audit"); |
| 83 | + command::run(&format!("NPM Audit `{package}`"), command, verbose) |
| 84 | + } |
| 85 | +} |
0 commit comments