-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathlockfile.rs
94 lines (85 loc) · 2.73 KB
/
lockfile.rs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use anyhow::bail;
use fs_err::tokio as fs;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct LockfileEntry {
pub hash: String,
pub asset_id: u64,
}
pub const CURRENT_VERSION: u32 = 1;
pub const FILE_NAME: &str = "asphalt.lock.toml";
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum Lockfile {
V0 {
entries: BTreeMap<String, LockfileEntry>,
},
V1 {
version: u32,
inputs: BTreeMap<String, BTreeMap<String, LockfileEntry>>,
},
}
impl Default for Lockfile {
fn default() -> Self {
Lockfile::V1 {
version: CURRENT_VERSION,
inputs: BTreeMap::new(),
}
}
}
impl Lockfile {
pub async fn read() -> anyhow::Result<Self> {
let content = fs::read_to_string(FILE_NAME).await;
match content {
Ok(content) => {
let parsed = toml::from_str(&content)?;
Ok(parsed)
}
Err(_) => Ok(Lockfile::default()),
}
}
pub fn get(&self, input_name: &str, path: &Path) -> Option<&LockfileEntry> {
match self {
Lockfile::V0 { .. } => None,
Lockfile::V1 { inputs, .. } => {
let path_str = path.to_string_lossy().replace("\\", "/");
inputs
.get(input_name)
.and_then(|assets| assets.get(&path_str))
}
}
}
pub fn insert(&mut self, input_name: &str, path: &Path, entry: LockfileEntry) {
match self {
Lockfile::V0 { .. } => {
panic!("Cannot insert into version 0 lockfile!");
}
Lockfile::V1 { inputs, .. } => {
let path_str = path.to_string_lossy().replace("\\", "/");
let input_map = inputs.entry(input_name.to_string()).or_default();
input_map.insert(path_str, entry);
}
}
}
pub async fn write(&self, filename: Option<&Path>) -> anyhow::Result<()> {
match self {
Lockfile::V0 { .. } => {
anyhow::bail!("Cannot write out a version 0 lockfile!");
}
Lockfile::V1 { .. } => {
let content = toml::to_string(self)?;
fs::write(filename.unwrap_or(Path::new(FILE_NAME)), content).await?;
Ok(())
}
}
}
pub fn get_all_if_v0(&self) -> anyhow::Result<BTreeMap<String, LockfileEntry>> {
match self {
Lockfile::V0 { entries } => Ok(entries.clone()),
Lockfile::V1 { .. } => {
bail!("Cannot flatten V1 lockfile into V0 format");
}
}
}
}