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
94
|
/*
Hurry Curry! - a game about cooking
Copyright (C) 2025 Hurry Curry! Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, version 3 of the License only.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use anyhow::{Context, Result, anyhow, bail};
use hurrycurry_protocol::{Gamedata, MapMetadata};
use serde::Deserialize;
use std::{
collections::{HashMap, HashSet},
fs::{File, read_to_string},
path::PathBuf,
str::FromStr,
sync::Mutex,
};
use crate::{MapDecl, Serverdata, book::book, build_data};
#[derive(Debug, Deserialize, Default)]
pub struct DataIndex {
pub maps: HashMap<String, MapMetadata>,
pub recipes: HashSet<String>,
}
pub static DATA_DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
fn data_dir() -> PathBuf {
DATA_DIR
.lock()
.unwrap()
.to_owned()
.unwrap_or_else(|| PathBuf::from_str("data").unwrap())
}
impl DataIndex {
pub fn load() -> Result<Self> {
let mut s = Self::default();
s.reload()?;
Ok(s)
}
pub fn reload(&mut self) -> Result<()> {
*self = serde_yml::from_reader(File::open(data_dir().join("index.yaml"))?)?;
Ok(())
}
pub fn read_map(&self, name: &str) -> Result<String> {
// Scary!
if name.contains("..") || name.starts_with("/") || name.contains("//") {
bail!("illegal map path");
}
let path = data_dir().join(format!("maps/{name}.yaml"));
Ok(read_to_string(path)?)
}
pub fn read_recipes(&self, name: &str) -> Result<String> {
if !self.recipes.contains(name) {
bail!("unknown recipes: {name:?}");
}
let path = data_dir().join(format!("recipes/{name}.yaml"));
Ok(read_to_string(path)?)
}
pub fn generate(&self, map: &str) -> Result<(Gamedata, Serverdata)> {
let map_in: MapDecl = serde_yml::from_str(
&self
.read_map(map)
.context(anyhow!("Failed to read map file ({map})"))?,
)
.context(anyhow!("Failed to parse map file ({map})"))?;
let recipes_in = serde_yml::from_str(
&self
.read_recipes(map_in.recipes.as_deref().unwrap_or("default"))
.context("Failed read recipe file")?,
)
.context("Failed to parse recipe file")?;
build_data(&self.maps, map.to_string(), map_in, recipes_in)
}
pub fn generate_with_book(&self, map: &str) -> Result<(Gamedata, Serverdata)> {
let (gd, mut sd) = self.generate(map)?;
sd.book = book(&gd, &sd).context("within book")?;
Ok((gd, sd))
}
}
|