git_workspace/
lockfile.rs1use crate::repository::Repository;
2use anyhow::Context;
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::path::PathBuf;
6
7pub struct Lockfile {
8 path: PathBuf,
9}
10
11#[derive(Deserialize, Serialize, Debug)]
12struct LockfileContents {
13 #[serde(rename = "repo")]
14 repos: Vec<Repository>,
15}
16
17impl Lockfile {
18 pub fn new(path: PathBuf) -> Lockfile {
19 Lockfile { path }
20 }
21
22 pub fn read(&self) -> anyhow::Result<Vec<Repository>> {
23 let config_data = fs::read_to_string(&self.path)
24 .with_context(|| format!("Cannot read file {}", self.path.display()))?;
25 let config: LockfileContents = toml::from_str(config_data.as_str())
26 .with_context(|| "Error deserializing".to_string())?;
27 Ok(config.repos)
28 }
29
30 pub fn write(&self, repositories: &[Repository]) -> anyhow::Result<()> {
31 let mut sorted_repositories = repositories.to_owned();
32 sorted_repositories.sort();
33
34 let toml = toml::to_string(&LockfileContents {
35 repos: sorted_repositories,
36 })?;
37 fs::write(&self.path, toml)
38 .with_context(|| format!("Error writing lockfile to {}", self.path.display()))?;
39
40 Ok(())
41 }
42}