Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor writer packages #517

Merged
merged 4 commits into from
Apr 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions src/cheatsh.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::parser;
use crate::structures::cheat::VariableMap;
use crate::structures::fetcher;
use crate::writer::Writer;
use anyhow::Context;
use anyhow::Result;
use std::collections::HashSet;
Expand All @@ -23,12 +22,7 @@ fn lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<String>> {
.into_iter()
}

fn read_all(
query: &str,
cheat: &str,
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
) -> Result<Option<VariableMap>> {
fn read_all(query: &str, cheat: &str, stdin: &mut std::process::ChildStdin) -> Result<Option<VariableMap>> {
let mut variables = VariableMap::new();
let mut visited_lines = HashSet::new();

Expand All @@ -50,7 +44,6 @@ Output:
0,
&mut variables,
&mut visited_lines,
writer,
stdin,
None,
None,
Expand Down Expand Up @@ -119,10 +112,9 @@ impl fetcher::Fetcher for Fetcher {
fn fetch(
&self,
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
_files: &mut Vec<String>,
) -> Result<Option<VariableMap>> {
let cheat = fetch(&self.query)?;
read_all(&self.query, &cheat, stdin, writer)
read_all(&self.query, &cheat, stdin)
}
}
6 changes: 0 additions & 6 deletions src/cmds/mod.rs

This file was deleted.

3 changes: 0 additions & 3 deletions src/filesystem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ pub use crate::fs::{
use crate::parser;
use crate::structures::cheat::VariableMap;
use crate::structures::fetcher;
use crate::writer::Writer;
use anyhow::Result;
use directories_next::BaseDirs;
use std::collections::HashSet;
Expand Down Expand Up @@ -103,7 +102,6 @@ impl fetcher::Fetcher for Fetcher {
fn fetch(
&self,
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
files: &mut Vec<String>,
) -> Result<Option<VariableMap>> {
let mut variables = VariableMap::new();
Expand Down Expand Up @@ -133,7 +131,6 @@ impl fetcher::Fetcher for Fetcher {
index,
&mut variables,
&mut visited_lines,
writer,
stdin,
self.allowlist.as_ref(),
self.denylist.as_ref(),
Expand Down
42 changes: 0 additions & 42 deletions src/handler.rs

This file was deleted.

13 changes: 3 additions & 10 deletions src/cmds/core.rs → src/handler/core.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
use crate::actor;
use crate::cheatsh;

use crate::writer;

use crate::extractor;
use crate::filesystem;
use crate::finder::structures::{Opts as FinderOpts, SuggestionType};
use crate::finder::Finder;
use crate::structures::fetcher::Fetcher;

use crate::structures::cheat::VariableMap;

use crate::structures::config::Config;
use crate::structures::config::Source;
use crate::structures::fetcher::Fetcher;
use crate::tldr;
use crate::welcome;
use anyhow::Context;
Expand Down Expand Up @@ -45,22 +40,20 @@ pub fn main(config: Config) -> Result<()> {
let (raw_selection, variables, files) = config
.finder
.call(opts, |stdin, files| {
let mut writer = writer::terminal::Writer::new();

let fetcher: Box<dyn Fetcher> = match config.source() {
Source::Cheats(query) => Box::new(cheatsh::Fetcher::new(query)),
Source::Tldr(query) => Box::new(tldr::Fetcher::new(query)),
Source::Filesystem(path, rules) => Box::new(filesystem::Fetcher::new(path, rules)),
};

let res = fetcher
.fetch(stdin, &mut writer, files)
.fetch(stdin, files)
.context("Failed to parse variables intended for finder")?;

if let Some(variables) = res {
Ok(Some(variables))
} else {
welcome::populate_cheatsheet(&mut writer, stdin);
welcome::populate_cheatsheet(stdin);
Ok(Some(VariableMap::new()))
}
})
Expand Down
File renamed without changes.
File renamed without changes.
50 changes: 50 additions & 0 deletions src/handler/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
pub mod core;
pub mod func;
pub mod info;
pub mod preview;
pub mod preview_var;
pub mod repo;
pub mod shell;

use crate::handler;
use crate::structures::config::Command::{Fn, Info, Preview, PreviewVar, Repo, Widget};
use crate::structures::config::{Config, RepoCommand};
use anyhow::Context;
use anyhow::Result;

pub fn handle_config(config: Config) -> Result<()> {
match config.cmd.as_ref() {
None => handler::core::main(config),

Some(c) => match c {
Preview { line } => handler::preview::main(&line),

PreviewVar {
selection,
query,
variable,
} => handler::preview_var::main(&selection, &query, &variable),

Widget { shell } => handler::shell::main(shell).context("Failed to print shell widget code"),

Fn { func, args } => handler::func::main(func, args.to_vec())
.with_context(|| format!("Failed to execute function `{:#?}`", func)),

Info { info } => {
handler::info::main(info).with_context(|| format!("Failed to fetch info `{:#?}`", info))
}

Repo { cmd } => match cmd {
RepoCommand::Add { uri } => {
handler::repo::add(uri.clone(), &config.finder)
.with_context(|| format!("Failed to import cheatsheets from `{}`", uri))?;
handler::core::main(config)
}
RepoCommand::Browse => {
handler::repo::browse(&config.finder).context("Failed to browse featured cheatsheets")?;
handler::core::main(config)
}
},
},
}
}
15 changes: 8 additions & 7 deletions src/cmds/preview.rs → src/handler/preview.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::ui;
use crate::writer;

use anyhow::Result;

use std::process;

fn extract_elements(argstr: &str) -> (&str, &str, &str) {
Expand All @@ -14,11 +13,13 @@ fn extract_elements(argstr: &str) -> (&str, &str, &str) {

pub fn main(line: &str) -> Result<()> {
let (tags, comment, snippet) = extract_elements(line);
writer::terminal::preview(comment, tags, snippet);
process::exit(0)
}

pub fn main_var(selection: &str, query: &str, variable: &str) -> Result<()> {
writer::terminal::preview_var(selection, query, variable);
println!(
"{comment} {tags} \n{snippet}",
comment = ui::style(comment).with(*ui::COMMENT_COLOR),
tags = ui::style(format!("[{}]", tags)).with(*ui::TAG_COLOR),
snippet = ui::style(writer::fix_newlines(snippet)).with(*ui::SNIPPET_COLOR),
);

process::exit(0)
}
92 changes: 92 additions & 0 deletions src/handler/preview_var.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use crate::env_var;
use crate::finder;

use crate::terminal::style::style;
use crate::ui;
use crate::writer;
use anyhow::Result;

use std::collections::HashSet;
use std::iter;
use std::process;

pub fn main(selection: &str, query: &str, variable: &str) -> Result<()> {
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 = *ui::TAG_COLOR;
let inactive_color = *ui::COMMENT_COLOR;

let mut colored_snippet = String::from(&snippet);
let mut visited_vars: HashSet<&str> = HashSet::new();

let mut variables = String::from("");

println!(
"{comment} {tags}",
comment = style(comment).with(*ui::COMMENT_COLOR),
tags = style(format!("[{}]", tags)).with(*ui::TAG_COLOR),
);

let bracketed_current_variable = format!("<{}>", variable);

let bracketed_variables: Vec<&str> = {
if snippet.contains(&bracketed_current_variable) {
writer::VAR_REGEX
.find_iter(&snippet)
.map(|m| m.as_str())
.collect()
} else {
iter::once(&bracketed_current_variable)
.map(|s| s.as_str())
.collect()
}
};

for bracketed_variable_name in bracketed_variables {
let variable_name = &bracketed_variable_name[1..bracketed_variable_name.len() - 1];

if visited_vars.contains(variable_name) {
continue;
} else {
visited_vars.insert(variable_name);
}

let is_current = variable_name == variable;
let variable_color = if is_current { active_color } else { inactive_color };
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::get(&env_variable_name) {
v
} else {
"".to_string()
};

let replacement = format!(
"{variable}",
variable = style(bracketed_variable_name).with(variable_color),
);

colored_snippet = colored_snippet.replace(bracketed_variable_name, &replacement);

variables = format!(
"{variables}\n{variable} = {value}",
variables = variables,
variable = style(variable_name).with(variable_color),
value = finder::process(value, column, delimiter.as_deref(), map.clone())
.expect("Unable to process value"),
);
}

println!("{snippet}", snippet = writer::fix_newlines(&colored_snippet));
println!("{variables}", variables = variables);

process::exit(0)
}
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ extern crate anyhow;
mod actor;
mod cheatsh;
mod clipboard;
mod cmds;
mod env_var;
mod extractor;
mod filesystem;
Expand All @@ -20,6 +19,7 @@ mod shell;
mod structures;
mod terminal;
mod tldr;
mod ui;
mod url;
mod welcome;
mod writer;
Expand Down
Loading