pub trait AsScriptFullTypeRef {
    fn get_ty(&self) -> &ScriptType;
    fn get_sub(&self) -> Option<&ScriptType>;

    fn display<'a>(&'a self) -> DisplayTy<'a, Self> { ... }
    fn fmt(&self, w: &mut Formatter<'_>) -> FmtResult { ... }
}

Required Methods§

Provided Methods§

Examples found in repository?
src/path.rs (line 221)
218
219
220
221
222
223
224
225
226
227
228
229
pub fn get_template_path<T: AsScriptFullTypeRef>(ty: &T) -> Result<PathBuf> {
    let p = get_home()
        .join(TEMPLATE)
        .join(format!("{}.hbs", ty.display()));
    if let Some(dir) = p.parent() {
        if !dir.exists() {
            log::info!("找不到模板資料夾,創建之");
            handle_fs_res(&[&dir], create_dir_all(&dir))?;
        }
    }
    Ok(p)
}
More examples
Hide additional examples
src/util/mod.rs (line 166)
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
pub fn get_or_create_template_path<T: AsScriptFullTypeRef>(
    ty: &T,
    force: bool,
    check_subtype: bool,
) -> Result<(PathBuf, Option<&'static str>)> {
    if !force {
        Config::get().get_script_conf(ty.get_ty())?; // 確認類型存在與否
    }
    let tmpl_path = path::get_template_path(ty)?;
    if !tmpl_path.exists() {
        if check_subtype && ty.get_sub().is_some() {
            return Err(Error::UnknownType(ty.display().to_string()));
        }
        let default_tmpl = get_default_template(ty);
        return write_file(&tmpl_path, default_tmpl).map(|_| (tmpl_path, Some(default_tmpl)));
    }
    Ok((tmpl_path, None))
}
Examples found in repository?
src/script_type.rs (line 239)
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
    fn fmt(&self, w: &mut Formatter<'_>) -> FmtResult {
        AsScriptFullTypeRef::fmt(self, w)
    }
}

impl AsScriptFullTypeRef for ScriptFullType {
    fn get_ty(&self) -> &ScriptType {
        &self.ty
    }
    fn get_sub(&self) -> Option<&ScriptType> {
        self.sub.as_ref()
    }
}

impl<'a> AsScriptFullTypeRef for (&'a ScriptType, Option<&'a ScriptType>) {
    fn get_ty(&self) -> &ScriptType {
        self.0
    }
    fn get_sub(&self) -> Option<&ScriptType> {
        self.1
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ScriptTypeConfig {
    pub ext: Option<String>,
    pub color: String,
    pub cmd: Option<String>,
    args: Vec<String>,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    env: HashMap<String, String>,
}

impl ScriptTypeConfig {
    // XXX: extract
    pub fn args(&self, info: &serde_json::Value) -> Result<Vec<String>, Error> {
        let reg = Handlebars::new();
        let mut args: Vec<String> = Vec::with_capacity(self.args.len());
        for c in self.args.iter() {
            let res = reg.render_template(c, &info)?;
            args.push(res);
        }
        Ok(args)
    }
    // XXX: extract
    pub fn gen_env(&self, info: &serde_json::Value) -> Result<Vec<(String, String)>, Error> {
        let reg = Handlebars::new();
        let mut env: Vec<(String, String)> = Vec::with_capacity(self.env.len());
        for (name, e) in self.env.iter() {
            let res = reg.render_template(e, &info)?;
            env.push((name.to_owned(), res));
        }
        Ok(env)
    }
    pub fn default_script_types() -> HashMap<ScriptType, ScriptTypeConfig> {
        let mut ret = HashMap::default();
        for (ty, conf) in iter_default_configs() {
            ret.insert(ty, conf);
        }
        ret
    }
}

macro_rules! create_default_types {
    ($(( $name:literal, $tmpl:ident, $conf:expr, [ $($sub:literal: $sub_tmpl:ident),* ] )),*) => {
        pub fn get_default_template<T: AsScriptFullTypeRef>(ty: &T) -> &'static str {
            match (ty.get_ty().as_ref(), ty.get_sub().map(|s| s.as_ref())) {
                $(
                    $(
                        ($name, Some($sub)) => $sub_tmpl,
                    )*
                    ($name, _) => $tmpl,
                )*
                _ => DEFAULT_WELCOME_MSG
            }
        }
        pub fn iter_default_templates() -> impl ExactSizeIterator<Item = (ScriptFullType, &'static str)> {
            let arr = [$(
                (ScriptFullType{ ty: ScriptType($name.to_owned()), sub: None }, $tmpl),
                $(
                    (ScriptFullType{ ty: ScriptType($name.to_owned()), sub: Some(ScriptType($sub.to_owned())) }, $sub_tmpl),
                )*
            )*];
            arr.into_iter()
        }
        fn iter_default_configs() -> impl ExactSizeIterator<Item = (ScriptType, ScriptTypeConfig)> {
            let arr = [$( (ScriptType($name.to_owned()), $conf), )*];
            arr.into_iter()
        }
    };
}

fn gen_map(arr: &[(&str, &str)]) -> HashMap<String, String> {
    arr.iter()
        .map(|(k, v)| (k.to_string(), v.to_string()))
        .collect()
}

create_default_types! {
    ("sh", SHELL_WELCOME_MSG, ScriptTypeConfig {
        ext: Some("sh".to_owned()),
        color: "bright magenta".to_owned(),
        cmd: Some("bash".to_owned()),
        args: vec!["{{path}}".to_owned()],
        env: Default::default()
    }, []),
    ("tmux", TMUX_WELCOME_MSG, ScriptTypeConfig {
        ext: Some("sh".to_owned()),
        color: "white".to_owned(),
        cmd: Some("bash".to_owned()),
        args: vec!["{{path}}".to_owned()],
        env: Default::default(),
    }, []),
    ("js", JS_WELCOME_MSG, ScriptTypeConfig {
        ext: Some("js".to_owned()),
        color: "bright cyan".to_owned(),
        cmd: Some("node".to_owned()),
        args: vec!["{{path}}".to_owned()],
        env: gen_map(&[(
            "NODE_PATH",
            "{{{home}}}/node_modules",
        )]),
    }, []),
    ("js-i", JS_WELCOME_MSG, ScriptTypeConfig {
        ext: Some("js".to_owned()),
        color: "bright cyan".to_owned(),
        cmd: Some("node".to_owned()),
        args: vec!["-i".to_owned(), "-e".to_owned(), "{{{content}}}".to_owned()],
        env: gen_map(&[(
            "NODE_PATH",
            "{{{home}}}/node_modules",
        )]),
    }, []),
    ("rb", RB_WELCOME_MSG, ScriptTypeConfig {
        ext: Some("rb".to_owned()),
        color: "bright red".to_owned(),
        cmd: Some("ruby".to_owned()),
        args: vec!["{{path}}".to_owned()],
        env: Default::default(),
    }, ["traverse": RB_TRAVERSE_WELCOME_MSG, "cd": RB_CD_WELCOME_MSG]),
    ("txt", DEFAULT_WELCOME_MSG, ScriptTypeConfig {
        ext: None,
        color: "bright black".to_owned(),
        cmd: Some("cat".to_owned()),
        args: vec!["{{path}}".to_owned()],
        env: Default::default(),
    }, [])
}

/// 因為沒辦法直接對 AsScriptFullTypeRef 實作 Display 不得不多包一層…
pub struct DisplayTy<'a, U: ?Sized>(pub &'a U);
impl<'a, U: AsScriptFullTypeRef> Display for DisplayTy<'a, U> {
    fn fmt(&self, w: &mut Formatter<'_>) -> FmtResult {
        self.0.fmt(w)
    }

Implementations on Foreign Types§

Implementors§