Skip to main content

podbox/
lock.rs

1use std::io::Write;
2use std::path::Path;
3
4use anyhow::{Context, Result};
5use serde::{Deserialize, Serialize};
6
7/// Lock file tracking definition hash and image digest.
8#[derive(Debug, Serialize, Deserialize)]
9pub struct LockFile {
10    pub config_checksum: String,
11    pub image_digest: String,
12}
13
14/// Read a lock file if it exists.
15pub fn read(path: &Path) -> Result<Option<LockFile>> {
16    if !path.exists() {
17        return Ok(None);
18    }
19    let content = std::fs::read_to_string(path)
20        .with_context(|| format!("failed to read lock file '{}'", path.display()))?;
21    let lock: LockFile = serde_json::from_str(&content)
22        .with_context(|| format!("failed to parse lock file '{}'", path.display()))?;
23    Ok(Some(lock))
24}
25
26/// Write a lock file.
27pub fn write(path: &Path, lock: &LockFile) -> Result<()> {
28    let mut file = std::fs::File::create(path)
29        .with_context(|| format!("failed to create lock file '{}'", path.display()))?;
30    let json = serde_json::to_string_pretty(lock)
31        .with_context(|| format!("failed to serialize lock data for '{}'", path.display()))?;
32    writeln!(file, "{}", json)
33        .with_context(|| format!("failed to write lock file '{}'", path.display()))?;
34    Ok(())
35}