summaryrefslogtreecommitdiff
path: root/src/config.rs
blob: b054c00fc6a709c571e2aaafd142b748076c2598 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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<Vec<CommentTokens>>{
	// 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<CommentTokens> = 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<CommentTokens>) -> Result<i32> {
	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<String>{
	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<CommentTokens>{
	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)
}