aboutsummaryrefslogtreecommitdiffstats
path: root/src/completion.rs
blob: 80a0ebb7671db8096ce16dbce19753983dae138f (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
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
use crate::*;
use std::path::{Path, PathBuf};
use std::{env, 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> {
    match _path_completion(prefix) {
        Ok(suggestions) => suggestions,
        Err(err) => {
            println!("path completion failed: {err:?}\r");
            Vec::new()
        }
    }
}

pub fn variable_completion(session: Arc<Mutex<Session>>, prefix: BString) -> Vec<Suggestion> {
    let se = session.lock().unwrap();
    let mut out = Vec::new();
    for var in se.vars.keys() {
        if var.starts_with(&prefix) {
            out.push(Suggestion {
                display: var.to_vec(),
                delta: var[prefix.len()..].to_vec(),
            });
        }
    }
    drop(se);
    for var in env::vars_os() {
        let var = var.0.as_bytes();
        if var.starts_with(&prefix) {
            out.push(Suggestion {
                display: var.to_vec(),
                delta: var[prefix.len()..].to_vec(),
            });
        }
    }
    out
}

#[derive(Default)]
pub struct PathCache {
    binaries: HashMap<BString, PathBuf>,
}

fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    fs::metadata(path)
        .map(|m| m.permissions().mode() & 0o111 != 0)
        .unwrap_or(false)
}

pub fn populate_path_cache(session: Arc<Mutex<Session>>) {
    let path_var = env::var_os("PATH").unwrap();

    let mut binaries = HashMap::new();

    for dir in env::split_paths(&path_var) {
        if let Ok(entries) = fs::read_dir(&dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_file() && is_executable(&path) {
                    binaries.insert(path.file_name().unwrap().as_bytes().to_vec(), path);
                }
            }
        }
    }

    session.lock().unwrap().path_cache = PathCache { binaries };
}

pub fn command_completion(session: Arc<Mutex<Session>>, prefix: BString) -> Vec<Suggestion> {
    let se = session.lock().unwrap();
    let mut out = Vec::new();
    for fun in se
        .funs
        .keys()
        .chain(se.builtins.keys())
        .chain(se.path_cache.binaries.keys())
    {
        if fun.starts_with(&prefix) {
            out.push(Suggestion {
                display: fun.to_vec(),
                delta: fun[prefix.len()..].to_vec(),
            })
        }
    }

    for s in out.iter_mut() {
        s.delta.push(b' ');
    }

    out
}