use std::{env, process};
use abscissa_core::{
application::{self, fatal_error, AppCell},
config::{self, CfgCell},
terminal::component::Terminal,
Application, Component, FrameworkError, FrameworkErrorKind, Shutdown, StandardPaths,
};
use anyhow::Result;
use crate::{commands::EntryPoint, config::RusticConfig};
pub static RUSTIC_APP: AppCell<RusticApp> = AppCell::new();
pub mod constants {
pub const RUSTIC_DOCS_URL: &str = "https://rustic.cli.rs/docs";
pub const RUSTIC_DEV_DOCS_URL: &str = "https://rustic.cli.rs/dev-docs";
pub const RUSTIC_CONFIG_DOCS_URL: &str =
"https://github.com/rustic-rs/rustic/blob/main/config/README.md";
}
#[derive(Debug)]
pub struct RusticApp {
config: CfgCell<RusticConfig>,
state: application::State<Self>,
}
impl Default for RusticApp {
fn default() -> Self {
Self {
config: CfgCell::default(),
state: application::State::default(),
}
}
}
impl Application for RusticApp {
type Cmd = EntryPoint;
type Cfg = RusticConfig;
type Paths = StandardPaths;
fn config(&self) -> config::Reader<RusticConfig> {
self.config.read()
}
fn state(&self) -> &application::State<Self> {
&self.state
}
fn framework_components(
&mut self,
command: &Self::Cmd,
) -> Result<Vec<Box<dyn Component<Self>>>, FrameworkError> {
let terminal = Terminal::new(self.term_colors(command));
Ok(vec![Box::new(terminal)])
}
fn register_components(&mut self, command: &Self::Cmd) -> Result<(), FrameworkError> {
let framework_components = self.framework_components(command)?;
let mut app_components = self.state.components_mut();
app_components.register(framework_components)
}
fn after_config(&mut self, config: Self::Cfg) -> Result<(), FrameworkError> {
self.state.components_mut().after_config(&config)?;
for (env, value) in config.global.env.iter() {
env::set_var(env, value);
}
let global_hooks = config.global.hooks.clone();
self.config.set_once(config);
global_hooks.run_before().map_err(|err| -> FrameworkError {
FrameworkErrorKind::ProcessError.context(err).into()
})?;
Ok(())
}
fn shutdown(&self, shutdown: Shutdown) -> ! {
let exit_code = match shutdown {
Shutdown::Crash => 1,
_ => 0,
};
self.shutdown_with_exitcode(shutdown, exit_code)
}
}
impl RusticApp {
fn shutdown_with_exitcode(&self, shutdown: Shutdown, exit_code: i32) -> ! {
let hooks = &RUSTIC_APP.config().global.hooks;
match shutdown {
Shutdown::Crash => _ = hooks.run_failed(),
_ => _ = hooks.run_after(),
};
_ = hooks.run_finally();
let result = self.state().components().shutdown(self, shutdown);
if let Err(e) = result {
fatal_error(self, &e)
}
process::exit(exit_code);
}
}