aboutsummaryrefslogtreecommitdiffstats
path: root/src/completion.rs
blob: 3adce907ba047f85d19d42efa242185f99ce555b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
use crate::*;
use std::fs;

pub struct Suggestion {
    pub display: BString,
    pub delta: BString,
}

fn _path_completion(mut prefix: BString) -> io::Result<Vec<Suggestion>> {
    let mut partial_entry = BString::new();
    while let Some(c) = prefix.last().cloned() {
        if c == b'/' {
            break;
        }
        partial_entry.push(c);
        prefix.pop();
    }
    partial_entry.reverse();

    let mut sugs = Vec::new();

    if prefix.is_empty() {
        prefix.push(b'.');
    }

    for entry in fs::read_dir(OsStr::from_bytes(&prefix))? {
        let entry = entry?;
        let name = entry.file_name().as_bytes().to_vec();
        if name.starts_with(&partial_entry) {
            let mut delta = name[partial_entry.len()..].to_vec();

            let is_dir = entry.metadata().map(|m| m.is_dir()).unwrap_or(false);
            if is_dir {
                delta.push(b'/');
            } else {
                delta.push(b' ');
            }

            sugs.push(Suggestion {
                display: name,
                delta,
            });
        }
    }

    Ok(sugs)
}

pub fn path_completion(prefix: BString) -> Vec<Suggestion> {
    eprintln!("path completion request for {}\r\n", String::from_utf8_lossy(&prefix));
    match _path_completion(prefix) {
        Ok(suggestions) => suggestions,
        Err(err) => {
            println!("path completion failed: {err:?}\r");
            Vec::new()
        }
    }
}