rustic_rs/
application.rs

1//! Rustic Abscissa Application
2use std::{env, process};
3
4use abscissa_core::{
5    Application, Component, FrameworkError, FrameworkErrorKind, Shutdown, StandardPaths,
6    application::{self, AppCell, fatal_error},
7    config::{self, CfgCell},
8    terminal::component::Terminal,
9};
10
11use anyhow::Result;
12
13// use crate::helpers::*;
14use crate::{commands::EntryPoint, config::RusticConfig};
15
16/// Application state
17pub static RUSTIC_APP: AppCell<RusticApp> = AppCell::new();
18
19// Constants
20pub mod constants {
21    pub const RUSTIC_DOCS_URL: &str = "https://rustic.cli.rs/docs";
22    pub const RUSTIC_DEV_DOCS_URL: &str = "https://rustic.cli.rs/dev-docs";
23    pub const RUSTIC_CONFIG_DOCS_URL: &str =
24        "https://github.com/rustic-rs/rustic/blob/main/config/README.md";
25}
26
27/// Rustic Application
28#[derive(Debug)]
29pub struct RusticApp {
30    /// Application configuration.
31    config: CfgCell<RusticConfig>,
32
33    /// Application state.
34    state: application::State<Self>,
35}
36
37/// Initialize a new application instance.
38///
39/// By default no configuration is loaded, and the framework state is
40/// initialized to a default, empty state (no components, threads, etc).
41impl Default for RusticApp {
42    fn default() -> Self {
43        Self {
44            config: CfgCell::default(),
45            state: application::State::default(),
46        }
47    }
48}
49
50impl Application for RusticApp {
51    /// Entrypoint command for this application.
52    type Cmd = EntryPoint;
53
54    /// Application configuration.
55    type Cfg = RusticConfig;
56
57    /// Paths to resources within the application.
58    type Paths = StandardPaths;
59
60    /// Accessor for application configuration.
61    fn config(&self) -> config::Reader<RusticConfig> {
62        self.config.read()
63    }
64
65    /// Borrow the application state immutably.
66    fn state(&self) -> &application::State<Self> {
67        &self.state
68    }
69
70    /// Returns the framework components used by this application.
71    fn framework_components(
72        &mut self,
73        command: &Self::Cmd,
74    ) -> Result<Vec<Box<dyn Component<Self>>>, FrameworkError> {
75        // we only use the terminal component
76        let terminal = Terminal::new(self.term_colors(command));
77
78        Ok(vec![Box::new(terminal)])
79    }
80
81    /// Register all components used by this application.
82    ///
83    /// If you would like to add additional components to your application
84    /// beyond the default ones provided by the framework, this is the place
85    /// to do so.
86    fn register_components(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
87        let framework_components = self.framework_components(command)?;
88        let mut app_components = self.state.components_mut();
89        app_components.register(framework_components)
90    }
91
92    /// Post-configuration lifecycle callback.
93    ///
94    /// Called regardless of whether config is loaded to indicate this is the
95    /// time in app lifecycle when configuration would be loaded if
96    /// possible.
97    fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {
98        // Configure components
99        self.state.components_mut().after_config(&config)?;
100
101        // set all given environment variables
102        for (env, value) in &config.global.env {
103            unsafe {
104                env::set_var(env, value);
105            }
106        }
107
108        let global_hooks = config.global.hooks.clone();
109        self.config.set_once(config);
110
111        global_hooks.run_before().map_err(|err| -> FrameworkError {
112            FrameworkErrorKind::ProcessError.context(err).into()
113        })?;
114
115        Ok(())
116    }
117
118    /// Shut down this application gracefully
119    fn shutdown(&self, shutdown: Shutdown) -> ! {
120        let exit_code = match shutdown {
121            Shutdown::Crash => 1,
122            _ => 0,
123        };
124        self.shutdown_with_exitcode(shutdown, exit_code)
125    }
126
127    /// Shut down this application gracefully, exiting with given exit code.
128    fn shutdown_with_exitcode(&self, shutdown: Shutdown, exit_code: i32) -> ! {
129        let hooks = &RUSTIC_APP.config().global.hooks;
130        match shutdown {
131            Shutdown::Crash => _ = hooks.run_failed(),
132            _ => _ = hooks.run_after(),
133        };
134        _ = hooks.run_finally();
135        let result = self.state().components().shutdown(self, shutdown);
136        if let Err(e) = result {
137            fatal_error(self, &e)
138        }
139
140        process::exit(exit_code);
141    }
142}