-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstasis.rs
93 lines (80 loc) · 2.5 KB
/
stasis.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use std::{
collections::HashMap,
fs::File,
io::{ErrorKind, Read, Seek, Write},
path::PathBuf,
};
use anyhow::{bail, Context, Result};
use azalea::{
app::{App, Plugin},
prelude::*,
BlockPos,
};
use derive_new::new as New;
use serde::{Deserialize, Serialize};
use serde_with::DisplayFromStr;
use uuid::Uuid;
#[serde_as]
#[derive(Clone, Default, Deserialize, Serialize, New)]
#[serde(default)]
pub struct StasisChamber {
#[serde_as(as = "DisplayFromStr")]
pub block_pos: BlockPos,
pub entity_id: u32,
pub owner_uuid: Uuid,
pub location: String,
}
#[serde_as]
#[derive(Clone, Default, Deserialize, Serialize, Resource)]
pub struct StasisChambers(#[serde_as(as = "Vec<(_, _)>")] pub HashMap<Uuid, StasisChamber>);
impl StasisChambers {
/// # Errors
/// Will return `Err` if `std::env::current_exe` or `std::env::current_dir` fails.
pub fn path() -> Result<PathBuf> {
let path = if cfg!(debug_assertions) {
let path = std::env::current_exe()?;
path.parent().context("None")?.to_path_buf()
} else {
std::env::current_dir()?
};
Ok(path.join("stasis-chambers.yaml"))
}
/// # Errors
/// Will return `Err` if `File::open`, `toml::to_string_pretty`, or `File::write_all` fails.
pub fn load() -> Result<Self> {
let path = Self::path()?;
let mut file = match File::open(&path) {
Ok(file) => file,
Err(error) if error.kind() == ErrorKind::NotFound => {
Self::default().save()?;
File::open(&path)?
}
Err(error) => bail!(error),
};
let mut text = String::new();
file.read_to_string(&mut text)?;
file.rewind()?;
Ok(serde_yml::from_str(&text)?)
}
/// # Errors
/// Will return `Err` if `File::open`, `File::read_to_string`, `File::rewind`, or `toml::from_str` fails.
pub fn save(&self) -> Result<()> {
let path = Self::path()?;
let mut file = File::options()
.write(true)
.create(true)
.truncate(true)
.open(&path)?;
let text = serde_yml::to_string(&self)?;
let buf = text.as_bytes();
file.write_all(buf)?;
Ok(())
}
}
/// Handle global stasis chambers.
pub struct StasisChambersPlugin;
impl Plugin for StasisChambersPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(StasisChambers::load().expect("Failed to load stasis chambers"));
}
}