- Notifications
You must be signed in to change notification settings - Fork24
A simple configuration parsing utility with no dependencies built on Rust.
License
Unknown, MIT licenses found
Licenses found
QEDK/configparser-rs
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
configparser is a configuration parsing utility with zero dependencies built in Rust. It is inspired by the similarly named Pythonconfigparser library.
This crate provides anIni struct which implements a succinct configuration language and provides a structure similar to what’s found inini files (similar to.env files). You can use this to write Rust programs which can be configured by end users.
We use semantic versioning, so breaking changes will only be introduced in major versions. The crate is stable and has been used in production for a long time.
A basicini-format file looks like this:
[DEFAULT]key1 = value1pizzatime = yescost = 9[topsecrets]nuclear launchcodes = topsecret[github.com]User = QEDK
Essentially, the syntax consists of sections, each of which can which contains keys with values. TheIni struct can read and write such values tostrings as well as files.
You can install this easily viacargo by including it in yourCargo.toml file like:
[dependencies]configparser ="3.2.0"
configparser does not guess the datatype of values in configuration files and stores everything as strings. However, some datatypes are so commonthat it's a safe bet that some values need to be parsed in other types. For this, theIni struct provides easy functions likegetint(),getuint(),getfloat() andgetbool(). The only bit of extra magic involved is that thegetbool() function will treat boolean values case-insensitively (sotrue is the same asTrue just likeTRUE). The crate also provides a strongergetboolcoerce() function that parses more values (such asT,yes and0, all case-insensitively), the function's documentation will give you the exact details.
use configparser::ini::Ini;letmut config =Ini::new();config.read(String::from("[somesection] someintvalue = 5"));let my_value = config.getint("somesection","someintvalue").unwrap().unwrap();assert_eq!(my_value,5);// value accessible!//You can ofcourse just choose to parse the values yourself:let my_string =String::from("1984");let my_int = my_string.parse::<i32>().unwrap();
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 theIni::new_cs() constructor. All leading and trailing whitespace is removed from stored keys, values and section names.Key values can be omitted, in which case the key-value delimitermay also be left out (but this is different from putting a delimiter, we'llexplain it later). You can use comment symbols (; and# to denote comments). This can be configured with theset_comment_symbols() method in theAPI. Keep in mind that key-value pairs or section headers cannot span multiple lines.Owing to how ini files usually are, this means that[,],=,:,; and# are special symbols by default (this crate will allow you to use] sparingly).
Let's take for example:
[section headers are case-insensitive by default][ section headers are case-insensitive by default ]are the section headers above same? = yessectionheaders_and_keysarestored_in_lowercase? = yeskeys_are_also_case_insensitive = Values are case sensitiveCase-sensitive_keys_and_sections = using a special constructoryou can also use colons : instead of the equal symbol;anything after a comment symbol is ignored#this is also a commentspaces inkeys=allowed;and everything before this is still valid!spaces invalues=allowed as wellspaces around thedelimiter = also OK[All values are strings]values likethis= 0000orthis= 0.999are they treated as numbers? = nointegers, floats and booleans are heldas= strings[value-less?]a_valueless_key_has_Nonethis key has an empty string value has Some("") = [indented sections]can_values_be_as_well = Truepurpose = formatting for readabilityis_this_same = yesis_this_same=yes
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 headeror property key) is the one that remains in theHashMap.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.Keep in mind that a section named "default" is also treated as sectionless so the output files remains consistent with no section header.
Let's take another simpleini file and talk about working with it:
[topsecret]KFC = the secret herb is orega-[values]Uint = 31415
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-insensitivemanner and 3) we can usegetuint() to parse theUint value into anu64. Let's see that in action.
use configparser::ini::{Ini,WriteOptions};use std::error::Error;fnmain() ->Result<(),Box<dynError>>{letmut config =Ini::new();// You can easily load a file to get a clone of the map:let map = config.load("tests/test.ini")?;println!("{:?}", map);// You can also safely not store the reference and access it later with get_map_ref() or get a clone with get_map()// If you want to access the value, then you can simply do:let val = config.get("TOPSECRET","KFC").unwrap();// Notice how get() can access indexes case-insensitively.assert_eq!(val,"the secret herb is orega-");// value accessible!// What if you want remove KFC's secret recipe? Just use set(): config.set("topsecret","kfc",None);assert_eq!(config.get("TOPSECRET","KFC"),None);// as expected!// What if you want to get an unsigned integer?let my_number = config.getuint("values","Uint")?.unwrap();assert_eq!(my_number,31415);// and we got it!// The Ini struct provides more getters for primitive datatypes.// You can also access it like a normal hashmap:let innermap = map["topsecret"].clone();// Remember that all indexes are stored in lowercase!// You can easily write the currently stored configuration to a file with the `write` method. This creates a compact format with as little spacing as possible: config.write("output.ini");// You can write the currently stored configuration with different spacing to a file with the `pretty_write` method:let write_options =WriteOptions::new_with_params(true,2,1);// or you can use the default configuration as `WriteOptions::new()` config.pretty_write("pretty_output.ini",&write_options);// If you want to simply mutate the stored hashmap, you can use get_mut_map()let map = config.get_mut_map();// You can then use normal HashMap functions on this map at your convenience.// Remember that functions which rely on standard formatting might stop working// if it's mutated differently.// If you want a case-sensitive map, just do:letmut config =Ini::new_cs();// This automatically changes the behaviour of every function and parses the file as case-sensitive.Ok(())}
TheIni struct offers great support for type conversion and type setting safely, as well as map accesses. See the API for more verbose documentation.
- indexmap: Activating the
indexmapfeature allows usingindexmap in placeofHashMapto store the sections and keys. This ensures that insertion order is preserved when iterating on orserializing the Ini object.Due to the nature of indexmap, it offers mostly similar performance to stdlib HashMaps but withslower lookup times.
You can activate it by adding it as a feature like this:
[dependencies]configparser = {version ="3.2.0",features = ["indexmap"] }
- tokio: Activating the
tokiofeature adds asynchronous functions for reading from (load_async()) andwriting to (write_async()) files usingtokio.
You can activate it by adding it as a feature like this:
[dependencies]configparser = {version ="3.2.0",features = ["tokio"] }
You can change the default configuration options like this.See the API for more verbose documentation.
let mut parser_options = IniDefault::default();parser_options.multiline = true;parser_options.enable_inline_comments = false;let mut config = Ini::new_from_defaults(parser_options);Licensed under either of
- MIT license (LICENSE-MIT orhttp://opensource.org/licenses/MIT)
- Lesser General Public license v3.0 or later (LICENSE-LGPL orhttps://www.gnu.org/licenses/lgpl-3.0.html)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submittedfor inclusion in the work by you, as defined in the LGPL-3.0 license, shall be dual licensed as above, without anyadditional terms or conditions.
Old changelogs are visible in the commit history.
- 3.0.1
- Uses
CRLFline endings for Windows files. - Bumps crate to 2021 edition.
- Adds features to CI pipeline.
- Uses
- 3.0.2
- Adds support for multi-line key-value pairs.
- Adds
async-stdfeature for asynchronous file operations. - Some performance optimizations.
- 3.0.3
- Add default empty line on empty strings.
- Feature to append to existing
Iniobjects. - Minor lint fixes.
- 3.0.4
- Adds pretty printing functionality
- Replaces
async-stdwithtokioas the available async runtime - The
async-stdfeature will be deprecated in a future release
- 3.1.0 (STABLE)
async-stdhas been deprecated- Fixes a bug where multiline values did not preserve newlines
- Fixes a bug where empty sections were removed
- Adds a feature to support inline comments
- 3.2.0
async-stdhas been removed- 🎉 Implements serde support
- Support for appending sections, coercing them as well.
- Benchmarking against similar packages.
About
A simple configuration parsing utility with no dependencies built on Rust.
Topics
Resources
License
Unknown, MIT licenses found
Licenses found
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.