Create file if necessary for YAML node registry
Updates the YAML node registry to create its backing file if it doesn't
exist on startup. This is necessary because of splinterd's change to
using a node registry file in its data directory instead of a
user-created registry file.
mod error;
use std::fs::File;
+use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use super::{
@@ -36,6 +37,9 @@ pub struct FileInternal {
impl YamlNodeRegistry {
pub fn new(file_path: &str) -> Result<YamlNodeRegistry, YamlNodeRegistryError> {
+ // If file already exists, read and verify its contents; otherwise create it and initialize
+ // the nodes list.
+ if PathBuf::from(file_path).is_file() {
let file = File::open(file_path)?;
let cached_nodes: Vec<Node> = serde_yaml::from_reader(&file)?;
@@ -44,14 +48,26 @@ impl YamlNodeRegistry {
check_if_node_is_duplicate(node, &cached_nodes[idx + 1..])?;
}
- let file_internal = FileInternal {
+ Ok(YamlNodeRegistry {
+ file_internal: Arc::new(Mutex::new(FileInternal {
file_path: file_path.into(),
cached_nodes,
+ })),
+ })
+ } else {
+ File::create(file_path)?;
+
+ let registry = YamlNodeRegistry {
+ file_internal: Arc::new(Mutex::new(FileInternal {
+ file_path: file_path.into(),
+ cached_nodes: vec![],
+ })),
};
- Ok(YamlNodeRegistry {
- file_internal: Arc::new(Mutex::new(file_internal)),
- })
+ registry.write_nodes(&[])?;
+
+ Ok(registry)
+ }
}
fn get_cached_nodes(&self) -> Result<Vec<Node>, YamlNodeRegistryError> {
