fzf-make 0.15.0

A command line tool that executes make target using fuzzy finder with preview window.
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use crate::models::makefile::Makefile;

use super::ui::ui;
use anyhow::{anyhow, Result};
use colored::Colorize;
use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture, KeyCode, KeyEvent},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use fuzzy_matcher::skim::SkimMatcherV2;
use fuzzy_matcher::FuzzyMatcher;
use ratatui::{
    backend::{Backend, CrosstermBackend},
    widgets::ListState,
    Terminal,
};
use std::{
    io::{self, Stderr},
    panic, process,
};
use tui_textarea::TextArea;

#[derive(Clone, PartialEq, Debug)]
pub enum AppState {
    SelectingTarget,
    ExecuteTarget(Option<String>),
    ShouldQuite,
}

#[derive(Clone, PartialEq, Debug)]
pub enum CurrentPane {
    Main,
    History,
}

impl CurrentPane {
    pub fn is_main(&self) -> bool {
        matches!(self, CurrentPane::Main)
    }

    pub fn is_history(&self) -> bool {
        matches!(self, CurrentPane::History)
    }
}

enum Message {
    MoveToNextPane,
    Quit,
    SearchTextAreaKeyInput(KeyEvent),
    Next,
    Previous,
    ExecuteTarget,
}

#[derive(Clone, PartialEq, Debug)]
pub struct Model<'a> {
    pub app_state: AppState,
    pub current_pane: CurrentPane,
    pub makefile: Makefile,
    pub targets_list_state: ListState,
    pub search_text_area: TextArea_<'a>,
}

#[derive(Clone, Debug)]
pub struct TextArea_<'a>(pub TextArea<'a>);

impl<'a> PartialEq for TextArea_<'a> {
    // for testing
    fn eq(&self, other: &Self) -> bool {
        self.0.lines().join("") == other.0.lines().join("")
    }
}

impl Model<'_> {
    pub fn new() -> Result<Self> {
        let makefile = match Makefile::create_makefile() {
            Err(e) => return Err(e),
            Ok(f) => f,
        };
        Ok(Model {
            app_state: AppState::SelectingTarget,
            current_pane: CurrentPane::Main,
            makefile: makefile.clone(),
            targets_list_state: ListState::with_selected(ListState::default(), Some(0)),
            search_text_area: TextArea_(TextArea::default()),
        })
    }

    pub fn narrow_down_targets(&self) -> Vec<String> {
        if self.search_text_area.0.is_empty() {
            return self.makefile.to_targets_string();
        }

        let matcher = SkimMatcherV2::default();
        let mut filtered_list: Vec<(Option<i64>, String)> = self
            .makefile
            .to_targets_string()
            .into_iter()
            .map(|target| {
                let mut key_input = self.search_text_area.0.lines().join("");
                key_input.retain(|c| !c.is_whitespace());
                match matcher.fuzzy_indices(&target, key_input.as_str()) {
                    Some((score, _)) => (Some(score), target),
                    None => (None, String::new()),
                }
            })
            .filter(|(score, _)| score.is_some())
            .collect();

        filtered_list.sort_by(|(score1, _), (score2, _)| score1.cmp(score2));
        filtered_list.reverse();

        filtered_list
            .into_iter()
            .map(|(_, target)| target)
            .collect()
    }

    fn next(&mut self) {
        let i = match self.targets_list_state.selected() {
            Some(i) => {
                if self.narrow_down_targets().len() - 1 <= i {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.targets_list_state.select(Some(i));
    }

    fn previous(&mut self) {
        let i = match self.targets_list_state.selected() {
            Some(i) => {
                if i == 0 {
                    self.narrow_down_targets().len() - 1
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.targets_list_state.select(Some(i));
    }

    fn reset_selection(&mut self) {
        if self.narrow_down_targets().is_empty() {
            self.targets_list_state.select(None);
        }
        self.targets_list_state.select(Some(0));
    }

    fn selected_target(&self) -> Option<String> {
        match self.targets_list_state.selected() {
            Some(i) => self.narrow_down_targets().get(i).map(|s| s.to_string()),
            None => None,
        }
    }

    pub fn should_quit(&self) -> bool {
        self.app_state == AppState::ShouldQuite
    }

    pub fn is_target_selected(&self) -> bool {
        matches!(self.app_state, AppState::ExecuteTarget(_))
    }

    pub fn target_to_execute(&self) -> Option<String> {
        match self.app_state.clone() {
            AppState::ExecuteTarget(Some(target)) => Some(target.clone()),
            _ => None,
        }
    }
}

pub fn main() -> Result<()> {
    let result = panic::catch_unwind(|| {
        enable_raw_mode()?;
        let mut stderr = io::stderr();
        execute!(stderr, EnterAlternateScreen, EnableMouseCapture)?;
        let backend = CrosstermBackend::new(stderr);
        let mut terminal = Terminal::new(backend)?;

        let target: Result<Option<String>> = match Model::new() {
            Err(e) => Err(e),
            Ok(model) => run(&mut terminal, model),
        };

        let target = match target {
            Ok(t) => t,
            Err(e) => {
                shutdown_terminal(&mut terminal)?;
                return Err(e);
            }
        };

        shutdown_terminal(&mut terminal)?;

        match target {
            Some(t) => {
                // Make output color configurable via config file https://github.com/kyu08/fzf-make/issues/67
                println!("{}", ("make ".to_string() + &t).blue());
                process::Command::new("make")
                    .stdin(process::Stdio::inherit())
                    .arg(t)
                    .spawn()
                    .expect("Failed to execute process")
                    .wait()
                    .expect("Failed to execute process");

                Ok(())
            }
            None => {
                println!("{}", ("no target selected.".to_string()).red());
                Ok(())
            }
        }
    });

    match result {
        Ok(usecase_result) => usecase_result,
        Err(e) => {
            disable_raw_mode()?;
            execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture)?;
            println!("panic: {:?}", e);
            process::exit(1);
        }
    }
}

fn run<B: Backend>(terminal: &mut Terminal<B>, mut model: Model) -> Result<Option<String>> {
    loop {
        if let Err(e) = terminal.draw(|f| ui(f, &mut model.clone())) {
            return Err(anyhow!(e));
        }
        match handle_event(&model) {
            Ok(message) => {
                update(&mut model, message);
                if model.should_quit() || model.is_target_selected() {
                    break;
                }
            }
            Err(_) => break,
        }
    }
    Ok(model.target_to_execute())
}

fn handle_event(model: &Model) -> io::Result<Option<Message>> {
    let message = if crossterm::event::poll(std::time::Duration::from_millis(2000))? {
        if let crossterm::event::Event::Key(key) = crossterm::event::read()? {
            match model.app_state {
                AppState::SelectingTarget => match key.code {
                    KeyCode::Tab => Some(Message::MoveToNextPane),
                    KeyCode::Esc => Some(Message::Quit),
                    _ => match model.current_pane {
                        CurrentPane::Main => match key.code {
                            KeyCode::Down => Some(Message::Next),
                            KeyCode::Up => Some(Message::Previous),
                            KeyCode::Enter => Some(Message::ExecuteTarget),
                            _ => Some(Message::SearchTextAreaKeyInput(key)),
                        },
                        CurrentPane::History => match key.code {
                            KeyCode::Char('q') => Some(Message::Quit),
                            _ => None,
                        },
                    },
                },
                _ => None,
            }
        } else {
            return Ok(None);
        }
    } else {
        return Ok(None);
    };
    Ok(message)
}

fn update(model: &mut Model, message: Option<Message>) {
    match message {
        Some(Message::MoveToNextPane) => match model.current_pane {
            CurrentPane::Main => model.current_pane = CurrentPane::History,
            CurrentPane::History => model.current_pane = CurrentPane::Main,
        },
        Some(Message::Quit) => model.app_state = AppState::ShouldQuite,
        Some(Message::Next) => model.next(),
        Some(Message::Previous) => model.previous(),
        Some(Message::ExecuteTarget) => {
            model.app_state = AppState::ExecuteTarget(model.selected_target());
        }
        Some(Message::SearchTextAreaKeyInput(key_event)) => {
            if let KeyCode::Char(_) = key_event.code {
                model.reset_selection();
            };
            model.search_text_area.0.input(key_event);
        }
        None => {}
    }
}

fn shutdown_terminal(terminal: &mut Terminal<CrosstermBackend<Stderr>>) -> Result<()> {
    if let Err(e) = disable_raw_mode() {
        return Err(anyhow!(e));
    }

    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;

    if let Err(e) = terminal.show_cursor() {
        return Err(anyhow!(e));
    }

    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;
    use tui_textarea::TextArea;

    fn init_model<'a>() -> Model<'a> {
        Model {
            app_state: AppState::SelectingTarget,
            current_pane: CurrentPane::Main,
            makefile: Makefile::new_for_test(),
            targets_list_state: ListState::with_selected(ListState::default(), Some(0)),
            search_text_area: TextArea_(TextArea::default()),
        }
    }

    #[test]
    fn update_test() {
        struct Case<'a> {
            title: &'static str,
            model: Model<'a>,
            message: Option<Message>,
            expect_model: Model<'a>,
        }
        let cases: Vec<Case> = vec![
            Case {
                title: "MoveToNextPane(Main -> History)",
                model: init_model(),
                message: Some(Message::MoveToNextPane),
                expect_model: Model {
                    current_pane: CurrentPane::History,
                    ..init_model()
                },
            },
            Case {
                title: "MoveToNextPane(History -> Main)",
                model: Model {
                    current_pane: CurrentPane::History,
                    ..init_model()
                },
                message: Some(Message::MoveToNextPane),
                expect_model: Model {
                    current_pane: CurrentPane::Main,
                    ..init_model()
                },
            },
            Case {
                title: "Quit",
                model: init_model(),
                message: Some(Message::Quit),
                expect_model: Model {
                    app_state: AppState::ShouldQuite,
                    ..init_model()
                },
            },
            Case {
                title: "SearchTextAreaKeyInput(a)",
                model: init_model(),
                message: Some(Message::SearchTextAreaKeyInput(KeyEvent::from(
                    KeyCode::Char('a'),
                ))),
                expect_model: Model {
                    search_text_area: {
                        let mut text_area = TextArea::default();
                        text_area.input(KeyEvent::from(KeyCode::Char('a')));
                        TextArea_(text_area)
                    },
                    ..init_model()
                },
            },
            Case {
                title: "Next(0 -> 1)",
                model: init_model(),
                message: Some(Message::Next),
                expect_model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(1)),
                    ..init_model()
                },
            },
            Case {
                title: "Next(2 -> 0)",
                model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(2)),
                    ..init_model()
                },
                message: Some(Message::Next),
                expect_model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(0)),
                    ..init_model()
                },
            },
            Case {
                title: "Previous(1 -> 0)",
                model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(1)),
                    ..init_model()
                },
                message: Some(Message::Previous),
                expect_model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(0)),
                    ..init_model()
                },
            },
            Case {
                title: "Previous(0 -> 2)",
                model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(0)),
                    ..init_model()
                },
                message: Some(Message::Previous),
                expect_model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(2)),
                    ..init_model()
                },
            },
            Case {
                title: "ExecuteTarget",
                model: Model { ..init_model() },
                message: Some(Message::ExecuteTarget),
                expect_model: Model {
                    app_state: AppState::ExecuteTarget(Some("target0".to_string())),
                    ..init_model()
                },
            },
            Case {
                title: "After Next, if char was inputted, select should be reset",
                model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(1)),
                    ..init_model()
                },
                message: Some(Message::SearchTextAreaKeyInput(KeyEvent::from(
                    KeyCode::Char('a'),
                ))),
                expect_model: Model {
                    targets_list_state: ListState::with_selected(ListState::default(), Some(0)),
                    search_text_area: {
                        let mut text_area = TextArea::default();
                        text_area.input(KeyEvent::from(KeyCode::Char('a')));
                        TextArea_(text_area)
                    },
                    ..init_model()
                },
            },
        ];

        for mut case in cases {
            update(&mut case.model, case.message);
            assert_eq!(
                case.expect_model, case.model,
                "\nFailed: 🚨{:?}🚨\n",
                case.title,
            );
        }
    }
}