changepacks_node/
workspace.rs

1use anyhow::Result;
2use async_trait::async_trait;
3use changepacks_core::{Language, UpdateType, Workspace};
4use changepacks_utils::next_version;
5use std::path::{Path, PathBuf};
6use tokio::fs::{read_to_string, write};
7
8#[derive(Debug)]
9pub struct NodeWorkspace {
10    path: PathBuf,
11    relative_path: PathBuf,
12    version: Option<String>,
13    name: Option<String>,
14    is_changed: bool,
15}
16
17impl NodeWorkspace {
18    pub fn new(
19        name: Option<String>,
20        version: Option<String>,
21        path: PathBuf,
22        relative_path: PathBuf,
23    ) -> Self {
24        Self {
25            path,
26            relative_path,
27            name,
28            version,
29            is_changed: false,
30        }
31    }
32}
33
34#[async_trait]
35impl Workspace for NodeWorkspace {
36    fn name(&self) -> Option<&str> {
37        self.name.as_deref()
38    }
39
40    fn path(&self) -> &Path {
41        &self.path
42    }
43
44    fn version(&self) -> Option<&str> {
45        self.version.as_deref()
46    }
47
48    async fn update_version(&self, update_type: UpdateType) -> Result<()> {
49        let next_version = next_version(
50            self.version.as_ref().unwrap_or(&String::from("0.0.0")),
51            update_type,
52        )?;
53
54        let package_json = read_to_string(Path::new(&self.path)).await?;
55        let mut package_json: serde_json::Value = serde_json::from_str(&package_json)?;
56        package_json["version"] = serde_json::Value::String(next_version.clone());
57        write(
58            Path::new(&self.path),
59            serde_json::to_string_pretty(&package_json)?,
60        )
61        .await?;
62        Ok(())
63    }
64
65    fn language(&self) -> Language {
66        Language::Node
67    }
68
69    fn is_changed(&self) -> bool {
70        self.is_changed
71    }
72
73    fn set_changed(&mut self, changed: bool) {
74        self.is_changed = changed;
75    }
76
77    fn relative_path(&self) -> &Path {
78        &self.relative_path
79    }
80}