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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use std::{
env,
fs,
cmp::Ordering::Equal,
os::unix::fs::PermissionsExt,
};
#[derive(Debug)]
pub enum Completion {
None,
Partial(Vec<String>),
Complete(String),
}
impl Completion {
pub fn is_complete(&self) -> bool {
match *self {
Completion::None |
Completion::Partial(_) => false,
Completion::Complete(_) => true,
}
}
pub fn first(&self) -> String {
match *self {
Completion::None => "".to_owned(),
Completion::Partial(ref p) => {
match p.first() {
Some(t) => t.to_owned(),
None => "".to_owned(),
}
},
Completion::Complete(ref s) => s.to_owned(),
}
}
pub fn possibilities(&self) -> Vec<String> {
match *self {
Completion::None => vec![],
Completion::Partial(ref p) => p.clone(),
Completion::Complete(ref t) => vec![t.clone()],
}
}
}
pub fn complete(text: &str) -> Completion {
match executable_completions(text) {
c @ Completion::Partial(_) |
c @ Completion::Complete(_) => c,
Completion::None => path_complete(text),
}
}
pub fn executable_completions(text: &str) -> Completion {
match env::var_os("PATH") {
Some(paths) => {
let mut matches = vec![];
for dir in env::split_paths(&paths) {
if let Ok(executables) = fs::read_dir(dir) {
let paths = executables.filter_map(|e| {
match e { Ok(p) => Some(p.path()), _ => None }
});
for path in paths {
if let Some(filename) = path.file_name() {
let filename = filename.to_string_lossy();
if let Ok(metadata) = fs::metadata(&path) {
if (metadata.permissions()
.mode() & 0o111 != 0)
&& filename.starts_with(text)
{
matches.push(filename.into());
}
}
}
}
}
}
match matches.len() {
0 => Completion::None,
1 => Completion::Complete(matches.remove(0)),
_ => {
matches.sort_by(|a, b| {
match a.len().cmp(&b.len()) {
Equal => b.cmp(&a),
o => o
}
});
Completion::Partial(matches)
}
}
}
None => panic!("PATH is undefined"),
}
}
pub fn path_complete(text: &str) -> Completion {
match text {
"/hom" => Completion::Complete("/home/".into()),
"/usr/b" => Completion::Complete("/usr/bin/".into()),
"ls /hom" => Completion::Complete("ls /home/".into()),
_ => Completion::None,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lexicographical_order() {
assert_eq!("cargo", complete("car").first());
}
#[test]
fn paths() {
assert_eq!("/home/", complete("/hom").first());
assert_eq!("/usr/bin/", complete("/usr/b").first());
assert_eq!("ls /home/", complete("ls /hom").first());
}
}