fpr_cli/
util.rs

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
use crate::com::*;

pub fn to_lines<const S: usize, I: AsRef<str>>(a: &[[I; S]]) -> Vec<String> {
    use unicode_width::*;
    let w = match (0..S)
        .map(|i| a.iter().map(|l| l[i].as_ref().width()).max().ok_or(()))
        .collect::<Result<Vec<_>, _>>()
    {
        Ok(e) => e,
        Err(_) => {
            return vec![];
        }
    };
    a.iter()
        .map(|v| {
            v.iter()
                .enumerate()
                .map(|(i, s)| format!("{}{: <2$}", s.as_ref(), "", w[i] - s.as_ref().width()))
                .join(" ")
        })
        .collect()
}
pub fn to_table<const S: usize, I: AsRef<str>>(a: &[[I; S]]) -> String {
    to_lines(a).join("\n")
}

fn to_option_lines<const S: usize, I: AsRef<str>, T>(
    t: &Vec<T>,
    f: fn(&T) -> [I; S],
) -> Vec<ListOption<String>> {
    to_lines(&t.iter().map(f).collect::<Vec<_>>())
        .into_iter()
        .enumerate()
        .map(|(i, e)| ListOption::new(i, e))
        .collect()
}

pub fn select_line<'a, const S: usize, I: AsRef<str>, T>(
    prompt: &'a str,
    t: &Vec<T>,
    f: fn(&T) -> [I; S],
) -> Select<'a, ListOption<String>> {
    Select::new(prompt, to_option_lines(t, f))
}
pub fn select_multiple_line<'a, const S: usize, I: AsRef<str>, T>(
    prompt: &'a str,
    t: &Vec<T>,
    f: fn(&T) -> [I; S],
) -> MultiSelect<'a, ListOption<String>> {
    MultiSelect::new(prompt, to_option_lines(t, f))
}

pub fn input_path<'a>(prompt: &'a str) -> Text {
    Text::new(prompt).with_autocomplete(filepath::Comp::default())
}

mod filepath {
    use crate::com::*;

    #[derive(Clone, Default)]
    pub struct Comp {
        input: String,
        paths: Vec<String>,
    }

    impl Comp {
        fn update_input(&mut self, input: &str) -> Result<(), CustomUserError> {
            if input == self.input {
                return Ok(());
            }

            self.input = input.to_owned();
            self.paths.clear();

            let input_path = PathBuf::from(input);

            let fb = input_path
                .parent()
                .map(|p| {
                    if p.to_string_lossy() == "" {
                        PathBuf::from(".")
                    } else {
                        p.to_owned()
                    }
                })
                .unwrap_or_else(|| PathBuf::from("."));

            let scan_dir = if input.ends_with('/') {
                input_path
            } else {
                fb.clone()
            };

            let entries = match std::fs::read_dir(scan_dir) {
                Ok(r) => r.filter_map(|e| e.ok()).collect(),
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    match std::fs::read_dir(fb) {
                        Ok(r) => r.filter_map(|e| e.ok()).collect(),
                        Err(_) => vec![],
                    }
                }
                Err(_) => vec![],
            };

            for entry in entries {
                let path = entry.path();
                let path_str = if path.is_dir() {
                    format!("{}/", path.to_string_lossy())
                } else {
                    path.to_string_lossy().to_string()
                };

                self.paths.push(path_str);
            }

            Ok(())
        }

        fn fuzzy_sort(&self, input: &str) -> Vec<(String, i64)> {
            let mut matches: Vec<(String, i64)> = self
                .paths
                .iter()
                .filter_map(|path| {
                    SkimMatcherV2::default()
                        .smart_case()
                        .fuzzy_match(path, input)
                        .map(|score| (path.clone(), score))
                })
                .collect();

            matches.sort_by(|a, b| b.1.cmp(&a.1));
            matches
        }
    }

    fn expand(s: &str) -> String {
        match shellexpand::full(s) {
            Ok(e) => e.to_string(),
            Err(_) => s.to_owned(),
        }
    }

    impl Autocomplete for Comp {
        fn get_suggestions(&mut self, input: &str) -> Result<Vec<String>, CustomUserError> {
            let input = &expand(input);
            self.update_input(input)?;

            let matches = self.fuzzy_sort(input);
            Ok(matches.into_iter().take(15).map(|(path, _)| path).collect())
        }

        fn get_completion(
            &mut self,
            input: &str,
            highlighted_suggestion: Option<String>,
        ) -> Result<Replacement, CustomUserError> {
            let input = &expand(input);
            self.update_input(input)?;

            Ok(match highlighted_suggestion {
                Some(e) => Replacement::Some(e),
                None => {
                    let matches = self.fuzzy_sort(input);
                    matches
                        .first()
                        .map(|(path, _)| Replacement::Some(path.clone()))
                        .unwrap_or(Replacement::None)
                }
            })
        }
    }
}