You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
malachite/src/lock.rs

87 lines
2.3 KiB
Rust

use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::config::Config;
use crate::errors::{AppError, ConfigError};
use crate::git::GitRepository;
pub const LOCKFILE_VERSION: &str = "1.0";
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Lockfile {
pub lockfile: Meta,
pub remote: HashMap<String, Remote>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Meta {
pub version: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Remote {
pub origin: String,
pub commit: String,
pub branch: String,
}
impl Lockfile {
pub fn new(config: &Config) -> Result<Self, ConfigError> {
let path = config.base.src.join(".mlc").join("mlc.lock");
let lockfile = match std::fs::read_to_string(path) {
Ok(lockfile) => toml::from_str(&lockfile)?,
Err(_) => Self {
lockfile: Meta {
version: LOCKFILE_VERSION.to_string(),
},
remote: HashMap::new(),
},
};
Ok(lockfile)
}
pub fn update(&mut self, config: &Config) -> Result<&mut Self, AppError> {
for repo in &config.repositories.names {
let git = GitRepository::new(config.base.src.join(&repo.name));
let config_url = repo.expand(config)?;
let remote_url = git.origin()?;
if config_url != remote_url {
git.update_origin(&config_url)?;
git.pull()?;
}
if let Some(branch) = &repo.rev {
if branch != &git.current_branch()? {
git.checkout(branch)?;
}
}
if repo.rev.is_none() && git.current_branch()? != git.default_branch()? {
git.checkout(git.default_branch()?.as_str())?;
}
let remote = Remote {
origin: config_url,
commit: git.hash()?,
branch: git.current_branch()?,
};
self.remote.insert(repo.name.clone(), remote);
}
Ok(self)
}
pub fn save(&self) -> Result<(), AppError> {
let lockfile = toml::to_string_pretty(&self)
.map_err(|e| AppError::Config(ConfigError::Serialize(e)))?;
std::fs::write(".mlc/mlc.lock", lockfile)?;
Ok(())
}
}