Skip to content

Commit

Permalink
refactor: refactor and and lint and re-format the whole proj
Browse files Browse the repository at this point in the history
  • Loading branch information
0x61nas committed Aug 27, 2023
1 parent 4dd0702 commit 6d07d80
Show file tree
Hide file tree
Showing 8 changed files with 37 additions and 36 deletions.
1 change: 0 additions & 1 deletion src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ impl Config {
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
use std::path::PathBuf;

#[test]
Expand Down
7 changes: 0 additions & 7 deletions src/config/plz_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,6 @@ impl Default for PlzMenu {
CHEATSHEETS_URL_TEMPLATE.to_string(),
)]),
},
PlzMenuEntry {
display_msg: "Show info page".to_string(),
operation: HashMap::from([(
"local".to_string(),
"~/info-pages/{cmd}.md".to_string(),
)]),
},
],
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ pub enum Error {
/// Error that might occur if the user provides an invalid operation.
#[error("Invalid operation there is no operation named `{0}`.")]
PlzMenuInvalidOperation(String),
/// Error that might occur if the timeout is reached while executing a command.
#[error("Command timeout.")]
CommandTimeoutError,
/// Error that might occur when trying to execute a command or collect its output.
#[error("Command error: `{0}`")]
CommandError(String),
}

/// Type alias for the standard [`Result`] type.
Expand Down
8 changes: 4 additions & 4 deletions src/helper/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ fn check_args<'a, ArgsIter: Iterator<Item = &'a str>, Output: Write>(
/// Shows command-line help about the given command.
pub fn get_args_help<Output: Write>(
cmd: &str,
config: &Config,
config: Config,
verbose: bool,
output: &mut Output,
) -> Result<()> {
Expand Down Expand Up @@ -215,7 +215,7 @@ Options:
fn test_get_default_help() -> Result<()> {
let config = Config::default();
let mut output = Vec::new();
get_args_help(&get_test_bin(), &config, false, &mut output)?;
get_args_help(&get_test_bin(), config, false, &mut output)?;
println!("{}", String::from_utf8_lossy(&output));
assert_eq!(
r#"(°ロ°) checking 'test -v'
Expand Down Expand Up @@ -250,7 +250,7 @@ Options:
..Default::default()
};
let mut output = Vec::new();
get_args_help(&get_test_bin(), &config, false, &mut output)?;
get_args_help(&get_test_bin(), config, false, &mut output)?;
println!("{}", String::from_utf8_lossy(&output));
assert_eq!(
r#"(°ロ°) checking 'test -x'
Expand All @@ -277,7 +277,7 @@ halp 0.1.0
..Default::default()
};
let mut output = Vec::new();
get_args_help("", &config, false, &mut output)?;
get_args_help("", config, false, &mut output)?;
assert!(String::from_utf8_lossy(&output).is_empty());
Ok(())
}
Expand Down
5 changes: 2 additions & 3 deletions src/helper/docs/handlers/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,13 @@ mod tests {
}

#[test]
fn test_fetch_unknown_topic() -> Result<()> {
fn test_fetch_unknown_topic() {
let output = FetchHandler.handle(
"https://cheat.sh/unknown".to_string(),
&HashMap::from([("user-agent".to_string(), "fetch".to_string())]),
)?;
);
assert!(output.is_err());
assert_eq!(output.expect_err("Unreachable").to_string(),
"External help provider error: `Unknown topic, This topic/command might has no page in this provider yet.`");
Ok(())
}
}
13 changes: 1 addition & 12 deletions src/helper/docs/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,5 @@ use std::collections::HashMap;
/// The operation handler trait.
pub trait Handler {
/// Handles the operation.
///
/// # Arguments
/// - `args_map`: The arguments map.
///
/// # Returns
/// This method returns a Result type. On successful, it contains a `String` with the content of the fetched page.
/// Or `None` if the operation don't have an output.
fn handle(
&self,
op_value: String,
args_map: &HashMap<String, String>,
) -> Result<Option<String>>;
fn handle(&self, _: String, args_map: &HashMap<String, String>) -> Result<Option<String>>;
}
29 changes: 22 additions & 7 deletions src/helper/docs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@ use crate::helper::docs::template::parse_template;
pub mod cmd_parse;
/// Plz menu operation handlers.
pub mod handlers;
/// Man page helper.
pub mod man;
/// Plz menu template parser.
pub mod template;

/// Shows documentation/usage help about the given command.
pub fn get_docs_help<Output: Write>(cmd: &str, config: &Config, output: &mut Output) -> Result<()> {
pub fn get_docs_help<Output: Write>(cmd: &str, config: Config, output: &mut Output) -> Result<()> {
let mut menu_options = config
.plz_menu
.entries
Expand All @@ -48,16 +46,30 @@ pub fn get_docs_help<Output: Write>(cmd: &str, config: &Config, output: &mut Out
// Exit conditions
let Some(selection) = selection else { break Ok(()); };
let Some(entry) = config.plz_menu.entries.get(selection) else { break Ok(()); };
let mut operation_iter = entry.operation.iter();
let operation_iter = entry.operation.iter();
// if there is no key, then return an error, the operation key is required.
let (op_key, op_value) = operation_iter.next().ok_or(Error::PlzMenuNoOperation)?;
let (mut op_key, mut op_value) = (None, None);
// Create a new map with the capacity of the values map minus the first entry, to contain the parsed values.
let mut parsed_map = HashMap::with_capacity(values_map.len() - 1);
for (key, value) in operation_iter {
// If the operation key is not set, then check if the key is a valid operation key.
if op_key.is_none()
&& (key == "fetch"
|| key == "url"
|| key == "command"
|| key == "run"
|| key == "local")
{
op_key = Some(key.clone());
op_value = Some(value.clone());
continue;
}
parsed_map.insert(key.as_str(), parse_template(value, &values_map)?);
}
let op_value = parse_template(op_value, &values_map)?;
let result = match op_key.to_lowercase().as_str() {
// If the operation key is not set, then return an error, the operation key is required.
let (Some(op_key), Some(op_value)) = (op_key, op_value) else {return Err(Error::PlzMenuNoOperation)};
let op_value = parse_template(&op_value, &values_map)?;
let result = match op_key.as_str() {
"fetch" | "url" => FetchHandler.handle(op_value, &entry.operation),
"command" | "run" => CommandHandler.handle(op_value, &entry.operation),
"local" => todo!("run local"),
Expand Down Expand Up @@ -97,6 +109,9 @@ pub fn get_docs_help<Output: Write>(cmd: &str, config: &Config, output: &mut Out
fn build_the_values_map(cmd: &str) -> HashMap<String, String> {
let mut map = HashMap::with_capacity(5);
parse_cmd(cmd, &mut map); // This will add at least one entry and at most 3 entries
if map.capacity() < 3 {
map.shrink_to(map.capacity() + 2);
}
map.insert(
"halp-version".to_string(),
env!("CARGO_PKG_VERSION").to_string(),
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ pub fn run<Output: Write>(cli_args: CliArgs, output: &mut Output) -> Result<()>
};
cli_args.update_config(&mut config);
if let Some(ref cmd) = cli_args.cmd {
get_args_help(cmd, &config, cli_args.verbose, output)?;
get_args_help(cmd, config, cli_args.verbose, output)?;
} else if let Some(CliCommands::Plz { ref cmd, .. }) = cli_args.subcommand {
get_docs_help(cmd, &config, output)?;
get_docs_help(cmd, config, output)?;
}
Ok(())
}

0 comments on commit 6d07d80

Please sign in to comment.