Skip to content

Commit

Permalink
Enable migration; ron->yaml
Browse files Browse the repository at this point in the history
Switch from ron serde_yaml because of ron-rs/ron#140
  • Loading branch information
srid committed Apr 13, 2021
1 parent fe1cb29 commit 70235ab
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 27 deletions.
48 changes: 35 additions & 13 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ version = "0.1.0"
clap = "2.33.3"
directories = "3.0.1"
exitfailure = "0.5.1"
ron = "0.6.4"
serde = "1.0.125"
serde = {version = "1.0", features = ["derive"]}
serde_yaml = ""

[dependencies.rustbreak]
features = ["ron_enc"]
features = ["yaml_enc"]
version = "2"
57 changes: 46 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,73 @@
use directories::ProjectDirs;
use exitfailure::ExitFailure;
use rustbreak::{deser::Ron, PathDatabase};
use rustbreak::{deser::Yaml, PathDatabase};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::io::{Error, ErrorKind};

#[derive(Serialize, Deserialize, Clone, Debug)]
enum Version {
V1,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
struct Doc {
// If data type changes, up the version and write migration.
version: Version,
data: serde_yaml::Value,
}

impl Default for Doc {
fn default() -> Self {
let data: V1Data = HashMap::new();
Doc {
version: Version::V1,
data: serde_yaml::to_value(data).expect("yaml opps"),
}
}
}

type V1Data = HashMap<u32, Entity>;

#[derive(Serialize, Deserialize, Clone, Debug)]
struct Entity {
id: String,
}

fn edit_data<F>(db: &mut Doc, f: F)
where
F: Fn(&mut V1Data) -> (),
{
let val: &mut V1Data = &mut serde_yaml::from_value(db.data.clone()).expect("err");
f(val);
db.data = serde_yaml::to_value(val).expect("err");
}

fn main() -> Result<(), ExitFailure> {
let proj_dirs =
ProjectDirs::from("ca", "srid", "X").ok_or(Error::new(ErrorKind::Other, "No Home"))?;
let ron_file = proj_dirs.data_dir().with_extension("ron");
let db_file = proj_dirs.data_dir().with_extension("yaml");

let db = PathDatabase::<HashMap<u32, Entity>, Ron>::load_from_path(ron_file)?;
let db = PathDatabase::<Doc, Yaml>::load_from_path_or_default(db_file)?;

db.read(|db| {
println!("Init: {:?}", db.get(&0));
println!("Init: {:?}", db.data);
})?;

db.write(|db| {
db.insert(
0,
Entity {
id: "test".to_string(),
},
);
edit_data(db, |val: &mut V1Data| {
val.insert(
0,
Entity {
id: "test".to_string(),
},
);
});
})?;
db.save()?;

db.read(|db| {
println!("Just wrote: {:?}", db.get(&0));
println!("Writ: {:?}", db.data);
})?;

Ok(())
Expand Down

0 comments on commit 70235ab

Please sign in to comment.