espforge_lib/examples/
config.rs1use crate::cli::model::ExampleConfig;
2use anyhow::{Context, Result, anyhow, bail};
3use std::fs;
4use std::path::{Path, PathBuf};
5
6pub struct ConfigFile {
7 path: PathBuf,
8}
9
10impl ConfigFile {
11 const DEFAULT_NAME: &'static str = "example.yaml";
12
13 pub fn locate(base_path: &Path) -> Result<Self> {
14 let path = base_path.join(Self::DEFAULT_NAME);
15
16 if !path.exists() {
17 bail!("The example template is missing the required 'example.yaml' file");
18 }
19
20 Ok(Self { path })
21 }
22
23 pub fn update(&self, config: &ExampleConfig) -> Result<()> {
24 let mut yaml_doc = self.read_yaml()?;
25
26 Self::apply_project_name(&mut yaml_doc, &config.project_name);
27 Self::apply_chip(&mut yaml_doc, &config.chip);
28
29 self.write_yaml(&yaml_doc)
30 }
31
32 pub fn rename_to(&self, project_name: &str) -> Result<String> {
33 let new_filename = format!("{}.yaml", project_name);
34 let new_path = self
35 .path
36 .parent()
37 .ok_or_else(|| anyhow!("Invalid config file path"))?
38 .join(&new_filename);
39
40 fs::rename(&self.path, &new_path).context("Failed to rename configuration file")?;
41
42 Ok(project_name.to_string())
43 }
44
45 fn read_yaml(&self) -> Result<serde_yaml_ng::Value> {
46 let content = fs::read_to_string(&self.path).context("Failed to read example.yaml")?;
47 serde_yaml_ng::from_str(&content).context("Failed to parse example.yaml")
48 }
49
50 fn write_yaml(&self, doc: &serde_yaml_ng::Value) -> Result<()> {
51 let content =
52 serde_yaml_ng::to_string(doc).context("Failed to serialize updated config")?;
53 fs::write(&self.path, content).context("Failed to write updated example.yaml")
54 }
55
56 fn apply_project_name(doc: &mut serde_yaml_ng::Value, name: &str) {
57 if let Some(espforge) = doc.get_mut("espforge") {
58 espforge["name"] = serde_yaml_ng::Value::String(name.to_string());
59 }
60 }
61
62 fn apply_chip(doc: &mut serde_yaml_ng::Value, chip: &str) {
63 if let Some(espforge) = doc.get_mut("espforge") {
64 espforge["platform"] = serde_yaml_ng::Value::String(chip.to_string());
65 }
66 }
67}