| 1 | # configparser |
| 2 | [](https://github.com/QEDK/configparser-rs/actions/workflows/rust.yaml) [](LICENSE-MIT) [](https://crates.io/crates/configparser) [](https://docs.rs/configparser) [](https://github.com/QEDK/configparser-rs) |
| 3 | |
| 4 | This crate provides the `Ini` struct which implements a basic configuration language which provides a structure similar to whatβs found in Windows' `ini` files. You can use this to write Rust programs which can be customized by end users easily. |
| 5 | |
| 6 | This is a simple configuration parsing utility with no dependencies built on Rust. It is inspired by Python's `configparser`. |
| 7 | |
| 8 | The current release is stable and changes will take place at a slower pace. We'll be keeping semver in mind for future releases as well. |
| 9 | |
| 10 | ## π Quick Start |
| 11 | |
| 12 | A basic `ini`-syntax file (we say ini-syntax files because the files don't need to be necessarily `*.ini`) looks like this: |
| 13 | ```INI |
| 14 | [DEFAULT] |
| 15 | key1 = value1 |
| 16 | pizzatime = yes |
| 17 | cost = 9 |
| 18 | |
| 19 | [topsecrets] |
| 20 | nuclear launch codes = topsecret |
| 21 | |
| 22 | [github.com] |
| 23 | User = QEDK |
| 24 | ``` |
| 25 | Essentially, the syntax consists of sections, each of which can which contains keys with values. The `Ini` struct can read and write such values to |
| 26 | strings as well as files. |
| 27 | |
| 28 | ### π§° Installation |
| 29 | You can install this easily via `cargo` by including it in your `Cargo.toml` file like: |
| 30 | ```TOML |
| 31 | [dependencies] |
| 32 | configparser = "3.0.3" |
| 33 | ``` |
| 34 | |
| 35 | ## β Supported datatypes |
| 36 | `configparser` does not guess the datatype of values in configuration files and stores everything as strings. However, some datatypes are so common |
| 37 | that it's a safe bet that some values need to be parsed in other types. For this, the `Ini` struct provides easy functions like `getint()`, `getuint()`, |
| 38 | `getfloat()` and `getbool()`. The only bit of extra magic involved is that the `getbool()` function will treat boolean values case-insensitively (so |
| 39 | `true` is the same as `True` just like `TRUE`). The crate also provides a stronger `getboolcoerce()` function that parses more values (such as `T`, `yes` and `0`, all case-insensitively), the function's documentation will give you the exact details. |
| 40 | ```rust |
| 41 | use configparser::ini::Ini; |
| 42 | |
| 43 | let mut config = Ini::new(); |
| 44 | config.read(String::from( |
| 45 | "[somesection] |
| 46 | someintvalue = 5")); |
| 47 | let my_value = config.getint("somesection", "someintvalue").unwrap().unwrap(); |
| 48 | assert_eq!(my_value, 5); // value accessible! |
| 49 | |
| 50 | //You can ofcourse just choose to parse the values yourself: |
| 51 | let my_string = String::from("1984"); |
| 52 | let my_int = my_string.parse::<i32>().unwrap(); |
| 53 | ``` |
| 54 | |
| 55 | ## π Supported `ini` file structure |
| 56 | A configuration file can consist of sections, each led by a `[section-name]` header, followed by key-value entries separated by a delimiter (`=` and `:`). By default, section names and key names are case-insensitive. Case-sensitivity can be enabled using the `Ini::new_cs()` constructor. All leading and trailing whitespace is removed from stored keys, values and section names. |
| 57 | Key values can be omitted, in which case the key-value delimiter |
| 58 | may also be left out (but this is different from putting a delimiter, we'll |
| 59 | explain it later). You can use comment symbols (`;` and `#` to denote comments). This can be configured with the `set_comment_symbols()` method in the |
| 60 | API. Keep in mind that key-value pairs or section headers cannot span multiple lines. |
| 61 | Owing to how ini files usually are, this means that `[`, `]`, `=`, `:`, `;` and `#` are special symbols by default (this crate will allow you to use `]` sparingly). |
| 62 | |
| 63 | Let's take for example: |
| 64 | ```INI |
| 65 | [section headers are case-insensitive by default] |
| 66 | [ section headers are case-insensitive by default ] |
| 67 | are the section headers above same? = yes |
| 68 | sectionheaders_and_keysarestored_in_lowercase? = yes |
| 69 | keys_are_also_case_insensitive = Values are case sensitive |
| 70 | Case-sensitive_keys_and_sections = using a special constructor |
| 71 | you can also use colons : instead of the equal symbol |
| 72 | ;anything after a comment symbol is ignored |
| 73 | #this is also a comment |
| 74 | spaces in keys=allowed ;and everything before this is still valid! |
| 75 | spaces in values=allowed as well |
| 76 | spaces around the delimiter = also OK |
| 77 | |
| 78 | |
| 79 | [All values are strings] |
| 80 | values like this= 0000 |
| 81 | or this= 0.999 |
| 82 | are they treated as numbers? = no |
| 83 | integers, floats and booleans are held as= strings |
| 84 | |
| 85 | [value-less?] |
| 86 | a_valueless_key_has_None |
| 87 | this key has an empty string value has Some("") = |
| 88 | |
| 89 | [indented sections] |
| 90 | can_values_be_as_well = True |
| 91 | purpose = formatting for readability |
| 92 | is_this_same = yes |
| 93 | is_this_same=yes |
| 94 | |
| 95 | ``` |
| 96 | An important thing to note is that values with the same keys will get updated, this means that the last inserted key (whether that's a section header |
| 97 | or property key) is the one that remains in the `HashMap`. |
| 98 | The only bit of magic the API does is the section-less properties are put in a section called "default". You can configure this variable via the API. |
| 99 | Keep in mind that a section named "default" is also treated as sectionless so the output files remains consistent with no section header. |
| 100 | |
| 101 | ## π Usage |
| 102 | Let's take another simple `ini` file and talk about working with it: |
| 103 | ```INI |
| 104 | [topsecret] |
| 105 | KFC = the secret herb is orega- |
| 106 | |
| 107 | [values] |
| 108 | Uint = 31415 |
| 109 | ``` |
| 110 | If you read the above sections carefully, you'll know that 1) all the keys are stored in lowercase, 2) `get()` can make access in a case-insensitive |
| 111 | manner and 3) we can use `getuint()` to parse the `Uint` value into an `u64`. Let's see that in action. |
| 112 | |
| 113 | ```rust |
| 114 | use configparser::ini::Ini; |
| 115 | use std::error::Error; |
| 116 | |
| 117 | fn main() -> Result<(), Box<dyn Error>> { |
| 118 | let mut config = Ini::new(); |
| 119 | |
| 120 | // You can easily load a file to get a clone of the map: |
| 121 | let map = config.load("tests/test.ini")?; |
| 122 | println!("{:?}", map); |
| 123 | // You can also safely not store the reference and access it later with get_map_ref() or get a clone with get_map() |
| 124 | |
| 125 | // If you want to access the value, then you can simply do: |
| 126 | let val = config.get("TOPSECRET", "KFC").unwrap(); |
| 127 | // Notice how get() can access indexes case-insensitively. |
| 128 | |
| 129 | assert_eq!(val, "the secret herb is orega-"); // value accessible! |
| 130 | |
| 131 | // What if you want remove KFC's secret recipe? Just use set(): |
| 132 | config.set("topsecret", "kfc", None); |
| 133 | |
| 134 | assert_eq!(config.get("TOPSECRET", "KFC"), None); // as expected! |
| 135 | |
| 136 | // What if you want to get an unsigned integer? |
| 137 | let my_number = config.getuint("values", "Uint")?.unwrap(); |
| 138 | assert_eq!(my_number, 31415); // and we got it! |
| 139 | // The Ini struct provides more getters for primitive datatypes. |
| 140 | |
| 141 | // You can also access it like a normal hashmap: |
| 142 | let innermap = map["topsecret"].clone(); |
| 143 | // Remember that all indexes are stored in lowercase! |
| 144 | |
| 145 | // You can easily write the currently stored configuration to a file like: |
| 146 | config.write("output.ini"); |
| 147 | |
| 148 | // If you want to simply mutate the stored hashmap, you can use get_mut_map() |
| 149 | let map = config.get_mut_map(); |
| 150 | // You can then use normal HashMap functions on this map at your convenience. |
| 151 | // Remember that functions which rely on standard formatting might stop working |
| 152 | // if it's mutated differently. |
| 153 | |
| 154 | // If you want a case-sensitive map, just do: |
| 155 | let mut config = Ini::new_cs(); |
| 156 | // This automatically changes the behaviour of every function and parses the file as case-sensitive. |
| 157 | |
| 158 | Ok(()) |
| 159 | } |
| 160 | ``` |
| 161 | The `Ini` struct offers great support for type conversion and type setting safely, as well as map accesses. See the API for more verbose documentation. |
| 162 | |
| 163 | ## πFeatures |
| 164 | |
| 165 | - *indexmap*: Activating the `indexmap` feature allows using [indexmap](https://crates.io/crates/indexmap) in place |
| 166 | of `HashMap` to store the sections and keys. This ensures that insertion order is preserved when iterating on or |
| 167 | serializing the Ini object. |
| 168 | Due to the nature of indexmap, it offers mostly similar performance to stdlib HashMaps but with |
| 169 | [slower lookup times](https://github.com/bluss/indexmap#performance). |
| 170 | |
| 171 | You can activate it by adding it as a feature like this: |
| 172 | ```TOML |
| 173 | [dependencies] |
| 174 | configparser = { version = "3.0.2", features = ["indexmap"] } |
| 175 | ``` |
| 176 | |
| 177 | - *async-std*: Activating the `async-std` feature adds asynchronous functions for reading from (`load_async()`) and |
| 178 | writing to (`write_async()`) files using [async-std](https://crates.io/crates/async-std). |
| 179 | |
| 180 | You can activate it by adding it as a feature like this: |
| 181 | ```TOML |
| 182 | [dependencies] |
| 183 | configparser = { version = "3.0.2", features = ["async-std"] } |
| 184 | ``` |
| 185 | |
| 186 | ## π License |
| 187 | |
| 188 | Licensed under either of |
| 189 | |
| 190 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) |
| 191 | * Lesser General Public license v3.0 or later ([LICENSE-LGPL](LICENSE-LGPL) or https://www.gnu.org/licenses/lgpl-3.0.html) |
| 192 | |
| 193 | at your option. |
| 194 | |
| 195 | ### β Contribution |
| 196 | |
| 197 | Unless you explicitly state otherwise, any contribution intentionally submitted |
| 198 | for inclusion in the work by you, as defined in the LGPL-3.0 license, shall be dual licensed as above, without any |
| 199 | additional terms or conditions. |
| 200 | |
| 201 | ## π Changelog |
| 202 | |
| 203 | Old changelogs are in [CHANGELOG.md](CHANGELOG.md). |
| 204 | - 2.0.1 |
| 205 | - Add first-class support for setting, loading and reading defaults |
| 206 | - New available struct `IniDefault` for fast templating |
| 207 | - 2.1.0 |
| 208 | - π― **BREAKING** Parse keys with higher priority, both brackets `[` and `]` can be part of values now. |
| 209 | - βΉ Only affects current behaviour **iff** your section headers had comments in front of them like, `comment[HEADER]`, you can fix it by adding the comment after the header like `[HEADER]#comment` or otherwise. |
| 210 | - π `load()` and `write()` work with `Path`-like arguments now. |
| 211 | - π Add docs for new struct |
| 212 | - 3.0.0 |
| 213 | - π **BREAKING** `IniDefault` is now a non-exhaustive struct, this will make future upgrades easier and non-breaking in nature. This change might also have a few implications in updating your existing codebase, please read the [official docs](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute) for more guidance. |
| 214 | - `IniDefault` is now internally used for generating defaults, reducing crate size. |
| 215 | - π There is now a new optional `indexmap` feature that preserves insertion order of your loaded configurations. |
| 216 | - 3.0.1 |
| 217 | - Uses `CRLF` line endings for Windows files. |
| 218 | - Bumps crate to 2021 edition. |
| 219 | - Adds features to CI pipeline. |
| 220 | - 3.0.2 |
| 221 | - Adds support for multi-line key-value pairs. |
| 222 | - Adds `async-std` feature for asynchronous file operations. |
| 223 | - Some performance optimizations. |
| 224 | - 3.0.3 (**STABLE**) |
| 225 | - Add default empty line on empty strings. |
| 226 | - Feature to append to existing `Ini` objects. |
| 227 | - Minor lint fixes. |
| 228 | |
| 229 | ### π Future plans |
| 230 | |
| 231 | - Support for appending sections, coercing them as well. |
| 232 | - Benchmarking against similar packages. |