Skip to content

Commit

Permalink
refactor(frontmatter-gen): 🎨 add new examples
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastienrousseau committed Oct 3, 2024
1 parent a16b0fe commit 7784e67
Show file tree
Hide file tree
Showing 9 changed files with 721 additions and 53 deletions.
22 changes: 22 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ serde_json = "1.0"
serde_yml = "0.0.12"
thiserror = "1.0"
toml = "0.8"
tokio = { version = "1.0", features = ["full"] }

# -----------------------------------------------------------------------------
# Build Dependencies
Expand All @@ -56,6 +57,27 @@ version_check = "0.9"
[dev-dependencies]
serde = { version = "1.0", features = ["derive"] }

[[example]]
name = "error"
path = "examples/error_examples.rs"

[[example]]
name = "extractor"
path = "examples/extractor_examples.rs"

[[example]]
name = "lib"
path = "examples/lib_examples.rs"

[[example]]
name = "parser"
path = "examples/parser_examples.rs"

[[example]]
name = "types"
path = "examples/types_examples.rs"


# [[bench]]
# name = "markdown_benchmark"
# harness = false
Expand Down
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,19 @@ assert!(yaml.contains("date: '2023-05-20'"));

For full API documentation, please visit [docs.rs/frontmatter-gen](https://docs.rs/frontmatter-gen).

## Contributing
## Examples

Contributions are welcome! Please feel free to submit a Pull Request.
To run the examples, clone the repository and use the following command:

```shell
cargo run --example example_name
```

Replace `example_name` with the name of the example you want to run.

## Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

## License

Expand Down
155 changes: 155 additions & 0 deletions examples/error_examples.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// Copyright © 2024 FrontMatterGen. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// See LICENSE-APACHE.md and LICENSE-MIT.md in the repository root for full license information.

//! # FrontMatterGen Error Handling Examples
//!
//! This example demonstrates the usage of the error types and error handling
//! functionality in the FrontMatterGen library. It covers various error scenarios,
//! error conversion, and error handling for frontmatter parsing, conversion, and extraction.
#![allow(missing_docs)]

use frontmatter_gen::error::FrontmatterError;

/// Entry point for the FrontMatterGen error handling examples.
///
/// This function runs various examples demonstrating error creation, conversion,
/// and handling for different scenarios in the FrontMatterGen library.
///
/// # Errors
///
/// Returns an error if any of the example functions fail.
pub(crate) fn main() -> Result<(), Box<dyn std::error::Error>> {
let rt = tokio::runtime::Runtime::new()?;
rt.block_on(async {
println!("\n🧪 FrontMatterGen Error Handling Examples\n");

yaml_parse_error_example()?;
toml_parse_error_example()?;
json_parse_error_example()?;
conversion_error_example()?;
unsupported_format_error_example()?;
extraction_error_example()?;

println!(
"\n🎉 All error handling examples completed successfully!"
);

Ok(())
})
}

/// Demonstrates handling of YAML parsing errors.
///
/// This function attempts to parse invalid YAML content and shows
/// how FrontMatterGen handles parsing errors.
fn yaml_parse_error_example() -> Result<(), FrontmatterError> {
println!("🦀 YAML Parse Error Example");
println!("---------------------------------------------");

let invalid_yaml = "invalid: yaml: data";
let result: Result<serde_yml::Value, _> =
serde_yml::from_str(invalid_yaml);

match result {
Ok(_) => println!(
" ❌ Unexpected success in parsing invalid YAML"
),
Err(e) => {
let error = FrontmatterError::YamlParseError { source: e };
println!(
" ✅ Successfully caught YAML parse error: {}",
error
);
}
}

Ok(())
}

/// Demonstrates handling of TOML parsing errors.
fn toml_parse_error_example() -> Result<(), FrontmatterError> {
println!("\n🦀 TOML Parse Error Example");
println!("---------------------------------------------");

let invalid_toml = "invalid = toml data";
match toml::from_str::<toml::Value>(invalid_toml) {
Ok(_) => println!(
" ❌ Unexpected success in parsing invalid TOML"
),
Err(e) => {
let error = FrontmatterError::TomlParseError(e);
println!(
" ✅ Successfully caught TOML parse error: {}",
error
);
}
}

Ok(())
}

/// Demonstrates handling of JSON parsing errors.
fn json_parse_error_example() -> Result<(), FrontmatterError> {
println!("\n🦀 JSON Parse Error Example");
println!("---------------------------------------------");

let invalid_json = "{ invalid json }";
match serde_json::from_str::<serde_json::Value>(invalid_json) {
Ok(_) => println!(
" ❌ Unexpected success in parsing invalid JSON"
),
Err(e) => {
let error = FrontmatterError::JsonParseError(e);
println!(
" ✅ Successfully caught JSON parse error: {}",
error
);
}
}

Ok(())
}

/// Demonstrates handling of frontmatter conversion errors.
fn conversion_error_example() -> Result<(), FrontmatterError> {
println!("\n🦀 Conversion Error Example");
println!("---------------------------------------------");

let error_message = "Failed to convert frontmatter data";
let error =
FrontmatterError::ConversionError(error_message.to_string());
println!(" ✅ Created Conversion Error: {}", error);

Ok(())
}

/// Demonstrates handling of unsupported format errors.
fn unsupported_format_error_example() -> Result<(), FrontmatterError> {
println!("\n🦀 Unsupported Format Error Example");
println!("---------------------------------------------");

let line = 42;
let error = FrontmatterError::unsupported_format(line);
println!(
" ✅ Created Unsupported Format Error for line {}: {}",
line, error
);

Ok(())
}

/// Demonstrates handling of extraction errors.
fn extraction_error_example() -> Result<(), FrontmatterError> {
println!("\n🦀 Extraction Error Example");
println!("---------------------------------------------");

let error_message = "Failed to extract frontmatter";
let error =
FrontmatterError::ExtractionError(error_message.to_string());
println!(" ✅ Created Extraction Error: {}", error);

Ok(())
}
127 changes: 127 additions & 0 deletions examples/extractor_examples.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Copyright © 2024 FrontMatterGen. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
// See LICENSE-APACHE.md and LICENSE-MIT.md in the repository root for full license information.

//! # FrontMatterGen Extractor Examples
//!
//! This example demonstrates the functionality for extracting frontmatter in
//! YAML, TOML, and JSON formats from content. It covers various scenarios for
//! frontmatter extraction, format detection, and error handling.
#![allow(missing_docs)]

use frontmatter_gen::error::FrontmatterError;
use frontmatter_gen::extractor::{
detect_format, extract_json_frontmatter, extract_raw_frontmatter,
};

/// Entry point for the FrontMatterGen extractor examples.
///
/// This function runs various examples demonstrating frontmatter extraction and
/// format detection for different scenarios in the FrontMatterGen library.
///
/// # Errors
///
/// Returns an error if any of the example functions fail.
#[tokio::main]
pub(crate) async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("\n🧪 FrontMatterGen Extractor Examples\n");

extract_yaml_example()?;
extract_toml_example()?;
extract_json_example()?;
extract_json_deeply_nested_example()?;
detect_format_example()?;

println!("\n🎉 All extractor examples completed successfully!");

Ok(())
}

/// Demonstrates extracting YAML frontmatter from content.
fn extract_yaml_example() -> Result<(), FrontmatterError> {
println!("🦀 YAML Frontmatter Extraction Example");
println!("---------------------------------------------");

let content = r#"---
title: Example
---
Content here"#;
let result = extract_raw_frontmatter(content)?;
println!(" ✅ Extracted frontmatter: {}\n", result.0);
println!(" Remaining content: {}", result.1);

Ok(())
}

/// Demonstrates extracting TOML frontmatter from content.
fn extract_toml_example() -> Result<(), FrontmatterError> {
println!("\n🦀 TOML Frontmatter Extraction Example");
println!("---------------------------------------------");

let content = r#"+++
title = "Example"
+++
Content here"#;
let result = extract_raw_frontmatter(content)?;
println!(" ✅ Extracted frontmatter: {}\n", result.0);
println!(" Remaining content: {}", result.1);

Ok(())
}

/// Demonstrates extracting JSON frontmatter from content.
fn extract_json_example() -> Result<(), FrontmatterError> {
println!("\n🦀 JSON Frontmatter Extraction Example");
println!("---------------------------------------------");

let content = r#"{ "title": "Example" }
Content here"#;
let result = extract_json_frontmatter(content)?;
println!(" ✅ Extracted JSON frontmatter: {}\n", result);

Ok(())
}

/// Demonstrates extracting deeply nested JSON frontmatter from content.
fn extract_json_deeply_nested_example() -> Result<(), FrontmatterError>
{
println!("\n🦀 Deeply Nested JSON Frontmatter Example");
println!("---------------------------------------------");

let content = r#"{ "a": { "b": { "c": { "d": { "e": {} }}}}}
Content here"#;
let result = extract_json_frontmatter(content)?;
println!(
" ✅ Extracted deeply nested frontmatter: {}\n",
result
);

Ok(())
}

/// Demonstrates detecting the format of frontmatter.
fn detect_format_example() -> Result<(), FrontmatterError> {
println!("\n🦀 Frontmatter Format Detection Example");
println!("---------------------------------------------");

let yaml = "title: Example";
let toml = "title = \"Example\"";
let json = "{ \"title\": \"Example\" }";

println!(
" Detected format for YAML: {:?}",
detect_format(yaml)?
);
println!(
" Detected format for TOML: {:?}",
detect_format(toml)?
);
println!(
" Detected format for JSON: {:?}",
detect_format(json)?
);

Ok(())
}
Loading

0 comments on commit 7784e67

Please sign in to comment.