1 use crate::{location_info, settings::structs::Settings, LemmyError};
2 use anyhow::{anyhow, Context};
3 use deser_hjson::from_str;
4 use std::{env, fs, io::Error, sync::RwLock};
8 static CONFIG_FILE: &str = "config/config.hjson";
11 static ref SETTINGS: RwLock<Settings> =
12 RwLock::new(Settings::init().expect("Failed to load settings file"));
16 /// Reads config from configuration file.
18 /// Note: The env var `LEMMY_DATABASE_URL` is parsed in
19 /// `lemmy_db_queries/src/lib.rs::get_database_url_from_env()`
20 fn init() -> Result<Self, LemmyError> {
21 // Read the config file
22 let config = from_str::<Settings>(&Self::read_config_file()?)?;
24 if config.hostname == "unset" {
25 return Err(anyhow!("Hostname variable is not set!").into());
31 /// Returns the config as a struct.
32 pub fn get() -> Self {
33 SETTINGS.read().expect("read config").to_owned()
36 pub fn get_database_url(&self) -> String {
37 let conf = &self.database;
39 "postgres://{}:{}@{}:{}/{}",
40 conf.user, conf.password, conf.host, conf.port, conf.database,
44 pub fn get_config_location() -> String {
45 env::var("LEMMY_CONFIG_LOCATION").unwrap_or_else(|_| CONFIG_FILE.to_string())
48 pub fn read_config_file() -> Result<String, Error> {
49 fs::read_to_string(Self::get_config_location())
52 /// Returns either "http" or "https", depending on tls_enabled setting
53 pub fn get_protocol_string(&self) -> &'static str {
61 /// Returns something like `http://localhost` or `https://lemmy.ml`,
62 /// with the correct protocol and hostname.
63 pub fn get_protocol_and_hostname(&self) -> String {
64 format!("{}://{}", self.get_protocol_string(), self.hostname)
67 /// When running the federation test setup in `api_tests/` or `docker/federation`, the `hostname`
68 /// variable will be like `lemmy-alpha:8541`. This method removes the port and returns
69 /// `lemmy-alpha` instead. It has no effect in production.
70 pub fn get_hostname_without_port(&self) -> Result<String, anyhow::Error> {
75 .collect::<Vec<&str>>()
77 .context(location_info!())?
82 pub fn save_config_file(data: &str) -> Result<String, LemmyError> {
83 fs::write(CONFIG_FILE, data)?;
85 // Reload the new settings
86 // From https://stackoverflow.com/questions/29654927/how-do-i-assign-a-string-to-a-mutable-static-variable/47181804#47181804
87 let mut new_settings = SETTINGS.write().expect("write config");
88 *new_settings = match Settings::init() {
90 Err(e) => panic!("{}", e),
93 Ok(Self::read_config_file()?)