manganis_common/
package.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{
4    asset::AssetType,
5    cache::{current_package_cache_dir, current_package_identifier},
6};
7
8/// Clears all assets from the current package
9pub fn clear_assets() -> std::io::Result<()> {
10    let dir = current_package_cache_dir();
11    if dir.exists() {
12        tracing::info!("Clearing assets in {:?}", dir);
13        std::fs::remove_dir_all(dir)?;
14    }
15    Ok(())
16}
17
18/// Adds an asset to the current package
19pub fn add_asset(asset: AssetType) -> std::io::Result<AssetType> {
20    let mut dir = current_package_cache_dir();
21    dir.push("assets.toml");
22    tracing::info!("Adding asset {:?} to {:?}", asset, dir);
23    let mut package_assets: PackageAssets = if dir.exists() {
24        let contents = std::fs::read_to_string(&dir)?;
25        toml::from_str(&contents).unwrap_or_else(|_| PackageAssets {
26            package: current_package_identifier(),
27            assets: vec![],
28        })
29    } else {
30        std::fs::create_dir_all(dir.parent().unwrap())?;
31        PackageAssets {
32            package: current_package_identifier(),
33            assets: vec![],
34        }
35    };
36
37    package_assets.add(asset.clone());
38    let contents = toml::to_string(&package_assets).unwrap();
39    std::fs::write(&dir, contents)?;
40
41    Ok(asset)
42}
43
44/// All assets collected from a specific package
45#[derive(Serialize, Deserialize, Debug, PartialEq, PartialOrd, Clone)]
46pub struct PackageAssets {
47    package: String,
48    assets: Vec<AssetType>,
49}
50
51impl PackageAssets {
52    /// Adds an asset to the package
53    pub fn add(&mut self, asset: AssetType) {
54        self.assets.push(asset);
55    }
56
57    /// Returns a reference to the package name
58    pub fn package(&self) -> &str {
59        &self.package
60    }
61
62    /// Returns a reference to the assets in this package
63    pub fn assets(&self) -> &Vec<AssetType> {
64        &self.assets
65    }
66}