Skip to content

Commit

Permalink
fix(edit)!: Allow disabling parser or display
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Nov 6, 2023
1 parent 5b53ff1 commit ef9fd0a
Show file tree
Hide file tree
Showing 29 changed files with 151 additions and 14 deletions.
4 changes: 2 additions & 2 deletions crates/toml/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ pre-release-replacements = [

[features]
default = ["parse", "display"]
parse = ["dep:toml_edit"]
display = ["dep:toml_edit"]
parse = ["dep:toml_edit", "toml_edit?/parse"]
display = ["dep:toml_edit", "toml_edit?/display"]

# Use indexmap rather than BTreeMap as the map type of toml::Value.
# This allows data to be read into a Value and written back to a TOML string
Expand Down
15 changes: 13 additions & 2 deletions crates/toml_edit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ keywords = ["encoding", "toml"]
categories = ["encoding", "parser-implementations", "parsing", "config"]
description = "Yet another format-preserving TOML parser."
authors = ["Andronik Ordian <write@reusable.software>", "Ed Page <eopage@gmail.com>"]
autotests = false
repository.workspace = true
license.workspace = true
edition.workspace = true
Expand All @@ -26,7 +27,9 @@ pre-release-replacements = [
]

[features]
default = []
default = ["parse", "display"]
parse = ["dep:winnow"]
display = []
perf = ["dep:kstring"]
serde = ["dep:serde", "toml_datetime/serde", "dep:serde_spanned"]
# Provide a method disable_recursion_limit to parse arbitrarily deep structures
Expand All @@ -38,7 +41,7 @@ unbounded = []

[dependencies]
indexmap = { version = "2.0.0", features = ["std"] }
winnow = "0.5.0"
winnow = { version = "0.5.0", optional = true }
serde = { version = "1.0.145", optional = true }
kstring = { version = "2.0.0", features = ["max_inline"], optional = true }
toml_datetime = { version = "0.6.5", path = "../toml_datetime" }
Expand All @@ -51,18 +54,26 @@ toml-test-data = "1.4.0"
libtest-mimic = "0.6.0"
snapbox = { version = "0.4.11", features = ["harness"] }

[[test]]
name = "testsuite"
required-features = ["parse", "display"]

[[test]]
name = "decoder_compliance"
required-features = ["parse"]
harness = false

[[test]]
name = "encoder_compliance"
required-features = ["parse", "display"]
harness = false

[[test]]
name = "invalid"
required-features = ["parse"]
harness = false

[[example]]
name = "visit"
required-features = ["parse", "display"]
test = true
7 changes: 7 additions & 0 deletions crates/toml_edit/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,11 @@ impl Array {
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "parse")] {
/// let formatted_value = "'literal'".parse::<toml_edit::Value>().unwrap();
/// let mut arr = toml_edit::Array::new();
/// arr.push_formatted(formatted_value);
/// # }
/// ```
pub fn push_formatted(&mut self, v: Value) {
self.values.push(Item::Value(v));
Expand Down Expand Up @@ -223,12 +225,14 @@ impl Array {
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "parse")] {
/// let mut arr = toml_edit::Array::new();
/// arr.push(1);
/// arr.push("foo");
///
/// let formatted_value = "'start'".parse::<toml_edit::Value>().unwrap();
/// arr.insert_formatted(0, formatted_value);
/// # }
/// ```
pub fn insert_formatted(&mut self, index: usize, v: Value) {
self.values.insert(index, Item::Value(v))
Expand Down Expand Up @@ -269,12 +273,14 @@ impl Array {
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "parse")] {
/// let mut arr = toml_edit::Array::new();
/// arr.push(1);
/// arr.push("foo");
///
/// let formatted_value = "'start'".parse::<toml_edit::Value>().unwrap();
/// arr.replace_formatted(0, formatted_value);
/// # }
/// ```
pub fn replace_formatted(&mut self, index: usize, v: Value) -> Value {
match mem::replace(&mut self.values[index], Item::Value(v)) {
Expand Down Expand Up @@ -383,6 +389,7 @@ impl Array {
}
}

#[cfg(feature = "display")]
impl std::fmt::Display for Array {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::encode::Encode::encode(self, f, None, ("", ""))
Expand Down
1 change: 1 addition & 0 deletions crates/toml_edit/src/array_of_tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ impl<'s> IntoIterator for &'s ArrayOfTables {
}
}

#[cfg(feature = "display")]
impl std::fmt::Display for ArrayOfTables {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// HACK: Without the header, we don't really have a proper way of printing this
Expand Down
3 changes: 3 additions & 0 deletions crates/toml_edit/src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ impl From<Error> for crate::TomlError {
impl std::error::Error for Error {}

/// Convert a value into `T`.
#[cfg(feature = "parse")]
pub fn from_str<T>(s: &'_ str) -> Result<T, Error>
where
T: DeserializeOwned,
Expand All @@ -96,6 +97,7 @@ where
}

/// Convert a value into `T`.
#[cfg(feature = "parse")]
pub fn from_slice<T>(s: &'_ [u8]) -> Result<T, Error>
where
T: DeserializeOwned,
Expand Down Expand Up @@ -125,6 +127,7 @@ impl Deserializer {
}
}

#[cfg(feature = "parse")]
impl std::str::FromStr for Deserializer {
type Err = Error;

Expand Down
1 change: 1 addition & 0 deletions crates/toml_edit/src/de/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ impl crate::Item {
}
}

#[cfg(feature = "parse")]
impl std::str::FromStr for ValueDeserializer {
type Err = Error;

Expand Down
1 change: 1 addition & 0 deletions crates/toml_edit/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ impl Default for Document {
}
}

#[cfg(feature = "parse")]
impl FromStr for Document {
type Err = crate::TomlError;

Expand Down
1 change: 1 addition & 0 deletions crates/toml_edit/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub struct TomlError {
}

impl TomlError {
#[cfg(feature = "parse")]
pub(crate) fn new(
error: winnow::error::ParseError<
crate::parser::prelude::Input<'_>,
Expand Down
5 changes: 5 additions & 0 deletions crates/toml_edit/src/inline_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,15 @@ impl InlineTable {
/// In the document above, tables `target` and `target."x86_64/windows.json"` are implicit.
///
/// ```
/// # #[cfg(feature = "parse")] {
/// # #[cfg(feature = "display")] {
/// use toml_edit::Document;
/// let mut doc = "[a]\n[a.b]\n".parse::<Document>().expect("invalid toml");
///
/// doc["a"].as_table_mut().unwrap().set_implicit(true);
/// assert_eq!(doc.to_string(), "[a.b]\n");
/// # }
/// # }
/// ```
pub(crate) fn set_implicit(&mut self, implicit: bool) {
self.implicit = implicit;
Expand Down Expand Up @@ -411,6 +415,7 @@ impl InlineTable {
}
}

#[cfg(feature = "display")]
impl std::fmt::Display for InlineTable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::encode::Encode::encode(self, f, None, ("", ""))
Expand Down
4 changes: 4 additions & 0 deletions crates/toml_edit/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ impl Clone for Item {
}
}

#[cfg(feature = "parse")]
impl FromStr for Item {
type Err = crate::TomlError;

Expand All @@ -339,6 +340,7 @@ impl FromStr for Item {
}
}

#[cfg(feature = "display")]
impl std::fmt::Display for Item {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self {
Expand All @@ -358,6 +360,7 @@ impl std::fmt::Display for Item {
///
/// # Examples
/// ```rust
/// # #[cfg(feature = "display")] {
/// # use snapbox::assert_eq;
/// # use toml_edit::*;
/// let mut table = Table::default();
Expand All @@ -372,6 +375,7 @@ impl std::fmt::Display for Item {
/// key2 = 42
/// key3 = ["hello", '\, world']
/// "#);
/// # }
/// ```
pub fn value<V: Into<Value>>(v: V) -> Item {
Item::Value(v.into())
Expand Down
38 changes: 30 additions & 8 deletions crates/toml_edit/src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ impl Key {
/// Parse a TOML key expression
///
/// Unlike `"".parse<Key>()`, this supports dotted keys.
#[cfg(feature = "parse")]
pub fn parse(repr: &str) -> Result<Vec<Self>, crate::TomlError> {
Self::try_parse_path(repr)
}
Expand Down Expand Up @@ -81,11 +82,13 @@ impl Key {
}

/// Returns the default raw representation.
#[cfg(feature = "display")]
pub fn default_repr(&self) -> Repr {
to_key_repr(&self.key)
}

/// Returns a raw representation.
#[cfg(feature = "display")]
pub fn display_repr(&self) -> Cow<'_, str> {
self.as_repr()
.and_then(|r| r.as_raw().as_str())
Expand Down Expand Up @@ -124,12 +127,14 @@ impl Key {
self.decor.clear();
}

#[cfg(feature = "parse")]
fn try_parse_simple(s: &str) -> Result<Key, crate::TomlError> {
let mut key = crate::parser::parse_key(s)?;
key.despan(s);
Ok(key)
}

#[cfg(feature = "parse")]
fn try_parse_path(s: &str) -> Result<Vec<Key>, crate::TomlError> {
let mut keys = crate::parser::parse_key_path(s)?;
for key in &mut keys {
Expand Down Expand Up @@ -206,12 +211,14 @@ impl PartialEq<String> for Key {
}
}

#[cfg(feature = "display")]
impl std::fmt::Display for Key {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crate::encode::Encode::encode(self, f, None, ("", ""))
}
}

#[cfg(feature = "parse")]
impl FromStr for Key {
type Err = crate::TomlError;

Expand All @@ -223,16 +230,28 @@ impl FromStr for Key {
}
}

#[cfg(feature = "display")]
fn to_key_repr(key: &str) -> Repr {
if key
.as_bytes()
.iter()
.copied()
.all(crate::parser::key::is_unquoted_char)
&& !key.is_empty()
#[cfg(feature = "parse")]
{
if key
.as_bytes()
.iter()
.copied()
.all(crate::parser::key::is_unquoted_char)
&& !key.is_empty()
{
Repr::new_unchecked(key)
} else {
crate::encode::to_string_repr(
key,
Some(crate::encode::StringStyle::OnelineSingle),
Some(false),
)
}
}
#[cfg(not(feature = "parse"))]
{
Repr::new_unchecked(key)
} else {
crate::encode::to_string_repr(
key,
Some(crate::encode::StringStyle::OnelineSingle),
Expand Down Expand Up @@ -290,11 +309,13 @@ impl<'k> KeyMut<'k> {
}

/// Returns the default raw representation.
#[cfg(feature = "display")]
pub fn default_repr(&self) -> Repr {
self.key.default_repr()
}

/// Returns a raw representation.
#[cfg(feature = "display")]
pub fn display_repr(&self) -> Cow<str> {
self.key.display_repr()
}
Expand Down Expand Up @@ -344,6 +365,7 @@ impl<'s> PartialEq<String> for KeyMut<'s> {
}
}

#[cfg(feature = "display")]
impl<'k> std::fmt::Display for KeyMut<'k> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.key, f)
Expand Down
10 changes: 10 additions & 0 deletions crates/toml_edit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
//! # Example
//!
//! ```rust
//! # #[cfg(feature = "parse")] {
//! # #[cfg(feature = "display")] {
//! use toml_edit::{Document, value};
//!
//! let toml = r#"
Expand All @@ -32,26 +34,32 @@
//! c = { d = "hello" }
//! "#;
//! assert_eq!(doc.to_string(), expected);
//! # }
//! # }
//! ```
//!
//! ## Controlling formatting
//!
//! By default, values are created with default formatting
//! ```rust
//! # #[cfg(feature = "display")] {
//! let mut doc = toml_edit::Document::new();
//! doc["foo"] = toml_edit::value("bar");
//! let expected = r#"foo = "bar"
//! "#;
//! assert_eq!(doc.to_string(), expected);
//! # }
//! ```
//!
//! You can choose a custom TOML representation by parsing the value.
//! ```rust
//! # #[cfg(feature = "display")] {
//! let mut doc = toml_edit::Document::new();
//! doc["foo"] = "'bar'".parse::<toml_edit::Item>().unwrap();
//! let expected = r#"foo = 'bar'
//! "#;
//! assert_eq!(doc.to_string(), expected);
//! # }
//! ```
//!
//! ## Limitations
Expand All @@ -65,13 +73,15 @@
mod array;
mod array_of_tables;
mod document;
#[cfg(feature = "display")]
mod encode;
mod error;
mod index;
mod inline_table;
mod internal_string;
mod item;
mod key;
#[cfg(feature = "parse")]
mod parser;
mod raw_string;
mod repr;
Expand Down
Loading

0 comments on commit ef9fd0a

Please sign in to comment.