From a07f7e00dc107324c37686e365bd992e3b65ac25 Mon Sep 17 00:00:00 2001 From: Danilo Bargen Date: Fri, 22 Jan 2016 08:27:09 +0100 Subject: [PATCH] Implement Decodable for OsType --- src/cache.rs | 2 +- src/main.rs | 7 +------ src/types.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/cache.rs b/src/cache.rs index d0e686d..d674ca1 100644 --- a/src/cache.rs +++ b/src/cache.rs @@ -105,7 +105,7 @@ impl Cache { let platform = match self.os { OsType::Linux => Some("linux"), OsType::OsX => Some("osx"), - OsType::SunOS => None, // TODO: Does Rust support SunOS + OsType::SunOs => None, // TODO: Does Rust support SunOS? OsType::Other => None, }; diff --git a/src/main.rs b/src/main.rs index f503157..6c9277c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -73,7 +73,7 @@ struct Args { flag_version: bool, flag_list: bool, flag_render: Option, - flag_os: Option, // TODO enum + flag_os: Option, flag_update: bool, flag_clear_cache: bool, } @@ -173,11 +173,6 @@ fn main() { process::exit(1); } - // Override OS and exit - if let Some(os) = args.flag_os { - println!("Flag --os not yet implemented."); - } - // Show command from cache if let Some(command) = args.arg_command { diff --git a/src/types.rs b/src/types.rs index 4594aa4..ae7bad3 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,15 +1,38 @@ //! Types used in the client. +use rustc_serialize::{Decodable, Decoder}; + + #[derive(Debug, Eq, PartialEq)] #[allow(dead_code)] pub enum OsType { Linux, OsX, - SunOS, + SunOs, Other, } +/// Custom Decodable implementation, so that we can parse command line arguments +/// directly into an `OsType` instance. +impl Decodable for OsType { + fn decode(d: &mut D) -> Result { + return d.read_str().and_then(|input| { + let lowercase = input.to_lowercase(); + match &lowercase[..] { + "linux" => Ok(OsType::Linux), + "osx" => Ok(OsType::OsX), + "sunos" => Ok(OsType::SunOs), + "other" => Ok(OsType::Other), + _ => Err(d.error(&format!("Invalid OS type: '{}'. Choose one of 'linux', \ + 'osx', 'sunos' or 'other'.", lowercase))) + } + }); + } +} + + + #[derive(Debug, Eq, PartialEq)] pub enum LineType { Empty, @@ -35,3 +58,30 @@ impl<'a> From<&'a str> for LineType { } } } + +#[cfg(test)] +mod test { + extern crate rustc_serialize; + extern crate docopt; + + use super::OsType::{self, Linux, OsX, SunOs, Other}; + use rustc_serialize::json; + + #[test] + fn test_os_type_decoding_regular() { + assert_eq!(json::decode::("\"linux\"").unwrap(), Linux); + assert_eq!(json::decode::("\"osx\"").unwrap(), OsX); + assert_eq!(json::decode::("\"sunos\"").unwrap(), SunOs); + assert_eq!(json::decode::("\"other\"").unwrap(), Other); + } + + #[test] + fn test_os_type_decoding_uppercase() { + assert_eq!(json::decode::("\"Linux\"").unwrap(), Linux); + assert_eq!(json::decode::("\"LINUX\"").unwrap(), Linux); + } +#[test] + fn test_os_type_decoding_unknown() { + assert!(json::decode::("\"lindows\"").is_err()); + } +}