Starting to write config file

This commit is contained in:
Dave Hrycyszyn
2024-06-06 15:54:33 +01:00
parent dc3d0ad83a
commit 1e1f452cff
6 changed files with 117 additions and 39 deletions

94
side-node/src/init/mod.rs Normal file
View File

@@ -0,0 +1,94 @@
use std::path::PathBuf;
use config::SideNodeConfig;
pub(crate) mod config;
mod keys;
const KEY_FILE: &str = "keys.pem";
const CONFIG_FILE: &str = "config.toml";
pub(crate) fn init(home: PathBuf, config: SideNodeConfig) -> Result<(), std::io::Error> {
ensure_side_directory_exists(&home)?;
let (key_path, config_path) = side_paths(home.clone());
let pem = keys::setup();
keys::write_pem(key_path, pem)?;
config::write_config_to_file(&config, &config_path).expect("unable to write config file");
Ok(())
}
/// Ensures that the directory at side_dir exists, so we have a place
/// to store our key file and config file.
fn ensure_side_directory_exists(side_dir: &PathBuf) -> Result<(), std::io::Error> {
if side_dir.exists() {
return Ok(());
}
println!("Creating side config directory: {:?}", side_dir);
std::fs::create_dir_all(side_dir)
}
/// Returns the path to the key file for this host OS.
fn side_paths(prefix: PathBuf) -> (PathBuf, PathBuf) {
let mut key_path = prefix.clone();
key_path.push(KEY_FILE);
let mut config_path = prefix.clone();
config_path.push(CONFIG_FILE);
(key_path, config_path)
}
#[cfg(test)]
mod tests {
use std::{fs, path::Path};
use super::*;
fn default_side_node_config() -> SideNodeConfig {
SideNodeConfig {
name: "alice".to_string(),
}
}
#[test]
fn creates_side_node_directory() {
let mut test_home = PathBuf::new();
let side_dir = "/tmp/side";
// clean up any previous test runs
fs::remove_dir_all(side_dir).expect("couldn't remove side directory during test");
test_home.push(side_dir);
let node_dir = Path::new(&test_home).parent().unwrap().to_str().unwrap();
let _ = init(test_home.clone(), default_side_node_config());
assert!(std::path::Path::new(node_dir).exists());
}
#[test]
fn creates_key_file() {
let mut file_path = PathBuf::new();
file_path.push("/tmp/side");
let side_dir = file_path.clone();
file_path.push(KEY_FILE);
let _ = init(side_dir.clone(), default_side_node_config());
assert!(file_path.exists());
// check that the pem is readable
let pem = fs::read_to_string(file_path).unwrap();
assert!(pem::parse_many(&pem).is_ok());
}
#[test]
fn creates_config_file() {
let mut file_path = PathBuf::new();
file_path.push("/tmp/side");
let side_dir = file_path.clone();
file_path.push(CONFIG_FILE);
let _ = init(side_dir.clone(), default_side_node_config());
assert!(file_path.exists());
}
}