summaryrefslogblamecommitdiff
path: root/server/src/config/load.rs
blob: 7566ad952233c8b7257806a514dd587bdcacaef3 (plain) (tree)














































                                                                                                                                   
// Copyright 2022-2024 Gabriel Bjørnager Jensen.

use crate::{Config, Error, Result};

use configparser::ini::Ini;
use std::env::args;
use std::path::PathBuf;

impl Config {
	pub fn load() -> Result<Self> {
		let path = {
			let mut args = args().skip(0x1);

			let Some(path) = args.next() else { return Err(Error::MissingConfig) };

			if let Some(arg) = args.next() { return Err(Error::IllegalArgument { arg }) };

			PathBuf::from(path)
		};

		let mut config = Ini::new();
		config
			.load(path)
			.map_err(|e| Error::ConfigError { message: e })?;

		macro_rules! get_field {
			($section:ident.$key:ident) => {{
				const FIELD: &str = concat!(stringify!($section), ".", stringify!($key));

				if let Some(value) = config.get(stringify!($section), stringify!($key)) {
					value
						.parse()
						.map_err(|e| Error::IllegalFieldValue { field: FIELD, value, source: Box::new(e) })
				} else {
					Err(Error::MissingField { field: FIELD })
				}
			}};
		}

		Ok(Self {
			name: get_field!(server.name)?,
			port: get_field!(server.port)?,

			max_player_count: get_field!(server.max_player_count)?,
		})
	}
}