aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJeff Vander Stoep <jeffv@google.com>2024-02-01 13:19:23 +0100
committerJeff Vander Stoep <jeffv@google.com>2024-02-01 13:19:24 +0100
commit7e4ddc6298f13d05206811ae8a1def72cab21885 (patch)
treed10bf54bb87252e573f204201a9db4b5364d1ea3
parent0b060bfff7d51b1d6796a37571c9aba9997f1ec1 (diff)
downloadconfigparser-7e4ddc6298f13d05206811ae8a1def72cab21885.tar.gz
Upgrade configparser to 3.0.4
This project was upgraded with external_updater. Usage: tools/external_updater/updater.sh update external/rust/crates/configparser For more info, check https://cs.android.com/android/platform/superproject/+/main:tools/external_updater/README.md Test: TreeHugger Change-Id: I373961630b339571b8412995b7e3ae7f8c54e943
-rw-r--r--.cargo_vcs_info.json2
-rwxr-xr-x.gitignore2
-rw-r--r--Android.bp2
-rw-r--r--[-rwxr-xr-x]CHANGELOG.md12
-rw-r--r--Cargo.toml23
-rw-r--r--[-rwxr-xr-x]Cargo.toml.orig14
-rw-r--r--LICENSE-LGPL167
-rw-r--r--LICENSE-MIT4
-rw-r--r--METADATA21
-rw-r--r--[-rwxr-xr-x]README.md43
-rw-r--r--[-rwxr-xr-x]src/ini.rs370
-rw-r--r--[-rwxr-xr-x]src/lib.rs9
-rw-r--r--[-rwxr-xr-x]tests/test.ini0
-rw-r--r--[-rwxr-xr-x]tests/test.rs238
-rw-r--r--tests/test_more.ini8
15 files changed, 831 insertions, 84 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
index be07c69..99c2780 100644
--- a/.cargo_vcs_info.json
+++ b/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "aca329bc1872624d98cc3486b2cbe643e6641278"
+ "sha1": "5544794cca81bc1b36f4b3f60c891be209c12b81"
},
"path_in_vcs": ""
} \ No newline at end of file
diff --git a/.gitignore b/.gitignore
index ee52156..50e331c 100755
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,5 @@ test2.ini
.vscode
output_async.ini
output_sync.ini
+pretty_output.ini
+pretty_output_async.ini
diff --git a/Android.bp b/Android.bp
index 3355024..59874ef 100644
--- a/Android.bp
+++ b/Android.bp
@@ -5,7 +5,7 @@ rust_library_host {
name: "libconfigparser",
crate_name: "configparser",
cargo_env_compat: true,
- cargo_pkg_version: "3.0.2",
+ cargo_pkg_version: "3.0.4",
srcs: ["src/lib.rs"],
edition: "2021",
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e251ec4..36a68f0 100755..100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -82,5 +82,17 @@
- 1.0.0
- Dropped support for `ini::load()`
- Updated tests
+- 2.0.0
+ - **BREAKING** Added Python-esque support for `:` as a delimiter.
+ - :new: Add support for case-sensitive maps with automatic handling under the hood.
+ - :hammer: Fixed buggy setters which went uncaught, to preserve case-insensitive nature.
+- 2.0.1
+ - Add first-class support for setting, loading and reading defaults
+ - New available struct `IniDefault` for fast templating
+- 2.1.0
+ - 😯 **BREAKING** Parse keys with higher priority, both brackets `[` and `]` can be part of values now.
+ - β„Ή 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.
+ - πŸš€ `load()` and `write()` work with `Path`-like arguments now.
+ - πŸ“œ Add docs for new struct
Older changelogs are preserved here, current changelog is present in [README.md](README.md).
diff --git a/Cargo.toml b/Cargo.toml
index 6d9376a..82531d8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,7 +12,7 @@
[package]
edition = "2021"
name = "configparser"
-version = "3.0.2"
+version = "3.0.4"
authors = ["QEDK <qedk.en@gmail.com>"]
description = "A simple configuration parsing utility with no dependencies that allows you to parse INI and ini-style syntax. You can use this to write Rust programs which can be customized by end users easily."
homepage = "https://github.com/QEDK/configparser-rs"
@@ -32,15 +32,26 @@ categories = [
]
license = "MIT OR LGPL-3.0-or-later"
repository = "https://github.com/QEDK/configparser-rs"
-resolver = "2"
-[dependencies.async-std]
-version = "1.12.0"
+[dependencies.indexmap]
+version = "2.1.0"
optional = true
-[dependencies.indexmap]
-version = "1.9.1"
+[dependencies.tokio]
+version = "1.35.1"
+features = ["fs"]
optional = true
+[dev-dependencies.tokio]
+version = "1.35.1"
+features = [
+ "fs",
+ "macros",
+ "rt-multi-thread",
+]
+
+[features]
+async-std = ["tokio"]
+
[badges.maintenance]
status = "actively-developed"
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
index f65b357..890a7d2 100755..100644
--- a/Cargo.toml.orig
+++ b/Cargo.toml.orig
@@ -1,6 +1,6 @@
[package]
name = "configparser"
-version = "3.0.2"
+version = "3.0.4"
authors = ["QEDK <qedk.en@gmail.com>"]
edition = "2021"
description = "A simple configuration parsing utility with no dependencies that allows you to parse INI and ini-style syntax. You can use this to write Rust programs which can be customized by end users easily."
@@ -15,8 +15,12 @@ categories = ["config", "encoding", "parser-implementations"]
[badges]
maintenance = { status = "actively-developed" }
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
[dependencies]
-async-std = { version = "1.12.0", optional = true }
-indexmap = { version = "1.9.1", optional = true }
+indexmap = { version = "2.1.0", optional = true }
+tokio = { version = "1.35.1", optional = true, features = ["fs"] }
+
+[dev-dependencies]
+tokio = { version = "1.35.1", features = ["fs", "macros", "rt-multi-thread"] }
+
+[features]
+async-std = ["tokio"]
diff --git a/LICENSE-LGPL b/LICENSE-LGPL
new file mode 100644
index 0000000..05f78f2
--- /dev/null
+++ b/LICENSE-LGPL
@@ -0,0 +1,167 @@
+Copyright (c) 2024 QEDK
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/LICENSE-MIT b/LICENSE-MIT
index fbe1dcb..2a5884c 100644
--- a/LICENSE-MIT
+++ b/LICENSE-MIT
@@ -1,6 +1,6 @@
MIT License
-Copyright (c) 2020 QEDK
+Copyright (c) 2024 QEDK
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
@@ -24,4 +24,4 @@ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE. \ No newline at end of file
+DEALINGS IN THE SOFTWARE.
diff --git a/METADATA b/METADATA
index 6d01048..6041010 100644
--- a/METADATA
+++ b/METADATA
@@ -1,19 +1,24 @@
+# This project was upgraded with external_updater.
+# Usage: tools/external_updater/updater.sh update external/rust/crates/configparser
+# For more info, check https://cs.android.com/android/platform/superproject/+/main:tools/external_updater/README.md
+
name: "configparser"
description: "A simple configuration parsing utility with no dependencies that allows you to parse INI and ini-style syntax. You can use this to write Rust programs which can be customized by end users easily."
third_party {
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2024
+ month: 2
+ day: 1
+ }
identifier {
type: "crates.io"
- value: "https://crates.io/crates/configparser"
+ value: "https://static.crates.io/crates/configparser/configparser-3.0.4.crate"
+ version: "3.0.2"
}
identifier {
type: "Archive"
value: "https://static.crates.io/crates/configparser/configparser-3.0.2.crate"
- }
- version: "3.0.2"
- license_type: NOTICE
- last_upgrade_date {
- year: 2023
- month: 8
- day: 23
+ version: "3.0.4"
}
}
diff --git a/README.md b/README.md
index 0481162..1964c9f 100755..100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,5 @@
# configparser
-[![Build Status](https://github.com/QEDK/configparser-rs/actions/workflows/rust.yaml/badge.svg)](https://github.com/QEDK/configparser-rs/actions/workflows/rust.yaml) [![Crates.io](https://img.shields.io/crates/l/configparser?color=black)](LICENSE-MIT) [![Crates.io](https://img.shields.io/crates/v/configparser?color=black)](https://crates.io/crates/configparser) [![Released API docs](https://docs.rs/configparser/badge.svg)](https://docs.rs/configparser) [![Maintenance](https://img.shields.io/maintenance/yes/2022)](https://github.com/QEDK/configparser-rs)
+[![Build Status](https://github.com/QEDK/configparser-rs/actions/workflows/rust.yaml/badge.svg)](https://github.com/QEDK/configparser-rs/actions/workflows/rust.yaml) [![Crates.io](https://img.shields.io/crates/l/configparser?color=black)](LICENSE-MIT) [![Crates.io](https://img.shields.io/crates/v/configparser?color=black)](https://crates.io/crates/configparser) [![Released API docs](https://docs.rs/configparser/badge.svg)](https://docs.rs/configparser) [![Maintenance](https://img.shields.io/maintenance/yes/2024)](https://github.com/QEDK/configparser-rs)
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.
@@ -29,7 +29,7 @@ strings as well as files.
You can install this easily via `cargo` by including it in your `Cargo.toml` file like:
```TOML
[dependencies]
-configparser = "3.0.2"
+configparser = "3.0.4"
```
## βž• Supported datatypes
@@ -111,7 +111,7 @@ If you read the above sections carefully, you'll know that 1) all the keys are s
manner and 3) we can use `getuint()` to parse the `Uint` value into an `u64`. Let's see that in action.
```rust
-use configparser::ini::Ini;
+use configparser::ini::{Ini, WriteOptions};
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
@@ -142,9 +142,14 @@ fn main() -> Result<(), Box<dyn Error>> {
let innermap = map["topsecret"].clone();
// Remember that all indexes are stored in lowercase!
- // You can easily write the currently stored configuration to a file like:
+ // 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.
@@ -171,16 +176,16 @@ The `Ini` struct offers great support for type conversion and type setting safel
You can activate it by adding it as a feature like this:
```TOML
[dependencies]
-configparser = { version = "3.0.2", features = ["indexmap"] }
+configparser = { version = "3.0.4", features = ["indexmap"] }
```
- - *async-std*: Activating the `async-std` feature adds asynchronous functions for reading from (`load_async()`) and
- writing to (`write_async()`) files using [async-std](https://crates.io/crates/async-std).
+ - *tokio*: Activating the `tokio` feature adds asynchronous functions for reading from (`load_async()`) and
+ writing to (`write_async()`) files using [tokio](https://crates.io/crates/tokio).
You can activate it by adding it as a feature like this:
```TOML
[dependencies]
-configparser = { version = "3.0.2", features = ["async-std"] }
+configparser = { version = "3.0.4", features = ["tokio"] }
```
## πŸ“œ License
@@ -201,18 +206,6 @@ additional terms or conditions.
## πŸ†• Changelog
Old changelogs are in [CHANGELOG.md](CHANGELOG.md).
-- 2.0.0
- - **BREAKING** Added Python-esque support for `:` as a delimiter.
- - :new: Add support for case-sensitive maps with automatic handling under the hood.
- - :hammer: Fixed buggy setters which went uncaught, to preserve case-insensitive nature.
-- 2.0.1
- - Add first-class support for setting, loading and reading defaults
- - New available struct `IniDefault` for fast templating
-- 2.1.0
- - 😯 **BREAKING** Parse keys with higher priority, both brackets `[` and `]` can be part of values now.
- - β„Ή 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.
- - πŸš€ `load()` and `write()` work with `Path`-like arguments now.
- - πŸ“œ Add docs for new struct
- 3.0.0
- πŸ˜… **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.
- `IniDefault` is now internally used for generating defaults, reducing crate size.
@@ -221,10 +214,18 @@ Old changelogs are in [CHANGELOG.md](CHANGELOG.md).
- Uses `CRLF` line endings for Windows files.
- Bumps crate to 2021 edition.
- Adds features to CI pipeline.
-- 3.0.2 (**STABLE**)
+- 3.0.2
- Adds support for multi-line key-value pairs.
- Adds `async-std` feature for asynchronous file operations.
- Some performance optimizations.
+- 3.0.3
+ - Add default empty line on empty strings.
+ - Feature to append to existing `Ini` objects.
+ - Minor lint fixes.
+- 3.0.4 (**STABLE**)
+ - Adds pretty printing functionality
+ - Replaces `async-std` with `tokio` as the available async runtime
+ - *The `async-std` feature will be deprecated in a future release*
### πŸ”œ Future plans
diff --git a/src/ini.rs b/src/ini.rs
index d966e78..b27848a 100755..100644
--- a/src/ini.rs
+++ b/src/ini.rs
@@ -5,14 +5,19 @@ use indexmap::IndexMap as Map;
#[cfg(not(feature = "indexmap"))]
use std::collections::HashMap as Map;
+#[deprecated(
+ since = "3.0.4",
+ note = "async-std runtime has been replaced with tokio"
+)]
#[cfg(feature = "async-std")]
-use async_std::{fs as async_fs, path::Path as AsyncPath};
+#[cfg(feature = "tokio")]
+use tokio::fs as async_fs;
use std::collections::HashMap;
use std::convert::AsRef;
+use std::fmt::Write;
use std::fs;
use std::path::Path;
-use std::fmt::Write;
///The `Ini` struct simply contains a nested hashmap of the loaded configuration, the default section header and comment symbols.
///## Example
@@ -109,14 +114,14 @@ impl Default for IniDefault {
boolean_values: [
(
true,
- vec!["true", "yes", "t", "y", "on", "1"]
+ ["true", "yes", "t", "y", "on", "1"]
.iter()
.map(|&s| s.to_owned())
.collect(),
),
(
false,
- vec!["false", "no", "f", "n", "off", "0"]
+ ["false", "no", "f", "n", "off", "0"]
.iter()
.map(|&s| s.to_owned())
.collect(),
@@ -130,6 +135,96 @@ impl Default for IniDefault {
}
}
+/// Use this struct to define formatting options for the `pretty_write` functions.
+#[derive(Debug, Clone, Eq, PartialEq)]
+#[non_exhaustive]
+pub struct WriteOptions {
+ ///If true then the keys and values will be separated by " = ". In the special case where the value is empty, the
+ ///line ends with " =".
+ ///If false then keys and values will be separated by "=".
+ ///Default is `false`.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::WriteOptions;
+ ///
+ ///let mut write_options = WriteOptions::default();
+ ///assert_eq!(write_options.space_around_delimiters, false);
+ ///```
+ pub space_around_delimiters: bool,
+
+ ///Defines the number of spaces for indentation of for multiline values.
+ ///Default is 4 spaces.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::WriteOptions;
+ ///
+ ///let mut write_options = WriteOptions::default();
+ ///assert_eq!(write_options.multiline_line_indentation, 4);
+ ///```
+ pub multiline_line_indentation: usize,
+
+ ///Defines the number of blank lines between sections.
+ ///Default is 0.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::WriteOptions;
+ ///
+ ///let mut write_options = WriteOptions::default();
+ ///assert_eq!(write_options.blank_lines_between_sections, 0);
+ ///```
+ pub blank_lines_between_sections: usize,
+}
+
+impl Default for WriteOptions {
+ fn default() -> Self {
+ Self {
+ space_around_delimiters: false,
+ multiline_line_indentation: 4,
+ blank_lines_between_sections: 0,
+ }
+ }
+}
+
+impl WriteOptions {
+ ///Creates a new `WriteOptions` object with the default values.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::WriteOptions;
+ ///
+ ///let write_options = WriteOptions::new();
+ ///assert_eq!(write_options.space_around_delimiters, false);
+ ///assert_eq!(write_options.multiline_line_indentation, 4);
+ ///assert_eq!(write_options.blank_lines_between_sections, 0);
+ ///```
+ ///Returns the struct and stores it in the calling variable.
+ pub fn new() -> WriteOptions {
+ WriteOptions::default()
+ }
+
+ ///Creates a new `WriteOptions` object with the given parameters.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::WriteOptions;
+ ///
+ ///let write_options = WriteOptions::new_with_params(true, 2, 1);
+ ///assert_eq!(write_options.space_around_delimiters, true);
+ ///assert_eq!(write_options.multiline_line_indentation, 2);
+ ///assert_eq!(write_options.blank_lines_between_sections, 1);
+ ///```
+ ///Returns the struct and stores it in the calling variable.
+ pub fn new_with_params(
+ space_around_delimiters: bool,
+ multiline_line_indentation: usize,
+ blank_lines_between_sections: usize,
+ ) -> WriteOptions {
+ Self {
+ space_around_delimiters,
+ multiline_line_indentation,
+ blank_lines_between_sections,
+ }
+ }
+}
+
#[cfg(windows)]
const LINE_ENDING: &str = "\r\n";
#[cfg(not(windows))]
@@ -164,7 +259,10 @@ impl Ini {
///```
///Returns the struct and stores it in the calling variable.
pub fn new_cs() -> Ini {
- Ini::new_from_defaults(IniDefault { case_sensitive: true, ..Default::default() })
+ Ini::new_from_defaults(IniDefault {
+ case_sensitive: true,
+ ..Default::default()
+ })
}
///Creates a new `Ini` with the given defaults from an existing `IniDefault` object.
@@ -336,6 +434,57 @@ impl Ini {
Ok(self.map.clone())
}
+ ///Loads a file from a defined path, parses it and applies it to the existing hashmap in our struct.
+ ///While `load()` will clear the existing `Map`, `load_and_append()` applies the new values on top of
+ ///the existing hashmap, preserving previous values.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::Ini;
+ ///
+ ///let mut config = Ini::new();
+ ///config.load("tests/test.ini").unwrap();
+ ///config.load_and_append("tests/sys_cfg.ini").ok(); // we don't have to worry if this doesn't succeed
+ ///config.load_and_append("tests/user_cfg.ini").ok(); // we don't have to worry if this doesn't succeed
+ ///let map = config.get_map().unwrap();
+ /////Then, we can use standard hashmap functions like:
+ ///let values = map.get("values").unwrap();
+ ///```
+ ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
+ ///Use `get_mut_map()` if you want a mutable reference.
+ pub fn load_and_append<T: AsRef<Path>>(
+ &mut self,
+ path: T,
+ ) -> Result<Map<String, Map<String, Option<String>>>, String> {
+ let loaded = match self.parse(match fs::read_to_string(&path) {
+ Err(why) => {
+ return Err(format!(
+ "couldn't read {}: {}",
+ &path.as_ref().display(),
+ why
+ ))
+ }
+ Ok(s) => s,
+ }) {
+ Err(why) => {
+ return Err(format!(
+ "couldn't read {}: {}",
+ &path.as_ref().display(),
+ why
+ ))
+ }
+ Ok(map) => map,
+ };
+
+ for (section, section_map) in loaded.iter() {
+ self.map
+ .entry(section.clone())
+ .or_default()
+ .extend(section_map.clone());
+ }
+
+ 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 `Map`, if present.
///## Example
@@ -365,8 +514,54 @@ impl Ini {
Ok(self.map.clone())
}
- ///Writes the current configuation to the specified 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.
+ ///Reads an input string, parses it and applies it to the existing hashmap in our struct.
+ ///While `read()` and `load()` will clear the existing `Map`, `read_and_append()` applies the new
+ ///values on top of the existing hashmap, preserving previous values.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::Ini;
+ ///
+ ///let mut config = Ini::new();
+ ///if let Err(why) = config.read(String::from(
+ /// "[2000s]
+ /// 2020 = bad
+ /// 2023 = better")) {
+ /// panic!("{}", why);
+ ///};
+ ///if let Err(why) = config.read_and_append(String::from(
+ /// "[2000s]
+ /// 2020 = terrible")) {
+ /// panic!("{}", why);
+ ///};
+ ///let map = config.get_map().unwrap();
+ ///let few_years_ago = map["2000s"]["2020"].clone().unwrap();
+ ///let this_year = map["2000s"]["2023"].clone().unwrap();
+ ///assert_eq!(few_years_ago, "terrible"); // value updated!
+ ///assert_eq!(this_year, "better"); // keeps old values!
+ ///```
+ ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
+ ///Use `get_mut_map()` if you want a mutable reference.
+ pub fn read_and_append(
+ &mut self,
+ input: String,
+ ) -> Result<Map<String, Map<String, Option<String>>>, String> {
+ let loaded = match self.parse(input) {
+ Err(why) => return Err(why),
+ Ok(map) => map,
+ };
+
+ for (section, section_map) in loaded.iter() {
+ self.map
+ .entry(section.clone())
+ .or_default()
+ .extend(section_map.clone());
+ }
+
+ Ok(self.map.clone())
+ }
+
+ ///Writes the current configuation to the specified path using default formatting.
+ ///If a file is not present then it is automatically created for you. If a file already exists then it is overwritten.
///## Example
///```rust
///use configparser::ini::Ini;
@@ -381,11 +576,39 @@ impl Ini {
///```
///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
pub fn write<T: AsRef<Path>>(&self, path: T) -> std::io::Result<()> {
- fs::write(path.as_ref(), self.unparse())
+ fs::write(path.as_ref(), self.unparse(&WriteOptions::default()))
+ }
+
+ ///Writes the current configuation to the specified path using the given formatting options.
+ ///If a file is not present then it is automatically created for you. If a file already exists then it is overwritten.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::{Ini, WriteOptions};
+ ///
+ ///fn main() -> std::io::Result<()> {
+ /// let mut write_options = WriteOptions::default();
+ /// write_options.space_around_delimiters = true;
+ /// write_options.multiline_line_indentation = 2;
+ /// write_options.blank_lines_between_sections = 1;
+ ///
+ /// let mut config = Ini::new();
+ /// config.read(String::from(
+ /// "[2000s]
+ /// 2020 = bad"));
+ /// config.pretty_write("output.ini", &write_options)
+ ///}
+ ///```
+ ///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
+ pub fn pretty_write<T: AsRef<Path>>(
+ &self,
+ path: T,
+ write_options: &WriteOptions,
+ ) -> std::io::Result<()> {
+ fs::write(path.as_ref(), self.unparse(write_options))
}
- ///Returns a string with the current configuration formatted with valid ini-syntax. This is always safe since the configuration is validated during
- ///parsing.
+ ///Returns a string with the current configuration formatted with valid ini-syntax using default formatting.
+ ///This is always safe since the configuration is validated during parsing.
///## Example
///```rust
///use configparser::ini::Ini;
@@ -398,31 +621,60 @@ impl Ini {
///```
///Returns a `String` type contatining the ini-syntax file.
pub fn writes(&self) -> String {
- self.unparse()
+ self.unparse(&WriteOptions::default())
+ }
+
+ ///Returns a string with the current configuration formatted with valid ini-syntax using the given formatting options.
+ ///This is always safe since the configuration is validated during parsing.
+ ///## Example
+ ///```rust
+ ///use configparser::ini::{Ini, WriteOptions};
+ ///
+ ///let mut write_options = WriteOptions::default();
+ ///write_options.space_around_delimiters = true;
+ ///write_options.multiline_line_indentation = 2;
+ ///write_options.blank_lines_between_sections = 1;
+ ///
+ ///let mut config = Ini::new();
+ ///config.read(String::from(
+ /// "[2000s]
+ /// 2020 = bad"));
+ ///let outstring = config.pretty_writes(&write_options);
+ ///```
+ ///Returns a `String` type contatining the ini-syntax file.
+ pub fn pretty_writes(&self, write_options: &WriteOptions) -> String {
+ self.unparse(write_options)
}
///Private function that converts the currently stored configuration into a valid ini-syntax string.
- fn unparse(&self) -> String {
+ fn unparse(&self, write_options: &WriteOptions) -> String {
// push key/value pairs in outmap to out string.
fn unparse_key_values(
out: &mut String,
outmap: &Map<String, Option<String>>,
multiline: bool,
+ space_around_delimiters: bool,
+ indent: usize,
) {
+ let delimiter = if space_around_delimiters { " = " } else { "=" };
for (key, val) in outmap.iter() {
out.push_str(key);
if let Some(value) = val {
- out.push('=');
+ if value.is_empty() {
+ out.push_str(delimiter.trim_end());
+ } else {
+ out.push_str(delimiter);
+ }
if multiline {
let mut lines = value.lines();
- out.push_str(lines.next().unwrap());
+ out.push_str(lines.next().unwrap_or_default());
for line in lines {
out.push_str(LINE_ENDING);
- out.push_str(" ");
+ out.push_str(" ".repeat(indent).as_ref());
out.push_str(line);
}
} else {
@@ -434,18 +686,36 @@ impl Ini {
}
}
+ let line_endings = LINE_ENDING.repeat(write_options.blank_lines_between_sections);
let mut out = String::new();
if let Some(defaultmap) = self.map.get(&self.default_section) {
- unparse_key_values(&mut out, defaultmap, self.multiline);
+ unparse_key_values(
+ &mut out,
+ defaultmap,
+ self.multiline,
+ write_options.space_around_delimiters,
+ write_options.multiline_line_indentation,
+ );
}
+ let mut is_first = true;
for (section, secmap) in self.map.iter() {
+ if !is_first {
+ out.push_str(line_endings.as_ref());
+ }
if section != &self.default_section {
write!(out, "[{}]", section).unwrap();
out.push_str(LINE_ENDING);
- unparse_key_values(&mut out, secmap, self.multiline);
+ unparse_key_values(
+ &mut out,
+ secmap,
+ self.multiline,
+ write_options.space_around_delimiters,
+ write_options.multiline_line_indentation,
+ );
}
+ is_first = false;
}
out
}
@@ -502,7 +772,7 @@ impl Ini {
}
};
- let valmap = map.entry(section.clone()).or_insert_with(Map::new);
+ let valmap = map.entry(section.clone()).or_default();
let val = valmap
.entry(key.clone())
@@ -521,7 +791,7 @@ impl Ini {
continue;
}
- let valmap = map.entry(section.clone()).or_insert_with(Map::new);
+ let valmap = map.entry(section.clone()).or_default();
match trimmed.find(&self.delimiters[..]) {
Some(delimiter) => {
@@ -934,7 +1204,7 @@ impl Ini {
///
///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
///Use `get_mut_map()` if you want a mutable reference.
- pub async fn load_async<T: AsRef<AsyncPath>>(
+ pub async fn load_async<T: AsRef<Path>>(
&mut self,
path: T,
) -> Result<Map<String, Map<String, Option<String>>>, String> {
@@ -960,13 +1230,69 @@ impl Ini {
Ok(self.map.clone())
}
- ///Writes the current configuation to the specified path asynchronously. If a file is not present, it is automatically created for you, if a file already
+ ///Loads a file from a defined path, parses it and applies it to the existing hashmap in our struct.
+ ///While `load_async()` will clear the existing `Map`, `load_and_append_async()` applies the new values on top
+ ///of the existing hashmap, preserving previous values.
+ ///
+ ///Usage is similar to `load_and_append`, but `.await` must be called after along with the usual async rules.
+ ///
+ ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
+ ///Use `get_mut_map()` if you want a mutable reference.
+ pub async fn load_and_append_async<T: AsRef<Path>>(
+ &mut self,
+ path: T,
+ ) -> Result<Map<String, Map<String, Option<String>>>, String> {
+ let loaded = match self.parse(match async_fs::read_to_string(&path).await {
+ Err(why) => {
+ return Err(format!(
+ "couldn't read {}: {}",
+ &path.as_ref().display(),
+ why
+ ))
+ }
+ Ok(s) => s,
+ }) {
+ Err(why) => {
+ return Err(format!(
+ "couldn't read {}: {}",
+ &path.as_ref().display(),
+ why
+ ))
+ }
+ Ok(map) => map,
+ };
+
+ for (section, section_map) in loaded.iter() {
+ self.map
+ .entry(section.clone())
+ .or_insert_with(Map::new)
+ .extend(section_map.clone());
+ }
+
+ Ok(self.map.clone())
+ }
+
+ ///Writes the current configuation to the specified path asynchronously using default formatting. 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.
///
///Usage is the same as `write`, but `.await` must be called after along with the usual async rules.
///
///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
pub async fn write_async<T: AsRef<Path>>(&self, path: T) -> std::io::Result<()> {
- async_fs::write(path.as_ref(), self.unparse()).await
+ async_fs::write(path.as_ref(), self.unparse(&WriteOptions::default())).await
+ }
+
+ ///Writes the current configuation to the specified path asynchronously using the given formatting options. 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.
+ ///
+ ///Usage is the same as `pretty_pretty_write`, but `.await` must be called after along with the usual async rules.
+ ///
+ ///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
+ pub async fn pretty_write_async<T: AsRef<Path>>(
+ &self,
+ path: T,
+ write_options: &WriteOptions,
+ ) -> std::io::Result<()> {
+ async_fs::write(path.as_ref(), self.unparse(write_options)).await
}
}
diff --git a/src/lib.rs b/src/lib.rs
index b313a56..ba38de9 100755..100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -103,7 +103,7 @@ If you read the above sections carefully, you'll know that 1) all the keys are s
manner and 3) we can use `getint()` to parse the `Int` value into an `i64`. Let's see that in action.
```rust
-use configparser::ini::Ini;
+use configparser::ini::{Ini, WriteOptions};
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
@@ -134,9 +134,14 @@ fn main() -> Result<(), Box<dyn Error>> {
let innermap = map["topsecret"].clone();
// Remember that all indexes are stored in lowercase!
- // You can easily write the currently stored configuration to a file like:
+ // 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.
diff --git a/tests/test.ini b/tests/test.ini
index 7da5603..7da5603 100755..100644
--- a/tests/test.ini
+++ b/tests/test.ini
diff --git a/tests/test.rs b/tests/test.rs
index b0f473c..ce71c49 100755..100644
--- a/tests/test.rs
+++ b/tests/test.rs
@@ -1,4 +1,4 @@
-use configparser::ini::Ini;
+use configparser::ini::{Ini, WriteOptions};
use std::error::Error;
#[test]
@@ -100,6 +100,32 @@ fn non_cs() -> Result<(), Box<dyn Error>> {
mut_map.clear();
config2.clear();
assert_eq!(config.get_map_ref(), config2.get_map_ref());
+
+ config.load("tests/test.ini")?;
+ config.read_and_append("defaultvalues=somenewvalue".to_owned())?;
+ assert_eq!(
+ config.get("default", "defaultvalues").unwrap(),
+ "somenewvalue"
+ );
+ assert_eq!(
+ config.get("topsecret", "KFC").unwrap(),
+ "the secret herb is orega-"
+ );
+
+ let mut config3 = config.clone();
+ let mut_map = config3.get_mut_map();
+ mut_map.clear();
+ config3.load("tests/test.ini")?;
+ config3.load_and_append("tests/test_more.ini")?;
+ assert_eq!(
+ config3.get("default", "defaultvalues").unwrap(),
+ "overwritten"
+ );
+ assert_eq!(config3.get("topsecret", "KFC").unwrap(), "redacted");
+ // spacing -> indented exists in tests/test.ini, but not tests/test_more.ini
+ assert_eq!(config3.get("spacing", "indented").unwrap(), "indented");
+ assert!(!config3.getbool("values", "Bool")?.unwrap());
+
Ok(())
}
@@ -236,8 +262,175 @@ Float=3.1415
}
#[test]
+#[cfg(feature = "indexmap")]
+fn pretty_writes_result_is_formatted_correctly() -> Result<(), Box<dyn Error>> {
+ use configparser::ini::IniDefault;
+
+ const OUT_FILE_CONTENTS: &str = "defaultvalues=defaultvalues
+[topsecret]
+KFC=the secret herb is orega-
+Empty string=
+None string
+Password=[in-brackets]
+[Section]
+Key1: Value1
+Key2: this is a haiku
+ spread across separate lines
+ a single value
+Key3: another value
+";
+
+ let mut ini_defaults = IniDefault::default();
+ ini_defaults.case_sensitive = true;
+ ini_defaults.multiline = true;
+ let mut config = Ini::new_from_defaults(ini_defaults);
+ config.read(OUT_FILE_CONTENTS.to_owned())?;
+
+ let mut write_options = WriteOptions::default();
+ write_options.space_around_delimiters = true;
+ write_options.multiline_line_indentation = 2;
+ write_options.blank_lines_between_sections = 1;
+ assert_eq!(
+ config.pretty_writes(&write_options),
+ "defaultvalues = defaultvalues
+
+[topsecret]
+KFC = the secret herb is orega-
+Empty string =
+None string
+Password = [in-brackets]
+
+[Section]
+Key1 = Value1
+Key2 = this is a haiku
+ spread across separate lines
+ a single value
+Key3 = another value
+"
+ );
+
+ Ok(())
+}
+
+#[test]
+#[cfg(feature = "indexmap")]
+#[cfg(feature = "async-std")]
+#[cfg(feature = "tokio")]
+fn pretty_write_result_is_formatted_correctly() -> Result<(), Box<dyn Error>> {
+ use configparser::ini::IniDefault;
+
+ const OUT_FILE_CONTENTS: &str = "defaultvalues=defaultvalues
+[topsecret]
+KFC=the secret herb is orega-
+Empty string=
+None string
+Password=[in-brackets]
+[Section]
+Key1: Value1
+Key2: this is a haiku
+ spread across separate lines
+ a single value
+Key3: another value
+";
+
+ let mut ini_defaults = IniDefault::default();
+ ini_defaults.case_sensitive = true;
+ ini_defaults.multiline = true;
+ let mut config = Ini::new_from_defaults(ini_defaults);
+ config.read(OUT_FILE_CONTENTS.to_owned())?;
+
+ let mut write_options = WriteOptions::default();
+ write_options.space_around_delimiters = true;
+ write_options.multiline_line_indentation = 2;
+ write_options.blank_lines_between_sections = 1;
+ config.pretty_write("pretty_output.ini", &write_options)?;
+
+ let file_contents = std::fs::read_to_string("pretty_output.ini")?;
+ assert_eq!(
+ file_contents,
+ "defaultvalues = defaultvalues
+
+[topsecret]
+KFC = the secret herb is orega-
+Empty string =
+None string
+Password = [in-brackets]
+
+[Section]
+Key1 = Value1
+Key2 = this is a haiku
+ spread across separate lines
+ a single value
+Key3 = another value
+"
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
+#[cfg(feature = "indexmap")]
+#[cfg(feature = "async-std")]
+#[cfg(feature = "tokio")]
+async fn async_pretty_print_result_is_formatted_correctly() -> Result<(), Box<dyn Error>> {
+ use configparser::ini::IniDefault;
+
+ const OUT_FILE_CONTENTS: &str = "defaultvalues=defaultvalues
+[topsecret]
+KFC=the secret herb is orega-
+Empty string=
+None string
+Password=[in-brackets]
+[Section]
+Key1: Value1
+Key2: this is a haiku
+ spread across separate lines
+ a single value
+Key3: another value
+";
+
+ let mut ini_defaults = IniDefault::default();
+ ini_defaults.case_sensitive = true;
+ ini_defaults.multiline = true;
+ let mut config = Ini::new_from_defaults(ini_defaults);
+ config.read(OUT_FILE_CONTENTS.to_owned())?;
+
+ let mut write_options = WriteOptions::default();
+ write_options.space_around_delimiters = true;
+ write_options.multiline_line_indentation = 2;
+ write_options.blank_lines_between_sections = 1;
+ config
+ .pretty_write_async("pretty_output_async.ini", &write_options)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let file_contents = std::fs::read_to_string("pretty_output_async.ini")?;
+ assert_eq!(
+ file_contents,
+ "defaultvalues = defaultvalues
+
+[topsecret]
+KFC = the secret herb is orega-
+Empty string =
+None string
+Password = [in-brackets]
+
+[Section]
+Key1 = Value1
+Key2 = this is a haiku
+ spread across separate lines
+ a single value
+Key3 = another value
+"
+ );
+
+ Ok(())
+}
+
+#[tokio::test]
#[cfg(feature = "async-std")]
-fn async_load_write() -> Result<(), Box<dyn Error>> {
+#[cfg(feature = "tokio")]
+async fn async_load_write() -> Result<(), Box<dyn Error>> {
const OUT_FILE_CONTENTS: &str = "defaultvalues=defaultvalues
[topsecret]
KFC = the secret herb is orega-
@@ -260,24 +453,37 @@ fn async_load_write() -> Result<(), Box<dyn Error>> {
config.read(OUT_FILE_CONTENTS.to_owned())?;
config.write("output_sync.ini")?;
- async_std::task::block_on::<_, Result<_, String>>(async {
- let mut config_async = Ini::new();
- config_async.read(OUT_FILE_CONTENTS.to_owned())?;
- config_async
- .write_async("output_async.ini")
- .await
- .map_err(|e| e.to_string())?;
- Ok(())
- })?;
+ let mut config_async = Ini::new();
+ config_async.read(OUT_FILE_CONTENTS.to_owned())?;
+ config_async
+ .write_async("output_async.ini")
+ .await
+ .map_err(|e| e.to_string())?;
let mut sync_content = Ini::new();
sync_content.load("output_sync.ini")?;
- let async_content = async_std::task::block_on::<_, Result<_, String>>(async {
- let mut async_content = Ini::new();
- async_content.load_async("output_async.ini").await?;
- Ok(async_content)
- })?;
+ let mut async_content = Ini::new();
+ async_content.load_async("output_async.ini").await?;
+
+ assert_eq!(sync_content, async_content);
+
+ Ok(())
+}
+
+#[tokio::test]
+#[cfg(feature = "async-std")]
+#[cfg(feature = "tokio")]
+async fn async_load_and_append() -> Result<(), Box<dyn Error>> {
+ let mut sync_content = Ini::new();
+ sync_content.load("tests/test.ini")?;
+ sync_content.load_and_append("tests/test_more.ini")?;
+
+ let mut async_content = Ini::new();
+ async_content.load_async("tests/test.ini").await?;
+ async_content
+ .load_and_append_async("tests/test_more.ini")
+ .await?;
assert_eq!(sync_content, async_content);
diff --git a/tests/test_more.ini b/tests/test_more.ini
new file mode 100644
index 0000000..629eec8
--- /dev/null
+++ b/tests/test_more.ini
@@ -0,0 +1,8 @@
+defaultvalues=overwritten
+
+[topsecret]
+KFC = redacted
+
+[values]
+Bool = False
+