♻️ [global] Para acceder a elementos globales

This commit is contained in:
Manuel Cillero 2022-11-10 21:43:38 +01:00
parent 885710e0c3
commit aa9f392ba9
17 changed files with 64 additions and 71 deletions

View file

@ -58,7 +58,7 @@ fn form_login() -> Form {
t( t(
"username_help", "username_help",
&args![ &args![
"app" => SETTINGS.app.name.to_owned() "app" => global::SETTINGS.app.name.to_owned()
], ],
) )
.as_str(), .as_str(),

View file

@ -4,9 +4,6 @@ pub use actix_web::{
pub use actix_web_files::Files as ActixFiles; pub use actix_web_files::Files as ActixFiles;
pub use actix_web_static_files::ResourceFiles; pub use actix_web_static_files::ResourceFiles;
pub mod config;
pub use config::SETTINGS;
mod banner; mod banner;
mod tracing; mod tracing;

View file

@ -1,10 +1,10 @@
use super::fatal_error::FatalError; use super::fatal_error::FatalError;
use super::SETTINGS;
use crate::core::module::ModuleStaticRef; use crate::core::module::ModuleStaticRef;
use crate::core::{module, theme}; use crate::core::{module, theme};
use crate::html::Markup; use crate::html::Markup;
use crate::response::page::ResultPage; use crate::response::page::ResultPage;
use crate::LazyStatic; use crate::{global, LazyStatic};
use actix_web::dev::Server; use actix_web::dev::Server;
@ -19,9 +19,6 @@ impl Application {
// Rótulo de presentación. // Rótulo de presentación.
super::banner::print_on_startup(); super::banner::print_on_startup();
// Inicializa la configuración global.
LazyStatic::force(&super::config::SETTINGS);
// Inicia registro de trazas y eventos. // Inicia registro de trazas y eventos.
LazyStatic::force(&super::tracing::TRACING); LazyStatic::force(&super::tracing::TRACING);
@ -58,7 +55,7 @@ impl Application {
}) })
.bind(format!( .bind(format!(
"{}:{}", "{}:{}",
&SETTINGS.server.bind_address, &SETTINGS.server.bind_port &global::SETTINGS.server.bind_address, &global::SETTINGS.server.bind_port
))? ))?
.run(); .run();

View file

@ -1,23 +1,23 @@
mod figfont; mod figfont;
use figfont::FIGFONT; use figfont::FIGFONT;
use super::SETTINGS; use crate::global;
use substring::Substring; use substring::Substring;
pub fn print_on_startup() { pub fn print_on_startup() {
if SETTINGS.app.startup_banner.to_lowercase() != "off" { if global::SETTINGS.app.startup_banner.to_lowercase() != "off" {
if let Some((term_width, _)) = term_size::dimensions() { if let Some((term_width, _)) = term_size::dimensions() {
if term_width >= 80 { if term_width >= 80 {
let maxlen = (term_width / 10) - 2; let maxlen = (term_width / 10) - 2;
let mut app = SETTINGS.app.name.substring(0, maxlen).to_owned(); let mut app = global::SETTINGS.app.name.substring(0, maxlen).to_owned();
if SETTINGS.app.name.len() > maxlen { if global::SETTINGS.app.name.len() > maxlen {
app = format!("{}...", app); app = format!("{}...", app);
} }
println!( println!(
"\n{} {}\n\n Powered by PageTop {}\n", "\n{} {}\n\n Powered by PageTop {}\n",
FIGFONT.convert(&app).unwrap(), FIGFONT.convert(&app).unwrap(),
&SETTINGS.app.description, &global::SETTINGS.app.description,
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
); );
return; return;
@ -25,8 +25,8 @@ pub fn print_on_startup() {
} }
println!( println!(
"\n{}\n{}\n\nPowered by PageTop {}\n", "\n{}\n{}\n\nPowered by PageTop {}\n",
&SETTINGS.app.name, &global::SETTINGS.app.name,
&SETTINGS.app.description, &global::SETTINGS.app.description,
env!("CARGO_PKG_VERSION") env!("CARGO_PKG_VERSION")
); );
} }

View file

@ -1,5 +1,4 @@
use crate::app::SETTINGS; use crate::{global, LazyStatic};
use crate::LazyStatic;
use figlet_rs::FIGfont; use figlet_rs::FIGfont;
@ -9,7 +8,7 @@ pub static FIGFONT: LazyStatic<FIGfont> = LazyStatic::new(|| {
let speed = include_str!("speed.flf"); let speed = include_str!("speed.flf");
let starwars = include_str!("starwars.flf"); let starwars = include_str!("starwars.flf");
FIGfont::from_content(match SETTINGS.app.startup_banner.to_lowercase().as_str() { FIGfont::from_content(match global::SETTINGS.app.startup_banner.to_lowercase().as_str() {
"off" => slant, "off" => slant,
"slant" => slant, "slant" => slant,
"small" => small, "small" => small,
@ -18,7 +17,7 @@ pub static FIGFONT: LazyStatic<FIGfont> = LazyStatic::new(|| {
_ => { _ => {
println!( println!(
"\n FIGfont \"{}\" not found for banner. Using \"Slant\". Check settings files.", "\n FIGfont \"{}\" not found for banner. Using \"Slant\". Check settings files.",
SETTINGS.app.startup_banner, global::SETTINGS.app.startup_banner,
); );
slant slant
} }

View file

@ -1,6 +1,5 @@
use super::SETTINGS;
use crate::db::*; use crate::db::*;
use crate::{run_now, trace, LazyStatic}; use crate::{global, run_now, trace, LazyStatic};
use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseBackend, Statement}; use sea_orm::{ConnectOptions, ConnectionTrait, Database, DatabaseBackend, Statement};
use tracing_unwrap::ResultExt; use tracing_unwrap::ResultExt;
@ -8,38 +7,38 @@ use tracing_unwrap::ResultExt;
pub static DBCONN: LazyStatic<DbConn> = LazyStatic::new(|| { pub static DBCONN: LazyStatic<DbConn> = LazyStatic::new(|| {
trace::info!( trace::info!(
"Connecting to database \"{}\" using a pool of {} connections", "Connecting to database \"{}\" using a pool of {} connections",
&SETTINGS.database.db_name, &global::SETTINGS.database.db_name,
&SETTINGS.database.max_pool_size &global::SETTINGS.database.max_pool_size
); );
let db_uri = match SETTINGS.database.db_type.as_str() { let db_uri = match global::SETTINGS.database.db_type.as_str() {
"mysql" | "postgres" => { "mysql" | "postgres" => {
let mut tmp_uri = DbUri::parse( let mut tmp_uri = DbUri::parse(
format!( format!(
"{}://{}/{}", "{}://{}/{}",
&SETTINGS.database.db_type, &global::SETTINGS.database.db_type,
&SETTINGS.database.db_host, &global::SETTINGS.database.db_host,
&SETTINGS.database.db_name &global::SETTINGS.database.db_name
) )
.as_str(), .as_str(),
) )
.unwrap(); .unwrap();
tmp_uri tmp_uri
.set_username(SETTINGS.database.db_user.as_str()) .set_username(global::SETTINGS.database.db_user.as_str())
.unwrap(); .unwrap();
// https://github.com/launchbadge/sqlx/issues/1624 // https://github.com/launchbadge/sqlx/issues/1624
tmp_uri tmp_uri
.set_password(Some(SETTINGS.database.db_pass.as_str())) .set_password(Some(global::SETTINGS.database.db_pass.as_str()))
.unwrap(); .unwrap();
if SETTINGS.database.db_port != 0 { if global::SETTINGS.database.db_port != 0 {
tmp_uri.set_port(Some(SETTINGS.database.db_port)).unwrap(); tmp_uri.set_port(Some(global::SETTINGS.database.db_port)).unwrap();
} }
tmp_uri tmp_uri
} }
"sqlite" => DbUri::parse( "sqlite" => DbUri::parse(
format!( format!(
"{}://{}", "{}://{}",
&SETTINGS.database.db_type, &SETTINGS.database.db_name &global::SETTINGS.database.db_type, &global::SETTINGS.database.db_name
) )
.as_str(), .as_str(),
) )
@ -47,7 +46,7 @@ pub static DBCONN: LazyStatic<DbConn> = LazyStatic::new(|| {
_ => { _ => {
trace::error!( trace::error!(
"Unrecognized database type \"{}\"", "Unrecognized database type \"{}\"",
&SETTINGS.database.db_type &global::SETTINGS.database.db_type
); );
DbUri::parse("").unwrap() DbUri::parse("").unwrap()
} }
@ -55,7 +54,7 @@ pub static DBCONN: LazyStatic<DbConn> = LazyStatic::new(|| {
run_now(Database::connect::<ConnectOptions>({ run_now(Database::connect::<ConnectOptions>({
let mut db_opt = ConnectOptions::new(db_uri.to_string()); let mut db_opt = ConnectOptions::new(db_uri.to_string());
db_opt.max_connections(SETTINGS.database.max_pool_size); db_opt.max_connections(global::SETTINGS.database.max_pool_size);
db_opt db_opt
})) }))
.expect_or_log("Failed to connect to database") .expect_or_log("Failed to connect to database")

View file

@ -1,5 +1,4 @@
use super::SETTINGS; use crate::{global, trace, LazyStatic};
use crate::{trace, LazyStatic};
use unic_langid::LanguageIdentifier; use unic_langid::LanguageIdentifier;
@ -7,14 +6,14 @@ use unic_langid::LanguageIdentifier;
/// ([Unicode Language Identifier](https://unicode.org/reports/tr35/tr35.html#Unicode_language_identifier)) /// ([Unicode Language Identifier](https://unicode.org/reports/tr35/tr35.html#Unicode_language_identifier))
/// de la aplicación, obtenido de `SETTINGS.app.language`. /// de la aplicación, obtenido de `SETTINGS.app.language`.
pub static LANGID: LazyStatic<LanguageIdentifier> = pub static LANGID: LazyStatic<LanguageIdentifier> =
LazyStatic::new(|| match SETTINGS.app.language.parse() { LazyStatic::new(|| match global::SETTINGS.app.language.parse() {
Ok(language) => language, Ok(language) => language,
Err(_) => { Err(_) => {
trace::warn!( trace::warn!(
"{}, {} \"{}\"! {}, {}", "{}, {} \"{}\"! {}, {}",
"Failed to parse language", "Failed to parse language",
"unrecognized Unicode Language Identifier", "unrecognized Unicode Language Identifier",
SETTINGS.app.language, global::SETTINGS.app.language,
"Using \"en-US\"", "Using \"en-US\"",
"check the settings file", "check the settings file",
); );

View file

@ -1,5 +1,4 @@
use super::SETTINGS; use crate::{global, LazyStatic};
use crate::LazyStatic;
use tracing_appender::non_blocking::WorkerGuard; use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
@ -20,14 +19,14 @@ use tracing_subscriber::EnvFilter;
#[rustfmt::skip] #[rustfmt::skip]
pub static TRACING: LazyStatic<WorkerGuard> = LazyStatic::new(|| { pub static TRACING: LazyStatic<WorkerGuard> = LazyStatic::new(|| {
let env_filter = let env_filter =
EnvFilter::try_new(&SETTINGS.log.tracing).unwrap_or_else(|_| EnvFilter::new("Info")); EnvFilter::try_new(&global::SETTINGS.log.tracing).unwrap_or_else(|_| EnvFilter::new("Info"));
let rolling = SETTINGS.log.rolling.to_lowercase(); let rolling = global::SETTINGS.log.rolling.to_lowercase();
let (non_blocking, guard) = match rolling.as_str() { let (non_blocking, guard) = match rolling.as_str() {
"stdout" => tracing_appender::non_blocking(std::io::stdout()), "stdout" => tracing_appender::non_blocking(std::io::stdout()),
_ => tracing_appender::non_blocking({ _ => tracing_appender::non_blocking({
let path = &SETTINGS.log.path; let path = &global::SETTINGS.log.path;
let prefix = &SETTINGS.log.prefix; let prefix = &global::SETTINGS.log.prefix;
match rolling.as_str() { match rolling.as_str() {
"daily" => tracing_appender::rolling::daily(path, prefix), "daily" => tracing_appender::rolling::daily(path, prefix),
"hourly" => tracing_appender::rolling::hourly(path, prefix), "hourly" => tracing_appender::rolling::hourly(path, prefix),
@ -36,7 +35,7 @@ pub static TRACING: LazyStatic<WorkerGuard> = LazyStatic::new(|| {
_ => { _ => {
println!( println!(
"Rolling value \"{}\" not valid. Using \"daily\". Check the settings file.", "Rolling value \"{}\" not valid. Using \"daily\". Check the settings file.",
SETTINGS.log.rolling, global::SETTINGS.log.rolling,
); );
tracing_appender::rolling::daily(path, prefix) tracing_appender::rolling::daily(path, prefix)
} }
@ -47,7 +46,7 @@ pub static TRACING: LazyStatic<WorkerGuard> = LazyStatic::new(|| {
.with_env_filter(env_filter) .with_env_filter(env_filter)
.with_writer(non_blocking) .with_writer(non_blocking)
.with_ansi(rolling.as_str() == "stdout"); .with_ansi(rolling.as_str() == "stdout");
match SETTINGS.log.format.to_lowercase().as_str() { match global::SETTINGS.log.format.to_lowercase().as_str() {
"json" => subscriber.json().init(), "json" => subscriber.json().init(),
"full" => subscriber.init(), "full" => subscriber.init(),
"compact" => subscriber.compact().init(), "compact" => subscriber.compact().init(),
@ -55,7 +54,7 @@ pub static TRACING: LazyStatic<WorkerGuard> = LazyStatic::new(|| {
_ => { _ => {
println!( println!(
"Tracing format \"{}\" not valid. Using \"Full\". Check the settings file.", "Tracing format \"{}\" not valid. Using \"Full\". Check the settings file.",
SETTINGS.log.format, global::SETTINGS.log.format,
); );
subscriber.init(); subscriber.init();
} }

View file

@ -57,7 +57,7 @@ fn hello_world() -> Container {
(e("hello_intro", &args![ (e("hello_intro", &args![
"app" => format!( "app" => format!(
"<span class=\"app-name\">{}</span>", "<span class=\"app-name\">{}</span>",
&SETTINGS.app.name, &global::SETTINGS.app.name,
) )
])) ]))
}) })
@ -108,7 +108,10 @@ fn welcome() -> Container {
.with_component( .with_component(
Heading::h3(html! { Heading::h3(html! {
(e("welcome_subtitle", &args![ (e("welcome_subtitle", &args![
"app" => format!("<span class=\"app-name\">{}</span>", &SETTINGS.app.name) "app" => format!(
"<span class=\"app-name\">{}</span>",
&global::SETTINGS.app.name
)
])) ]))
}) })
.with_display(HeadingDisplay::Subtitle), .with_display(HeadingDisplay::Subtitle),

View file

@ -100,9 +100,9 @@
//! use pagetop::prelude::*; //! use pagetop::prelude::*;
//! //!
//! fn global_settings() { //! fn global_settings() {
//! println!("App name: {}", &SETTINGS.app.name); //! println!("App name: {}", &global::SETTINGS.app.name);
//! println!("App description: {}", &SETTINGS.app.description); //! println!("App description: {}", &global::SETTINGS.app.description);
//! println!("Value of PAGETOP_RUN_MODE: {}", &SETTINGS.app.run_mode); //! println!("Value of PAGETOP_RUN_MODE: {}", &global::SETTINGS.app.run_mode);
//! } //! }
//! //!
//! fn module_settings() { //! fn module_settings() {

View file

@ -1,7 +1,5 @@
use crate::app; use crate::{app, concat_string, global};
use crate::app::SETTINGS;
use crate::base::component::{Container, Html}; use crate::base::component::{Container, Html};
use crate::concat_string;
use crate::core::component::ComponentTrait; use crate::core::component::ComponentTrait;
use crate::html::{html, Favicon, Markup}; use crate::html::{html, Favicon, Markup};
use crate::response::page::{Page, PageContext, PageOp}; use crate::response::page::{Page, PageContext, PageOp};
@ -43,9 +41,9 @@ pub trait ThemeTrait: BaseTheme + Send + Sync {
@match page.title().get() { @match page.title().get() {
Some(t) => title { Some(t) => title {
(concat_string!(SETTINGS.app.name, " | ", t)) (concat_string!(global::SETTINGS.app.name, " | ", t))
}, },
None => title { (SETTINGS.app.name) } None => title { (global::SETTINGS.app.name) }
} }
@if let Some(d) = page.description().get() { @if let Some(d) = page.description().get() {

View file

@ -1,5 +1,3 @@
//! Ajustes globales de la configuración.
use crate::pub_config; use crate::pub_config;
use serde::Deserialize; use serde::Deserialize;

View file

@ -62,6 +62,9 @@ pub mod html;
#[cfg(feature = "database")] #[cfg(feature = "database")]
pub mod db; pub mod db;
// Acceso a declaraciones globales.
pub mod global;
// Prepara y ejecuta la aplicación. // Prepara y ejecuta la aplicación.
pub mod app; pub mod app;

View file

@ -19,11 +19,12 @@ pub use crate::html::*;
#[cfg(feature = "database")] #[cfg(feature = "database")]
pub use crate::{db, db::*, migration_item, pub_migration}; pub use crate::{db, db::*, migration_item, pub_migration};
pub use crate::global;
pub use crate::app; pub use crate::app;
pub use crate::app::application::Application; pub use crate::app::application::Application;
pub use crate::app::fatal_error::FatalError; pub use crate::app::fatal_error::FatalError;
pub use crate::app::HttpMessage; pub use crate::app::HttpMessage;
pub use crate::app::SETTINGS;
pub use crate::core::{component::*, hook::*, module::*, theme::*}; pub use crate::core::{component::*, hook::*, module::*, theme::*};

View file

@ -1,11 +1,11 @@
use super::PageOp; use super::PageOp;
use crate::app::SETTINGS;
use crate::core::theme::{all::theme_by_single_name, ThemeStaticRef}; use crate::core::theme::{all::theme_by_single_name, ThemeStaticRef};
use crate::html::{html, Assets, Favicon, IdentifierValue, JavaScript, Markup, ModeJS, StyleSheet}; use crate::html::{html, Assets, Favicon, IdentifierValue, JavaScript, Markup, ModeJS, StyleSheet};
use crate::{base, concat_string, util, LazyStatic}; use crate::{base, concat_string, global, util, LazyStatic};
static DEFAULT_THEME: LazyStatic<ThemeStaticRef> = static DEFAULT_THEME: LazyStatic<ThemeStaticRef> =
LazyStatic::new(|| match theme_by_single_name(&SETTINGS.app.theme) { LazyStatic::new(|| match theme_by_single_name(&global::SETTINGS.app.theme) {
Some(theme) => theme, Some(theme) => theme,
None => &base::theme::bootsier::Bootsier, None => &base::theme::bootsier::Bootsier,
}); });

View file

@ -1,15 +1,15 @@
use super::{BeforeRenderPageHook, PageContext, PageOp, ResultPage, HOOK_BEFORE_RENDER_PAGE}; use super::{BeforeRenderPageHook, PageContext, PageOp, ResultPage, HOOK_BEFORE_RENDER_PAGE};
use crate::app::fatal_error::FatalError; use crate::app::fatal_error::FatalError;
use crate::app::SETTINGS;
use crate::core::component::*; use crate::core::component::*;
use crate::core::hook::{action_ref, run_actions}; use crate::core::hook::{action_ref, run_actions};
use crate::html::{html, AttributeValue, Classes, ClassesOp, Markup, DOCTYPE}; use crate::html::{html, AttributeValue, Classes, ClassesOp, Markup, DOCTYPE};
use crate::{trace, LazyStatic}; use crate::{global, trace, LazyStatic};
use std::collections::HashMap; use std::collections::HashMap;
static DEFAULT_LANGUAGE: LazyStatic<Option<String>> = LazyStatic::new(|| { static DEFAULT_LANGUAGE: LazyStatic<Option<String>> = LazyStatic::new(|| {
let language = SETTINGS.app.language[..2].to_lowercase(); let language = global::SETTINGS.app.language[..2].to_lowercase();
if !language.is_empty() { if !language.is_empty() {
Some(language) Some(language)
} else { } else {
@ -18,7 +18,7 @@ static DEFAULT_LANGUAGE: LazyStatic<Option<String>> = LazyStatic::new(|| {
}); });
static DEFAULT_DIRECTION: LazyStatic<Option<String>> = LazyStatic::new(|| { static DEFAULT_DIRECTION: LazyStatic<Option<String>> = LazyStatic::new(|| {
let direction = SETTINGS.app.direction.to_lowercase(); let direction = global::SETTINGS.app.direction.to_lowercase();
match direction.as_str() { match direction.as_str() {
"auto" => Some("auto".to_owned()), "auto" => Some("auto".to_owned()),
"ltr" => Some("ltr".to_owned()), "ltr" => Some("ltr".to_owned()),
@ -27,7 +27,7 @@ static DEFAULT_DIRECTION: LazyStatic<Option<String>> = LazyStatic::new(|| {
_ => { _ => {
trace::warn!( trace::warn!(
"Text direction \"{}\" not valid, {}", "Text direction \"{}\" not valid, {}",
SETTINGS.app.direction, global::SETTINGS.app.direction,
"check the settings file" "check the settings file"
); );
None None

View file

@ -169,7 +169,7 @@ macro_rules! args {
#[macro_export] #[macro_export]
macro_rules! configure_service_for_static_files { macro_rules! configure_service_for_static_files {
( $cfg:ident, $dir:expr, $embed:ident ) => {{ ( $cfg:ident, $dir:expr, $embed:ident ) => {{
let static_files = &$crate::app::SETTINGS.dev.static_files; let static_files = &$crate::global::SETTINGS.dev.static_files;
if static_files.is_empty() { if static_files.is_empty() {
$cfg.service($crate::app::ResourceFiles::new($dir, $embed())); $cfg.service($crate::app::ResourceFiles::new($dir, $embed()));
} else { } else {