use clap::ArgMatches; use std::fs; use std::io; use crate::client::{ build_url_from_config, create_snippet, ApiResult, OutgoingSnippet, ServerConfig, }; fn build_snippet_from_matches(matches: &ArgMatches) -> io::Result { let title = matches.value_of("name").unwrap(); let input = matches.value_of("file"); let filetype = matches.value_of("filetype").unwrap(); let mut rdr: Box = match input { Some(file) => Box::new(fs::File::open(file)?), None => Box::new(io::stdin()), }; let mut body = String::new(); rdr.read_to_string(&mut body)?; Ok(OutgoingSnippet { title: title.to_string(), body, filetype: filetype.to_string(), }) } fn build_server_config_from_matches(matches: &ArgMatches) -> ServerConfig { let protocol = matches.value_of("protocol").unwrap(); let hostname = matches.value_of("hostname").unwrap(); let port = matches.value_of("port").unwrap(); ServerConfig { protocol: protocol.to_string(), hostname: hostname.to_string(), port: port.parse::().expect("Port should be numeric"), } } pub fn new_snippet(matches: &ArgMatches) -> io::Result<()> { let snippet = build_snippet_from_matches(matches)?; let config = build_server_config_from_matches(matches); let url = build_url_from_config(&config); match create_snippet(snippet, &config) { Ok(resp) => match resp { ApiResult::IncomingSnippet { uuid, .. } => println!("{}/snippets/{}", url, uuid), ApiResult::IncomingError { message } => println!("error: {}", message), }, Err(err) => println!("{}", err), } Ok(()) }