From 7c29036bf54277806dc0bad2d961a2b5740fecd6 Mon Sep 17 00:00:00 2001 From: Rizky Luthfianto Date: Wed, 6 Jan 2016 23:34:24 +0700 Subject: [PATCH] refactor(main.rs): create the `fetch_from_internet` function --- src/main.rs | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index a17ef8f..69901ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,23 +16,17 @@ const PLATFORM: &'static str = "osx"; #[cfg(not(target_os = "macos"))] const PLATFORM: &'static str = "linux"; -fn main() { - let args: Vec = env::args().collect(); - - if args.len() < 2 { - let error = "Specify an argument!"; - println!("{}", format!("{error} \nExample: \n$ tldr ls", error = Red.paint(error).to_string())); - process::exit(1); - } - - let common_url = format!("https://raw.github.com/tldr-pages/tldr/master/pages/common/{page}.md", page = args[1]); - let platform_url = format!("https://raw.github.com/tldr-pages/tldr/master/pages/{platform}/{page}.md", page = args[1], platform=PLATFORM); +fn fetch_from_internet(command: &str) -> String { + let common_url = format!("https://raw.github.com/tldr-pages/tldr/master/pages/common/{page}.md", page = command); + let platform_url = format!("https://raw.github.com/tldr-pages/tldr/master/pages/{platform}/{page}.md", page = command, platform=PLATFORM); let client = Client::new(); - // Creating an outgoing request. + // Fetch common tldr let mut res = match client.get(&common_url).send() { Ok(res) => res, + + // Fetch platform tldr if 404 _ => client.get(&platform_url).send().unwrap(), }; @@ -40,6 +34,20 @@ fn main() { let mut the_tldr = String::new(); res.read_to_string(&mut the_tldr).unwrap(); + the_tldr +} + +fn main() { + let args: Vec = env::args().collect(); + + if args.len() < 2 { + let error = "Specify an argument!"; + println!("{}", format!("{error} \nExample: \n$ tldr ls", error = Red.paint(error).to_string())); + std::process::exit(1); + } + + let the_tldr = fetch_from_internet(&args[1]); + render(&the_tldr); }