summaryrefslogtreecommitdiffstats
path: root/src/actor.rs
blob: 238e13ddc17bcd948a73622a03943bd58b54c848 (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
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
use crate::clipboard;
use crate::config::Action;
use crate::config::CONFIG;
use crate::env_var;
use crate::extractor;
use crate::finder::structures::{Opts as FinderOpts, SuggestionType};
use crate::finder::Finder;
use crate::fs;
use crate::shell;
use crate::shell::ShellSpawnError;
use crate::structures::cheat::{Suggestion, VariableMap};
use crate::writer;
use anyhow::Context;
use anyhow::Result;
use shell::EOF;
use std::io::Write;
use std::path::Path;
use std::process::Stdio;

fn prompt_finder(
    variable_name: &str,
    suggestion: Option<&Suggestion>,
    variable_count: usize,
) -> Result<String> {
    env_var::remove(env_var::PREVIEW_COLUMN);
    env_var::remove(env_var::PREVIEW_DELIMITER);
    env_var::remove(env_var::PREVIEW_MAP);

    let mut extra_preview: Option<String> = None;

    let (suggestions, initial_opts) = if let Some(s) = suggestion {
        let (suggestion_command, suggestion_opts) = s;

        if let Some(sopts) = suggestion_opts {
            if let Some(c) = &sopts.column {
                env_var::set(env_var::PREVIEW_COLUMN, c.to_string());
            }
            if let Some(d) = &sopts.delimiter {
                env_var::set(env_var::PREVIEW_DELIMITER, d);
            }
            if let Some(m) = &sopts.map {
                env_var::set(env_var::PREVIEW_MAP, m);
            }
            if let Some(p) = &sopts.preview {
                extra_preview = Some(p.into());
            }
        }

        let child = shell::out()
            .stdout(Stdio::piped())
            .arg(&suggestion_command)
            .spawn()
            .map_err(|e| ShellSpawnError::new(suggestion_command, e))?;

        let text = String::from_utf8(
            child
                .wait_with_output()
                .context("Failed to wait and collect output from bash")?
                .stdout,
        )
        .context("Suggestions are invalid utf8")?;

        (text, suggestion_opts)
    } else {
        ('\n'.to_string(), &None)
    };

    let overrides = {
        let mut o = CONFIG.fzf_overrides_var();
        if let Some(io) = initial_opts {
            if io.overrides.is_some() {
                o = io.overrides.clone()
            }
        }
        o
    };

    let exe = fs::exe_string()?;
    let extra = extra_preview.clone().unwrap_or_default();

    let preview = if cfg!(target_os = "windows") {
        format!(
            r#"(@echo.{{+}}{eof}{{q}}{eof}{name}){eof}{extra} | {exe} preview-var-stdin"#,
            exe = exe,
            name = variable_name,
            extra = extra,
            eof = EOF,
        )
    } else {
        format!(
            r#"{exe} preview-var "$(cat <<{eof}
{{+}}
{eof}
)" "$(cat <<{eof}
{{q}}
{eof}
)" "{name}"; {extra}"#,
            exe = exe,
            name = variable_name,
            extra = extra,
            eof = EOF,
        )
    };

    let mut opts = FinderOpts {
        overrides,
        preview: Some(preview),
        ..initial_opts.clone().unwrap_or_default()
    };

    opts.query = env_var::get(format!("{}__query", variable_name)).ok();

    if let Ok(f) = env_var::get(format!("{}__best", variable_name)) {
        opts.filter = Some(f);
        opts.suggestion_type = SuggestionType::SingleSelection;
    }

    if opts.preview_window.is_none() {
        opts.preview_window = Some(if extra_preview.is_none() {
            format!("up:{}", variable_count + 3)
        } else {
            "right:50%".to_string()
        });
    }

    if suggestion.is_none() {
        opts.suggestion_type = SuggestionType::Disabled;
    };

    let (output, _, _) = CONFIG
        .finder()
        .call(opts, |stdin, _| {
            stdin
                .write_all(suggestions.as_bytes())
                .context("Could not write to finder's stdin")?;
            Ok(None)
        })
        .context("finder was unable to prompt with suggestions")?;

    Ok(output)
}

fn unique_result_count(results: &[&str]) -> usize {
    let mut vars = results.to_owned();
    vars.sort_unstable();
    vars.dedup();
    vars.len()
}

fn replace_variables_from_snippet(snippet: &str, tags: &str, variables: VariableMap) -> Result<String> {
    let mut interpolated_snippet = String::from(snippet);
    let variables_found: Vec<&str> = writer::VAR_REGEX.find_iter(snippet).map(|m| m.as_str()).collect();
    let variable_count = unique_result_count(&variables_found);

    for bracketed_variable_name in variables_found {
        let variable_name = &bracketed_variable_name[1..bracketed_variable_name.len() - 1];

        let env_variable_name = env_var::escape(variable_name);
        let env_value = env_var::get(&env_variable_name);

        let value = if let Ok(e) = env_value {
            e
        } else if let Some(suggestion) = variables.get_suggestion(&tags, &variable_name) {
            let mut new_suggestion = suggestion.clone();
            new_suggestion.0 = replace_variables_from_snippet(&new_suggestion.0, tags, variables.clone())?;
            prompt_finder(variable_name, Some(&new_suggestion), variable_count)?
        } else {
            prompt_finder(variable_name, None, variable_count)?
        };

        env_var::set(env_variable_name, &value);

        interpolated_snippet = if value.as_str() == "\n" {
            interpolated_snippet.replacen(bracketed_variable_name, "", 1)
        } else {
            interpolated_snippet.replacen(bracketed_variable_name, value.as_str(), 1)
        };
    }

    Ok(interpolated_snippet)
}

// TODO: make it depend on less inputs
pub fn act(
    extractions: Result<extractor::Output>,
    files: Vec<String>,
    variables: Option<VariableMap>,
) -> Result<()> {
    let (key, tags, comment, snippet, file_index) = extractions.unwrap();

    if key == "ctrl-o" {
        edit::edit_file(Path::new(&files[file_index.expect("No files found")]))
            .expect("Could not open file in external editor");
        return Ok(());
    }

    env_var::set(env_var::PREVIEW_INITIAL_SNIPPET, &snippet);
    env_var::set(env_var::PREVIEW_TAGS, &tags);
    env_var::set(env_var::PREVIEW_COMMENT, &comment);

    let interpolated_snippet = writer::with_new_lines(
        replace_variables_from_snippet(
            snippet,
            tags,
            variables.expect("No variables received from finder"),
        )
        .context("Failed to replace variables from snippet")?,
    );

    match CONFIG.action() {
        Action::Print => {
            println!("{}", interpolated_snippet);
        }
        Action::Execute => match key {
            "ctrl-y" => {
                clipboard::copy(interpolated_snippet)?;
            }
            _ => {
                shell::out()
                    .arg(&interpolated_snippet[..])
                    .spawn()
                    .map_err(|e| ShellSpawnError::new(&interpolated_snippet[..], e))?
                    .wait()
                    .context("bash was not running")?;
            }
        },
    };

    Ok(())
}