Skip to main content

auths_cli/adapters/
local_file.rs

1//! Local filesystem artifact adapter.
2
3use auths_sdk::ports::artifact::{ArtifactDigest, ArtifactError, ArtifactMetadata, ArtifactSource};
4use sha2::{Digest, Sha256};
5use std::io::Read;
6use std::path::{Path, PathBuf};
7
8/// Artifact source backed by a local file.
9///
10/// Usage:
11/// ```ignore
12/// let artifact = LocalFileArtifact::new("path/to/file.tar.gz");
13/// let digest = artifact.digest()?;
14/// ```
15pub struct LocalFileArtifact {
16    path: PathBuf,
17}
18
19impl LocalFileArtifact {
20    pub fn new(path: impl Into<PathBuf>) -> Self {
21        Self { path: path.into() }
22    }
23
24    pub fn path(&self) -> &Path {
25        &self.path
26    }
27}
28
29impl ArtifactSource for LocalFileArtifact {
30    fn digest(&self) -> Result<ArtifactDigest, ArtifactError> {
31        let mut file = std::fs::File::open(&self.path)
32            .map_err(|e| ArtifactError::Io(format!("{}: {}", self.path.display(), e)))?;
33
34        let mut hasher = Sha256::new();
35        let mut buf = [0u8; 8192];
36
37        loop {
38            let n = file
39                .read(&mut buf)
40                .map_err(|e| ArtifactError::Io(e.to_string()))?;
41            if n == 0 {
42                break;
43            }
44            hasher.update(&buf[..n]);
45        }
46
47        Ok(ArtifactDigest {
48            algorithm: "sha256".to_string(),
49            hex: hex::encode(hasher.finalize()),
50        })
51    }
52
53    fn metadata(&self) -> Result<ArtifactMetadata, ArtifactError> {
54        let digest = self.digest()?;
55        let file_meta = std::fs::metadata(&self.path)
56            .map_err(|e| ArtifactError::Metadata(format!("{}: {}", self.path.display(), e)))?;
57
58        Ok(ArtifactMetadata {
59            artifact_type: "file".to_string(),
60            digest,
61            name: self
62                .path
63                .file_name()
64                .map(|n| n.to_string_lossy().to_string()),
65            size: Some(file_meta.len()),
66        })
67    }
68}