carbone_sdk_rust/
template.rs1use std::fs;
2use std::path::Path;
3use std::str;
4
5use std::fs::Metadata;
6
7use std::ops::Deref;
8
9use sha2::{Digest, Sha256};
10
11use serde::{Deserialize, Serialize};
12
13use crate::errors::CarboneError;
14use crate::types::*;
15
16use crate::types::Result;
17
18#[derive(Debug, Clone)]
19pub struct TemplateFile {
20 path: String,
21 pub content: Option<Vec<u8>>,
22 pub metadata: Metadata,
23}
24
25impl TemplateFile {
26 pub fn new(path: String, content: Option<Vec<u8>>) -> Result<Self> {
27 if Path::new(path.as_str()).is_dir() {
28 return Err(CarboneError::IsADirectory(path));
29 }
30
31 if !Path::new(path.as_str()).is_file() {
32 return Err(CarboneError::TemplateFileNotFound(path));
33 }
34
35 let metadata = fs::metadata(path.as_str())?;
36
37 Ok(Self {
38 path,
39 content,
40 metadata,
41 })
42 }
43
44 pub fn generate_id(&self, payload: Option<&str>) -> Result<TemplateId> {
45 let file_content = match self.content.to_owned() {
46 Some(c) => c,
47 None => fs::read(self.path_as_str())?,
48 };
49
50 TemplateId::from_bytes(file_content, payload)
51 }
52
53 pub fn path_as_str(&self) -> &str {
54 &self.path
55 }
56}
57
58#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
59pub struct TemplateId(Id);
60
61impl TemplateId {
62 pub fn new<T: Into<String>>(id: T) -> Result<Self> {
83 let id = Id::new(id, "template_id")?;
84 Ok(TemplateId(id))
85 }
86
87 pub fn from_bytes(data: Vec<u8>, payload: Option<&str>) -> Result<Self> {
88 let mut sha256 = Sha256::new();
89
90 let payload = payload.unwrap_or("");
91
92 sha256.update(payload);
93 sha256.update(data);
94
95 let result: String = format!("{:X}", sha256.finalize());
97
98 Self::new(result.to_lowercase())
99 }
100}
101
102impl Deref for TemplateId {
103 type Target = Id;
104
105 fn deref(&self) -> &Self::Target {
106 &self.0
107 }
108}
109
110impl AsRef<str> for TemplateId {
111 fn as_ref(&self) -> &str {
112 self.0.as_ref()
113 }
114}