substrate_manager/core/
manifest.rs

1use std::{
2    fs::{self, OpenOptions},
3    io::{Seek, SeekFrom, Write},
4    path::PathBuf,
5};
6
7use anyhow::Ok;
8use toml_edit::Document;
9
10use crate::util::SubstrateResult;
11
12#[derive(Debug)]
13pub struct Manifest {
14    path: PathBuf,
15}
16
17impl Manifest {
18    pub fn new(path: PathBuf) -> Self {
19        Self { path }
20    }
21
22    pub fn read_document(&mut self) -> SubstrateResult<Document> {
23        let toml = fs::read_to_string(&self.path)?;
24        toml.parse()
25            .map_err(|e| anyhow::Error::from(e).context("could not parse input as TOML"))
26    }
27
28    pub fn write_document(&mut self, document: Document) -> SubstrateResult<()> {
29        let toml = document.to_string();
30        let bytes = toml.as_bytes();
31
32        self.write(bytes)
33    }
34
35    // TODO: decouple from this class and make as reusable utility function
36    fn write(&mut self, bytes: &[u8]) -> SubstrateResult<()> {
37        let path = &self.path;
38
39        let mut file = OpenOptions::new()
40            .create(true)
41            .read(true)
42            .write(true)
43            .append(false)
44            .open(path)?;
45
46        file.seek(SeekFrom::Start(0))?;
47        file.write_all(bytes)?;
48        file.set_len(bytes.len() as u64)?;
49        Ok(())
50    }
51}