1use std::{fs, path::PathBuf};
2
3use crate::config::Workspace;
4use anyhow::{bail, Result};
5
6const CONFIG_FILE: &str = "Crux.toml";
7
8pub fn read_config() -> Result<Workspace> {
9 let path = PathBuf::from(CONFIG_FILE);
10 if let Ok(file) = &fs::read_to_string(path) {
11 let mut workspace: Workspace = toml::from_str(file)?;
12
13 let all_cores = workspace.cores.keys().cloned().collect::<Vec<_>>();
14 if all_cores.is_empty() {
15 bail!("{CONFIG_FILE}: no cores defined");
16 }
17
18 for (name, core) in &mut workspace.cores {
19 core.name = name.to_string();
20 if !core.source.exists() {
21 bail!(
22 "{CONFIG_FILE}: core ({name}) source directory ({path}) does not exist",
23 path = core.source.display()
24 );
25 }
26 }
27
28 if let Some(shells) = &mut workspace.shells {
29 for (name, shell) in shells {
30 shell.name = name.to_string();
31 if !shell.source.exists() {
32 bail!(
33 "{CONFIG_FILE}: shell ({name}) source directory ({path}) does not exist",
34 path = shell.source.display()
35 );
36 }
37 if !shell.cores.iter().all(|core| all_cores.contains(core)) {
38 bail!("{CONFIG_FILE}: shell ({name}) references a core that does not exist");
39 }
40 }
41 }
42
43 Ok(workspace)
44 } else {
45 Ok(Workspace::default())
46 }
47}
48
49pub fn write_config(workspace: &Workspace) -> Result<()> {
50 let path = PathBuf::from(CONFIG_FILE);
51 let toml = toml::to_string(workspace)?;
52 fs::write(path, toml)?;
53 Ok(())
54}