Refactor env_vars package (#485)

This commit is contained in:
Denis Isidoro 2021-04-06 10:53:21 -03:00 committed by GitHub
parent 243a2c8472
commit 1f3560f7f9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 76 additions and 68 deletions

View file

@ -1,5 +1,5 @@
use crate::clipboard;
use crate::env_vars;
use crate::env_var;
use crate::extractor;
use crate::writer;
@ -13,7 +13,6 @@ use crate::structures::config::Config;
use anyhow::Context;
use anyhow::Error;
use std::env;
use std::fs;
use std::io::Write;
use std::path::Path;
@ -25,9 +24,9 @@ fn prompt_finder(
suggestion: Option<&Suggestion>,
variable_count: usize,
) -> Result<String, Error> {
env::remove_var(env_vars::PREVIEW_COLUMN);
env::remove_var(env_vars::PREVIEW_DELIMITER);
env::remove_var(env_vars::PREVIEW_MAP);
env_var::remove(env_var::PREVIEW_COLUMN);
env_var::remove(env_var::PREVIEW_DELIMITER);
env_var::remove(env_var::PREVIEW_MAP);
let mut extra_preview = None;
@ -36,13 +35,13 @@ fn prompt_finder(
if let Some(sopts) = suggestion_opts {
if let Some(c) = &sopts.column {
env::set_var(env_vars::PREVIEW_COLUMN, c.to_string());
env_var::set(env_var::PREVIEW_COLUMN, c.to_string());
}
if let Some(d) = &sopts.delimiter {
env::set_var(env_vars::PREVIEW_DELIMITER, d);
env_var::set(env_var::PREVIEW_DELIMITER, d);
}
if let Some(m) = &sopts.map {
env::set_var(env_vars::PREVIEW_MAP, m);
env_var::set(env_var::PREVIEW_MAP, m);
}
if let Some(p) = &sopts.preview {
extra_preview = Some(format!(";echo;{}", p));
@ -87,9 +86,9 @@ NAVIEOF
..opts.clone().unwrap_or_default()
};
opts.query = env::var(format!("{}__query", variable_name)).ok();
opts.query = env_var::get(format!("{}__query", variable_name)).ok();
if let Ok(f) = env::var(format!("{}__best", variable_name)) {
if let Ok(f) = env_var::get(format!("{}__best", variable_name)) {
opts.filter = Some(f);
opts.suggestion_type = SuggestionType::SingleSelection;
}
@ -139,8 +138,8 @@ fn replace_variables_from_snippet(
for bracketed_variable_name in variables_found {
let variable_name = &bracketed_variable_name[1..bracketed_variable_name.len() - 1];
let env_variable_name = variable_name.replace('-', "_");
let env_value = env::var(&env_variable_name);
let env_variable_name = env_var::escape(variable_name);
let env_value = env_var::get(&env_variable_name);
let value = if let Ok(e) = env_value {
e
@ -153,7 +152,7 @@ fn replace_variables_from_snippet(
prompt_finder(variable_name, &config, None, variable_count)?
};
env::set_var(env_variable_name, &value);
env_var::set(env_variable_name, &value);
interpolated_snippet = if value.as_str() == "\n" {
interpolated_snippet.replacen(bracketed_variable_name, "", 1)
@ -180,9 +179,9 @@ pub fn act(
return Ok(());
}
env::set_var(env_vars::PREVIEW_INITIAL_SNIPPET, &snippet);
env::set_var(env_vars::PREVIEW_TAGS, &tags);
env::set_var(env_vars::PREVIEW_COMMENT, &comment);
env_var::set(env_var::PREVIEW_INITIAL_SNIPPET, &snippet);
env_var::set(env_var::PREVIEW_TAGS, &tags);
env_var::set(env_var::PREVIEW_COMMENT, &comment);
let interpolated_snippet = writer::with_new_lines(
replace_variables_from_snippet(

View file

@ -1,3 +1,4 @@
use crate::env_var;
use crate::filesystem;
use crate::shell::BashSpawnError;
use crate::structures::cheat::Suggestion;
@ -6,7 +7,6 @@ use crate::structures::fetcher::Fetcher;
use crate::writer;
use anyhow::Context;
use anyhow::Error;
use std::env;
use std::process::{Command, Stdio};
pub fn main(config: Config) -> Result<(), Error> {
@ -67,8 +67,8 @@ pub fn suggestions(config: Config, dry_run: bool) -> Result<(), Error> {
.context("Failed to parse variables intended for finder")?
.expect("Empty variable map");
let tags = env::var("tags").context(r#"The env var "tags" isn't set"#)?;
let snippet = env::var("snippet").context(r#"The env var "snippet" isn't set"#)?;
let tags = env_var::get("tags").context(r#"The env var "tags" isn't set"#)?;
let snippet = env_var::get("snippet").context(r#"The env var "snippet" isn't set"#)?;
let capture = writer::VAR_REGEX.captures_iter(&snippet).next();
let bracketed_varname = &(capture.expect("Invalid capture"))[0];
@ -99,12 +99,12 @@ pub fn suggestions(config: Config, dry_run: bool) -> Result<(), Error> {
}
pub fn transform() -> Result<(), Error> {
let snippet = env::var("snippet").context(r#"The env var "snippet" isn't set"#)?;
let varname = env::var("varname").context(r#"The env var "varname" isn't set"#)?;
let value = if let Ok(v) = env::var(&varname) {
let snippet = env_var::get("snippet").context(r#"The env var "snippet" isn't set"#)?;
let varname = env_var::get("varname").context(r#"The env var "varname" isn't set"#)?;
let value = if let Ok(v) = env_var::get(&varname) {
v
} else {
env::var("free").context("The env var for varname isn't set")?
env_var::get("free").context("The env var for varname isn't set")?
};
let bracketed_varname = format!("<{}>", varname);

View file

@ -1,3 +1,9 @@
pub use env::remove_var as remove;
pub use env::set_var as set;
pub use env::var as get;
use std::env;
use std::str::FromStr;
pub const PREVIEW_INITIAL_SNIPPET: &str = "NAVI_PREVIEW_INITIAL_SNIPPET";
pub const PREVIEW_TAGS: &str = "NAVI_PREVIEW_TAGS";
pub const PREVIEW_COMMENT: &str = "NAVI_PREVIEW_COMMENT";
@ -16,3 +22,23 @@ pub const PATH: &str = "NAVI_PATH";
pub const FZF_OVERRIDES: &str = "NAVI_FZF_OVERRIDES";
pub const FZF_OVERRIDES_VAR: &str = "NAVI_FZF_OVERRIDES_VAR";
pub const FINDER: &str = "NAVI_FINDER";
pub fn parse<T: FromStr>(varname: &str) -> Option<T> {
if let Ok(x) = env::var(varname) {
x.parse::<T>().ok()
} else {
None
}
}
pub fn must_get(name: &str) -> String {
if let Ok(v) = env::var(name) {
v
} else {
panic!("{} not set", name)
}
}
pub fn escape(name: &str) -> String {
name.replace('-', "_")
}

View file

@ -7,7 +7,7 @@ mod actor;
mod cheatsh;
mod clipboard;
mod cmds;
mod env_vars;
mod env_var;
mod extractor;
mod filesystem;
mod finder;

View file

@ -1,9 +1,9 @@
use std::env;
use crate::env_var;
use std::fmt::Debug;
use thiserror::Error;
lazy_static! {
pub static ref IS_FISH: bool = env::var("SHELL")
pub static ref IS_FISH: bool = env_var::get("SHELL")
.unwrap_or_else(|_| "".to_string())
.contains(&"fish");
}

View file

@ -1,6 +1,6 @@
use crate::cmds::func::Func;
use crate::cmds::info::Info;
use crate::env_vars;
use crate::env_var;
use crate::finder::FinderChoice;
use crate::shell::Shell;
use clap::{crate_version, AppSettings, Clap};
@ -81,7 +81,7 @@ EXAMPLES:
#[clap(version = crate_version!())]
pub struct Config {
/// List of :-separated paths containing .cheat files
#[clap(short, long, env = env_vars::PATH)]
#[clap(short, long, env = env_var::PATH)]
pub path: Option<String>,
/// [Experimental] Instead of executing a snippet, saves it to a file
@ -113,15 +113,15 @@ pub struct Config {
query: Option<String>,
/// finder overrides for cheat selection
#[clap(long, env = env_vars::FZF_OVERRIDES)]
#[clap(long, env = env_var::FZF_OVERRIDES)]
pub fzf_overrides: Option<String>,
/// finder overrides for variable selection
#[clap(long, env = env_vars::FZF_OVERRIDES_VAR)]
#[clap(long, env = env_var::FZF_OVERRIDES_VAR)]
pub fzf_overrides_var: Option<String>,
/// which finder application to use
#[clap(long, env = env_vars::FINDER, default_value = "fzf", possible_values = &["fzf", "skim"], case_insensitive = true)]
#[clap(long, env = env_var::FINDER, default_value = "fzf", possible_values = &["fzf", "skim"], case_insensitive = true)]
pub finder: FinderChoice,
#[clap(subcommand)]

View file

@ -1,4 +1,4 @@
use crate::env_vars;
use crate::env_var;
use crate::finder;
use crate::structures::item::Item;
use crate::terminal;
@ -6,21 +6,10 @@ use crate::terminal::style::{style, Color};
use crate::writer;
use std::cmp::max;
use std::collections::HashSet;
use std::env;
use std::iter;
use std::str::FromStr;
// TODO: extract
pub fn parse_env_var<T: FromStr>(varname: &str) -> Option<T> {
if let Ok(x) = env::var(varname) {
x.parse::<T>().ok()
} else {
None
}
}
fn parse_ansi(varname: &str, default: Color) -> Color {
let value: Option<String> = parse_env_var(varname);
let value: Option<String> = env_var::parse(varname);
if let Some(v) = value {
if let Some(a) = terminal::parse_ansi(&v) {
return a;
@ -30,11 +19,11 @@ fn parse_ansi(varname: &str, default: Color) -> Color {
}
lazy_static! {
pub static ref TAG_COLOR: Color = parse_ansi(env_vars::TAG_COLOR, Color::Cyan);
pub static ref COMMENT_COLOR: Color = parse_ansi(env_vars::COMMENT_COLOR, Color::Blue);
pub static ref SNIPPET_COLOR: Color = parse_ansi(env_vars::SNIPPET_COLOR, Color::White);
pub static ref TAG_WIDTH_PERCENTAGE: u16 = parse_env_var(env_vars::TAG_WIDTH).unwrap_or(20);
pub static ref COMMENT_WIDTH_PERCENTAGE: u16 = parse_env_var(env_vars::COMMENT_WIDTH).unwrap_or(40);
pub static ref TAG_COLOR: Color = parse_ansi(env_var::TAG_COLOR, Color::Cyan);
pub static ref COMMENT_COLOR: Color = parse_ansi(env_var::COMMENT_COLOR, Color::Blue);
pub static ref SNIPPET_COLOR: Color = parse_ansi(env_var::SNIPPET_COLOR, Color::White);
pub static ref TAG_WIDTH_PERCENTAGE: u16 = env_var::parse(env_var::TAG_WIDTH).unwrap_or(20);
pub static ref COMMENT_WIDTH_PERCENTAGE: u16 = env_var::parse(env_var::COMMENT_WIDTH).unwrap_or(40);
}
pub fn preview(comment: &str, tags: &str, snippet: &str) {
@ -45,27 +34,18 @@ pub fn preview(comment: &str, tags: &str, snippet: &str) {
snippet = style(writer::fix_newlines(snippet)).with(*SNIPPET_COLOR),
);
}
fn get_env_var(name: &str) -> String {
if let Ok(v) = env::var(name) {
v
} else {
panic!("{} not set", name)
}
}
pub fn preview_var(selection: &str, query: &str, variable: &str) {
let snippet = &get_env_var(env_vars::PREVIEW_INITIAL_SNIPPET);
let tags = get_env_var(env_vars::PREVIEW_TAGS);
let comment = get_env_var(env_vars::PREVIEW_COMMENT);
let column = writer::terminal::parse_env_var(env_vars::PREVIEW_COLUMN);
let delimiter = env::var(env_vars::PREVIEW_DELIMITER).ok();
let map = env::var(env_vars::PREVIEW_MAP).ok();
let snippet = env_var::must_get(env_var::PREVIEW_INITIAL_SNIPPET);
let tags = env_var::must_get(env_var::PREVIEW_TAGS);
let comment = env_var::must_get(env_var::PREVIEW_COMMENT);
let column = env_var::parse(env_var::PREVIEW_COLUMN);
let delimiter = env_var::get(env_var::PREVIEW_DELIMITER).ok();
let map = env_var::get(env_var::PREVIEW_MAP).ok();
let active_color = *TAG_COLOR;
let inactive_color = *COMMENT_COLOR;
let mut colored_snippet = String::from(snippet);
let mut colored_snippet = String::from(&snippet);
let mut visited_vars: HashSet<&str> = HashSet::new();
let mut variables = String::from("");
@ -80,7 +60,10 @@ pub fn preview_var(selection: &str, query: &str, variable: &str) {
let bracketed_variables: Vec<&str> = {
if snippet.contains(&bracketed_current_variable) {
writer::VAR_REGEX.find_iter(snippet).map(|m| m.as_str()).collect()
writer::VAR_REGEX
.find_iter(&snippet)
.map(|m| m.as_str())
.collect()
} else {
iter::once(&bracketed_current_variable)
.map(|s| s.as_str())
@ -99,12 +82,12 @@ pub fn preview_var(selection: &str, query: &str, variable: &str) {
let is_current = variable_name == variable;
let variable_color = if is_current { active_color } else { inactive_color };
let env_variable_name = variable_name.replace('-', "_");
let env_variable_name = env_var::escape(variable_name);
let value = if is_current {
let v = selection.trim_matches('\'');
if v.is_empty() { query.trim_matches('\'') } else { v }.to_string()
} else if let Ok(v) = env::var(&env_variable_name) {
} else if let Ok(v) = env_var::get(&env_variable_name) {
v
} else {
"".to_string()