navi/src/parser.rs

247 lines
8.2 KiB
Rust
Raw Normal View History

2020-08-27 18:15:09 +00:00
use crate::common::hash::fnv;
2020-04-19 18:51:04 +00:00
use crate::display::{self, Writer};
use crate::structures::cheat::VariableMap;
use crate::structures::finder::{Opts as FinderOpts, SuggestionType};
2020-08-27 18:15:09 +00:00
use crate::structures::item::Item;
2020-03-22 00:51:38 +00:00
use anyhow::{Context, Error};
2020-03-04 21:01:23 +00:00
use regex::Regex;
2020-03-18 15:29:29 +00:00
use std::collections::HashSet;
2020-03-04 21:01:23 +00:00
use std::io::Write;
2020-03-21 02:22:11 +00:00
lazy_static! {
2020-08-28 12:21:24 +00:00
pub static ref VAR_LINE_REGEX: Regex = Regex::new(r"^\$\s*([^:]+):(.*)").expect("Invalid regex");
2020-03-21 02:22:11 +00:00
}
fn parse_opts(text: &str) -> Result<FinderOpts, Error> {
2020-03-04 21:01:23 +00:00
let mut multi = false;
2020-03-17 15:39:38 +00:00
let mut prevent_extra = false;
let mut is_global = false;
let mut opts = FinderOpts::default();
2020-08-28 12:21:24 +00:00
let parts = shellwords::split(text).map_err(|_| anyhow!("Given options are missing a closing quote"))?;
2020-03-22 00:51:38 +00:00
parts
.into_iter()
.filter(|part| {
// We'll take parts in pairs of 2: (argument, value). Flags don't have a value tho, so we filter and handle them beforehand.
match part.as_str() {
"--multi" => {
multi = true;
false
}
"--prevent-extra" => {
prevent_extra = true;
false
}
"--global" => {
is_global = true;
false
}
2020-03-22 00:51:38 +00:00
_ => true,
2020-03-04 21:01:23 +00:00
}
2020-03-22 00:51:38 +00:00
})
.collect::<Vec<_>>()
.chunks(2)
.map(|flag_and_value| {
if let [flag, value] = flag_and_value {
match flag.as_str() {
"--headers" | "--header-lines" => {
opts.header_lines = value
.parse::<u8>()
.context("Value for `--headers` is invalid u8")?
}
"--column" => {
opts.column = Some(
value
.parse::<u8>()
.context("Value for `--column` is invalid u8")?,
)
}
"--map" => opts.map = Some(value.to_string()),
2020-03-22 00:51:38 +00:00
"--delimiter" => opts.delimiter = Some(value.to_string()),
"--query" => opts.query = Some(value.to_string()),
"--filter" => opts.filter = Some(value.to_string()),
"--preview" => opts.preview = Some(value.to_string()),
"--preview-window" => opts.preview_window = Some(value.to_string()),
"--header" => opts.header = Some(value.to_string()),
"--overrides" => opts.overrides = Some(value.to_string()),
_ => (),
}
Ok(())
} else if let [flag] = flag_and_value {
Err(anyhow!("No value provided for the flag `{}`", flag))
2020-03-22 00:51:38 +00:00
} else {
unreachable!() // Chunking by 2 allows only for tuples of 1 or 2 items...
}
})
.collect::<Result<_, _>>()
.context("Failed to parse finder options")?;
2020-03-04 21:01:23 +00:00
let suggestion_type = match (multi, prevent_extra) {
(true, _) => SuggestionType::MultipleSelections, // multi wins over prevent-extra
(false, false) => SuggestionType::SingleRecommendation,
(false, true) => SuggestionType::SingleSelection,
};
opts.suggestion_type = suggestion_type;
opts.global = is_global;
2020-03-22 00:51:38 +00:00
Ok(opts)
2020-03-04 21:01:23 +00:00
}
fn parse_variable_line(line: &str) -> Result<(&str, &str, Option<FinderOpts>), Error> {
2020-08-28 12:21:24 +00:00
let caps = VAR_LINE_REGEX
.captures(line)
.ok_or_else(|| anyhow!("No variables, command, and options found in the line `{}`", line))?;
2020-03-22 00:51:38 +00:00
let variable = caps
.get(1)
.ok_or_else(|| anyhow!("No variable captured in the line `{}`", line))?
2020-03-22 00:51:38 +00:00
.as_str()
.trim();
let mut command_plus_opts = caps
.get(2)
.ok_or_else(|| anyhow!("No command and options captured in the line `{}`", line))?
2020-03-22 00:51:38 +00:00
.as_str()
.split("---");
let command = command_plus_opts
.next()
.ok_or_else(|| anyhow!("No command captured in the line `{}`", line))?;
2020-03-22 00:51:38 +00:00
let command_options = command_plus_opts.next().map(parse_opts).transpose()?;
Ok((variable, command, command_options))
2020-03-04 21:01:23 +00:00
}
2020-11-21 18:42:35 +00:00
fn write_cmd(
tags: &str,
comment: &str,
snippet: &str,
2020-11-26 20:36:20 +00:00
file_index: &usize,
2020-11-21 18:42:35 +00:00
writer: &mut dyn Writer,
stdin: &mut std::process::ChildStdin,
) -> Result<(), Error> {
if snippet.len() <= 1 {
2020-03-22 00:51:38 +00:00
Ok(())
} else {
2020-04-19 18:51:04 +00:00
let item = Item {
tags: &tags,
comment: &comment,
snippet: &snippet,
2020-11-26 20:36:20 +00:00
file_index: &file_index,
2020-04-19 18:51:04 +00:00
};
stdin
2020-04-19 18:51:04 +00:00
.write_all(writer.write(item).as_bytes())
.context("Failed to write command to finder's stdin")
}
}
2020-10-08 20:45:01 +00:00
fn without_prefix(line: &str) -> String {
if line.len() > 2 {
String::from(line[2..].trim())
} else {
String::from("")
}
}
2020-08-27 18:15:09 +00:00
pub fn read_lines(
lines: impl Iterator<Item = Result<String, Error>>,
id: &str,
2020-11-26 20:36:20 +00:00
file_index: usize,
2020-03-18 11:38:13 +00:00
variables: &mut VariableMap,
2020-03-18 15:29:29 +00:00
visited_lines: &mut HashSet<u64>,
writer: &mut dyn Writer,
2020-03-04 21:01:23 +00:00
stdin: &mut std::process::ChildStdin,
2020-03-22 00:51:38 +00:00
) -> Result<(), Error> {
2020-03-04 21:01:23 +00:00
let mut tags = String::from("");
let mut comment = String::from("");
let mut snippet = String::from("");
2020-03-18 11:38:13 +00:00
let mut should_break = false;
2020-03-04 21:01:23 +00:00
2020-08-27 18:15:09 +00:00
for (line_nr, line_result) in lines.enumerate() {
let line = line_result
.with_context(|| format!("Failed to read line number {} in cheatsheet `{}`", line_nr, id))?;
2020-03-22 00:51:38 +00:00
if should_break {
break;
}
2020-03-22 00:51:38 +00:00
// duplicate
if !tags.is_empty() && !comment.is_empty() {}
// blank
if line.is_empty() {
}
// tag
else if line.starts_with('%') {
2020-11-26 20:36:20 +00:00
should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err();
2020-03-22 00:51:38 +00:00
snippet = String::from("");
2020-10-08 20:45:01 +00:00
tags = without_prefix(&line);
2020-03-22 00:51:38 +00:00
}
// dependency
else if line.starts_with('@') {
2020-10-08 20:45:01 +00:00
let tags_dependency = without_prefix(&line);
variables.insert_dependency(&tags, &tags_dependency);
}
2020-03-22 00:51:38 +00:00
// metacomment
else if line.starts_with(';') {
}
// comment
else if line.starts_with('#') {
2020-11-26 20:36:20 +00:00
should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err();
2020-03-22 00:51:38 +00:00
snippet = String::from("");
2020-10-08 20:45:01 +00:00
comment = without_prefix(&line);
2020-03-22 00:51:38 +00:00
}
// variable
else if line.starts_with('$') {
2020-11-26 20:36:20 +00:00
should_break = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin).is_err();
2020-03-22 00:51:38 +00:00
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
)
})?;
variables.insert_suggestion(&tags, &variable, (String::from(command), opts));
2020-03-22 00:51:38 +00:00
}
// snippet
else {
2020-08-27 18:15:09 +00:00
let hash = fnv(&format!("{}{}", &comment, &line));
2020-03-22 00:51:38 +00:00
if visited_lines.contains(&hash) {
continue;
2020-03-04 21:01:23 +00:00
}
2020-03-22 00:51:38 +00:00
visited_lines.insert(hash);
2020-03-22 00:51:38 +00:00
if !(&snippet).is_empty() {
snippet.push_str(display::LINE_SEPARATOR);
2020-03-04 21:01:23 +00:00
}
2020-03-22 00:51:38 +00:00
snippet.push_str(&line);
2020-03-04 21:01:23 +00:00
}
2020-03-22 00:51:38 +00:00
}
Initial cheat repo support (#258) This PR makes navi stop bundling `.cheat` files and makes it able to download from repos on GitHub, using a standardized config directory. - it fixes #233 and #237 - it makes #52, #256 and #257 much easier to implement - it makes #40 harder to implement - it's an alternate solution to #140 - it's influenced by #238 and #254. This PR ended up being much bigger than I would like so if you could review only this description it would be already very nice! When navi is started for the first time, a welcome cheatsheet is shown: ![Screenshot at 2020-03-15 10-20-04](https://user-images.githubusercontent.com/3226564/76702240-19fffd80-66a7-11ea-884f-97c565bc1ead.png) If the user selects the first option, the user is prompted to download `.cheat`s from https://github.com/denisidoro/cheats: ![Screenshot at 2020-03-15 10-20-35](https://user-images.githubusercontent.com/3226564/76702239-19fffd80-66a7-11ea-8f69-324f669b1e01.png) ![Screenshot at 2020-03-15 10-22-59](https://user-images.githubusercontent.com/3226564/76702236-18363a00-66a7-11ea-8ff4-53b497f85888.png) The config folder is populated: ![Screenshot at 2020-03-15 10-21-11](https://user-images.githubusercontent.com/3226564/76702238-19676700-66a7-11ea-8367-3e7b5733f2b4.png) When run again, cheats are available: ![Screenshot at 2020-03-15 10-21-34](https://user-images.githubusercontent.com/3226564/76702237-19676700-66a7-11ea-9c2a-d8829340f3e9.png) ### Breaking changes In order to make navi stop bundling shell widgets as well, a breaking change has been introduced: `source $(navi widget bash)` won't work anymore. It should be `source <(navi widget bash)` now. Any ideas on how to make this transition more graceful?
2020-03-15 16:46:58 +00:00
2020-03-22 00:51:38 +00:00
if !should_break {
2020-11-26 20:36:20 +00:00
let _ = write_cmd(&tags, &comment, &snippet, &file_index, writer, stdin);
2020-03-04 21:01:23 +00:00
}
2020-03-22 00:51:38 +00:00
Ok(())
2020-03-04 21:01:23 +00:00
}
2020-03-14 08:09:09 +00:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_variable_line() {
let (variable, command, command_options) =
parse_variable_line("$ user : echo -e \"$(whoami)\\nroot\" --- --prevent-extra").unwrap();
2020-03-14 08:09:09 +00:00
assert_eq!(command, " echo -e \"$(whoami)\\nroot\" ");
assert_eq!(variable, "user");
2020-03-14 12:33:07 +00:00
assert_eq!(
command_options,
Some(FinderOpts {
2020-03-14 12:33:07 +00:00
header_lines: 0,
column: None,
delimiter: None,
suggestion_type: SuggestionType::SingleSelection,
..Default::default()
2020-03-14 12:33:07 +00:00
})
);
2020-03-14 08:09:09 +00:00
}
}