tfc_toolset_extras/file/
variable.rs

1use crate::ExtrasError;
2use serde::{Deserialize, Serialize};
3use std::{fs::File, io::BufReader, path::Path};
4use tfc_toolset::{
5    error::ToolError,
6    variable::Attributes,
7    workspace::{Workspace, WorkspaceVariables},
8};
9
10#[derive(Clone, Debug, Deserialize, Serialize)]
11pub struct Variable {
12    #[serde(skip_serializing_if = "Option::is_none")]
13    pub id: Option<String>,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    pub attributes: Option<Attributes>,
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub var: Option<String>,
18    pub workspace: Option<Workspace>,
19}
20
21#[derive(Clone, Debug, Deserialize, Serialize)]
22pub struct VariablesFile {
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub variables: Option<Vec<Variable>>,
25}
26
27impl From<Vec<WorkspaceVariables>> for VariablesFile {
28    fn from(vec: Vec<WorkspaceVariables>) -> Self {
29        let mut variables_file = VariablesFile { variables: None };
30        let mut variables_vec = Vec::new();
31        for workspace_variables in vec {
32            for variable in workspace_variables.variables {
33                let entry = Variable {
34                    id: variable.id,
35                    attributes: Some(variable.attributes),
36                    var: None,
37                    workspace: Some(workspace_variables.workspace.clone()),
38                };
39                variables_vec.push(entry);
40            }
41        }
42        variables_file.variables = Some(variables_vec);
43        variables_file
44    }
45}
46
47impl VariablesFile {
48    pub fn load<P: AsRef<Path>>(path: P) -> Result<Self, ExtrasError> {
49        let file = File::open(path).map_err(ToolError::Io)?;
50        let reader = BufReader::new(file);
51        let variables_file: Self =
52            serde_json::from_reader(reader).map_err(ToolError::Json)?;
53        Ok(variables_file)
54    }
55
56    pub fn save<P: AsRef<Path>>(
57        &self,
58        path: P,
59        pretty: bool,
60    ) -> Result<(), ToolError> {
61        if pretty {
62            serde_json::to_writer_pretty(&File::create(path)?, self)?;
63        } else {
64            serde_json::to_writer(&File::create(path)?, self)?;
65        }
66        Ok(())
67    }
68}