Skip to content
This repository has been archived by the owner on Oct 8, 2024. It is now read-only.

Commit

Permalink
fix: more refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
PThorpe92 committed Apr 22, 2024
1 parent e7197b5 commit dc09c0d
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 81 deletions.
28 changes: 20 additions & 8 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct App<'a> {
pub screen_stack: Vec<Screen>,
/// index of selected item
pub selected: Option<usize>,
/// command (curl or wget)
/// command curl
pub command: Curl,
/// Input struct for tui_input dependency
pub input: Input,
Expand Down Expand Up @@ -351,14 +351,17 @@ impl<'a> App<'a> {

// Takes an array index of the selected item
pub fn execute_saved_command(&mut self, json: &str) {
let mut command: Curl = serde_json::from_str(json)
.map_err(|e| e.to_string())
.unwrap();
command.easy_from_opts();
match command.execute(None) {
Ok(_) => self.set_response(&command.get_response().unwrap_or("".to_string())),
let command: Result<Curl, String> = serde_json::from_str(json).map_err(|e| e.to_string());
match command {
Ok(mut cmd) => {
cmd.easy_from_opts();
match cmd.execute(None) {
Ok(_) => self.set_response(&cmd.get_response().unwrap_or("".to_string())),
Err(e) => self.set_response(&e),
};
}
Err(e) => self.set_response(&e),
};
}
}

pub fn copy_to_clipboard(&self, opt: &str) -> Result<(), String> {
Expand Down Expand Up @@ -410,6 +413,15 @@ impl<'a> App<'a> {
}

fn should_add_option(&self, opt: &AppOptions) -> bool {
if let AppOptions::ContentHeaders(headers) = opt {
return !self.command.opts.iter().any(|x| {
if let AppOptions::ContentHeaders(h) = x {
h == headers
} else {
false
}
});
}
match opt {
opt if opt.should_append() => true,
_ => !self.has_app_option(opt),
Expand Down
48 changes: 46 additions & 2 deletions src/display/inputopt.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use crate::request::curl::{AuthKind, Method};
use crate::{
request::curl::{AuthKind, Method},
screens::Screen,
};
use std::fmt::Display;

#[derive(Debug, Clone, PartialEq)]
Expand Down Expand Up @@ -37,8 +40,49 @@ pub enum InputOpt {
}

impl InputOpt {
pub fn get_return_screen(&self) -> Screen {
match self {
InputOpt::KeyLabel(_) => Screen::SavedKeys(None),
InputOpt::CmdLabel(id) => Screen::SavedCommands {
id: Some(*id),
opt: None,
},
InputOpt::CaPath => Screen::RequestMenu(None),
InputOpt::CaCert => Screen::RequestMenu(None),
InputOpt::CookiePath => Screen::RequestMenu(None),
InputOpt::CookieJar => Screen::RequestMenu(None),
InputOpt::CookieExpires(_) => Screen::RequestMenu(None),
InputOpt::CmdDescription(id) => Screen::SavedCommands {
id: Some(*id),
opt: None,
},
InputOpt::ApiKey => Screen::SavedKeys(None),
InputOpt::UnixSocket => Screen::RequestMenu(None),
InputOpt::UserAgent => Screen::RequestMenu(None),
InputOpt::MaxRedirects => Screen::RequestMenu(None),
InputOpt::NewCookie => Screen::RequestMenu(None),
InputOpt::Referrer => Screen::RequestMenu(None),
InputOpt::FtpAccount => Screen::RequestMenu(None),
InputOpt::VerifyPeer => Screen::RequestMenu(None),
InputOpt::Method(_) => Screen::RequestMenu(None),
InputOpt::RequestError(_) => Screen::RequestMenu(None),
InputOpt::AlertMessage(_) => Screen::RequestMenu(None),
InputOpt::ImportCollection => Screen::SavedCollections(None),
InputOpt::RenameCollection(_) => Screen::SavedCollections(None),
InputOpt::Execute => Screen::Response(String::new()),
InputOpt::CollectionDescription(_) => Screen::SavedCollections(None),
InputOpt::URL => Screen::RequestMenu(None),
InputOpt::UploadFile => Screen::RequestMenu(None),
InputOpt::Headers => Screen::Headers,
InputOpt::Output => Screen::Response(String::new()),
InputOpt::Verbose => Screen::RequestMenu(None),
InputOpt::RequestBody => Screen::RequestMenu(None),
InputOpt::Auth(_) => Screen::RequestMenu(None),
InputOpt::CookieValue(_) => Screen::RequestMenu(None),
}
}
pub fn is_error(&self) -> bool {
matches!(self, InputOpt::RequestError(_))
matches!(self, InputOpt::RequestError(_) | InputOpt::AlertMessage(_))
}
}

Expand Down
7 changes: 0 additions & 7 deletions src/display/menuopts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,6 @@ pub const ERROR_MENU_TITLE: &str = "* CuTE ** Error! *";
pub const SUCCESS_MENU_TITLE: &str = "* CuTE ** Success! *";
pub const POSTMAN_COLLECTION_TITLE: &str = "* CuTE ** Postman Collections";
pub const SUCCESS_MESSAGE: &str = "Request saved successfully";
pub const INPUT_OPT_URL: &str = "Enter a URL for your {}\n and press Enter";
pub const INPUT_OPT_HEADERS: &str =
"MUST be \"Key:Value\" pair and press Enter \n Example: Content-Type: application/json";
pub const INPUT_OPT_AUTH_BASIC: &str = "Enter username:password and press Enter";
pub const INPUT_OPT_AUTH_ANY: &str = "Enter your username and press Enter";
pub const INPUT_OPT_AUTH_BEARER: &str = "Enter your API token and press Enter";
pub const INPUT_OPT_BASIC: &str = "Enter a value and press Enter";
// This padds the choices in the menu. This is the least hideous way to do this.(I think)
pub const OPTION_PADDING_MAX: &str = "\n\n\n\n";
pub const OPTION_PADDING_MID: &str = "\n\n\n";
Expand Down
5 changes: 1 addition & 4 deletions src/display/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,7 @@ impl AppOptions {
)
}
pub fn should_append(&self) -> bool {
matches!(
self,
Self::Headers(_) | Self::NewCookie(_) | Self::ContentHeaders(_)
)
matches!(self, Self::Headers(_) | Self::NewCookie(_))
}
pub fn replace_value(&mut self, val: String) {
match self {
Expand Down
74 changes: 16 additions & 58 deletions src/screens/input/input_screen.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use crate::app::App;
use crate::display::menuopts::{
CERT_ERROR, HEADER_ERROR, INPUT_OPT_AUTH_ANY, INPUT_OPT_AUTH_BASIC, INPUT_OPT_AUTH_BEARER,
INPUT_OPT_BASIC, INPUT_OPT_HEADERS, PARSE_INT_ERROR, SOCKET_ERROR, UPLOAD_FILEPATH_ERROR,
CERT_ERROR, HEADER_ERROR, PARSE_INT_ERROR, SOCKET_ERROR, UPLOAD_FILEPATH_ERROR,
};
use crate::display::AppOptions;
use crate::request::curl::AuthKind;
use crate::screens::{centered_rect, Screen};
use crate::screens::Screen;
use crate::{app::InputMode, display::inputopt::InputOpt};
use std::path::Path;
use tui::prelude::Line;
use tui::style::{Color, Modifier};
use tui::style::Color;
use tui::widgets::Paragraph;
use tui::widgets::{Block, Borders};
use tui::{
Expand All @@ -20,50 +19,22 @@ use tui::{
};
use tui_input::InputRequest;

// Takes the current option and returns a prompt for that screen
pub fn get_input_prompt(opt: InputOpt) -> Text<'static> {
match opt {
InputOpt::URL => Text::from(Line::from("Enter a URL for your request and press Enter")),
InputOpt::RequestBody => Text::from("Enter a body for your request and press Enter"),
InputOpt::Headers => Text::from(Line::from(INPUT_OPT_HEADERS)),
InputOpt::Auth(auth) => match auth {
AuthKind::Basic(_) => Text::from(INPUT_OPT_AUTH_BASIC),
AuthKind::Bearer(_) => Text::from(INPUT_OPT_AUTH_BEARER),
_ => Text::from(INPUT_OPT_AUTH_ANY),
},
InputOpt::CookiePath => Text::from("Enter the path to the cookie jar file"),
InputOpt::NewCookie => Text::from("Enter the name of the cookie"),
InputOpt::CookieValue(ref name) => Text::from(format!("Enter the value for {}", name)),
InputOpt::CookieExpires(_) => {
Text::from("Enter the (optional) expiration date for the cookie")
}
InputOpt::ImportCollection => Text::from("Enter the path to the collection file.json"),
_ => Text::from(INPUT_OPT_BASIC),
}
}

pub fn handle_default_input_screen(app: &mut App, frame: &mut Frame<'_>, opt: InputOpt) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![
Constraint::Percentage(10),
Constraint::Percentage(10),
Constraint::Percentage(80),
Constraint::Percentage(13),
Constraint::Percentage(9),
Constraint::Percentage(78),
])
.horizontal_margin(6)
.split(frame.size());
let input_textbox = chunks[1];
let bottom_box = centered_rect(chunks[2], crate::screens::ScreenArea::Top);
let prompt = get_input_prompt(opt.clone());
frame.render_widget(
Paragraph::new(prompt).style(Style::default().add_modifier(Modifier::BOLD)),
centered_rect(bottom_box, crate::screens::ScreenArea::Top),
);
// prompt needs to be _directly_ below the input box
let top_box = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(40), Constraint::Percentage(60)].as_ref())
.split(input_textbox);
let width = top_box[1].width.max(3) - 3;
.split(chunks[1]);
let width = top_box[0].width.max(3) - 3;
let scroll = app.input.visual_scroll(width as usize);
match opt {
InputOpt::URL => {
Expand Down Expand Up @@ -213,18 +184,15 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
match opt {
InputOpt::URL => {
app.add_app_option(AppOptions::URL(message));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::ApiKey => {
let _ = app.db.as_ref().add_key(&message);
app.goto_screen(&Screen::SavedKeys(None));
}
InputOpt::UnixSocket => {
if let Err(e) = is_valid_unix_socket_path(&message) {
app.goto_screen(&Screen::RequestMenu(Some(InputOpt::RequestError(e))));
} else {
app.add_app_option(AppOptions::UnixSocket(message.clone()));
app.goto_screen(&Screen::RequestMenu(None));
}
}
InputOpt::Headers => {
Expand All @@ -234,27 +202,22 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
))));
} else {
app.add_app_option(AppOptions::Headers(message.clone()));
app.goto_screen(&Screen::RequestMenu(None));
}
}
InputOpt::RenameCollection(ref id) => {
if app.db.as_ref().rename_collection(*id, &message).is_ok() {
app.goto_screen(&Screen::SavedCollections(None));
} else {
app.goto_screen(&Screen::Error("Failed to rename collection".to_string()));
}
}
InputOpt::Output => {
app.add_app_option(AppOptions::Outfile(message));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::CookiePath => {
app.add_app_option(AppOptions::CookiePath(message));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::CookieJar => {
app.add_app_option(AppOptions::CookieJar(message));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::NewCookie => {
app.goto_screen(&Screen::RequestMenu(Some(InputOpt::CookieValue(message))));
Expand Down Expand Up @@ -284,11 +247,9 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
InputOpt::CookieExpires(ref cookie) => {
let cookie = format!("{} {}", cookie, message);
app.add_app_option(AppOptions::NewCookie(cookie));
app.goto_screen(&Screen::RequestMenu(None))
}
InputOpt::Referrer => {
app.add_app_option(AppOptions::Referrer(message.clone()));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::CaPath => {
if !validate_path(&message) {
Expand All @@ -297,17 +258,14 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
))));
} else {
app.add_app_option(AppOptions::CaPath(message.clone()));
app.goto_screen(&Screen::RequestMenu(None));
}
}
InputOpt::UserAgent => {
app.add_app_option(AppOptions::UserAgent(message.clone()));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::MaxRedirects => {
if let Ok(num) = message.parse::<usize>() {
app.add_app_option(AppOptions::MaxRedirects(num));
app.goto_screen(&Screen::RequestMenu(None));
} else {
app.goto_screen(&Screen::RequestMenu(Some(InputOpt::RequestError(
String::from(PARSE_INT_ERROR),
Expand All @@ -321,13 +279,12 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
))));
}
app.add_app_option(AppOptions::UploadFile(message));
app.goto_screen(&Screen::RequestMenu(None));
}
InputOpt::Execute => {
// This means they have executed the HTTP Request, and want to write to a file
app.command.set_outfile(&message);
if let Err(e) = app.command.write_output() {
app.goto_screen(&Screen::Error(e.to_string()));
app.goto_screen(&Screen::Response(e.to_string()));
} else {
app.goto_screen(&Screen::Response(String::from(
app.response.as_ref().unwrap_or(&String::new()).as_str(),
Expand All @@ -341,13 +298,13 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
match std::fs::read_to_string(&message) {
Ok(body) => {
app.add_app_option(AppOptions::RequestBody(body));
app.goto_screen(&Screen::RequestMenu(None));
}
Err(e) => app.goto_screen(&Screen::Error(e.to_string())),
Err(e) => app.goto_screen(&Screen::RequestMenu(Some(InputOpt::AlertMessage(
e.to_string(),
)))),
}
} else {
app.add_app_option(AppOptions::RequestBody(message.clone()));
app.goto_screen(&Screen::RequestMenu(None));
}
}
InputOpt::ImportCollection => {
Expand Down Expand Up @@ -380,11 +337,12 @@ pub fn parse_input(message: String, opt: InputOpt, app: &mut App) {
opt: Some(InputOpt::RequestError(format!("Error: {}", e))),
}),
},
InputOpt::Auth(auth) => {
InputOpt::Auth(ref auth) => {
parse_auth(auth, app, &message);
}
_ => {}
}
app.goto_screen(&opt.get_return_screen());
}

pub fn render_input_with_prompt<'a, T: Into<Text<'a>>>(frame: &mut Frame<'_>, prompt: T) {
Expand Down Expand Up @@ -414,7 +372,7 @@ fn validate_path(path: &str) -> bool {
Path::new(path).exists()
}

fn parse_auth(auth: AuthKind, app: &mut App, message: &str) {
fn parse_auth(auth: &AuthKind, app: &mut App, message: &str) {
app.command.set_auth(match auth {
AuthKind::Basic(_) => AuthKind::Basic(String::from(message)),
AuthKind::Bearer(_) => AuthKind::Bearer(String::from(message)),
Expand Down
1 change: 1 addition & 0 deletions src/screens/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ pub fn centered_rect(r: Rect, area: ScreenArea) -> Rect {
]
.as_ref(),
)
.vertical_margin(2)
.split(r)[1];
Layout::default()
.direction(Direction::Vertical)
Expand Down
2 changes: 1 addition & 1 deletion src/screens/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pub fn render(app: &mut App, frame: &mut Frame<'_>) {
.borders(Borders::ALL)
.border_type(BorderType::Double)
.title_style(Style::new().bold().italic())
.title("-Request Options-"),
.title("* Request Options *"),
)
.fg(app.config.get_fg_color())
.bg(app.config.get_bg_color())
Expand Down
2 changes: 1 addition & 1 deletion src/screens/saved_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub fn handle_alert_menu(app: &mut App, frame: &mut Frame<'_>, cmd: i32, opt: Op
.split(frame.size());
let options_box = layout[1].inner(&Margin {
vertical: 1,
horizontal: 25,
horizontal: 15,
});
let mut list_state = ListState::with_selected(ListState::default(), Some(app.cursor));
app.state = Some(list_state.clone());
Expand Down

0 comments on commit dc09c0d

Please sign in to comment.