Skip to content
1        10        20        30        40        50        60        70        80        901use std::error::Error;2use std::fmt;3use std::fs;4use std::path::{Path, PathBuf};5use std::time::{SystemTime, UNIX_EPOCH};67mod discover;8pub mod mcp;9pub mod report;1011#[derive(Debug, Default)]12pub struct AuditReport {13    pub discovered_source_count: usize,14    pub files: Vec<FileMetric>,15    pub warnings: Vec<ScanWarning>,16}1718#[derive(Debug, Clone, PartialEq, Eq)]19pub struct FileMetric {20    pub path: PathBuf,21    pub bytes: u64,22    pub physical_lines: usize,23}2425#[derive(Debug, Clone, PartialEq, Eq)]26pub struct ScanWarning {27    pub path: PathBuf,28    pub message: String,29}3031#[derive(Debug)]32pub enum AuditError {33    Discovery {34        path: PathBuf,35        source: std::io::Error,36    },37    ReportWrite {38        path: PathBuf,39        source: std::io::Error,40    },41}4243impl fmt::Display for AuditError {44    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {45        match self {46            Self::Discovery { path, source } => {47                write!(48                    formatter,49                    "could not discover Rust source files under {}: {source}",50                    path.display()51                )52            }53            Self::ReportWrite { path, source } => {54                write!(55                    formatter,56                    "could not write report {}: {source}",57                    path.display()58                )59            }60        }61    }62}6364impl Error for AuditError {65    fn source(&self) -> Option<&(dyn Error + 'static)> {66        match self {67            Self::Discovery { source, .. } | Self::ReportWrite { source, .. } => Some(source),68        }69    }70}7172pub fn audit_project(root: &Path) -> Result<AuditReport, AuditError> {73    let source_paths = discover::discover_sources(root)?;74    let mut report = AuditReport {75        discovered_source_count: source_paths.len(),76        ..AuditReport::default()77    };7879    for relative_path in source_paths {80        let absolute_path = root.join(&relative_path);81        match fs::read(&absolute_path) {82            Ok(source) => report.files.push(FileMetric {83                path: relative_path,84                bytes: source.len() as u64,85                physical_lines: physical_line_count(&source),86            }),87            Err(error) => report.warnings.push(ScanWarning {88                path: relative_path,89                message: error.to_string(),90            }),91        }92    }9394    Ok(report)95}9697pub fn utc_date() -> Result<String, String> {98    let duration = SystemTime::now()99        .duration_since(UNIX_EPOCH)100        .map_err(|error| error.to_string())?;101    Ok(utc_date_from_epoch_days(duration.as_secs() / 86_400))102}103104fn utc_date_from_epoch_days(epoch_days: u64) -> String {105    let shifted_days = epoch_days as i64 + 719_468;106    let era = (if shifted_days >= 0 {107        shifted_days108    } else {109        shifted_days - 146_096110    }) / 146_097;111    let day_of_era = shifted_days - era * 146_097;112    let year_of_era =113        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;114    let mut year = year_of_era + era * 400;115    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);116    let month_prime = (5 * day_of_year + 2) / 153;117    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;118    let month = month_prime + if month_prime < 10 { 3 } else { -9 };119    year += i64::from(month <= 2);120121    format!("{year:04}-{month:02}-{day:02}")122}123124fn physical_line_count(source: &[u8]) -> usize {125    let newline_count = source.iter().filter(|byte| **byte == b'\n').count();126    if source.is_empty() || source.last() == Some(&b'\n') {127        newline_count128    } else {129        newline_count + 1130    }131}132133#[cfg(test)]134mod tests {135    use super::{physical_line_count, utc_date_from_epoch_days};136137    #[test]138    fn physical_lines_count_newlines_and_final_unterminated_line() {139        assert_eq!(physical_line_count(b""), 0);140        assert_eq!(physical_line_count(b"\n"), 1);141        assert_eq!(physical_line_count(b"first\nsecond\n"), 2);142        assert_eq!(physical_line_count(b"first\nsecond"), 2);143        assert_eq!(physical_line_count(&[0xff, b'\n', 0xfe]), 2);144    }145146    #[test]147    fn utc_date_formats_epoch_day() {148        assert_eq!(utc_date_from_epoch_days(0), "1970-01-01");149    }150151    #[test]152    fn utc_date_handles_leap_day() {153        assert_eq!(utc_date_from_epoch_days(11_016), "2000-02-29");154    }155}