gt/src/util.rs

83 lines
2.7 KiB
Rust
Raw Normal View History

2021-12-18 19:08:03 -06:00
use std::io;
2024-08-17 07:54:49 -05:00
use clap::{ArgMatches, Error};
use crate::request::RequestType;
pub enum ErrorKind {
BadRequest,
ForbiddenRequest,
NotFound,
UnprocessiableRequest,
}
2021-12-18 19:08:03 -06:00
// TODO: Can't get this function to properly work
// Currently, I'm grabbing input and have the server tell me whether or
// not input was validated. What I want to have happen is if there's
// a failure in input validation, I want the program to tell right away
// not have the server tell me when I'm doen inputting values
2021-12-19 13:50:36 -06:00
/// Function to get input from the user. It successfully grabs input but there's
/// no input validation as the server handles that.
2021-12-18 19:08:03 -06:00
pub fn get_input(question: String) -> String {
let result: String;
loop {
let mut input = String::new();
println!("{}", &question);
io::stdin().read_line(&mut input).unwrap();
match input.len() {
0 => println!("{}", "Sorry, that wasn't valid input. Please try again.\n"),
_ => {
result = input.trim().to_string();
break;
}
}
2024-08-17 07:54:49 -05:00
}
2021-12-18 19:08:03 -06:00
result
2024-08-17 07:54:49 -05:00
}
/// When you get a bad response from your Gitea server (any HTTP response that has
/// a status code not 2xx), and given the kind of response a user receives, the
/// appropriate message should be returned
pub fn bad_response_message(message: &String, error_kind: ErrorKind) -> String {
let final_message: String;
match error_kind {
ErrorKind::BadRequest => {
final_message = format!(
"Client error - please try again!\nError message: {}",
message
);
}
ErrorKind::ForbiddenRequest => {
final_message = format!(
"Client error - unauthorized. Please try again!\nError message: {}",
message
);
}
ErrorKind::NotFound => {
final_message = format!("Client error - not found!\nError message: {}", message);
}
ErrorKind::UnprocessiableRequest => {
final_message = format!("Client error - the request can't be processed. Please try again!\nError message: {}", message);
}
}
String::from(final_message)
}
/// Based on a subcommand that is passed, return the appropriate request
/// type
pub fn get_request_type(args: &ArgMatches) -> Result<RequestType, clap::Error> {
let request_type: &str = args.subcommand().0;
match request_type {
"repo" => Ok(RequestType::Repository),
"issue" => Ok(RequestType::Issue),
"pr" => Ok(RequestType::PullRequest),
"user" => Ok(RequestType::User),
_ => Err(clap::Error::with_description(
"Unknown or invalid command",
clap::ErrorKind::InvalidSubcommand,
)),
}
}