diff --git a/src/cheatsh.rs b/src/cheatsh.rs index 9cec1ec..224e9fc 100644 --- a/src/cheatsh.rs +++ b/src/cheatsh.rs @@ -27,7 +27,7 @@ fn lines(query: &str, markdown: &str) -> impl Iterator Result, Error> { let mut variables = VariableMap::new(); let mut visited_lines = HashSet::new(); - parser::read_lines(lines(query, cheat), "cheat.sh", &mut variables, &mut visited_lines, writer, stdin)?; + parser::read_lines(lines(query, cheat), "cheat.sh", 0, &mut variables, &mut visited_lines, writer, stdin)?; Ok(Some(variables)) } @@ -85,7 +85,7 @@ impl Fetcher { } impl fetcher::Fetcher for Fetcher { - fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer) -> Result, Error> { + fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer, _files: &mut Vec) -> Result, Error> { let cheat = fetch(&self.query)?; read_all(&self.query, &cheat, stdin, writer) } diff --git a/src/cmds/alfred.rs b/src/cmds/alfred.rs index b541c8d..4898ba5 100644 --- a/src/cmds/alfred.rs +++ b/src/cmds/alfred.rs @@ -18,7 +18,7 @@ pub fn main(config: Config) -> Result<(), Error> { let fetcher = filesystem::Fetcher::new(config.path); fetcher - .fetch(stdin, &mut writer) + .fetch(stdin, &mut writer, &mut Vec::new()) .context("Failed to parse variables intended for finder")?; // make sure everything was printed to stdout before attempting to close the items vector @@ -55,7 +55,7 @@ pub fn suggestions(config: Config, dry_run: bool) -> Result<(), Error> { let fetcher = filesystem::Fetcher::new(config.path); let variables = fetcher - .fetch(stdin, &mut writer) + .fetch(stdin, &mut writer, &mut Vec::new()) .context("Failed to parse variables intended for finder")? .expect("Empty variable map"); diff --git a/src/cmds/core.rs b/src/cmds/core.rs index c0cf89a..58e5177 100644 --- a/src/cmds/core.rs +++ b/src/cmds/core.rs @@ -40,7 +40,7 @@ fn gen_core_finder_opts(config: &Config) -> Result { Ok(opts) } -fn extract_from_selections(raw_snippet: &str, is_single: bool) -> Result<(&str, &str, &str, &str, &str), Error> { +fn extract_from_selections(raw_snippet: &str, is_single: bool) -> Result<(&str, &str, &str, &str, Option), Error> { let mut lines = raw_snippet.split('\n'); let key = if is_single { "enter" @@ -53,8 +53,8 @@ fn extract_from_selections(raw_snippet: &str, is_single: bool) -> Result<(&str, let tags = parts.next().unwrap_or(""); let comment = parts.next().unwrap_or(""); let snippet = parts.next().unwrap_or(""); - let suggestion_file = parts.next().unwrap_or(""); - Ok((key, tags, comment, snippet, suggestion_file)) + let file_index = parts.next().unwrap_or("").parse().ok(); + Ok((key, tags, comment, snippet, file_index)) } fn prompt_finder(variable_name: &str, config: &Config, suggestion: Option<&Suggestion>, variable_count: usize) -> Result { @@ -137,7 +137,7 @@ NAVIEOF let (output, _) = config .finder - .call(opts, |stdin| { + .call(opts, &mut Vec::new(), |stdin, _| { stdin.write_all(suggestions.as_bytes()).context("Could not write to finder's stdin")?; Ok(None) }) @@ -188,9 +188,11 @@ fn replace_variables_from_snippet(snippet: &str, tags: &str, variables: Variable pub fn main(config: Config) -> Result<(), Error> { let opts = gen_core_finder_opts(&config).context("Failed to generate finder options")?; + let mut files = Vec::new(); + let (raw_selection, variables) = config .finder - .call(opts, |stdin| { + .call(opts, &mut files, |stdin, files| { let mut writer = display::terminal::Writer::new(); let fetcher: Box = match config.source() { @@ -200,7 +202,7 @@ pub fn main(config: Config) -> Result<(), Error> { }; let res = fetcher - .fetch(stdin, &mut writer) + .fetch(stdin, &mut writer, files) .context("Failed to parse variables intended for finder")?; if let Some(variables) = res { @@ -212,7 +214,7 @@ pub fn main(config: Config) -> Result<(), Error> { }) .context("Failed getting selection and variables from finder")?; - let (key, tags, comment, snippet, suggestion_file) = extract_from_selections(&raw_selection, config.get_best_match())?; + let (key, tags, comment, snippet, file_index) = extract_from_selections(&raw_selection, config.get_best_match())?; env::set_var(env_vars::PREVIEW_INITIAL_SNIPPET, &snippet); env::set_var(env_vars::PREVIEW_TAGS, &tags); @@ -234,7 +236,7 @@ pub fn main(config: Config) -> Result<(), Error> { if key == "ctrl-y" { clipboard::copy(interpolated_snippet)?; } else if key == "ctrl-o" { - edit::edit_file(Path::new(suggestion_file)).expect("Cound not open file in external editor"); + edit::edit_file(Path::new(&files[file_index.expect("No files found")])).expect("Cound not open file in external editor"); } else { Command::new("bash") .arg("-c") diff --git a/src/cmds/repo.rs b/src/cmds/repo.rs index b0b323a..8e5ea5f 100644 --- a/src/cmds/repo.rs +++ b/src/cmds/repo.rs @@ -25,7 +25,7 @@ pub fn browse(finder: &FinderChoice) -> Result<(), Error> { }; let (repo, _) = finder - .call(opts, |stdin| { + .call(opts, &mut Vec::new(), |stdin, _| { stdin.write_all(repos.as_bytes()).context("Unable to prompt featured repositories")?; Ok(None) }) @@ -44,7 +44,7 @@ pub fn ask_if_should_import_all(finder: &FinderChoice) -> Result { }; let (response, _) = finder - .call(opts, |stdin| { + .call(opts, &mut Vec::new(), |stdin, _| { stdin.write_all(b"Yes\nNo").context("Unable to writer alternatives")?; Ok(None) }) @@ -85,7 +85,7 @@ pub fn add(uri: String, finder: &FinderChoice) -> Result<(), Error> { all_files } else { let (files, _) = finder - .call(opts, |stdin| { + .call(opts, &mut Vec::new(), |stdin, _| { stdin.write_all(all_files.as_bytes()).context("Unable to prompt cheats to import")?; Ok(None) }) diff --git a/src/display/terminal.rs b/src/display/terminal.rs index 19533dc..ed864fd 100644 --- a/src/display/terminal.rs +++ b/src/display/terminal.rs @@ -152,7 +152,7 @@ impl Writer { impl display::Writer for Writer { fn write(&mut self, item: Item) -> String { format!( - "{tag_color}{tags_short}{delimiter}{comment_color}{comment_short}{delimiter}{snippet_color}{snippet_short}{delimiter}{tags}{delimiter}{comment}{delimiter}{snippet}{delimiter}{file}{delimiter}\n", + "{tag_color}{tags_short}{delimiter}{comment_color}{comment_short}{delimiter}{snippet_color}{snippet_short}{delimiter}{tags}{delimiter}{comment}{delimiter}{snippet}{delimiter}{file_index}{delimiter}\n", tags_short = limit_str(item.tags, self.tag_width), comment_short = limit_str(item.comment, self.comment_width), snippet_short = display::fix_newlines(item.snippet), @@ -163,7 +163,7 @@ impl display::Writer for Writer { comment = item.comment, delimiter = display::DELIMITER, snippet = &item.snippet, - file = item.file, + file_index = item.file_index, ) } } diff --git a/src/fetcher/filesystem.rs b/src/fetcher/filesystem.rs index 2efb824..37fcd25 100644 --- a/src/fetcher/filesystem.rs +++ b/src/fetcher/filesystem.rs @@ -31,13 +31,14 @@ fn paths_from_path_param<'a>(env_var: &'a str) -> impl Iterator // TODO: move fn read_file( path: &str, + file_index: usize, variables: &mut VariableMap, visited_lines: &mut HashSet, writer: &mut dyn Writer, stdin: &mut std::process::ChildStdin, ) -> Result<(), Error> { let lines = read_lines(path)?; - parser::read_lines(lines, path, variables, visited_lines, writer, stdin) + parser::read_lines(lines, path, file_index, variables, visited_lines, writer, stdin) } pub fn default_cheat_pathbuf() -> Result { @@ -57,7 +58,7 @@ pub fn cheat_paths(path: Option) -> Result { } } -pub fn read_all(path: Option, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer) -> Result, Error> { +pub fn read_all(path: Option, files: &mut Vec, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer) -> Result, Error> { let mut variables = VariableMap::new(); let mut found_something = false; let mut visited_lines = HashSet::new(); @@ -73,7 +74,8 @@ pub fn read_all(path: Option, stdin: &mut std::process::ChildStdin, writ for folder in folders { for file in all_cheat_files(folder) { let full_filename = format!("{}/{}", &folder, &file); - if read_file(&full_filename, &mut variables, &mut visited_lines, writer, stdin).is_ok() && !found_something { + files.push(full_filename.clone()); + if read_file(&full_filename, files.len()-1, &mut variables, &mut visited_lines, writer, stdin).is_ok() && !found_something { found_something = true } } @@ -101,7 +103,7 @@ mod tests { let child_stdin = child.stdin.as_mut().unwrap(); let mut visited_lines: HashSet = HashSet::new(); let mut writer: Box = Box::new(display::terminal::Writer::new()); - read_file(path, &mut variables, &mut visited_lines, &mut *writer, child_stdin).unwrap(); + read_file(path, 0, &mut variables, &mut visited_lines, &mut *writer, child_stdin).unwrap(); let expected_suggestion = ( r#" echo -e "$(whoami)\nroot" "#.to_string(), Some(FinderOpts { diff --git a/src/fetcher/mod.rs b/src/fetcher/mod.rs index 36b77f2..3f91657 100644 --- a/src/fetcher/mod.rs +++ b/src/fetcher/mod.rs @@ -5,5 +5,5 @@ use crate::structures::cheat::VariableMap; use anyhow::Error; pub trait Fetcher { - fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer) -> Result, Error>; + fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer, files: &mut Vec) -> Result, Error>; } diff --git a/src/filesystem.rs b/src/filesystem.rs index 93a788a..f93f6a7 100644 --- a/src/filesystem.rs +++ b/src/filesystem.rs @@ -21,7 +21,7 @@ impl Fetcher { } impl fetcher::Fetcher for Fetcher { - fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer) -> Result, Error> { - read_all(self.path.clone(), stdin, writer) + fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer, files: &mut Vec) -> Result, Error> { + read_all(self.path.clone(), files, stdin, writer) } } diff --git a/src/finder.rs b/src/finder.rs index 005c847..d41bf7f 100644 --- a/src/finder.rs +++ b/src/finder.rs @@ -14,9 +14,9 @@ pub enum FinderChoice { } pub trait Finder { - fn call(&self, opts: Opts, stdin_fn: F) -> Result<(String, Option), Error> + fn call(&self, opts: Opts, files: &mut Vec, stdin_fn: F) -> Result<(String, Option), Error> where - F: Fn(&mut process::ChildStdin) -> Result, Error>; + F: Fn(&mut process::ChildStdin, &mut Vec) -> Result, Error>; } fn apply_map(text: String, map_fn: Option) -> String { @@ -102,9 +102,9 @@ fn parse(out: Output, opts: Opts) -> Result { } impl Finder for FinderChoice { - fn call(&self, finder_opts: Opts, stdin_fn: F) -> Result<(String, Option), Error> + fn call(&self, finder_opts: Opts, files: &mut Vec, stdin_fn: F) -> Result<(String, Option), Error> where - F: Fn(&mut process::ChildStdin) -> Result, Error>, + F: Fn(&mut process::ChildStdin, &mut Vec) -> Result, Error>, { let finder_str = match self { Self::Fzf => "fzf", @@ -215,7 +215,7 @@ impl Finder for FinderChoice { }; let stdin = child.stdin.as_mut().ok_or_else(|| anyhow!("Unable to acquire stdin of finder"))?; - let result_map = stdin_fn(stdin).context("Failed to pass data to finder")?; + let result_map = stdin_fn(stdin, files).context("Failed to pass data to finder")?; let out = child.wait_with_output().context("Failed to wait for finder")?; diff --git a/src/parser.rs b/src/parser.rs index e581c27..4501c5b 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -103,7 +103,7 @@ fn write_cmd( tags: &str, comment: &str, snippet: &str, - file: &str, + file_index: &usize, writer: &mut dyn Writer, stdin: &mut std::process::ChildStdin, ) -> Result<(), Error> { @@ -114,7 +114,7 @@ fn write_cmd( tags: &tags, comment: &comment, snippet: &snippet, - file: &file, + file_index: &file_index, }; stdin .write_all(writer.write(item).as_bytes()) @@ -133,6 +133,7 @@ fn without_prefix(line: &str) -> String { pub fn read_lines( lines: impl Iterator>, id: &str, + file_index: usize, variables: &mut VariableMap, visited_lines: &mut HashSet, writer: &mut dyn Writer, @@ -157,7 +158,7 @@ pub fn read_lines( } // tag else if line.starts_with('%') { - should_break = write_cmd(&tags, &comment, &snippet, &id, writer, stdin).is_err(); + should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err(); snippet = String::from(""); tags = without_prefix(&line); } @@ -171,13 +172,13 @@ pub fn read_lines( } // comment else if line.starts_with('#') { - should_break = write_cmd(&tags, &comment, &snippet, &id, writer, stdin).is_err(); + should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err(); snippet = String::from(""); comment = without_prefix(&line); } // variable else if line.starts_with('$') { - should_break = write_cmd(&tags, &comment, &snippet, &id, writer, stdin).is_err(); + should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err(); snippet = String::from(""); let (variable, command, opts) = parse_variable_line(&line) .with_context(|| format!("Failed to parse variable line. See line number {} in cheatsheet `{}`", line_nr + 1, id))?; @@ -199,7 +200,7 @@ pub fn read_lines( } if !should_break { - let _ = write_cmd(&tags, &comment, &snippet, &id, writer, stdin); + let _ = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin); } Ok(()) diff --git a/src/structures/item.rs b/src/structures/item.rs index 19ef103..c370e6f 100644 --- a/src/structures/item.rs +++ b/src/structures/item.rs @@ -2,5 +2,5 @@ pub struct Item<'a> { pub tags: &'a str, pub comment: &'a str, pub snippet: &'a str, - pub file: &'a str, + pub file_index: &'a usize, } diff --git a/src/tldr.rs b/src/tldr.rs index f5801b5..d7d985a 100644 --- a/src/tldr.rs +++ b/src/tldr.rs @@ -66,6 +66,7 @@ fn read_all(query: &str, markdown: &str, stdin: &mut std::process::ChildStdin, w parser::read_lines( markdown_lines(query, markdown), "markdown", + 0, &mut variables, &mut visited_lines, writer, @@ -144,7 +145,7 @@ impl Fetcher { } impl fetcher::Fetcher for Fetcher { - fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer) -> Result, Error> { + fn fetch(&self, stdin: &mut std::process::ChildStdin, writer: &mut dyn Writer, _files: &mut Vec) -> Result, Error> { let markdown = fetch(&self.query)?; read_all(&self.query, &markdown, stdin, writer) } diff --git a/src/welcome.rs b/src/welcome.rs index 3b8c6b0..5be067f 100644 --- a/src/welcome.rs +++ b/src/welcome.rs @@ -7,7 +7,7 @@ fn add_msg(tags: &str, comment: &str, snippet: &str, writer: &mut dyn Writer, st tags: &tags, comment: &comment, snippet: &snippet, - file: "", + file_index: &0, }; stdin.write_all(writer.write(item).as_bytes()).expect("Could not write to fzf's stdin"); }