hyper_scripter/util/
holder.rs

1use crate::args::RootArgs;
2use crate::error::Result;
3use crate::script_repo::{DBEnv, ScriptRepo};
4use crate::{path, util};
5use hyper_scripter_historian::Historian;
6
7pub enum Resource {
8    None,
9    Repo(ScriptRepo),
10    Historian(Historian),
11    Env(DBEnv),
12}
13impl Resource {
14    pub async fn close(self) {
15        match self {
16            Self::None => (),
17            Self::Repo(repo) => repo.close().await,
18            Self::Historian(historian) => historian.close().await,
19            Self::Env(env) => env.close().await,
20        }
21    }
22}
23
24pub struct RepoHolder<'a> {
25    pub root_args: RootArgs,
26    pub need_journal: bool,
27    pub resource: &'a mut Resource,
28}
29
30impl<'a> RepoHolder<'a> {
31    pub async fn init(self) -> Result<&'a mut ScriptRepo> {
32        let repo = util::init_repo(self.root_args, self.need_journal).await?;
33        *self.resource = Resource::Repo(repo);
34        match self.resource {
35            Resource::Repo(repo) => Ok(repo),
36            _ => unreachable!(),
37        }
38    }
39    pub async fn historian(self) -> Result<&'a mut Historian> {
40        let historian = Historian::new(path::get_home().to_owned()).await?;
41        *self.resource = Resource::Historian(historian);
42        match self.resource {
43            Resource::Historian(historian) => Ok(historian),
44            _ => unreachable!(),
45        }
46    }
47    pub async fn env(self) -> Result<&'a mut DBEnv> {
48        let (env, init) = util::init_env(self.need_journal).await?;
49        if init {
50            log::error!("還沒初始化就想做進階操作 ==");
51            std::process::exit(0);
52        }
53        *self.resource = Resource::Env(env);
54        match self.resource {
55            Resource::Env(env) => Ok(env),
56            _ => unreachable!(),
57        }
58    }
59}