1
use std::path::Path;
2

            
3
use crate::matcher::Matcher;
4

            
5
/// Create completion hint for given directory and term. If term is None, return
6
/// all components of the directory. If term is Some, return the directory
7
/// component that is the closest fuzzy match to the term.
8
///
9
/// # Examples
10
///
11
/// ## For Some term
12
///
13
/// ```
14
/// let matcher = cdup::matcher::Matcher::default();
15
/// let cwd = std::path::Path::new("/home/rsprta/games/angband");
16
/// let term = Some("ang");
17
/// let expected = String::from("angband");
18
///
19
/// assert_eq!(expected, cdup::hint::completion_for(&matcher, &cwd, term));
20
/// ```
21
///
22
/// ## For None term
23
/// ```
24
/// let matcher = cdup::matcher::Matcher::default();
25
/// let cwd = std::path::Path::new("/home/rsprta/games/angband");
26
/// let term = None;
27
/// let expected = String::from("/\nhome\nrsprta\ngames\nangband");
28
///
29
/// assert_eq!(expected, cdup::hint::completion_for(&matcher, &cwd, term));
30
/// ```
31
4
pub fn completion_for(matcher: &Matcher, directory: &Path, term: Option<&str>) -> String {
32
4
    let components: Vec<&str> = directory
33
4
        .components()
34
18
        .map(|c| c.as_os_str().to_str().unwrap())
35
4
        .collect();
36

            
37
4
    match term {
38
2
        Some(term) => {
39
2
            let best_match = matcher.best_match(&components, term);
40
2
            match best_match {
41
                Some(index) => components[index].to_string(),
42
2
                None => String::new(),
43
            }
44
        }
45
2
        None => components.join("\n"),
46
    }
47
4
}