summaryrefslogtreecommitdiffstats
path: root/src/flows/core.rs
blob: c2814ed4d989b9be59f9e89e22a43d028fec9aa7 (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
use crate::display;
use crate::filesystem;
use crate::flows;
use crate::fzf;
use crate::handler;
use crate::parser;
use crate::structures::cheat::{Suggestion, VariableMap};
use crate::structures::fzf::{Opts as FzfOpts, SuggestionType};
use crate::structures::option;
use crate::structures::option::Config;
use regex::Regex;
use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::io::Write;
use std::process::{Command, Stdio};

pub enum Variant {
    Core,
    Filter(String),
    Query(String),
}

fn gen_core_fzf_opts(variant: Variant, config: &Config) -> FzfOpts {
    let mut opts = FzfOpts {
        preview: if config.no_preview {
            None
        } else {
            Some(format!("{} preview {{}}", filesystem::exe_string()))
        },
        autoselect: !config.no_autoselect,
        overrides: config.fzf_overrides.clone(),
        suggestion_type: SuggestionType::SnippetSelection,
        ..Default::default()
    };

    match variant {
        Variant::Core => (),
        Variant::Filter(f) => opts.filter = Some(f),
        Variant::Query(q) => opts.query = Some(q),
    }

    opts
}

fn extract_from_selections(raw_snippet: &str, contains_key: bool) -> (&str, &str, &str) {
    let mut lines = raw_snippet.split('\n');
    let key = if contains_key {
        lines.next().unwrap()
    } else {
        "enter"
    };

    let mut parts = lines.next().unwrap().split(display::DELIMITER);
    parts.next();
    parts.next();
    parts.next();

    let tags = parts.next().unwrap_or("");
    parts.next();

    let snippet = parts.next().unwrap_or("");
    (key, tags, snippet)
}

fn prompt_with_suggestions(
    varname: &str,
    config: &Config,
    suggestion: &Suggestion,
    values: &HashMap<String, String>,
) -> String {
    let mut vars_cmd = String::from("");
    for (key, value) in values.iter() {
        vars_cmd.push_str(format!("{}=\"{}\"; ", key, value).as_str());
    }
    let (suggestion_command, suggestion_opts) = suggestion;
    let command = format!("{} {}", vars_cmd, suggestion_command);

    let child = Command::new("bash")
        .stdout(Stdio::piped())
        .arg("-c")
        .arg(command)
        .spawn()
        .unwrap();

    let suggestions = String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap();

    let opts = suggestion_opts.clone().unwrap_or_default();
    let opts = FzfOpts {
        autoselect: !config.no_autoselect,
        overrides: config.fzf_overrides_var.clone(),
        prompt: Some(display::variable_prompt(varname)),
        ..opts
    };

    let (output, _) = fzf::call(opts, |stdin| {
        stdin.write_all(suggestions.as_bytes()).unwrap();
        None
    });

    output
}

fn prompt_without_suggestions(variable_name: &str) -> String {
    let opts = FzfOpts {
        autoselect: false,
        prompt: Some(display::variable_prompt(variable_name)),
        suggestion_type: SuggestionType::Disabled,
        ..Default::default()
    };

    let (output, _) = fzf::call(opts, |_stdin| None);

    output
}

fn replace_variables_from_snippet(
    snippet: &str,
    tags: &str,
    variables: VariableMap,
    config: &Config,
) -> String {
    let mut interpolated_snippet = String::from(snippet);
    let mut values: HashMap<String, String> = HashMap::new();

    let re = Regex::new(r"<(\w[\w\d\-_]*)>").unwrap();
    for captures in re.captures_iter(snippet) {
        let bracketed_variable_name = &captures[0];
        let variable_name = &bracketed_variable_name[1..bracketed_variable_name.len() - 1];

        let value = values
            .get(variable_name)
            .map(|s| s.to_string())
            .unwrap_or_else(|| {
                variables
                    .get(&tags, &variable_name)
                    .map(|suggestion| {
                        prompt_with_suggestions(variable_name, &config, suggestion, &values)
                    })
                    .unwrap_or_else(|| prompt_without_suggestions(variable_name))
            });

        values.insert(variable_name.to_string(), value.clone());

        interpolated_snippet =
            interpolated_snippet.replacen(bracketed_variable_name, value.as_str(), 1);
    }

    interpolated_snippet
}

fn with_new_lines(txt: String) -> String {
    txt.replace(display::LINE_SEPARATOR, "\n")
}

pub fn main(variant: Variant, config: Config, contains_key: bool) -> Result<(), Box<dyn Error>> {
    let _ = display::WIDTHS;

    let opts = gen_core_fzf_opts(variant, &config);
    let (raw_selection, variables) =
        fzf::call(opts, |stdin| Some(parser::read_all(&config, stdin)));

    let (key, tags, snippet) = extract_from_selections(&raw_selection[..], contains_key);

    let interpolated_snippet = with_new_lines(replace_variables_from_snippet(
        snippet,
        tags,
        variables.unwrap(),
        &config,
    ));

    // copy to clipboard
    if key == "ctrl-y" {
        flows::aux::abort("copying snippets to the clipboard", 201)?
    // print to stdout
    } else if config.print {
        println!("{}", interpolated_snippet);
    // save to file
    } else if let Some(s) = config.save {
        fs::write(s, interpolated_snippet)?;
    // call navi (this prevents "failed to read /dev/tty" from fzf)
    } else if interpolated_snippet.starts_with("navi") {
        let new_config = option::config_from_iter(interpolated_snippet.split(' ').collect());
        handler::handle_config(new_config)?;
    // shell out and execute snippet
    } else {
        Command::new("bash")
            .arg("-c")
            .arg(&interpolated_snippet[..])
            .spawn()?;
    }

    Ok(())
}