navi/src/parser.rs

247 lines
8.1 KiB
Rust
Raw Normal View History

2021-04-05 09:37:35 -03:00
use crate::finder::structures::{Opts as FinderOpts, SuggestionType};
2021-04-04 17:46:33 -03:00
use crate::hash::fnv;
use crate::structures::cheat::VariableMap;
2020-08-27 15:15:09 -03:00
use crate::structures::item::Item;
2021-04-16 09:23:53 -03:00
use crate::writer;
2021-04-16 08:29:04 -03:00
use anyhow::{Context, Result};
2020-03-04 18:01:23 -03:00
use regex::Regex;
2020-03-18 12:29:29 -03:00
use std::collections::HashSet;
2020-03-04 18:01:23 -03:00
use std::io::Write;
2020-03-21 03:22:11 +01:00
lazy_static! {
2020-08-28 09:21:24 -03:00
pub static ref VAR_LINE_REGEX: Regex = Regex::new(r"^\$\s*([^:]+):(.*)").expect("Invalid regex");
2020-03-21 03:22:11 +01:00
}
2021-04-16 08:29:04 -03:00
fn parse_opts(text: &str) -> Result<FinderOpts> {
2020-03-04 18:01:23 -03:00
let mut multi = false;
2020-03-17 12:39:38 -03:00
let mut prevent_extra = false;
let mut opts = FinderOpts::default();
2020-08-28 09:21:24 -03:00
let parts = shellwords::split(text).map_err(|_| anyhow!("Given options are missing a closing quote"))?;
2020-03-22 01:51:38 +01: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
}
_ => true,
2020-03-04 18:01:23 -03:00
}
2020-03-22 01:51:38 +01:00
})
.collect::<Vec<_>>()
.chunks(2)
.try_for_each(|flag_and_value| {
2020-03-22 01:51:38 +01:00
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 01:51:38 +01: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()),
"--fzf-overrides" => opts.overrides = Some(value.to_string()),
2020-03-22 01:51:38 +01:00
_ => (),
}
Ok(())
} else if let [flag] = flag_and_value {
Err(anyhow!("No value provided for the flag `{}`", flag))
2020-03-22 01:51:38 +01:00
} else {
unreachable!() // Chunking by 2 allows only for tuples of 1 or 2 items...
}
})
.context("Failed to parse finder options")?;
2020-03-04 18:01:23 -03: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;
2020-03-22 01:51:38 +01:00
Ok(opts)
2020-03-04 18:01:23 -03:00
}
2021-04-16 08:29:04 -03:00
fn parse_variable_line(line: &str) -> Result<(&str, &str, Option<FinderOpts>)> {
2020-08-28 09:21:24 -03: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 01:51:38 +01:00
let variable = caps
.get(1)
.ok_or_else(|| anyhow!("No variable captured in the line `{}`", line))?
2020-03-22 01:51:38 +01: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 01:51:38 +01:00
.as_str()
.split("---");
let command = command_plus_opts
.next()
.ok_or_else(|| anyhow!("No command captured in the line `{}`", line))?;
2020-03-22 01:51:38 +01:00
let command_options = command_plus_opts.next().map(parse_opts).transpose()?;
Ok((variable, command, command_options))
2020-03-04 18:01:23 -03:00
}
2020-11-21 19:42:35 +01:00
fn write_cmd(
2021-04-15 10:49:23 -03:00
item: &Item,
2020-11-21 19:42:35 +01:00
stdin: &mut std::process::ChildStdin,
2021-04-15 10:49:23 -03:00
allowlist: Option<&Vec<String>>,
denylist: Option<&Vec<String>>,
2021-04-16 08:29:04 -03:00
) -> Result<()> {
2021-04-15 10:49:23 -03:00
if item.snippet.len() <= 1 {
return Ok(());
}
if let Some(list) = allowlist {
for v in list {
if !item.tags.contains(v) {
return Ok(());
}
}
}
2021-04-15 10:49:23 -03:00
if let Some(list) = denylist {
for v in list {
if item.tags.contains(v) {
return Ok(());
}
}
}
return stdin
2021-04-16 09:23:53 -03:00
.write_all(writer::write(item).as_bytes())
2021-04-15 10:49:23 -03:00
.context("Failed to write command to finder's stdin");
}
2020-10-08 17:45:01 -03:00
fn without_prefix(line: &str) -> String {
if line.len() > 2 {
String::from(line[2..].trim())
} else {
String::from("")
}
}
2021-04-15 10:49:23 -03:00
#[allow(clippy::too_many_arguments)]
2020-08-27 15:15:09 -03:00
pub fn read_lines(
2021-04-16 08:29:04 -03:00
lines: impl Iterator<Item = Result<String>>,
2020-08-27 15:15:09 -03:00
id: &str,
2020-11-26 21:36:20 +01:00
file_index: usize,
2020-03-18 08:38:13 -03:00
variables: &mut VariableMap,
2020-03-18 12:29:29 -03:00
visited_lines: &mut HashSet<u64>,
2020-03-04 18:01:23 -03:00
stdin: &mut std::process::ChildStdin,
2021-04-15 10:49:23 -03:00
allowlist: Option<&Vec<String>>,
denylist: Option<&Vec<String>>,
2021-04-16 08:29:04 -03:00
) -> Result<()> {
2021-04-15 10:49:23 -03:00
let mut item = Item::new();
item.file_index = file_index;
2020-03-18 08:38:13 -03:00
let mut should_break = false;
2020-03-04 18:01:23 -03:00
2020-08-27 15:15:09 -03: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 01:51:38 +01:00
if should_break {
break;
}
2020-03-22 01:51:38 +01:00
// duplicate
2021-04-15 10:49:23 -03:00
if !item.tags.is_empty() && !item.comment.is_empty() {}
2020-03-22 01:51:38 +01:00
// blank
if line.is_empty() {
}
// tag
else if line.starts_with('%') {
2021-04-16 09:23:53 -03:00
should_break = write_cmd(&item, stdin, allowlist, denylist).is_err();
2021-04-15 10:49:23 -03:00
item.snippet = String::from("");
item.tags = without_prefix(&line);
2020-03-22 01:51:38 +01:00
}
// dependency
else if line.starts_with('@') {
2020-10-08 17:45:01 -03:00
let tags_dependency = without_prefix(&line);
2021-04-15 10:49:23 -03:00
variables.insert_dependency(&item.tags, &tags_dependency);
}
2020-03-22 01:51:38 +01:00
// metacomment
else if line.starts_with(';') {
}
// comment
else if line.starts_with('#') {
2021-04-16 09:23:53 -03:00
should_break = write_cmd(&item, stdin, allowlist, denylist).is_err();
2021-04-15 10:49:23 -03:00
item.snippet = String::from("");
item.comment = without_prefix(&line);
2020-03-22 01:51:38 +01:00
}
// variable
else if line.starts_with('$') {
2021-04-16 09:23:53 -03:00
should_break = write_cmd(&item, stdin, allowlist, denylist).is_err();
2021-04-15 10:49:23 -03:00
item.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
)
})?;
2021-04-15 10:49:23 -03:00
variables.insert_suggestion(&item.tags, &variable, (String::from(command), opts));
2020-03-22 01:51:38 +01:00
}
// snippet
else {
2021-04-15 10:49:23 -03:00
let hash = fnv(&format!("{}{}", &item.comment, &line));
2020-03-22 01:51:38 +01:00
if visited_lines.contains(&hash) {
continue;
2020-03-04 18:01:23 -03:00
}
2020-03-22 01:51:38 +01:00
visited_lines.insert(hash);
2021-04-15 10:49:23 -03:00
if !(&item.snippet).is_empty() {
item.snippet.push_str(writer::LINE_SEPARATOR);
2020-03-04 18:01:23 -03:00
}
2021-04-15 10:49:23 -03:00
item.snippet.push_str(&line);
2020-03-04 18:01:23 -03:00
}
2020-03-22 01:51:38 +01: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 13:46:58 -03:00
2020-03-22 01:51:38 +01:00
if !should_break {
2021-04-16 09:23:53 -03:00
let _ = write_cmd(&item, stdin, allowlist, denylist);
2020-03-04 18:01:23 -03:00
}
2020-03-22 01:51:38 +01:00
Ok(())
2020-03-04 18:01:23 -03:00
}
2020-03-14 16:09:09 +08: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 16:09:09 +08:00
assert_eq!(command, " echo -e \"$(whoami)\\nroot\" ");
assert_eq!(variable, "user");
2020-03-14 20:33:07 +08:00
assert_eq!(
command_options,
Some(FinderOpts {
2020-03-14 20:33:07 +08:00
header_lines: 0,
column: None,
delimiter: None,
suggestion_type: SuggestionType::SingleSelection,
..Default::default()
2020-03-14 20:33:07 +08:00
})
);
2020-03-14 16:09:09 +08:00
}
}