Skip to content

Commit

Permalink
refactor(cli): simplify file parsing (#176)
Browse files Browse the repository at this point in the history
* refactor(cli): remove unnecessary allocation from parse_requests_threaded

* fix: remove indent layer

* fix: remove unnecessary iteration

* refactor(cli): simpligy file parsing
  • Loading branch information
hougesen authored Feb 12, 2024
1 parent 1c85361 commit 0c27949
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 43 deletions.
51 changes: 51 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions hitt-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ path = "src/main.rs"
[dependencies]
clap = { version = "4.4.18", features = ["derive"] }
crossterm = "0.27.0"
futures = "0.3.30"
hitt-formatter = { workspace = true }
hitt-parser = { workspace = true }
hitt-request = { workspace = true }
Expand Down
32 changes: 19 additions & 13 deletions hitt-cli/src/commands/run.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use std::sync::Arc;

use crossterm::{style::Print, style::Stylize, QueueableCommand};
use hitt_request::send_request;

use crate::{
config::{variables::parse_variable_argument, RunCommandArguments},
error::HittCliError,
fs::{find_http_files, parse_requests_threaded},
fs::{find_http_files, parse_file, parse_files},
terminal::handle_response,
};

Expand All @@ -20,14 +22,6 @@ pub async fn run_command<W: std::io::Write + Send>(
return Err(HittCliError::RecursiveNotEnabled);
}

let http_file_paths = if is_dir_path {
find_http_files(&args.path)
} else {
vec![args.path.clone()]
};

let timeout = args.timeout.map(core::time::Duration::from_millis);

let mut vars = std::collections::HashMap::new();

if let Some(arg_variables) = args.var.clone() {
Expand All @@ -38,19 +32,31 @@ pub async fn run_command<W: std::io::Write + Send>(
}
}

let parsed_files = parse_requests_threaded(http_file_paths, vars).await?;
let parsed_files = if is_dir_path {
parse_files(find_http_files(&args.path), vars).await
} else {
parse_file(&args.path, Arc::new(vars))
.await
.map(|r| vec![r])
}?;

let timeout = args.timeout.map(core::time::Duration::from_millis);

let mut request_count: u16 = 0;

for (path, file) in parsed_files {
if !args.vim {
term.queue(Print(format!("hitt: running {path:?}\n\n").cyan()))?;
if request_count > 0 {
term.queue(Print('\n'))?;
}

term.queue(Print(format!("hitt: running {path:?}\n").cyan()))?;
term.flush()?;
}

for req in file {
if request_count > 0 {
term.queue(Print("\n"))?;
if !args.vim || request_count != 0 {
term.queue(Print('\n'))?;
}

match send_request(&http_client, &req, &timeout).await {
Expand Down
51 changes: 22 additions & 29 deletions hitt-cli/src/fs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,28 @@
use std::sync::Arc;

use futures::future::TryJoinAll;
use hitt_parser::HittRequest;

use crate::error::HittCliError;

#[inline]
async fn get_file_content(path: &std::path::Path) -> Result<String, std::io::Error> {
tokio::fs::read(path)
.await
.map(|buf| String::from_utf8_lossy(&buf).to_string())
pub async fn parse_file(
path: &std::path::Path,
input_variables: Arc<std::collections::HashMap<String, String>>,
) -> Result<(std::path::PathBuf, Vec<HittRequest>), HittCliError> {
match tokio::fs::read(&path).await {
Ok(buf) => {
let content = String::from_utf8_lossy(&buf);

match hitt_parser::parse_requests(&content, &input_variables) {
Ok(reqs) => Ok((path.to_owned(), reqs)),
Err(e) => Err(HittCliError::Parse(path.to_owned(), e)),
}
}
Err(err) => Err(HittCliError::IoRead(path.to_owned(), err)),
}
}

pub async fn parse_requests_threaded(
pub async fn parse_files(
paths: Vec<std::path::PathBuf>,
input_variables: std::collections::HashMap<String, String>,
) -> Result<Vec<(std::path::PathBuf, Vec<HittRequest>)>, HittCliError> {
Expand All @@ -22,36 +33,18 @@ pub async fn parse_requests_threaded(
.map(|path| {
let var_clone = Arc::clone(&vars);

tokio::task::spawn(async move {
(
get_file_content(&path)
.await
.map(|content| {
hitt_parser::parse_requests(&content, &var_clone)
.map_err(|error| HittCliError::Parse(path.clone(), error))
})
.map_err(|error| HittCliError::IoRead(path.clone(), error)),
path,
)
})
tokio::task::spawn(async move { parse_file(&path, var_clone).await })
})
.collect::<Vec<_>>();
.collect::<TryJoinAll<_>>()
.await?;

let mut parsed_requests = Vec::new();

for handle in handles {
let result = handle.await.map_err(HittCliError::Join)?;

// TODO: clean up this mess
let reqs = result.0??;

parsed_requests.push((reqs, result.1));
parsed_requests.push(handle?);
}

Ok(parsed_requests
.into_iter()
.map(|(reqs, path)| (path, reqs))
.collect())
Ok(parsed_requests)
}

pub fn find_http_files(path: &std::path::Path) -> Vec<std::path::PathBuf> {
Expand Down
2 changes: 1 addition & 1 deletion hitt-cli/src/terminal/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use hitt_formatter::ContentType;

#[inline]
fn __print_body<W: std::io::Write>(term: &mut W, body: &str) -> Result<(), std::io::Error> {
queue!(term, Print("\n"), Print(body.dark_yellow()), Print("\n\n"))
queue!(term, Print('\n'), Print(body.dark_yellow()), Print("\n\n"))
}

#[cfg(test)]
Expand Down

0 comments on commit 0c27949

Please sign in to comment.