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
|
use std::fs;
use std::path::{Path, PathBuf};
use serde::Deserialize;
#[derive(Deserialize)]
struct ConfigFile {
site_title: Option<String>,
data_dir: Option<PathBuf>,
external_root: Option<String>,
listen_port: Option<u16>,
footer_copyright: Option<String>,
}
pub struct Config {
pub site_title: String,
pub data_dir: PathBuf,
pub external_root: String,
pub listen_port: u16,
pub footer_copyright: Option<String>,
}
#[cfg(feature = "ssr")]
impl Config {
pub fn read_from_file() -> Result<Self, String> {
let config_path = Self::get_location()?;
let config_contents = fs::read_to_string(&config_path)
.map_err(|_| "Unable to open config file".to_string())?;
let file: ConfigFile = toml::from_str(&config_contents).map_err(|err| err.to_string())?;
let port = file.listen_port.unwrap_or(3000);
Ok(Self {
site_title: file
.site_title
.unwrap_or("Untitled StormScribe Site".to_string()),
data_dir: file.data_dir.unwrap_or(
PathBuf::from(&config_path)
.canonicalize()
.map_err(|_| "Cannot resolve config file location".to_string())?
.parent()
.ok_or("Cannot resolve data dir".to_string())?
.to_path_buf(),
),
external_root: file
.external_root
.unwrap_or(format!("http://localhost:{port}/")),
listen_port: port,
footer_copyright: file.footer_copyright,
})
}
fn get_location() -> Result<String, String> {
Ok(
std::env::var("STORMSCRIBE_CONFIG_FILE").or_else(|_| -> Result<String, String> {
Ok(std::path::Path::join(
&std::env::current_dir()
.map_err(|_| "Could not read current directory".to_string())?,
"config.toml",
)
.to_string_lossy()
.to_string())
})?,
)
}
}
|