diff --git a/beacon_node/Cargo.toml b/beacon_node/Cargo.toml index f1f47bef3..3107068d9 100644 --- a/beacon_node/Cargo.toml +++ b/beacon_node/Cargo.toml @@ -5,7 +5,9 @@ authors = ["Paul Hauner ", "Age Manning c, + Err(e) => { + crit!(logger, "Failed to load/generate a ChainConfig"; "error" => format!("{:?}", e)); + return; + } + }; match config.apply_cli_args(&matches) { Ok(()) => (), @@ -109,3 +123,42 @@ fn main() { Err(e) => crit!(logger, "Beacon node failed to start"; "reason" => format!("{:}", e)), } } + +/// Loads a `ClientConfig` from file. If unable to load from file, generates a default +/// configuration and saves that as a sample file. +fn load_config(data_dir: Option<&str>) -> Result { + let data_dir = data_dir.unwrap_or_else(|| DEFAULT_DATA_DIR); + + let path = dirs::home_dir() + .ok_or_else(|| "Unable to locate home directory")? + .join(&data_dir); + fs::create_dir_all(&path).map_err(|_| "Unable to open data_dir")?; + + if let Ok(mut file) = File::open(path.join(CONFIG_FILENAME)) { + let mut contents = String::new(); + file.read_to_string(&mut contents).map_err(|e| { + format!( + "Unable to read existing {}. Error: {:?}", + CONFIG_FILENAME, e + ) + })?; + + toml::from_str(&contents).map_err(|_| format!("Unable to parse {}", CONFIG_FILENAME)) + } else { + let mut config = ClientConfig::default(); + config.data_dir = data_dir.to_string(); + + if let Ok(mut file) = File::create(path.join(SAMPLE_CONFIG_FILENAME)) { + let toml_encoded = toml::to_string(&config).map_err(|e| { + format!( + "Failed to write configuration to {}. Error: {:?}", + SAMPLE_CONFIG_FILENAME, e + ) + })?; + file.write_all(toml_encoded.as_bytes()) + .expect(&format!("Unable to write to {}", SAMPLE_CONFIG_FILENAME)); + } + + Ok(config) + } +}