Skip to content

Commit

Permalink
support curl import location from command line
Browse files Browse the repository at this point in the history
  • Loading branch information
jwtly10 committed May 2, 2024
1 parent 7189aa3 commit ae71028
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 33 deletions.
45 changes: 23 additions & 22 deletions src/app/files/curl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ use crate::request::method::Method;
use crate::request::request::{KeyValue, Request};

impl App<'_> {
pub fn import_curl_file(&mut self, path_buf: &PathBuf) {
println!("Parsing curl file");
pub fn import_curl_file(&mut self, path_buf: &PathBuf, save_to: &str) {
println!("Importing curl file from {:?} to {:?}", path_buf, save_to);

let original_curl = match fs::read_to_string(path_buf) {
Ok(original_curl) => original_curl,
Expand All @@ -29,46 +29,37 @@ impl App<'_> {
Err(e) => panic_error(format!("Could not parse cURL\n\t{e}")),
};

// For now, the stem of the file is the name of the request
let req_name = match extract_file_name(path_buf){
Ok(name) => name,
Err(e) => panic_error(format!("Could not extract file name\n\t{e}"))
let (collection_name, req_name) = match validate_save_to(save_to) {
Ok((collection_name, req_name)) => (collection_name, req_name),
Err(e) => panic_error(format!("Could not validate chosen collection/request\n\t{e}")),
};

// We will check if theres an 'imported collection', if so we will append, else create
let imported_exists = self.collections.iter().any(|c| c.name == "imported");
let collection_exists = self.collections.iter().any(|c| c.name == collection_name);

if imported_exists {
if collection_exists {
let imported = self
.collections
.iter_mut()
.find(|c| c.name == "imported")
.find(|c| c.name == collection_name.clone())
.unwrap();
imported.requests.push(Arc::new(RwLock::new(parse_request(&curl, req_name))));
} else {
let collection = Collection {
name: "imported".to_string(),
name: collection_name.clone(),
requests: vec![Arc::new(RwLock::new(parse_request(&curl, req_name)))],
path: ARGS.directory.join("imported.json"),
path: ARGS.directory.join(collection_name.clone() + ".json"),
};

self.collections.push(collection);
}

let imported_index = self.collections.iter().position(|c| c.name == "imported").unwrap();
let imported_index = self.collections.iter().position(|c| c.name == collection_name).unwrap();
self.save_collection_to_file(imported_index);
}
}

fn extract_file_name(path_buf: &PathBuf) -> Result<String, String> {
path_buf.file_stem()
.ok_or_else(|| "Filename not found".to_string())
.and_then(|name| name.to_str().ok_or_else(|| "Filename is not valid UTF-8".to_string()))
.map(|name| name.to_string())
}

fn parse_request(curl: &Curl, req_name: String) -> Request {
print!("Found cURL: {:?}", curl);
println!("Found cURL: {:?}", curl);

let mut request = Request::default();

Expand Down Expand Up @@ -127,7 +118,7 @@ fn parse_request(curl: &Curl, req_name: String) -> Request {

/* BODY */

// TODO: Handle content type
// TODO: Handle content type, for now we just assume raw
request.body = ContentType::Raw(curl.options_data_raw.to_string());

request
Expand All @@ -146,3 +137,13 @@ fn get_http_method(curl: &Curl) -> Method {
Method::GET
}
}

fn validate_save_to(save_to: &str) -> Result<(String, String), String> {
let parts: Vec<&str> = save_to.split('/').collect();

if parts.len() != 2 {
return Err("Path is not in the format collection/request name".to_string());
}

Ok((parts[0].to_string(), parts[1].to_string()))
}
10 changes: 8 additions & 2 deletions src/app/startup/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::env;
use std::path::PathBuf;
use clap::{Parser, Subcommand};
use lazy_static::lazy_static;
use crate::{panic_error};
use crate::panic_error;

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
Expand All @@ -27,7 +27,13 @@ pub enum Command {

#[derive(Debug, clap::Args, PartialEq)]
pub struct ImportArgs {
/// A file to import, only Postman v2.1 JSON collection for now
/// The type of file to import, Postman v2.1 JSON collection (postman), or a curl file (curl)
pub import_type: String,

/// The path to save the imported collection including the request name (collection/request_name)
pub save_to: String,

/// A file to import, only Postman v2.1 JSON and curl files are supported
pub path: PathBuf,

/// Max depth at which import should stop creating nested collections and only get the deeper requests
Expand Down
18 changes: 9 additions & 9 deletions src/app/startup/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ impl App<'_> {
if let Some(command) = &ARGS.command {
match command {
Command::Import(import_args) => {
print!("Importing: {}", import_args.path.display());

let extension = import_args.path.extension().unwrap_or_default().to_str().unwrap_or_default();
if extension == "json" {
// If the file is json, we attempt to import postman collection
self.import_postman_collection(&import_args.path, import_args.max_depth.unwrap_or(99));
} else {
// We attempt to import a curl file
self.import_curl_file(&import_args.path);
println!("Importing: {}", import_args.path.display());

if import_args.import_type == "postman" {
self.import_postman_collection(
&import_args.path,
import_args.max_depth.unwrap_or(99),
);
} else if import_args.import_type == "curl" {
self.import_curl_file(&import_args.path, &import_args.save_to);
}
}
}
Expand Down

0 comments on commit ae71028

Please sign in to comment.