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
//! SimpleIni is a simple crate to parse and create INI files
//!
//! # Examples
//! **Read an INI file from disk**
//! ```
//! use simpleini::Ini;
//!
//! fn main() {
//!     let path = "/tmp/example.ini";
//!     let ini = match Ini::from_file(path) {
//!         Ok(ini) => ini,
//!         Err(e) => {
//!             eprintln!("Failed to parse /tmp/example.ini: {:?}", e);
//!             std::process::exit(1);
//!         }
//!     };
//! }
//! ```
//!
//! **Create a new INI file**
//! ```
//! use simpleini::{Ini, IniSection};
//!
//! // These are only needed when using Ini#add_section_with_values
//! use std::collections::HashMap;
//! use std::iter::FromIterator;
//! use std::array::IntoIter;
//!
//! fn main() {
//!     let mut ini = Ini::new();
//!     ini.set("some_global", "VALUE");
//!
//!     // Manually (and verbosely) create a section
//!     let mut section = IniSection::new("SectionA");
//!     section.set("some_section_variable", "OTHER_VALUE");
//!     ini.add_section(section);
//!
//!     // Create a Section from a name and a HashMap<AsRef<str>, AsRef<str>>
//!     ini.add_section_with_values("SectionB", HashMap::from_iter(IntoIter::new([("var_b", "value_b")])));
//!
//!     // Write the INI file to disk
//!     match ini.to_file("/tmp/example.ini") {
//!         Ok(()) => {},
//!         Err(e) => {
//!             eprintln!("Failed to write INI to disk: {:?}", e);
//!             std::process::exit(1);
//!         }
//!     };
//! }
//! ```


use std::fmt;
use std::fmt::Formatter;
use std::fmt::Write;
use std::collections::HashMap;
use std::path::Path;
use std::fs;

use regex::Regex;
use lazy_static::lazy_static;

lazy_static! {
    static ref SECTION_REGEX: Regex = Regex::new(r#"\[(.*)\]"#).unwrap();
    static ref KEY_VALUE_REGEX: Regex = Regex::new(r#"^([^=]+)=(.*)(.*)"#).unwrap();
}

/// A `Result` alias where the `Err` case is `simpleini::IniError`
pub type Result<T> = std::result::Result<T, IniError>;

/// The Error that may occur when parsing or writing with this crate
#[derive(Debug)]
pub struct IniError {
    e: String
}

impl fmt::Display for IniError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.e.as_str())
    }
}

impl std::error::Error for IniError {}

impl<T> From<T> for IniError where T: AsRef<str> {
    fn from(i: T) -> Self {
        let r = i.as_ref();
        Self {
            e: r.to_string()
        }
    }
}

/// Ini
#[derive(Debug, Eq, PartialEq)]
pub struct Ini {
    pub(crate) sections:   Vec<IniSection>,
    pub(crate) globals:    HashMap<String, String>
}

impl Ini {
    /// Create an empty Ini instace
    pub fn new() -> Self {
        Self {
            sections:   Vec::new(),
            globals:    HashMap::new()
        }
    }

    /// Create an Ini instance from a file
    ///
    /// # Errors
    /// Returns Err when reading the file failed
    pub fn from_file<P>(path: P) -> Result<Self> where P: AsRef<Path> {
        let path = path.as_ref();
        let contents = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => return Err(e.to_string().into())
        };

        Self::deserialize(contents)
    }

    /// Write the Ini instance to a file
    ///
    /// # Errors
    /// Returns Err when writing the file failed
    pub fn to_file<P>(&self, path: P) -> Result<()> where P: AsRef<Path> {
        let serialized = self.serialize()?;
        match fs::write(path, serialized) {
            Ok(_) => Ok(()),
            Err(e) => return Err(e.to_string().into())
        }
    }

    /// Deserialize an AsRef<str> into an instance of Ini
    ///
    /// # Errors
    /// Returns Err when the provided string is not valid
    pub fn deserialize<T>(input: T) -> Result<Self> where T: AsRef<str> {
        let input = input.as_ref();

        let mut globals = HashMap::new();
        let mut sections = Vec::new();
        let mut working_section = None;

        for line in input.lines() {
            let line = line.trim();

            if line.is_empty() {
                continue;
            }

            // Skip over comments
            if line.starts_with(";") {
                continue;
            }

            // A section starts with '['
            if line.starts_with("[") {
                if let Some(section) = working_section {
                    sections.push(section);
                }

                let captures = match SECTION_REGEX.captures(line) {
                    Some(c) => c,
                    None => return Err(format!("Invalid INI file. Line {} is invalid! (No matches)", line).into())
                };

                let section_name = match captures.get(1) {
                    Some(n) => n,
                    None => return Err(format!("Invalid INI File. Line {} is invalid! (Capture group 1)", line).into())
                };

                let section = IniSection::new(section_name.as_str());
                working_section = Some(section)
            } else if let Some(section) = &mut working_section {
                let (k, v) = Self::get_kv(line)?;
                section.keys.insert(k.to_string(), v.to_string());
            } else {
                let (k, v) = Self::get_kv(line)?;
                globals.insert(k.to_string(), v.to_string());
            }
        }

        if let Some(section) = working_section {
            sections.push(section);
        }

        Ok(Self {
            sections,
            globals
        })
    }

    /// Serialize an Ini instance into a String
    pub fn serialize(&self) -> Result<String> {
        let mut builder = String::new();
        for (k, v) in &self.globals {
            let _ = writeln!(&mut builder, "{}={}", k, v);
        }

        for section in &self.sections {
            let _ = writeln!(&mut builder, "");
            let _ = writeln!(&mut builder, "[{}]", section.name);
            for (k, v) in &section.keys {
                let _ = writeln!(&mut builder, "{}={}", k, v);
            }
        }

        Ok(builder)
    }

    /// Add an IniSection to the Ini instance
    pub fn add_section(&mut self, section: IniSection) {
        self.sections.push(section);
    }

    /// Add an IniSection to the Ini instance
    pub fn add_section_with_values<T, K, V>(&mut self, name: T, values: HashMap<K, V>) where T: AsRef<str>, K: AsRef<str>, V: AsRef<str> {
        let keys: HashMap<String, String> = values.iter().map(|(k, v)| (k.as_ref().to_string(), v.as_ref().to_string())).collect();
        let section = IniSection {
            name: name.as_ref().to_string(),
            keys
        };

        self.sections.push(section);
    }

    /// Get an IniSection by name from the Ini instance
    ///
    /// # Option
    /// Returns None when no IniSection exists for the provided name
    pub fn get_section<K>(&self, name: K) -> Option<&IniSection> where K: AsRef<str> {
        for section in &self.sections {
            if section.name.eq(name.as_ref()) {
                return Some(section)
            }
        }

        None
    }

    /// Get a mutable reference to an IniSection by name from the Ini instance
    ///
    /// # Option
    /// Returns None when no IniSection exists for the provided name
    pub fn get_section_mut<K>(&mut self, name: K) -> Option<&mut IniSection> where K: AsRef<str> {
        for section in &mut self.sections {
            if section.name.eq(name.as_ref()) {
                return Some(section)
            }
        }

        None
    }

    /// Get a global value from the Ini instance
    ///
    /// # Option
    /// Returns None when no global key-value pair exists for the provided key
    pub fn get<K>(&self, key: K) -> Option<&str> where K: AsRef<str> {
        match self.globals.get(key.as_ref()) {
            Some(g) => Some(g.as_str()),
            None => None
        }
    }

    /// Set a global key-value pair for the Ini instance
    pub fn set<K, V>(&mut self, key: K, value: V) where K: AsRef<str>, V: AsRef<str> {
        self.globals.insert(key.as_ref().to_string(), value.as_ref().to_string());
    }

    fn get_kv(line: &str) -> Result<(&str, &str)> {
        let captures = match KEY_VALUE_REGEX.captures(line) {
            Some(c) => c,
            None => return Err(format!("Invalid INI file. Line {} is invalid!", line).into())
        };

        let k = match captures.get(1) {
            Some(k) => k,
            None => return Err(format!("Invalid INI file. Line {} is invalid!", line).into())
        };

        let v = match captures.get(2) {
            Some(v) => v,
            None => return Err(format!("Invalid INI file. Line {} is invalid!", line).into())
        };

        Ok((k.as_str(), v.as_str()))
    }
}

/// A Section in an Ini file
#[derive(Debug, Eq, PartialEq)]
pub struct IniSection {
    /// The name of the section
    pub(crate) name: String,
    /// The key-value pairs in this section
    pub(crate) keys: HashMap<String, String>
}

impl IniSection {
    /// Create an empty IniSection instance
    pub fn new<T>(name: T) -> Self where T: AsRef<str> {
        let name = name.as_ref().to_string();
        Self {
            name,
            keys: HashMap::new()
        }
    }

    /// Set a variable inside the IniSection
    pub fn set<K, V>(&mut self, key: K, value: V) where K: AsRef<str>, V: AsRef<str> {
        self.keys.insert(key.as_ref().to_string(), value.as_ref().to_string());
    }

    /// Get a variable from the IniSection
    ///
    /// # Option
    /// Returs None when no key-value pair exists for the provided key
    pub fn get<K>(&self, key: K) -> Option<&str> where K: AsRef<str> {
        match self.keys.get(key.as_ref()) {
            Some(v) => Some(v.as_str()),
            None => None
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{Ini, IniSection};
    use std::collections::HashMap;
    use std::array::IntoIter;
    use std::iter::FromIterator;

    #[test]
    fn parse_from_str() {
        let ini = "some_global=VALUE\n\n[A]\nsome_section_variable=OTHER_VALUE\n";

        let parsed = Ini::deserialize(ini).unwrap();
        let correct = Ini { globals: HashMap::from_iter(IntoIter::new([("some_global".to_string(), "VALUE".to_string())])), sections: vec![
            IniSection {
                name: "A".to_string(),
                keys: HashMap::from_iter(IntoIter::new([("some_section_variable".to_string(), "OTHER_VALUE".to_string())]))
            }
        ]};

        assert_eq!(correct, parsed);
    }

    #[test]
    fn set_replace() {
        let mut ini = Ini::new();
        ini.set("foo", "bar");
        ini.set("foo", "baz");

        let serialized = ini.serialize().unwrap();
        assert_eq!(&serialized, "foo=baz\n");
    }

    #[test]
    fn serialize_to_str() {
        let ini = "some_global=VALUE\n\n[A]\nsome_section_variable=OTHER_VALUE\n";

        let parsed = Ini::deserialize(ini).unwrap();
        let serialized = parsed.serialize().unwrap();

        assert_eq!(serialized, ini);
    }

    #[test]
    fn test_value_with_equals() {
        let mut ini = Ini::new();
        ini.set("foo", "'bar=baz'");

        let serialized = ini.serialize().unwrap();
        assert_eq!(&serialized, "foo='bar=baz'\n");

        let deserialized = Ini::deserialize(&serialized).expect("Failed to deserialize");
        assert_eq!(deserialized.get("foo").expect("Missing foo"), "'bar=baz'")
    }

    #[test]
    fn build_manually() {
        let ini = "some_global=VALUE\n\n[A]\nsome_section_variable=OTHER_VALUE\n[B]\nvar_b=value_b";
        let parsed = Ini::deserialize(ini).unwrap();

        let mut ini = Ini::new();
        ini.set("some_global", "VALUE");

        let mut section = IniSection::new("A");
        section.set("some_section_variable", "OTHER_VALUE");
        ini.add_section(section);

        ini.add_section_with_values("B", HashMap::from_iter(IntoIter::new([("var_b", "value_b")])));

        assert_eq!(parsed, ini);
    }
}