Skip to main content

cup_cli/
utils.rs

1use std::{collections::HashMap, env::home_dir, fmt::Debug, path::PathBuf};
2
3pub fn template_f<'a, T: Into<HashMap<&'a str, String>>>(template: &str, replace: T) -> String {
4    let mut result = template.to_string();
5    let replace_map: HashMap<&str, String> = replace.into();
6    for (key, value) in replace_map {
7        result = result.replace(key, &value);
8    }
9    result
10}
11
12#[macro_export]
13macro_rules! write_template {
14    ($f:expr, $p:expr) => {
15        $f.write_fmt(format_args!("{}", include_str!($p)))
16    };
17    ($f:expr, $p: expr => [$($k: ident = $e: expr);+ $(;)?]) => {
18        $f.write_fmt(format_args!("{}", $crate::utils::template_f(include_str!($p), [$((constcat::concat!("{{", stringify!($k), "}}"), $e),)*])))
19    }
20}
21
22pub struct CupData {}
23
24impl CupData {
25    pub fn base() -> PathBuf {
26        home_dir().unwrap().join(".cup")
27    }
28
29    pub fn packages() -> PathBuf {
30        CupData::base().join("packages")
31    }
32
33    pub fn git(owner: &str, repo: &str, tag: &str) -> PathBuf {
34        CupData::base()
35            .join("gits")
36            .join(format!("{}-{}-{}", owner, repo, tag))
37    }
38}
39
40/// 此 trait 用于处理返回 Result 类型的迭代器,只有当所有元素都成功时才返回 Ok,否则返回 Err。
41pub trait TryAll<T, U, E: Debug> {
42    fn try_all(self, f: impl Fn(T) -> Result<U, E>) -> Result<impl Iterator<Item = U>, E>;
43}
44
45impl<T, U, E: Debug, I: Iterator<Item = T>> TryAll<T, U, E> for I {
46    fn try_all(self, f: impl Fn(T) -> Result<U, E>) -> Result<impl Iterator<Item = U>, E> {
47        let mut iter = self.map(f);
48        iter.try_for_each(|i| i.map(|_| ()))?;
49        Ok(iter.map(Result::unwrap))
50    }
51}