Skip to content
Snippets Groups Projects
conf.rs 1.57 KiB
Newer Older
Hugo Trentesaux's avatar
Hugo Trentesaux committed
use crate::*;
use serde::{Deserialize, Serialize};

const APP_NAME: &str = "gcli";

Hugo Trentesaux's avatar
Hugo Trentesaux committed
#[derive(Serialize, Deserialize, Debug)]
pub struct Config {
	// duniter endpoint
	pub duniter_endpoint: String,
	// indexer endpoint
	pub indexer_endpoint: String,
	// user address
	pub address: Option<AccountId>,
Hugo Trentesaux's avatar
Hugo Trentesaux committed
}

impl std::default::Default for Config {
	fn default() -> Self {
		Self {
			duniter_endpoint: String::from(data::LOCAL_DUNITER_ENDPOINT),
			indexer_endpoint: String::from(data::LOCAL_INDEXER_ENDPOINT),
			address: None,
/// load config file and manage error if could not
pub fn load_conf() -> Config {
	match confy::load(APP_NAME, None) {
		Ok(cfg) => cfg,
		Err(e) => {
			log::warn!("met error while loading config file");
			log::error!("{}", e);
			log::info!("removing the old conf file and creating a new one");
			let cfg = Config::default();
			confy::store(APP_NAME, None, &cfg).expect("unable to write default config");
			cfg
		}
	}
Hugo Trentesaux's avatar
Hugo Trentesaux committed

#[derive(Clone, Default, Debug, clap::Parser)]
pub enum Subcommand {
	#[default]
	/// Show config path
	Where,
Hugo Trentesaux's avatar
Hugo Trentesaux committed
	/// Show config
	Show,
	/// Save config as modified by command line arguments
	Save,
/// handle conf command
Hugo Trentesaux's avatar
Hugo Trentesaux committed
pub fn handle_command(data: Data, command: Subcommand) -> anyhow::Result<()> {
	// match subcommand
	match command {
		Subcommand::Where => {
			println!(
				"{}",
				confy::get_configuration_file_path(APP_NAME, None)?.display()
			);
		}
		Subcommand::Show => {
Hugo Trentesaux's avatar
Hugo Trentesaux committed
			println!("{:?}", data.cfg);
		}
		Subcommand::Save => {
			confy::store(APP_NAME, None, &data.cfg).expect("unable to write config");
		}
Hugo Trentesaux's avatar
Hugo Trentesaux committed
	};

	Ok(())
}