🏡 index : quine-global/quorum.git

//! SHA256SUMS files and hashing.

use std::fs::File;
use std::io::Read;
use std::path::Path;

use anyhow::{Context, Result};
use sha2::{Digest, Sha256};

/// Lines of `<hex>  <name>` (or `<hex> *<name>`, binary mode).
pub fn parse(data: &[u8]) -> Vec<(String, String)> {
    String::from_utf8_lossy(data)
        .lines()
        .filter_map(|line| {
            let (hash, rest) = line.trim_end_matches('\r').split_once(' ')?;
            let name = rest.trim_start_matches(' ').trim_start_matches('*');
            let ok =
                hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()) && !name.is_empty();
            ok.then(|| (hash.to_ascii_lowercase(), name.to_string()))
        })
        .collect()
}

pub fn sha256_file(path: &Path) -> Result<String> {
    let mut f = File::open(path).with_context(|| format!("opening {}", path.display()))?;
    let mut h = Sha256::new();
    let mut buf = vec![0u8; 1 << 20];
    loop {
        let n = f
            .read(&mut buf)
            .with_context(|| format!("reading {}", path.display()))?;
        if n == 0 {
            break;
        }
        h.update(&buf[..n]);
    }
    Ok(hex::encode(h.finalize()))
}

/// The release in a file name that starts with `prefix`, up to the next `-`:
/// with prefix `bitcoin-`, `bitcoin-32.1-win64-setup.exe` → `32.1`,
/// `bitcoin-32.0rc1-…` → `32.0rc1`.
pub fn release_from_name(name: &str, prefix: &str) -> Option<String> {
    let rest = name.strip_prefix(prefix)?;
    let v = rest.split('-').next()?;
    let v = v
        .strip_suffix(".exe")
        .or(v.strip_suffix(".zip"))
        .unwrap_or(v);
    v.starts_with(|c: char| c.is_ascii_digit())
        .then(|| v.to_string())
}

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

    #[test]
    fn parses_both_modes() {
        let a = "a".repeat(64);
        let b = "B".repeat(64);
        let got = parse(format!("{a}  x.exe\r\n{b} *y.zip\njunk\n").as_bytes());
        assert_eq!(
            got,
            vec![(a, "x.exe".into()), ("b".repeat(64), "y.zip".into())]
        );
    }

    #[test]
    fn versions() {
        let r = |n| release_from_name(n, "bitcoin-");
        assert_eq!(r("bitcoin-32.1-win64-setup.exe").as_deref(), Some("32.1"));
        assert_eq!(r("bitcoin-32.0rc1-win64.zip").as_deref(), Some("32.0rc1"));
        assert_eq!(r("SHA256SUMS"), None);
        assert_eq!(
            release_from_name("Hyper-4.0.0.exe", "Hyper-").as_deref(),
            Some("4.0.0")
        );
    }
}