summaryrefslogtreecommitdiffstats
path: root/src/finder/mod.rs
blob: 9b4ccfd1d37465079a1ceaf60d42361bfee3901f (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
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
use crate::deser;
use crate::prelude::*;
use std::io::Write;
use std::process::{self, Output};
use std::process::{Command, Stdio};
pub mod structures;
use clap::ValueEnum;
pub use post::process;
use structures::Opts;
use structures::SuggestionType;

mod post;

#[derive(Debug, Clone, Copy, Deserialize, ValueEnum)]
pub enum FinderChoice {
    Fzf,
    Skim,
}

impl FromStr for FinderChoice {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "fzf" => Ok(FinderChoice::Fzf),
            "skim" => Ok(FinderChoice::Skim),
            _ => Err("no match"),
        }
    }
}

fn parse(out: Output, opts: Opts) -> Result<String> {
    let text = match out.status.code() {
        Some(0) | Some(1) | Some(2) => {
            String::from_utf8(out.stdout).context("Invalid utf8 received from finder")?
        }
        Some(130) => process::exit(130),
        _ => {
            let err = String::from_utf8(out.stderr)
                .unwrap_or_else(|_| "<stderr contains invalid UTF-8>".to_owned());
            panic!("External command failed:\n {err}")
        }
    };

    let output = post::parse_output_single(text, opts.suggestion_type)?;
    post::process(output, opts.column, opts.delimiter.as_deref(), opts.map)
}

impl FinderChoice {
    pub fn call<F, R>(&self, finder_opts: Opts, stdin_fn: F) -> Result<(String, R)>
    where
        F: Fn(&mut dyn Write) -> Result<R>,
    {
        let finder_str = match self {
            Self::Fzf => "fzf",
            Self::Skim => "sk",
        };

        let mut command = Command::new(finder_str);
        let opts = finder_opts.clone();

        let preview_height = match self {
            FinderChoice::Skim => 3,
            _ => 2,
        };

        let bindings = if opts.suggestion_type == SuggestionType::MultipleSelections {
            ",ctrl-r:toggle-all"
        } else {
            ""
        };

        command.args([
            "--preview",
            "",
            "--preview-window",
            format!("up:{preview_height}:nohidden").as_str(),
            "--delimiter",
            deser::terminal::DELIMITER.to_string().as_str(),
            "--ansi",
            "--bind",
            format!("ctrl-j:down,ctrl-k:up{bindings}").as_str(),
            "--exact",
        ]);

        if !opts.show_all_columns {
            command.args(["--with-nth", "1,2,3"]);
        }

        if !opts.prevent_select1 {
            if let Self::Fzf = self {
                command.arg("--select-1");
            }
        }

        match opts.suggestion_type {
            SuggestionType::MultipleSelections => {
                command.arg("--multi");
            }
            SuggestionType::Disabled => {
                if let Self::Fzf = self {
                    command.args(["--print-query", "--no-select-1"]);
                };
            }
            SuggestionType::SnippetSelection => {
                command.args(["--expect", "ctrl-y,ctrl-o,enter"]);
            }
            SuggestionType::SingleRecommendation => {
                command.args(["--print-query", "--expect", "tab,enter"]);
            }
            _ => {}
        }

        if let Some(p) = opts.preview {
            command.args(["--preview", &p]);
        }

        if let Some(q) = opts.query {
            command.args(["--query", &q]);
        }

        if let Some(f) = opts.filter {
            command.args(["--filter", &f]);
        }

        if let Some(d) = opts.delimiter {
            command.args(["--delimiter", &d]);
        }

        if let Some(h) = opts.header {
            command.args(["--header", &h]);
        }

        if let Some(p) = opts.prompt {
            command.args(["--prompt", &p]);
        }

        if let Some(pw) = opts.preview_window {
            command.args(["--preview-window", &pw]);
        }

        if opts.header_lines > 0 {
            command.args(["--header-lines", format!("{}", opts.header_lines).as_str()]);
        }

        if let Some(o) = opts.overrides {
            shellwords::split(&o)?
                .into_iter()
                .filter(|s| !s.is_empty())
                .for_each(|s| {
                    command.arg(s);
                });
        }

        command
            .env("SHELL", CONFIG.finder_shell())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped());
        debug!(cmd = ?command);

        let child = command.spawn();

        let mut child = match child {
            Ok(x) => x,
            Err(_) => {
                let repo = match self {
                    Self::Fzf => "https://github.com/junegunn/fzf",
                    Self::Skim => "https://github.com/lotabout/skim",
                };
                eprintln!(
                    "navi was unable to call {cmd}.
                Please make sure it's correctly installed.
                Refer to {repo} for more info.",
                    cmd = &finder_str,
                    repo = repo
                );
                process::exit(33)
            }
        };

        let stdin = child
            .stdin
            .as_mut()
            .ok_or_else(|| anyhow!("Unable to acquire stdin of finder"))?;

        let mut writer: Box<&mut dyn Write> = Box::new(stdin);

        let return_value = stdin_fn(&mut writer).context("Failed to pass data to finder")?;

        let out = child.wait_with_output().context("Failed to wait for finder")?;

        let output = parse(out, finder_opts).context("Unable to get output")?;
        Ok((output, return_value))
    }
}