summaryrefslogtreecommitdiffstats
path: root/src/commands/fzf.rs
blob: 8aeaa1ba6ebfcef6d092f4e85aa9fc1bd4e76b41 (plain)
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
use std::io::{BufWriter, Write};
use std::process::{Command, Stdio};
use std::str::from_utf8;

use crate::config::clean::app::search::CaseSensitivity;
use crate::context::AppContext;
use crate::error::{AppError, AppResult};
use crate::ui::AppBackend;

pub fn fzf(
    context: &mut AppContext,
    backend: &mut AppBackend,
    items: Vec<String>,
) -> AppResult<String> {
    let mut args = Vec::new();

    let case_sensitivity = context
        .config_ref()
        .search_options_ref()
        .fzf_case_sensitivity;

    match case_sensitivity {
        CaseSensitivity::Insensitive => args.push("-i".to_owned()),
        CaseSensitivity::Sensitive => args.push("+i".to_owned()),
        CaseSensitivity::Smart => {}
    }

    fzf_impl(backend, items, args)
}

pub fn fzf_multi(
    context: &mut AppContext,
    backend: &mut AppBackend,
    items: Vec<String>,
) -> AppResult<String> {
    let mut args = Vec::new();

    let case_sensitivity = context
        .config_ref()
        .search_options_ref()
        .fzf_case_sensitivity;

    match case_sensitivity {
        CaseSensitivity::Insensitive => args.push("-i".to_owned()),
        CaseSensitivity::Sensitive => args.push("+i".to_owned()),
        CaseSensitivity::Smart => {}
    }

    args.push("-m".to_owned());
    fzf_impl(backend, items, args)
}

fn fzf_impl(backend: &mut AppBackend, items: Vec<String>, args: Vec<String>) -> AppResult<String> {
    backend.terminal_drop();

    let mut cmd = Command::new("fzf");
    cmd.stdout(Stdio::piped()).args(&args);

    if !items.is_empty() {
        cmd.stdin(Stdio::piped());
    }

    let mut fzf = match cmd.spawn() {
        Ok(child) => child,
        Err(e) => {
            backend.terminal_restore()?;
            return Err(AppError::from(e));
        }
    };

    if let Some(fzf_stdin) = fzf.stdin.as_mut() {
        let mut writer = BufWriter::new(fzf_stdin);

        for item in items {
            writer.write_all(item.as_bytes())?;
        }
    }

    let fzf_output = fzf.wait_with_output();
    backend.terminal_restore()?;

    if let Ok(output) = fzf_output {
        if output.status.success() {
            if let Ok(output) = from_utf8(&output.stdout) {
                return Ok(output.to_owned());
            }
        }
    }

    Ok(String::new())
}