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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//!The ini module provides all the things necessary to load and parse ini-syntax files. The most important of which is the `Ini` struct.
//!See the [implementation](https://docs.rs/configparser/*/configparser/ini/struct.Ini.html) documentation for more details.
use std::fs;
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use std::collections::HashMap;

///A public function of the module to load and parse files into a hashmap.
///Support for this function will be dropped in the near future and replaced with a macro.
#[deprecated(
	since = "0.3.0",
	note = "Please use the Ini struct instead."
	)]
pub fn load(path: &str) -> HashMap<String, HashMap<String, Option<String>>> {
	let mut config = Ini::new();
	match config.load(path) {
		Err(why) => panic!("{}", why),
		Ok(_) => ()
	}
	match config.get_map() {
		Some(map) => map,
		None => HashMap::new()
	}
}

///The `Ini` struct simply contains a nested hashmap of the loaded configuration, the default section header and comment symbols.
///## Example
///```rust
///use configparser::ini::Ini;
///
///let mut config = Ini::new();
///```
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Ini {
	map: HashMap<String, HashMap<String, Option<String>>>,
	default_section: std::string::String,
	comment_symbols: Vec<char>
}

impl Ini {
	///Creates a new `HashMap` of `HashMap<String, HashMap<String, Option<String>>>` type for the struct.
	///All values in the HashMap are stored in `String` type.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///```
	///Returns the struct and stores it in the calling variable.
	pub fn new() -> Ini {
		Ini {
			map: HashMap::new(),
			default_section: String::from("default"),
			comment_symbols: vec![';', '#']
		}
	}

	///Creates a new `HashMap` of `HashMap<String, HashMap<String, Option<String>>>` type for the struct.
	///All values in the HashMap are stored in `String` type.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///```
	///Returns the struct and stores it in the calling variable.

	///Sets the default section header to the defined string (the default is `default`).
	///It must be set before `load()` or `read()` is called in order to take effect.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///
	///config.set_default_section("topsecret");
	///let map = config.load("tests/test.ini").unwrap();
	///```
	///Returns nothing.
	pub fn set_default_section(&mut self, section: &str) {
		self.default_section = section.to_string();
	}

	///Sets the default comment symbols to the defined character slice (the defaults are `;` and `#`).
	///Keep in mind that this will remove the default symbols. It must be set before `load()` or `read()` is called in order to take effect.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///config.set_comment_symbols(&['!', '#']);
	///let map = config.load("tests/test.ini").unwrap();
	///```
	///Returns nothing.
	pub fn set_comment_symbols(&mut self, symlist: &[char]) {
		self.comment_symbols = symlist.to_vec();
	}

	///Loads a file from a defined path, parses it and puts the hashmap into our struct.
	///At one time, it only stores one configuration, so each call to `load()` or `read()` will clear the existing `HashMap`, if present.
	///## Example
	///```ignore,rust
	///let map = match config.load("Path/to/file...").unwrap();
	///let location = map["tupac's"]["crib"].clone().unwrap();
	///```
	///Returns `Ok(map)` with a clone of the stored `HashMap` if no errors are thrown or else `Err(error_string)`.
	///Use `get_mut_map()` if you want a mutable reference.
	pub fn load(&mut self, path: &str) -> Result<HashMap<String, HashMap<String, Option<String>>>, String> {
		let path = Path::new(path);
		let display = path.display();

		let mut file = match File::open(&path) {
			Err(why) => return Err(format!("couldn't open {}: {}", display, why)),
			Ok(file) => file
		};

		let mut s = String::new();
		self.map = match file.read_to_string(&mut s) {
			Err(why) => return Err(format!("couldn't read {}: {}", display, why)),
			Ok(_) => match self.parse(s) {
				Err(why) => return Err(why),
				Ok(map) => map
			}
		};
		Ok(self.map.clone())
	}

	///Reads an input string, parses it and puts the hashmap into our struct.
	///At one time, it only stores one configuration, so each call to `load()` or `read()` will clear the existing `HashMap`, if present.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///let map = match config.read(String::from(
	///	"[2000s]
	///	2020 = bad")) {
	/// Err(why) => panic!("{}", why),
	/// Ok(inner) => inner
	///};
	///let this_year = map["2000s"]["2020"].clone().unwrap();
	///assert_eq!(this_year, "bad"); // value accessible!
	///```
	///Returns `Ok(map)` with a clone of the stored `HashMap` if no errors are thrown or else `Err(error_string)`.
	///Use `get_mut_map()` if you want a mutable reference.
	pub fn read(&mut self, input: String) -> Result<HashMap<String, HashMap<String, Option<String>>>, String> {
		self.map = match self.parse(input) {
			Err(why) => return Err(why),
			Ok(map) => map
		};
		Ok(self.map.clone())
	}

	///Writes the current configuation to the specfied path. If a file is not present, it is automatically created for you, if a file already
	///exists, it is truncated and the configuration is written to it.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///fn main() -> std::io::Result<()> {
	///  let mut config = Ini::new();
	///  config.read(String::from(
	///    "[2000s]
	///    2020 = bad"));
	///  config.write("output.ini")
	///}
	///```
	///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
	pub fn write(&self, path: &str) -> std::io::Result<()> {
		let mut out = String::new();
		let mut cloned = self.map.clone();
		if let Some(defaultmap) = cloned.get("default") {
			for (key, val) in defaultmap.iter() {
				out.push_str(&key);
				if let Some(value) = val {
					out.push_str("=");
					out.push_str(&value);
				}
				out.push_str("\n");
			}
			cloned.remove("default");
		}
		for (section, secmap) in cloned.iter() {
			out.push_str(&format!("[{}]", section));
			out.push_str("\n");
			for (key, val) in secmap.iter() {
				out.push_str(&key);
				if let Some(value) = val {
					out.push_str("=");
					out.push_str(&value);
				}
				out.push_str("\n");
			}
		}
		fs::write(path, out)
	}

	///Private function that parses ini-style syntax into a HashMap.
	fn parse(&self, input: String) -> Result<HashMap<String, HashMap<String, Option<String>>>, String> {
		let mut map: HashMap<String, HashMap<String, Option<String>>> = HashMap::new();
		let mut section = self.default_section.clone();
		for (num, lines) in input.lines().enumerate() {
			let trimmed = match lines.find(|c: char| self.comment_symbols.contains(&c)) {
				Some(idx) => lines[..idx].trim(),
				None => lines.trim()
			};
			if trimmed.len() == 0 {
				continue;
			}
			match trimmed.find('[') {
				Some(start) => match trimmed.rfind(']') {
					Some(end) => {
						section = trimmed[start+1..end].trim().to_lowercase();
					},
					None => {
						return Err(format!("line {}:{}: Found opening bracket but no closing bracket", num, start));
					}
				}
				None => match trimmed.find('=') {
					Some(delimiter) => {
						match map.get_mut(&section) {
							Some(valmap) => {
								let key = trimmed[..delimiter].trim().to_lowercase();
								let value = trimmed[delimiter+1..].trim().to_string();
								if key.len() == 0 {
									return Err(format!("line {}:{}: Key cannot be empty", num, delimiter));
								}
								else {
									valmap.insert(key, Some(value));
								}
							},
							None => {
								let mut valmap: HashMap<String, Option<String>> = HashMap::new();
								let key = trimmed[..delimiter].trim().to_lowercase();
								let value = trimmed[delimiter+1..].trim().to_string();
								if key.len() == 0 {
									return Err(format!("line {}:{}: Key cannot be empty", num, delimiter));
								}
								else {
									valmap.insert(key, Some(value));
								}
								map.insert(section.clone(), valmap);
							}
						}
					},
					None => match map.get_mut(&section) {
						Some(valmap) => {
							let key = trimmed.to_lowercase();
							valmap.insert(key, None);
						},
						None => {
							let mut valmap: HashMap<String, Option<String>> = HashMap::new();
							let key = trimmed.to_lowercase();
							valmap.insert(key, None);
							map.insert(section.clone(), valmap);
						}
					}
				}
			}
		}
		Ok(map)
	}

	///Returns a clone of the stored value from the key stored in the defined section.
	///Unlike accessing the map directly, `get()` processes your input to make case-insensitive access.
	///All `get` functions will do this automatically.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///config.load("tests/test.ini");
	///let value = config.get("default", "defaultvalues").unwrap();
	///assert_eq!(value, String::from("defaultvalues"));
	///```
	///Returns `Some(value)` of type `String` if value is found or else returns `None`.
	pub fn get(&self, section: &str, key: &str) -> Option<String> {
		self.map.get(&section.to_lowercase())?.get(&key.to_lowercase())?.clone()
	}

	///Parses the stored value from the key stored in the defined section to a `bool`.
	///For ease of use, the function converts the type case-insensitively (`true` == `True`).
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///config.load("tests/test.ini");
	///let value = config.getbool("values", "bool").unwrap().unwrap();
	///assert!(value);  // value accessible!
	///```
	///Returns `Ok(Some(value))` of type `bool` if value is found or else returns `Ok(None)`.
	///If the parsing fails, it returns an `Err(string)`.
	pub fn getbool(&self, section: &str, key: &str) -> Result<Option<bool>, String> {
		match self.map.get(&section.to_lowercase()) {
			Some(secmap) => match secmap.get(&key.to_lowercase()) {
				Some(val) => match val {
					Some(inner) => match inner.to_lowercase().parse::<bool>() {
						Err(why) => Err(why.to_string()),
						Ok(boolean) => Ok(Some(boolean))
					},
					None => Ok(None)
				},
				None => Ok(None)
			},
			None => Ok(None)
		}
	}

	///Parses the stored value from the key stored in the defined section to a `bool`. For ease of use, the function converts the type coerces a match.
	///It attempts to case-insenstively find `true`, `yes`, `t`, `y` and `1` to parse it as `True`.
	///Similarly it attempts to case-insensitvely find `false`, `no`, `f`, `n` and `0` to parse it as `False`.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///config.load("tests/test.ini");
	///let value = config.getboolcoerce("values", "boolcoerce").unwrap().unwrap();
	///assert!(!value);  // value accessible!
	///```
	///Returns `Ok(Some(value))` of type `bool` if value is found or else returns `Ok(None)`.
	///If the parsing fails, it returns an `Err(string)`.
	pub fn getboolcoerce(&self, section: &str, key: &str) -> Result<Option<bool>, String> {
		match self.map.get(&section.to_lowercase()) {
			Some(secmap) => match secmap.get(&key.to_lowercase()) {
				Some(val) => match val {
					Some(inner) => {
						let boolval = &inner.to_lowercase().clone()[..];
						if ["true", "yes", "t", "y", "1"].contains(&&boolval) {
							return Ok(Some(true));
						} else if ["false", "no", "f", "n", "0"].contains(&&boolval) {
							return Ok(Some(false));
						} else {
							return Err(format!("Unable to parse value into bool at {}:{}", section, key));
						}
					},
					None => Ok(None)
				},
				None => Ok(None)
			},
			None => Ok(None)
		}
	}

	///Parses the stored value from the key stored in the defined section to an `i64`.
	///## Example
	///```ignore,rust
	///let value = config.getint("section", "key")?.unwrap();
	///```
	///Returns `Ok(Some(value))` of type `i64` if value is found or else returns `Ok(None)`.
	///If the parsing fails, it returns an `Err(string)`.
	pub fn getint(&self, section: &str, key: &str) -> Result<Option<i64>, String> {
		match self.map.get(&section.to_lowercase()) {
			Some(secmap) => match secmap.get(&key.to_lowercase()) {
				Some(val) => match val {
					Some(inner) => match inner.parse::<i64>() {
						Err(why) => Err(why.to_string()),
						Ok(int) => Ok(Some(int))
					},
					None => Ok(None)
				},
				None => Ok(None)
			},
			None => Ok(None)
		}
	}

	///Parses the stored value from the key stored in the defined section to a `u64`.
	///## Example
	///```ignore,rust
	///let value = config.getuint("section", "key")?.unwrap();
	///```
	///Returns `Ok(Some(value))` of type `u64` if value is found or else returns `Ok(None)`.
	///If the parsing fails, it returns an `Err(string)`.
	pub fn getuint(&self, section: &str, key: &str) -> Result<Option<u64>, String> {
		match self.map.get(&section.to_lowercase()) {
			Some(secmap) => match secmap.get(&key.to_lowercase()) {
				Some(val) => match val {
					Some(inner) => match inner.parse::<u64>() {
						Err(why) => Err(why.to_string()),
						Ok(uint) => Ok(Some(uint))
					},
					None => Ok(None)
				},
				None => Ok(None)
			},
			None => Ok(None)
		}
	}

	///Parses the stored value from the key stored in the defined section to a `f64`.
	///## Example
	///```ignore,rust
	///let value = config.getfloat("section", "key")?.unwrap();
	///```
	///Returns `Ok(Some(value))` of type `f64` if value is found or else returns `Ok(None)`.
	///If the parsing fails, it returns an `Err(string)`.
	pub fn getfloat(&self, section: &str, key: &str) -> Result<Option<f64>, String> {
		match self.map.get(&section.to_lowercase()) {
			Some(secmap) => match secmap.get(&key.to_lowercase()) {
				Some(val) => match val {
					Some(inner) => match inner.parse::<f64>() {
						Err(why) => Err(why.to_string()),
						Ok(float) => Ok(Some(float))
					},
					None => Ok(None)
				},
				None => Ok(None)
			},
			None => Ok(None)
		}
	}

	///Returns a clone of the `HashMap` stored in our struct.
	///## Example
	///```ignore,rust
	///let map = config.get_map().unwrap();
	///```
	///Returns `Some(map)` if map is non-empty or else returns `None`.
	///Similar to `load()` but returns an `Option` type with the currently stored `HashMap`.
	pub fn get_map(&self) -> Option<HashMap<String, HashMap<String, Option<String>>>> {
		if self.map.is_empty() { None } else { Some(self.map.clone()) }
	}

	///Returns an immutable reference to the `HashMap` stored in our struct.
	///## Example
	///```ignore,rust
	///let map = config.get_map_ref();
	///let sectionmap = map["section name"].clone();
	///```
	///If you just need to definitely mutate the map, use `get_mut_map()` instead.
	pub fn get_map_ref(&self) -> &HashMap<String, HashMap<String, Option<String>>> {
		&self.map
	}

	///Returns a mutable reference to the `HashMap` stored in our struct.
	///## Example
	///```ignore,rust
	///let map = config.get_mut_map();
	///map.get_mut("topsecrets").unwrap().insert(String::from("nuclear launch codes"), None);
	///```
	///If you just need to access the map without mutating, use `get_map_ref()` or make a clone with `get_map()` instead.
	pub fn get_mut_map(&mut self) -> &mut HashMap<String, HashMap<String, Option<String>>> {
		&mut self.map
	}

	///Sets an `Option<String>` in the `HashMap` stored in our struct. If a particular section or key does not exist, it will be automatically created.
	///An existing value in the map  will be overwritten. You can also set `None` safely.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///config.read(String::from(
	///  "[section]
	///  key=value"));
	///let key_value = String::from("value");
	///config.set("section", "key", Some(key_value));
	///config.set("section", "key", None);  // also valid!
	///assert_eq!(config.get("section", "key"), None);  // correct!
	///```
	///Returns `None` if there is no existing value, else returns `Option<Option<String>`, with the existing value being the wrapped `Option<String>`.
	///If you want to insert using a string literal, use `setstr()` instead.
	pub fn set(&mut self, section: &str, key: &str, value:Option<String>) -> Option<Option<String>> {
		match self.map.get_mut(&section.to_lowercase()) {
			Some(secmap) => secmap.insert(key.to_lowercase(), value),
			None => {
				let mut valmap: HashMap<String, Option<String>> = HashMap::new();
				valmap.insert(key.to_lowercase(), value);
				self.map.insert(section.to_lowercase(), valmap);
				None
			}
		}
	}

	///Sets an `<Option<&str>>` in the `HashMap` stored in our struct. If a particular section or key does not exist, it will be automatically created.
	///An existing value in the map  will be overwritten. You can also set `None` safely.
	///## Example
	///```rust
	///use configparser::ini::Ini;
	///
	///let mut config = Ini::new();
	///config.read(String::from(
	///  "[section]
	///  key=notvalue"));
	///config.setstr("section", "key", Some("value"));
	///config.setstr("section", "key", None);  // also valid!
	///assert_eq!(config.get("section", "key"), None);  // correct!
	///```
	///Returns `None` if there is no existing value, else returns `Option<Option<String>`, with the existing value being the wrapped `Option<String>`.
	///If you want to insert using a `String`, use `set()` instead.
	pub fn setstr(&mut self, section: &str, key: &str, value:Option<&str>) -> Option<Option<String>> {
		self.set(section, key, value.map(String::from))
	}
}