pub enum ScriptName {
    Anonymous(u32),
    Named(ConcreteScriptName),
}

Variants§

§

Anonymous(u32)

§

Named(ConcreteScriptName)

Implementations§

Examples found in repository?
src/script.rs (line 370)
368
369
370
371
372
373
374
375
fn string_into_script_name(s: String, check: bool) -> Result<ScriptName> {
    log::debug!("解析腳本名:{} {}", s, check);
    if let Some(id) = ScriptName::valid(&s, false, false, check)? {
        id.into_script_name()
    } else {
        Ok(ScriptName::Named(ConcreteScriptName::new_unchecked(s))) // NOTE: already checked by `ScriptName::valid`
    }
}
More examples
Hide additional examples
src/query/mod.rs (line 229)
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    fn from_str(mut s: &str) -> DisplayResult<Self> {
        let bang = if s.ends_with('!') {
            if s == "!" {
                return Ok(ScriptQuery {
                    inner: ScriptQueryInner::Prev(none0_usize(1)),
                    bang: true,
                });
            }
            s = &s[..s.len() - 1];
            true
        } else {
            false
        };
        let inner = if s.starts_with('=') {
            s = &s[1..s.len()];
            let name = s.to_owned().into_script_name()?;
            ScriptQueryInner::Exact(name)
        } else if s == "-" {
            ScriptQueryInner::Prev(none0_usize(1))
        } else if s.starts_with('^') {
            ScriptQueryInner::Prev(parse_prev(s)?)
        } else {
            ScriptName::valid(s, true, true, true).context("模糊搜尋仍需符合腳本名格式!")?; // NOTE: 單純檢查用
            ScriptQueryInner::Fuzz(s.to_owned())
        };
        Ok(ScriptQuery { inner, bang })
    }
Examples found in repository?
src/script_repo/helper.rs (line 62)
61
62
63
    fn fuzz_key(&self) -> std::borrow::Cow<'_, str> {
        self.info.name.key()
    }
More examples
Hide additional examples
src/script.rs (line 210)
209
210
211
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.key())
    }
src/list/tree.rs (line 51)
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    fn display_key(&self) -> Cow<'b, str> {
        match &self.0 {
            Cow::Borrowed(s) => Cow::Borrowed(s),
            Cow::Owned(_) => self.1.name.key(),
        }
    }
}
impl<'b, W: Write> TreeFormatter<'b, TrimmedScriptInfo<'b>, W> for ShortFormatter {
    fn fmt_leaf(&mut self, f: &mut W, t: &TrimmedScriptInfo<'b>) -> Result {
        let TrimmedScriptInfo(_, script) = t;
        let ty = get_display_type(&script.ty);
        let ident = ident_string(self.ident_style, &*ty.display(), t);
        let ident = style(self.plain, ident, |s| s.color(ty.color()).bold());
        if self.latest_script_id == script.id && !self.plain {
            write!(f, "{}", "*".color(Color::Yellow).bold())?;
        }
        writeln!(f, "{}", ident)?;
        Ok(())
    }
    fn fmt_nonleaf(&mut self, f: &mut W, t: &str) -> Result {
        let ident = style(self.plain, t, |s| s.dimmed().italic());
        writeln!(f, "{}", ident)?;
        Ok(())
    }
}

impl<'b> TreeFormatter<'b, TrimmedScriptInfo<'b>, Vec<u8>> for LongFormatter<'b> {
    fn fmt_leaf(&mut self, f: &mut Vec<u8>, t: &TrimmedScriptInfo<'b>) -> Result {
        let TrimmedScriptInfo(name, script) = t;
        let ty = get_display_type(&script.ty);
        let color = ty.color();

        let mut ident_width = {
            let t = std::str::from_utf8(&f)?;
            t.width()
        };
        ident_width += name.len();
        let ident = style(self.plain, name, |s| s.color(color).bold());
        if self.latest_script_id == script.id && !self.plain {
            write!(f, "{}", "*".color(Color::Yellow).bold())?;
            ident_width += 1;
        }
        write!(f, "{}", ident)?;

        let ty = ty.display();
        let ty_width = ty.len();
        let ty_txt = style(self.plain, ty, |s| s.color(color).bold());

        let help_msg = extract_help(script);

        let row = vec![
            Cell::new_with_len(std::str::from_utf8(&f)?.to_string(), ident_width),
            Cell::new_with_len(ty_txt.to_string(), ty_width),
            Cell::new(time_fmt::fmt(&script.write_time)),
            Cell::new(exec_time_str(script).to_string()),
            Cell::new(help_msg),
        ];
        self.table.add_row(row);
        f.clear();
        Ok(())
    }
    fn fmt_nonleaf(&mut self, f: &mut Vec<u8>, name: &str) -> Result {
        let mut ident_width = {
            let t = std::str::from_utf8(&f)?;
            t.width()
        };
        let ident = style(self.plain, name, |s| s.dimmed().italic());
        ident_width += name.len();
        write!(f, "{}", ident)?;
        let row = vec![Cell::new_with_len(
            std::str::from_utf8(&f)?.to_string(),
            ident_width,
        )];
        self.table.add_row(row);
        f.clear();
        Ok(())
    }
}

type TreeNode<'b> = tree_lib::TreeNode<'b, TrimmedScriptInfo<'b>>;

fn build_forest(scripts: Vec<&ScriptInfo>) -> Vec<TreeNode<'_>> {
    let mut m = HashMap::default();
    for script in scripts.into_iter() {
        let name = script.name.key();
        let name_key = match name {
            Cow::Borrowed(s) => s,
            _ => {
                m.insert(
                    (false, name.clone()),
                    TreeNode::new_leaf(TrimmedScriptInfo(name, script)),
                );
                continue;
            }
        };
        let mut path: Vec<_> = name_key.split('/').collect();
        let name = Cow::Borrowed(path.pop().unwrap());
        let leaf = TreeNode::new_leaf(TrimmedScriptInfo(name, script));
        TreeNode::insert_to_map(&mut m, &path, leaf);
    }
    let mut forest: Vec<_> = m.into_iter().map(|(_, t)| t).collect();
    forest.sort_by(|a, b| a.simple_cmp(b));
    forest
}
src/script_repo/mod.rs (line 200)
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
    async fn handle_insert(&self, info: &ScriptInfo) -> Result<i64> {
        assert!(self.modifies_script);
        let name_cow = info.name.key();
        let name = name_cow.as_ref();
        let ty = info.ty.as_ref();
        let tags = join_tags(info.tags.iter());
        let res = sqlx::query!(
            "
            INSERT INTO script_infos (name, ty, tags)
            VALUES(?, ?, ?)
            RETURNING id
            ",
            name,
            ty,
            tags,
        )
        .fetch_one(&self.info_pool)
        .await?;
        Ok(res.id)
    }

    async fn handle_change(&self, info: &ScriptInfo) -> Result<i64> {
        log::debug!("開始修改資料庫 {:?}", info);
        if info.changed {
            assert!(self.modifies_script);
            let name = info.name.key();
            let name = name.as_ref();
            let tags = join_tags(info.tags.iter());
            let ty = info.ty.as_ref();
            sqlx::query!(
                "UPDATE script_infos SET name = ?, tags = ?, ty = ? where id = ?",
                name,
                tags,
                ty,
                info.id,
            )
            .execute(&self.info_pool)
            .await?;
        }

        if matches!(self.trace_opt, TraceOption::NoTrace) {
            return Ok(0);
        }

        let mut last_event_id = 0;
        macro_rules! record_event {
            ($time:expr, $data:expr) => {
                self.historian.record(&Event {
                    script_id: info.id,
                    humble: matches!(self.trace_opt, TraceOption::Humble),
                    time: $time,
                    data: $data,
                })
            };
        }

        if let Some(time) = info.exec_done_time.as_ref() {
            if let Some(&(code, main_event_id)) = time.data() {
                log::debug!("{:?} 的執行完畢事件", info.name);
                last_event_id = record_event!(
                    **time,
                    EventData::ExecDone {
                        code,
                        main_event_id,
                    }
                )
                .await?;

                if last_event_id != 0 {
                    self.update_last_time(info).await?;
                } else {
                    log::info!("{:?} 的執行完畢事件被忽略了", info.name);
                }
                return Ok(last_event_id); // XXX: 超級醜的作法,為了避免重復記錄其它的事件
            }
        }

        self.update_last_time(info).await?;

        if info.read_time.has_changed() {
            log::debug!("{:?} 的讀取事件", info.name);
            last_event_id = record_event!(*info.read_time, EventData::Read).await?;
        }
        if info.write_time.has_changed() {
            log::debug!("{:?} 的寫入事件", info.name);
            last_event_id = record_event!(*info.write_time, EventData::Write).await?;
        }
        if let Some(time) = info.miss_time.as_ref() {
            if time.has_changed() {
                log::debug!("{:?} 的錯過事件", info.name);
                last_event_id = record_event!(**time, EventData::Miss).await?;
            }
        }
        if let Some(time) = info.exec_time.as_ref() {
            if let Some((content, args, envs, dir)) = time.data() {
                log::debug!("{:?} 的執行事件", info.name);
                last_event_id = record_event!(
                    **time,
                    EventData::Exec {
                        content,
                        args,
                        envs,
                        dir: dir.as_deref(),
                    }
                )
                .await?;
            }
        }

        Ok(last_event_id)
    }
}

fn join_tags<'a, I: Iterator<Item = &'a Tag>>(tags: I) -> String {
    let tags_arr: Vec<&str> = tags.map(|t| t.as_ref()).collect();
    tags_arr.join(",")
}

#[derive(Debug)]
pub struct ScriptRepo {
    map: HashMap<String, ScriptInfo>,
    hidden_map: HashMap<String, ScriptInfo>,
    latest_name: Option<String>,
    db_env: DBEnv,
}

macro_rules! iter_by_vis {
    ($self:expr, $vis:expr) => {{
        let (iter, iter2) = match $vis {
            Visibility::Normal => ($self.map.iter_mut(), None),
            Visibility::All => ($self.map.iter_mut(), Some($self.hidden_map.iter_mut())),
            Visibility::Inverse => ($self.hidden_map.iter_mut(), None),
        };
        IterWithoutEnv { iter, iter2 }
    }};
}

impl ScriptRepo {
    pub async fn close(self) {
        self.db_env.close().await;
    }
    pub fn iter(&self) -> impl Iterator<Item = &ScriptInfo> {
        self.map.iter().map(|(_, info)| info)
    }
    pub fn iter_mut(&mut self, visibility: Visibility) -> Iter<'_> {
        Iter {
            iter: iter_by_vis!(self, visibility),
            env: &self.db_env,
        }
    }
    pub fn historian(&self) -> &Historian {
        &self.db_env.historian
    }
    pub async fn new(
        recent: Option<RecentFilter>,
        db_env: DBEnv,
        selector: &TagSelectorGroup,
    ) -> Result<ScriptRepo> {
        let mut hidden_map = HashMap::<String, ScriptInfo>::default();
        let mut map: HashMap<String, ScriptInfo> = Default::default();
        let time_bound = recent.map(|r| {
            let mut time = Utc::now().naive_utc();
            time -= Duration::days(r.recent.into());
            (time, r.archaeology)
        });

        let scripts = sqlx::query!(
            "SELECT * FROM script_infos si LEFT JOIN last_events le ON si.id = le.script_id"
        )
        .fetch_all(&db_env.info_pool)
        .await?;
        for record in scripts.into_iter() {
            let name = record.name;
            log::trace!("載入腳本:{} {} {}", name, record.ty, record.tags);
            let script_name = name.clone().into_script_name_unchecked()?; // NOTE: 從資料庫撈出來就別檢查了吧

            let mut builder = ScriptInfo::builder(
                record.id,
                script_name,
                ScriptType::new_unchecked(record.ty),
                record.tags.split(',').filter_map(|s| {
                    if s.is_empty() {
                        None
                    } else {
                        Some(Tag::new_unchecked(s.to_string()))
                    }
                }),
            );

            builder.created_time(record.created_time);
            if let Some(count) = record.exec_count {
                builder.exec_count(count as u64);
            }
            if let Some(time) = record.write {
                builder.write_time(time);
            }
            if let Some(time) = record.read {
                builder.read_time(time);
            }
            if let Some(time) = record.miss {
                builder.miss_time(time);
            }
            if let Some(time) = record.exec {
                builder.exec_time(time);
            }
            if let Some(time) = record.exec_done {
                builder.exec_done_time(time);
            }
            if let Some(time) = record.neglect {
                builder.neglect_time(time);
            }
            if let Some(time) = record.humble {
                builder.humble_time(time);
            }

            let script = builder.build();

            let mut hide = false;
            if let Some((mut time_bound, archaeology)) = time_bound {
                if let Some(neglect) = record.neglect {
                    log::debug!("腳本 {} 曾於 {} 被忽略", script.name, neglect);
                    time_bound = std::cmp::max(neglect, time_bound);
                }
                let overtime = time_bound > script.last_major_time();
                hide = archaeology ^ overtime
            }
            if !hide {
                hide = !selector.select(&script.tags, &script.ty);
            }

            if hide {
                hidden_map.insert(name, script);
            } else {
                log::trace!("腳本 {:?} 通過篩選", name);
                map.insert(name, script);
            }
        }
        Ok(ScriptRepo {
            map,
            hidden_map,
            latest_name: None,
            db_env,
        })
    }
    pub fn no_trace(&mut self) {
        self.db_env.trace_opt = TraceOption::NoTrace;
    }
    pub fn humble(&mut self) {
        self.db_env.trace_opt = TraceOption::Humble;
    }
    // fn latest_mut_no_cache(&mut self) -> Option<&mut ScriptInfo<'a>> {
    //     let latest = self.map.iter_mut().max_by_key(|(_, info)| info.last_time());
    //     if let Some((name, info)) = latest {
    //         self.latest_name = Some(name.clone());
    //         Some(info)
    //     } else {
    //         None
    //     }
    // }
    pub fn latest_mut(&mut self, n: usize, visibility: Visibility) -> Option<RepoEntry<'_>> {
        // if let Some(name) = &self.latest_name {
        //     // FIXME: 一旦 rust nll 進化就修掉這段
        //     if self.map.contains_key(name) {
        //         return self.map.get_mut(name);
        //     }
        //     log::warn!("快取住的最新資訊已經不見了…?重找一次");
        // }
        // self.latest_mut_no_cache()
        let mut v: Vec<_> = iter_by_vis!(self, visibility).collect();
        v.sort_by_key(|s| s.last_time());
        if v.len() >= n {
            let t = v.remove(v.len() - n);
            Some(RepoEntry::new(t, &self.db_env))
        } else {
            None
        }
    }
    pub fn get_mut(&mut self, name: &ScriptName, visibility: Visibility) -> Option<RepoEntry<'_>> {
        // FIXME: 一旦 NLL 進化就修掉這個 unsafe
        let map = &mut self.map as *mut HashMap<String, ScriptInfo>;
        let map = unsafe { &mut *map };
        let key = name.key();
        let info = match visibility {
            Visibility::Normal => map.get_mut(&*key),
            Visibility::Inverse => self.hidden_map.get_mut(&*key),
            Visibility::All => {
                let info = map.get_mut(&*key);
                // 用 Option::or 有一些生命週期的怪問題…
                if info.is_some() {
                    info
                } else {
                    self.hidden_map.get_mut(&*key)
                }
            }
        };
        let env = &self.db_env;
        info.map(move |info| RepoEntry::new(info, env))
    }
    pub fn get_mut_by_id(&mut self, id: i64) -> Option<RepoEntry<'_>> {
        // XXX: 複雜度很瞎
        self.iter_mut(Visibility::All).find(|e| e.id == id)
    }

    pub async fn remove(&mut self, id: i64) -> Result {
        // TODO: 從 map 中刪掉?但如果之後沒其它用途似乎也未必需要...
        log::debug!("從資料庫刪除腳本 {:?}", id);
        self.db_env.handle_delete(id).await?;
        Ok(())
    }
    pub fn entry(&mut self, name: &ScriptName) -> RepoEntryOptional<'_> {
        // TODO: 決定要插 hidden 與否
        let entry = self.map.entry(name.key().into_owned());
        RepoEntryOptional {
            entry,
            env: &self.db_env,
        }
    }
src/util/completion_util.rs (line 41)
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
async fn fuzz_arr<'a>(
    name: &str,
    iter: impl Iterator<Item = RepoEntry<'a>>,
) -> Result<Vec<RepoEntry<'a>>> {
    // TODO: 測試這個複雜的函式,包括前綴和次級結果
    let res = fuzz_with_multifuzz_ratio(name, iter, SEP, Some(60)).await?;
    Ok(match res {
        None => vec![],
        Some(FuzzResult::High(t) | FuzzResult::Low(t)) => vec![t],
        Some(FuzzResult::Multi {
            ans,
            others,
            mut still_others,
        }) => {
            let prefix = ans.name.key();
            let mut first_others = vec![];
            let mut prefixed_others = vec![];
            for candidate in others.into_iter() {
                if is_prefix(&*prefix, &*candidate.name.key(), SEP) {
                    prefixed_others.push(candidate);
                } else {
                    first_others.push(candidate);
                }
            }
            first_others.push(ans);

            sort(&mut first_others);
            sort(&mut prefixed_others);
            sort(&mut still_others);
            first_others.append(&mut prefixed_others);
            first_others.append(&mut still_others);
            first_others
        }
    })
}

pub async fn handle_completion(comp: Completion, repo: &mut Option<ScriptRepo>) -> Result {
    match comp {
        Completion::LS { name, args } => {
            let mut new_root = match Root::try_parse_from(args) {
                Ok(Root {
                    subcmd: Some(Subs::Tags(_) | Subs::Types(_)),
                    ..
                }) => {
                    // TODO: 在補全腳本中處理,而不要在這邊
                    return Err(Error::Completion);
                }
                Ok(t) => t,
                Err(e) => {
                    log::warn!("補全時出錯 {}", e);
                    // NOTE: -V 或 --help 也會走到這裡
                    return Err(Error::Completion);
                }
            };
            log::info!("補完模式,參數為 {:?}", new_root);
            new_root.set_home_unless_from_alias(false)?;
            new_root.sanitize_flags();
            *repo = Some(init_repo(new_root.root_args, false).await?);

            let iter = repo.as_mut().unwrap().iter_mut(Visibility::Normal);
            let scripts = if let Some(name) = name {
                fuzz_arr(&name, iter).await?
            } else {
                let mut t: Vec<_> = iter.collect();
                sort(&mut t);
                t
            };

            print_iter(scripts.iter().map(|s| s.name.key()), " ");
        }
        Completion::NoSubcommand { args } => {
            if let Ok(root) = parse_alias_root(&args) {
                if root.subcmd.is_some() {
                    log::debug!("子命令 = {:?}", root.subcmd);
                    return Err(Error::Completion);
                }
            } // else: 解析錯誤當然不可能有子命令啦
        }
        Completion::Alias { args } => {
            let root = parse_alias_root(&args)?;

            if root.root_args.no_alias {
                log::info!("無別名模式");
                return Err(Error::Completion);
            }

            let home = path::compute_home_path_optional(root.root_args.hs_home.as_ref(), false)?;
            let conf = Config::load(&home)?;
            if let Some(new_args) = root.expand_alias(&args, &conf) {
                print_iter(new_args, " ");
            } else {
                log::info!("並非別名");
                return Err(Error::Completion);
            };
        }
        Completion::Home { args } => {
            let root = parse_alias_root(&args)?;
            let home = root.root_args.hs_home.ok_or_else(|| Error::Completion)?;
            print!("{}", home);
        }
        Completion::ParseRun { args } => {
            let mut root = Root::try_parse_from(args).map_err(|e| {
                log::warn!("補全時出錯 {}", e);
                Error::Completion
            })?;
            root.sanitize()?;
            match root.subcmd {
                Some(Subs::Run {
                    script_query, args, ..
                }) => {
                    let iter = std::iter::once(script_query.to_string())
                        .chain(args.into_iter().map(|s| to_display_args(s)));
                    print_iter(iter, " ");
                }
                res @ _ => {
                    log::warn!("非執行指令 {:?}", res);
                    return Err(Error::Completion);
                }
            }
        }
    }
    Ok(())
}
src/query/util.rs (line 46)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
pub async fn do_list_query<'a>(
    repo: &'a mut ScriptRepo,
    queries: &[ListQuery],
) -> Result<Vec<RepoEntry<'a>>> {
    if queries.is_empty() {
        return Ok(repo.iter_mut(Visibility::Normal).collect());
    }
    let mut mem = HashSet::<i64>::default();
    let mut ret = vec![];
    let repo_ptr = repo as *mut ScriptRepo;
    for query in queries.iter() {
        macro_rules! insert {
            ($script:ident) => {
                if mem.contains(&$script.id) {
                    continue;
                }
                mem.insert($script.id);
                ret.push($script);
            };
        }
        // SAFETY: `mem` 已保證回傳的陣列不可能包含相同的資料
        let repo = unsafe { &mut *repo_ptr };
        match query {
            ListQuery::Pattern(re, og, bang) => {
                let mut is_empty = true;
                for script in repo.iter_mut(compute_vis(*bang)) {
                    if re.is_match(&script.name.key()) {
                        is_empty = false;
                        insert!(script);
                    }
                }
                if is_empty {
                    return Err(Error::ScriptNotFound(og.to_owned()));
                }
            }
            ListQuery::Query(query) => {
                let script = match do_script_query_strict(query, repo).await {
                    Err(Error::DontFuzz) => continue,
                    Ok(entry) => entry,
                    Err(e) => return Err(e),
                };
                insert!(script);
            }
        }
    }
    if ret.is_empty() {
        log::debug!("列表查不到東西,卻又不是因為 pattern not match,想必是因為使用者取消了模糊搜");
        Err(Error::DontFuzz)
    } else {
        Ok(ret)
    }
}

impl<'a> MultiFuzzObj for RepoEntry<'a> {
    fn beats(&self, other: &Self) -> bool {
        self.last_time() > other.last_time()
    }
}

pub async fn do_script_query<'b>(
    script_query: &ScriptQuery,
    script_repo: &'b mut ScriptRepo,
    finding_filtered: bool,
    forbid_prompt: bool,
) -> Result<Option<RepoEntry<'b>>> {
    log::debug!("開始尋找 `{:?}`", script_query);
    let mut visibility = compute_vis(script_query.bang);
    if finding_filtered {
        visibility = visibility.invert();
    }
    match &script_query.inner {
        ScriptQueryInner::Prev(prev) => {
            assert!(!finding_filtered); // XXX 很難看的作法,應設法靜態檢查
            let latest = script_repo.latest_mut(prev.get(), visibility);
            log::trace!("找最新腳本");
            return if latest.is_some() {
                Ok(latest)
            } else {
                Err(Error::Empty)
            };
        }
        ScriptQueryInner::Exact(name) => Ok(script_repo.get_mut(name, visibility)),
        ScriptQueryInner::Fuzz(name) => {
            let level = if forbid_prompt {
                PromptLevel::Never
            } else {
                Config::get_prompt_level()
            };

            let iter = script_repo.iter_mut(visibility);
            let fuzz_res = fuzzy::fuzz(name, iter, SEP).await?;
            let mut is_low = false;
            let mut is_multi_fuzz = false;
            let entry = match fuzz_res {
                Some(fuzzy::High(entry)) => entry,
                Some(fuzzy::Low(entry)) => {
                    is_low = true;
                    entry
                }
                #[cfg(feature = "benching")]
                Some(fuzzy::Multi { ans, .. }) => {
                    is_multi_fuzz = true;
                    ans
                }
                #[cfg(not(feature = "benching"))]
                Some(fuzzy::Multi { ans, others, .. }) => {
                    is_multi_fuzz = true;
                    the_multifuzz_algo(ans, others)
                }
                None => return Ok(None),
            };
            let need_prompt = {
                match level {
                    PromptLevel::Always => true,
                    PromptLevel::Never => false,
                    PromptLevel::Smart => is_low || is_multi_fuzz,
                    PromptLevel::OnMultiFuzz => is_multi_fuzz,
                }
            };
            if need_prompt {
                prompt_fuzz_acceptable(&*entry)?;
            }
            Ok(Some(entry))
        }
    }
}
pub async fn do_script_query_strict<'b>(
    script_query: &ScriptQuery,
    script_repo: &'b mut ScriptRepo,
) -> Result<RepoEntry<'b>> {
    // FIXME: 一旦 NLL 進化就修掉這段 unsafe
    let ptr = script_repo as *mut ScriptRepo;
    if let Some(info) = do_script_query(script_query, script_repo, false, false).await? {
        return Ok(info);
    }

    let script_repo = unsafe { &mut *ptr };
    #[cfg(not(feature = "benching"))]
    if !script_query.bang {
        let filtered = do_script_query(script_query, script_repo, true, true).await?;
        if let Some(mut filtered) = filtered {
            filtered.update(|script| script.miss()).await?;
            return Err(Error::ScriptIsFiltered(filtered.name.key().to_string()));
        }
    };

    Err(Error::ScriptNotFound(script_query.to_string()))
}

回傳值是相對於 HS_HOME 的路徑

Examples found in repository?
src/path.rs (line 199)
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
pub fn open_script(
    name: &ScriptName,
    ty: &ScriptType,
    check_exist: Option<bool>,
) -> Result<PathBuf> {
    let mut err_in_fallback = None;
    let script_path = if check_exist == Some(true) {
        let (p, e) = name.to_file_path_fallback(ty);
        err_in_fallback = e;
        p
    } else {
        name.to_file_path(ty)?
    };
    let script_path = get_home().join(script_path);

    if let Some(should_exist) = check_exist {
        if !script_path.exists() && should_exist {
            if let Some(e) = err_in_fallback {
                return Err(e);
            }
            return Err(
                Error::PathNotFound(vec![script_path]).context("開腳本失敗:應存在卻不存在")
            );
        } else if script_path.exists() && !should_exist {
            return Err(Error::PathExist(script_path).context("開腳本失敗:不應存在卻存在"));
        }
    }
    Ok(script_path)
}

回傳值是相對於 HS_HOME 的路徑,對未知的類別直接用類別名作擴展名

Examples found in repository?
src/script.rs (line 290)
289
290
291
    pub fn file_path_fallback(&self) -> PathBuf {
        self.name.to_file_path_fallback(&self.ty).0
    }
More examples
Hide additional examples
src/path.rs (line 195)
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
pub fn open_script(
    name: &ScriptName,
    ty: &ScriptType,
    check_exist: Option<bool>,
) -> Result<PathBuf> {
    let mut err_in_fallback = None;
    let script_path = if check_exist == Some(true) {
        let (p, e) = name.to_file_path_fallback(ty);
        err_in_fallback = e;
        p
    } else {
        name.to_file_path(ty)?
    };
    let script_path = get_home().join(script_path);

    if let Some(should_exist) = check_exist {
        if !script_path.exists() && should_exist {
            if let Some(e) = err_in_fallback {
                return Err(e);
            }
            return Err(
                Error::PathNotFound(vec![script_path]).context("開腳本失敗:應存在卻不存在")
            );
        } else if script_path.exists() && !should_exist {
            return Err(Error::PathExist(script_path).context("開腳本失敗:不應存在卻存在"));
        }
    }
    Ok(script_path)
}

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Formats the value using the given formatter. Read more
The associated error which can be returned from parsing.
Parses a string s to return a value of this type. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.