hyper_scripter/util/
init_repo.rs

1use super::main_util;
2use crate::args::RootArgs;
3use crate::config::Config;
4use crate::error::{Contextable, Error, Result};
5use crate::path;
6use crate::script_repo::{DBEnv, RecentFilter, ScriptRepo};
7use futures::try_join;
8use fxhash::FxHashSet as HashSet;
9use hyper_scripter_historian::Historian;
10
11/// 即使 `need_journal=false` 也可能使用 journal,具體條件同 `crate::db::get_pool`
12pub async fn init_env(mut need_journal: bool) -> Result<(DBEnv, bool)> {
13    async fn init_historian() -> Result<Historian> {
14        let h = Historian::new(path::get_home().to_owned()).await?;
15        Ok(h)
16    }
17    let ((pool, init), historian) =
18        try_join!(crate::db::get_pool(&mut need_journal), init_historian())?;
19    Ok((DBEnv::new(pool, historian, need_journal), init))
20}
21
22/// 即使 `need_journal=false` 也可能使用 journal,具體條件同 `crate::db::get_pool`
23pub async fn init_repo(args: RootArgs, need_journal: bool) -> Result<ScriptRepo> {
24    let RootArgs {
25        no_trace,
26        humble,
27        archaeology,
28        select,
29        toggle,
30        recent,
31        timeless,
32        ..
33    } = args;
34
35    let conf = Config::get();
36
37    let recent = if timeless {
38        None
39    } else {
40        Some(RecentFilter {
41            recent: recent.or(conf.recent),
42            archaeology,
43        })
44    };
45
46    // TODO: 測試 toggle 功能,以及名字不存在的錯誤
47    let tag_group = {
48        let mut toggle: HashSet<_> = toggle.into_iter().collect();
49        let mut tag_group = conf.get_tag_selector_group(&mut toggle);
50        if let Some(name) = toggle.into_iter().next() {
51            return Err(Error::TagSelectorNotFound(name));
52        }
53        for select in select.into_iter() {
54            tag_group.push(select);
55        }
56        tag_group
57    };
58
59    let (env, init) = init_env(need_journal).await?;
60    let mut repo = ScriptRepo::new(recent, env, &tag_group)
61        .await
62        .context("載入腳本倉庫失敗")?;
63    if no_trace {
64        repo.no_trace();
65    } else if humble {
66        repo.humble();
67    }
68
69    if init {
70        log::info!("初次使用,載入好用工具和預執行腳本");
71        main_util::load_utils(&mut repo).await?;
72        main_util::prepare_pre_run(None)?;
73        main_util::load_templates()?;
74    }
75
76    Ok(repo)
77}