Skip to content

Commit

Permalink
Refactor env_vars package (#485)
Browse files Browse the repository at this point in the history
  • Loading branch information
denisidoro authored Apr 6, 2021
1 parent 243a2c8 commit 1f3560f
Show file tree
Hide file tree
Showing 7 changed files with 76 additions and 68 deletions.
31 changes: 15 additions & 16 deletions src/actor.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::clipboard;
use crate::env_vars;
use crate::env_var;
use crate::extractor;
use crate::writer;

Expand All @@ -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;
Expand All @@ -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;

Expand All @@ -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));
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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(
Expand Down
14 changes: 7 additions & 7 deletions src/cmds/alfred.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::env_var;
use crate::filesystem;
use crate::shell::BashSpawnError;
use crate::structures::cheat::Suggestion;
Expand All @@ -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> {
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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);
Expand Down
26 changes: 26 additions & 0 deletions src/env_vars.rs → src/env_var.rs
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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('-', "_")
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod actor;
mod cheatsh;
mod clipboard;
mod cmds;
mod env_vars;
mod env_var;
mod extractor;
mod filesystem;
mod finder;
Expand Down
4 changes: 2 additions & 2 deletions src/shell.rs
Original file line number Diff line number Diff line change
@@ -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");
}
Expand Down
10 changes: 5 additions & 5 deletions src/structures/config.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)]
Expand Down
57 changes: 20 additions & 37 deletions src/writer/terminal.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,15 @@
use crate::env_vars;
use crate::env_var;
use crate::finder;
use crate::structures::item::Item;
use crate::terminal;
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;
Expand All @@ -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) {
Expand All @@ -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("");
Expand All @@ -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())
Expand All @@ -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()
Expand Down

0 comments on commit 1f3560f

Please sign in to comment.