chore: renames

This commit is contained in:
əlemi 2024-10-20 01:32:05 +02:00
parent 26d996fbf9
commit 77fec19a22
Signed by: alemi
GPG key ID: A4895B84D311642C
5 changed files with 35 additions and 38 deletions

View file

@ -2,12 +2,11 @@ mod model;
mod errors; mod errors;
mod ext; mod ext;
use std::sync::Arc;
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use model::PostWomanConfig; pub use model::PostWomanCollection;
pub use errors::PostWomanError; pub use errors::PostWomanError;
pub static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); pub static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
/// API tester and debugger from your CLI /// API tester and debugger from your CLI
@ -63,14 +62,6 @@ pub enum PostWomanActions {
const TIMESTAMP_FMT: &str = "%H:%M:%S%.6f"; const TIMESTAMP_FMT: &str = "%H:%M:%S%.6f";
fn print_results(res: String, name: String, before: chrono::DateTime<chrono::Local>, suffix: String) {
let after = chrono::Local::now();
let elapsed = (after - before).num_milliseconds();
let timestamp = after.format(TIMESTAMP_FMT);
eprintln!(" + [{timestamp}] {name} {suffix}done in {elapsed}ms", );
print!("{}", res);
}
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), PostWomanError> { async fn main() -> Result<(), PostWomanError> {
let args = PostWomanArgs::parse(); let args = PostWomanArgs::parse();
@ -96,11 +87,11 @@ async fn main() -> Result<(), PostWomanError> {
PostWomanActions::Run { query, parallel, repeat, debug } => { PostWomanActions::Run { query, parallel, repeat, debug } => {
let pattern = regex::Regex::new(&query)?; let pattern = regex::Regex::new(&query)?;
let mut joinset = tokio::task::JoinSet::new(); let mut joinset = tokio::task::JoinSet::new();
let client = Arc::new(config.client); let client = std::sync::Arc::new(collection.client);
let env = Arc::new(config.env); let env = std::sync::Arc::new(collection.env);
for (name, mut endpoint) in config.route { for (name, mut endpoint) in collection.route {
if pattern.find(&name).is_some() { if pattern.find(&name).is_some() {
if debug { endpoint.extract = Some(ext::StringOr::T(model::Extractor::Debug)) }; if debug { endpoint.extract = Some(ext::StringOr::T(model::ExtractorConfig::Debug)) };
for i in 0..repeat { for i in 0..repeat {
let suffix = if repeat > 1 { let suffix = if repeat > 1 {
format!("#{} ", i+1) format!("#{} ", i+1)
@ -136,11 +127,15 @@ async fn main() -> Result<(), PostWomanError> {
} }
} }
}, },
// PostWomanActions::Save { name, url, method, headers, body } => {
// todo!();
// },
} }
Ok(()) Ok(())
} }
fn print_results(res: String, name: String, before: chrono::DateTime<chrono::Local>, suffix: String) {
let after = chrono::Local::now();
let elapsed = (after - before).num_milliseconds();
let timestamp = after.format(TIMESTAMP_FMT);
eprintln!(" + [{timestamp}] {name} {suffix}done in {elapsed}ms", );
print!("{}", res);
}

View file

@ -1,4 +1,6 @@
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct PostWomanClient { pub struct ClientConfig {
/// user agent for requests, defaults to 'postwoman/<version>'
pub user_agent: Option<String>, pub user_agent: Option<String>,
} }

View file

@ -7,11 +7,11 @@ use jaq_interpret::FilterT;
use crate::{PostWomanError, APP_USER_AGENT}; use crate::{PostWomanError, APP_USER_AGENT};
use crate::ext::{stringify_toml, stringify_json, StringOr}; use crate::ext::{stringify_toml, stringify_json, StringOr};
use super::{Extractor, PostWomanClient}; use super::{ExtractorConfig, ClientConfig};
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct Endpoint { pub struct EndpointConfig {
/// endpoint url, required /// endpoint url, required
pub url: String, pub url: String,
/// http method for request, default GET /// http method for request, default GET
@ -25,10 +25,10 @@ pub struct Endpoint {
/// expected error code, will fail if different /// expected error code, will fail if different
pub expect: Option<u16>, pub expect: Option<u16>,
/// response extractor /// response extractor
pub extract: Option<StringOr<Extractor>>, pub extract: Option<StringOr<ExtractorConfig>>,
} }
impl Endpoint { impl EndpointConfig {
pub fn fill(mut self, env: &toml::Table) -> Self { pub fn fill(mut self, env: &toml::Table) -> Self {
let mut vars: HashMap<String, String> = HashMap::default(); let mut vars: HashMap<String, String> = HashMap::default();
@ -80,7 +80,7 @@ impl Endpoint {
self self
} }
pub async fn execute(self, opts: &PostWomanClient) -> Result<String, PostWomanError> { pub async fn execute(self, opts: &ClientConfig) -> Result<String, PostWomanError> {
let method = match self.method { let method = match self.method {
Some(m) => reqwest::Method::from_str(&m)?, Some(m) => reqwest::Method::from_str(&m)?,
None => reqwest::Method::GET, None => reqwest::Method::GET,
@ -120,22 +120,22 @@ impl Endpoint {
} }
Ok(match self.extract.unwrap_or_default() { Ok(match self.extract.unwrap_or_default() {
StringOr::T(Extractor::Discard) => "".to_string(), StringOr::T(ExtractorConfig::Discard) => "".to_string(),
StringOr::T(Extractor::Body) => format_body(res).await?, StringOr::T(ExtractorConfig::Body) => format_body(res).await?,
StringOr::T(Extractor::Debug) => { StringOr::T(ExtractorConfig::Debug) => {
// TODO needless double format // TODO needless double format
let res_dbg = format!("{res:#?}"); let res_dbg = format!("{res:#?}");
let body = format_body(res).await?; let body = format_body(res).await?;
format!("{res_dbg}\nBody: {body}\n") format!("{res_dbg}\nBody: {body}\n")
}, },
StringOr::T(Extractor::Header { key }) => res StringOr::T(ExtractorConfig::Header { key }) => res
.headers() .headers()
.get(&key) .get(&key)
.ok_or(PostWomanError::HeaderNotFound(key))? .ok_or(PostWomanError::HeaderNotFound(key))?
.to_str()? .to_str()?
.to_string() .to_string()
+ "\n", + "\n",
StringOr::T(Extractor::Regex { pattern }) => { StringOr::T(ExtractorConfig::Regex { pattern }) => {
let pattern = regex::Regex::new(&pattern)?; let pattern = regex::Regex::new(&pattern)?;
let body = format_body(res).await?; let body = format_body(res).await?;
pattern.find(&body) pattern.find(&body)
@ -145,7 +145,7 @@ impl Endpoint {
+ "\n" + "\n"
}, },
// bare string defaults to JQL query // bare string defaults to JQL query
StringOr::T(Extractor::JQ { query }) | StringOr::Str(query) => { StringOr::T(ExtractorConfig::JQ { query }) | StringOr::Str(query) => {
let json: serde_json::Value = res.json().await?; let json: serde_json::Value = res.json().await?;
let selection = jq(&query, json)?; let selection = jq(&query, json)?;
if selection.len() == 1 { if selection.len() == 1 {

View file

@ -1,7 +1,7 @@
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")] #[serde(tag = "type", rename_all = "lowercase")]
pub enum Extractor { pub enum ExtractorConfig {
#[default] #[default]
Body, Body,
Debug, Debug,

View file

@ -2,14 +2,14 @@ mod client;
mod endpoint; mod endpoint;
mod extractor; mod extractor;
pub use client::PostWomanClient; pub use client::ClientConfig;
pub use endpoint::Endpoint; pub use endpoint::EndpointConfig;
pub use extractor::Extractor; pub use extractor::ExtractorConfig;
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct PostWomanConfig { pub struct PostWomanCollection {
pub client: PostWomanClient, pub client: ClientConfig,
pub env: toml::Table, pub env: toml::Table,
// it's weird to name it singular but makes more sense in config // it's weird to name it singular but makes more sense in config
pub route: indexmap::IndexMap<String, Endpoint>, pub route: indexmap::IndexMap<String, EndpointConfig>,
} }