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
use crate::download::get_archive_file;
use crate::BunLanguage;
use proto_core::{async_trait, color, get_sha256_hash_of_file, ProtoError, Resolvable, Verifiable};
use starbase_utils::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use tracing::debug;

#[async_trait]
impl Verifiable<'_> for BunLanguage {
    fn get_checksum_path(&self) -> Result<PathBuf, ProtoError> {
        Ok(self
            .temp_dir
            .join(format!("v{}-SHASUMS256.txt", self.get_resolved_version())))
    }

    fn get_checksum_url(&self) -> Result<Option<String>, ProtoError> {
        Ok(Some(format!(
            "https://github.com/oven-sh/bun/releases/download/bun-v{}/SHASUMS256.txt",
            self.get_resolved_version()
        )))
    }

    async fn verify_checksum(
        &self,
        checksum_file: &Path,
        download_file: &Path,
    ) -> Result<bool, ProtoError> {
        debug!(
            "Verifiying checksum of downloaded file {} using {}",
            color::path(download_file),
            color::path(checksum_file),
        );

        let checksum = get_sha256_hash_of_file(download_file)?;

        let file = fs::open_file(checksum_file)?;
        let file_name = get_archive_file()?;

        for line in BufReader::new(file).lines().flatten() {
            // <checksum>  bun-<os>-<arch>.zip
            if line.starts_with(&checksum) && line.ends_with(&file_name) {
                debug!("Successfully verified, checksum matches");

                return Ok(true);
            }
        }

        Err(ProtoError::VerifyInvalidChecksum(
            download_file.to_path_buf(),
            checksum_file.to_path_buf(),
        ))
    }
}