From 885710e0c30004421fe132b1f334f170e8a08c5a Mon Sep 17 00:00:00 2001 From: Manuel Cillero Date: Thu, 10 Nov 2022 21:14:57 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20Y=20a=C3=B1ade=20pub=5Fconfig!()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pagetop/Cargo.toml | 1 + pagetop/src/app/config.rs | 80 ++++++++++++++-------------------- pagetop/src/config.rs | 91 ++++++++++++++++----------------------- pagetop/src/lib.rs | 2 +- pagetop/src/prelude.rs | 4 +- 5 files changed, 73 insertions(+), 105 deletions(-) diff --git a/pagetop/Cargo.toml b/pagetop/Cargo.toml index dca3a63b..6376768f 100644 --- a/pagetop/Cargo.toml +++ b/pagetop/Cargo.toml @@ -24,6 +24,7 @@ categories = [ [dependencies] async-trait = "0.1.58" concat-string = "1.0.1" +doc-comment = "0.3.3" figlet-rs = "0.1.4" futures = "0.3.25" nom = "7.1.1" diff --git a/pagetop/src/app/config.rs b/pagetop/src/app/config.rs index c95ff3ae..4bdac5a2 100644 --- a/pagetop/src/app/config.rs +++ b/pagetop/src/app/config.rs @@ -1,8 +1,6 @@ //! Ajustes globales de la configuración. -use crate::config; -use crate::predefined_settings; -use crate::LazyStatic; +use crate::pub_config; use serde::Deserialize; @@ -53,9 +51,9 @@ pub struct Database { pub db_pass: String, /// Valor predefinido: *"localhost"* pub db_host: String, - /// Valor predefinido: *"0"* + /// Valor predefinido: *0* pub db_port: u16, - /// Valor predefinido: *"5"* + /// Valor predefinido: *5* pub max_pool_size: u32, } @@ -92,53 +90,39 @@ pub struct Log { pub struct Server { /// Valor predefinido: *"localhost"* pub bind_address: String, - /// Valor predefinido: *"8088"* + /// Valor predefinido: *8088* pub bind_port: u16, } -/// Declara y asigna los valores predefinidos de los ajustes globales para la estructura -/// [`Settings`]. -/// -/// ``` -/// use pagetop::prelude::*; -/// -/// fn demo() { -/// println!("App name: {}", &SETTINGS.app.name); -/// println!("App description: {}", &SETTINGS.app.description); -/// println!("Value of PAGETOP_RUN_MODE: {}", &SETTINGS.app.run_mode); -/// } -/// ``` -pub static SETTINGS: LazyStatic = LazyStatic::new(|| { - config::try_into::(predefined_settings!( - // [app] - "app.name" => "PageTop Application", - "app.description" => "Developed with the amazing PageTop framework.", - "app.theme" => "Bootsier", - "app.language" => "en-US", - "app.direction" => "ltr", - "app.startup_banner" => "Slant", +pub_config!(SETTINGS: Settings, + // [app] + "app.name" => "PageTop Application", + "app.description" => "Developed with the amazing PageTop framework.", + "app.theme" => "Bootsier", + "app.language" => "en-US", + "app.direction" => "ltr", + "app.startup_banner" => "Slant", - // [database] - "database.db_type" => "", - "database.db_name" => "", - "database.db_user" => "", - "database.db_pass" => "", - "database.db_host" => "localhost", - "database.db_port" => "0", - "database.max_pool_size" => "5", + // [database] + "database.db_type" => "", + "database.db_name" => "", + "database.db_user" => "", + "database.db_pass" => "", + "database.db_host" => "localhost", + "database.db_port" => 0, + "database.max_pool_size" => 5, - // [dev] - "dev.static_files" => "", + // [dev] + "dev.static_files" => "", - // [log] - "log.tracing" => "Info", - "log.rolling" => "Stdout", - "log.path" => "log", - "log.prefix" => "tracing.log", - "log.format" => "Full", + // [log] + "log.tracing" => "Info", + "log.rolling" => "Stdout", + "log.path" => "log", + "log.prefix" => "tracing.log", + "log.format" => "Full", - // [server] - "server.bind_address" => "localhost", - "server.bind_port" => "8088" - )) -}); + // [server] + "server.bind_address" => "localhost", + "server.bind_port" => 8088, +); diff --git a/pagetop/src/config.rs b/pagetop/src/config.rs index cff20237..318e47e5 100644 --- a/pagetop/src/config.rs +++ b/pagetop/src/config.rs @@ -50,9 +50,8 @@ //! serde = { version = "1.0", features = ["derive"] } //! ``` //! -//! Y luego declara con [`LazyStatic`] tus ajustes, usando tipos seguros mediante -//! [`config::try_into()`](try_into) y asignando los valores predefinidos directamente con la -//! macro [`predefined_settings!`](crate::predefined_settings) para la estructura asociada: +//! Y luego declara con la macro [`pub_config!`](crate::pub_config) tus ajustes, usando tipos +//! seguros y asignando los valores predefinidos para la estructura asociada: //! //! ``` //! use pagetop::prelude::*; @@ -71,14 +70,12 @@ //! pub height: u16, //! } //! -//! pub static MY_SETTINGS: LazyStatic = LazyStatic::new(|| { -//! config::try_into::(predefined_settings!( -//! // [myapp] -//! "myapp.name" => "Value Name", -//! "myapp.width" => "900", -//! "myapp.height" => "320" -//! )) -//! }); +//! pub_config!(MY_SETTINGS: MySettings, +//! // [myapp] +//! "myapp.name" => "Value Name", +//! "myapp.width" => 900, +//! "myapp.height" => 320, +//! ); //! ``` //! //! De hecho, así se declaran los ajustes globales de la configuración (ver @@ -100,7 +97,15 @@ //! # Cómo usar tus nuevos ajustes de configuración //! //! ``` -//! fn demo() { +//! use pagetop::prelude::*; +//! +//! fn global_settings() { +//! println!("App name: {}", &SETTINGS.app.name); +//! println!("App description: {}", &SETTINGS.app.description); +//! println!("Value of PAGETOP_RUN_MODE: {}", &SETTINGS.app.run_mode); +//! } +//! +//! fn module_settings() { //! println!("{} - {:?}", &MY_SETTINGS.myapp.name, &MY_SETTINGS.myapp.description); //! println!("{}", &MY_SETTINGS.myapp.width); //! } @@ -119,39 +124,14 @@ use crate::LazyStatic; use crate::config::data::ConfigData; use crate::config::file::File; -use std::collections::HashMap; use std::env; -use serde::Deserialize; - -/// Un *HashMap* con una lista de literales `"clave" => "valor"` para asignar ajustes de -/// configuración predefinidos. -/// -/// Ver [`cómo añadir ajustes de configuración`](index.html#cómo-añadir-ajustes-de-configuración). -pub type PredefinedSettings = HashMap<&'static str, &'static str>; - -#[macro_export] -/// Macro para crear e inicializar un *HashMap* ([`PredefinedSettings`]) con una lista de literales -/// `"clave" => "valor"` para asignar los ajustes de configuración predefinidos. -/// -/// Ver [`cómo añadir ajustes de configuración`](config/index.html#cómo-añadir-ajustes-de-configuración). -macro_rules! predefined_settings { - ( $($key:literal => $value:literal),* ) => {{ - #[allow(unused_mut)] - let mut a = $crate::config::PredefinedSettings::new(); - $( - a.insert($key, $value); - )* - a - }}; -} - /// Directorio donde se encuentran los archivos de configuración. const CONFIG_DIR: &str = "config"; /// Todos los valores originales de la configuración en forma de pares `clave = valor` recogidos de /// los archivos de configuración. -static CONFIG_DATA: LazyStatic = LazyStatic::new(|| { +pub static CONFIG: LazyStatic = LazyStatic::new(|| { // Modo de ejecución según la variable de entorno PAGETOP_RUN_MODE. Por defecto 'default'. let run_mode = env::var("PAGETOP_RUN_MODE").unwrap_or_else(|_| "default".into()); @@ -176,22 +156,27 @@ static CONFIG_DATA: LazyStatic = LazyStatic::new(|| { settings }); -/// Asigna los ajustes de configuración de tu módulo usando tipos seguros y valores predefinidos -/// para la estructura asociada S. +#[macro_export] +/// Asigna los ajustes de configuración de tu módulo usando tipos seguros y valores predefinidos. /// /// Detiene la aplicación con un panic! si no pueden asignarse los ajustes de configuración. /// -/// Ver [`Cómo añadir ajustes de configuración`](index.html#cómo-añadir-ajustes-de-configuración). -pub fn try_into(values: PredefinedSettings) -> S -where - S: Deserialize<'static>, -{ - let mut settings = CONFIG_DATA.clone(); - for (key, value) in values.iter() { - settings.set_default(key, *value).unwrap(); - } - match settings.try_into() { - Ok(s) => s, - Err(e) => panic!("Error parsing settings: {}", e), - } +/// Ver [`Cómo añadir ajustes de configuración`](config/index.html#cómo-añadir-ajustes-de-configuración). +macro_rules! pub_config { + ( $S:ident: $t:ty $(, $k:literal => $v:literal)*$(,)* ) => { crate::doc_comment! { + concat!( + "Declara y asigna los valores predefinidos para los ajustes de configuración ", + "asociados a la estructura [`", stringify!($t), "`]." + ), + pub static $S: $crate::LazyStatic<$t> = $crate::LazyStatic::new(|| { + let mut settings = $crate::config::CONFIG.clone(); + $( + settings.set_default($k, $v).unwrap(); + )* + match settings.try_into() { + Ok(s) => s, + Err(e) => panic!("Error parsing settings: {}", e), + } + }); + }}; } diff --git a/pagetop/src/lib.rs b/pagetop/src/lib.rs index a61ee3ad..ff543aed 100644 --- a/pagetop/src/lib.rs +++ b/pagetop/src/lib.rs @@ -40,11 +40,11 @@ // GLOBAL. pub use concat_string::concat_string; +pub use doc_comment::doc_comment; pub use once_cell::sync::Lazy as LazyStatic; // LOCAL. -#[allow(unused_imports)] pub(crate) use futures::executor::block_on as run_now; // APIs PÚBLICAS. diff --git a/pagetop/src/prelude.rs b/pagetop/src/prelude.rs index ab2d1df4..de5b762f 100644 --- a/pagetop/src/prelude.rs +++ b/pagetop/src/prelude.rs @@ -2,9 +2,7 @@ pub use crate::{concat_string, LazyStatic}; // Macros. -pub use crate::{ - args, configure_service_for_static_files, predefined_settings, pub_handle, pub_locale, -}; +pub use crate::{args, configure_service_for_static_files, pub_config, pub_handle, pub_locale}; // Helpers. pub use crate::util;