From c65bcc3c0b6a2cd602c42287acd1e2f1ff4a830b Mon Sep 17 00:00:00 2001 From: Kirottu Date: Fri, 14 Jul 2023 16:50:57 +0300 Subject: [PATCH] Added option to allow "invalid" inputs to be allowed in the Stdin plugin --- Cargo.lock | 2 ++ plugins/stdin/Cargo.toml | 2 ++ plugins/stdin/src/lib.rs | 50 +++++++++++++++++++++++++++++++++------- 3 files changed, 46 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4127545..d5458f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2022,6 +2022,8 @@ dependencies = [ "abi_stable", "anyrun-plugin", "fuzzy-matcher", + "ron", + "serde", ] [[package]] diff --git a/plugins/stdin/Cargo.toml b/plugins/stdin/Cargo.toml index a45bc28..93c4652 100644 --- a/plugins/stdin/Cargo.toml +++ b/plugins/stdin/Cargo.toml @@ -12,3 +12,5 @@ crate-type = ["cdylib"] anyrun-plugin = { path = "../../anyrun-plugin" } fuzzy-matcher = "0.3.7" abi_stable = "0.11.1" +ron = "0.8.0" +serde = { version = "1.0.152", features = ["derive"] } diff --git a/plugins/stdin/src/lib.rs b/plugins/stdin/src/lib.rs index ead5c3d..2d6a029 100644 --- a/plugins/stdin/src/lib.rs +++ b/plugins/stdin/src/lib.rs @@ -1,12 +1,42 @@ -use std::io::stdin; +use std::{fs, io::stdin}; use abi_stable::std_types::{ROption, RString, RVec}; use anyrun_plugin::*; use fuzzy_matcher::FuzzyMatcher; +use serde::Deserialize; + +#[derive(Deserialize)] +struct Config { + allow_invalid: bool, + max_entries: usize, +} + +impl Default for Config { + fn default() -> Self { + Self { + allow_invalid: false, + max_entries: 5, + } + } +} + +struct State { + config: Config, + lines: Vec, +} #[init] -fn init(_config_dir: RString) -> Vec { - stdin().lines().filter_map(|line| line.ok()).collect() +fn init(config_dir: RString) -> State { + let config = if let Ok(content) = fs::read_to_string(format!("{}/stdin.ron", config_dir)) { + ron::from_str(&content).unwrap_or_default() + } else { + Config::default() + }; + + State { + config, + lines: stdin().lines().filter_map(|line| line.ok()).collect(), + } } #[handler] @@ -15,10 +45,11 @@ fn handler(_match: Match) -> HandleResult { } #[get_matches] -fn get_matches(input: RString, lines: &Vec) -> RVec { +fn get_matches(input: RString, state: &State) -> RVec { let matcher = fuzzy_matcher::skim::SkimMatcherV2::default().smart_case(); - let mut lines = lines + let mut lines = state + .lines .clone() .into_iter() .filter_map(|line| { @@ -28,9 +59,12 @@ fn get_matches(input: RString, lines: &Vec) -> RVec { }) .collect::>(); - lines.sort_by(|a, b| b.1.cmp(&a.1)); - - lines.truncate(5); + if !lines.is_empty() { + lines.sort_by(|a, b| b.1.cmp(&a.1)); + lines.truncate(state.config.max_entries); + } else if state.config.allow_invalid { + lines.push((input.into(), 0)); + } lines .into_iter()