use std::fs::File; use std::option::Option; use std::process::*; use std::env::home_dir; use std::io::*; use std::io::ErrorKind::Other; static LOCAL_CONF_FILE_NAME: &'static str = ".loc.config"; static GLOBAL_CONF_FILE_NAME: &'static str = "/etc/loc/config"; pub struct CommentTokens { pub file_ending: String, pub single_line: String, pub begin_comment_block: String, pub end_comment_block: String, } pub fn read_config() -> Result>{ // first read the local files .loc.config let mut local_error = false; let mut global_error = false; let mut user_error = false; let mut conf: Vec = Vec::new(); match read_config_file(LOCAL_CONF_FILE_NAME, &mut conf) { Ok(_i) => {}, Err(_e) => {local_error = true}, } if let Some(mut x) = home_dir() { x.push(LOCAL_CONF_FILE_NAME); let user_conf_file_name = x.to_str().unwrap(); match read_config_file(user_conf_file_name, &mut conf) { Ok(_i) => {}, Err(_e) => { user_error = true}, } } match read_config_file(GLOBAL_CONF_FILE_NAME,&mut conf) { Ok(_i) => {}, Err(_e) => {global_error= true}, } // quit programm if could not read any config file if local_error && global_error && user_error { println!("failed to read config files:\n\ {}: \n\ {}:", LOCAL_CONF_FILE_NAME, GLOBAL_CONF_FILE_NAME); exit(1); } Ok(conf) } fn read_config_file(config_file: &str, conf: &mut Vec) -> Result { let f = try!(File::open(config_file)); let bufread = BufReader::new(f); for (index, line) in bufread.lines().enumerate() { match parse_config_file_line(&try!(line)) { Ok(conf_tok) => conf.push(conf_tok), Err(e)=> println!("error file {}, line {}: {}", config_file, index+1, e), } } Ok(10) } fn config_file_line_unwrap_element(elem: Option<&str>) -> Result{ match elem { Some(line) => Ok(line.to_string()), None => Err(Error::new(Other, "must have four tokens")), } } fn parse_config_file_line(line: &str) -> Result{ let mut tokens = line.split_whitespace(); let conf = CommentTokens { file_ending : try!(config_file_line_unwrap_element(tokens.next())), single_line : try!(config_file_line_unwrap_element(tokens.next())), begin_comment_block : try!(config_file_line_unwrap_element(tokens.next())), end_comment_block : try!(config_file_line_unwrap_element(tokens.next())), }; // there should not be anymore value otherwise print warning // for wrong config file format if tokens.next() != None { return Err(Error::new(Other, "more than four tokens")); } Ok(conf) }