Skip to content

Commit

Permalink
Templates require Scheme enum wrapping struct instance
Browse files Browse the repository at this point in the history
- Remove anyhow crate from tinted-builder lib
  • Loading branch information
JamyGolden committed Aug 31, 2024
1 parent 5c3faca commit a0bde42
Show file tree
Hide file tree
Showing 19 changed files with 613 additions and 327 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@

## Changed

- Breaking change: `tinted-builder` library includes an API change and
`tinted-builder-rust` now exports the new `tinted-builder` API
- Breaking change: Use `SchemeSystem` and `SchemeVariant` enums for
scheme `system` and `variant` properties respectively instead of using
string values

## Removed

- Remove deprecated `render_to_file` `Template` method

## [0.9.5] - 2024-08-24

## Fixed
Expand Down
28 changes: 20 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,11 @@ use std::fs::read_to_string;

let template_str = read_to_string("path/to/template.mustache").unwrap();
let scheme_str = read_to_string("path/to/scheme.yml").unwrap();
let scheme: Scheme = serde_yaml::from_str(&scheme_str).unwrap();
let template = Template::new(template_str, scheme.system.clone());
let scheme = Scheme::Base16(serde_yaml::from_str(&scheme_str).unwrap());
let template = Template::new(template_str, scheme);

template
.render_to_file("path/to/rendered/template", &scheme)
.render()
.unwrap();
```

Expand Down
2 changes: 1 addition & 1 deletion tinted-builder-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ Download the relevant binary from the [repository releases] page.

## Basic Usage

```shell
```sh
tinted-builder-rust sync # To sync with latest schemes
tinted-builder-rust build path/to/base16-template
```
Expand Down
15 changes: 7 additions & 8 deletions tinted-builder-rust/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// With the new split of tinted-builder-rust (cli) and
// tinted-builder (lib), tinted-builder is exported here for bakward
// tinted-builder (lib), tinted-builder is exported here for backward
// compatibility for a time. Everyone should move to using
// tinted-builder as the rust library.
#[doc = include_str!("../README.md")]

mod operations {
pub mod build;
Expand All @@ -10,8 +11,7 @@ mod utils;

pub use crate::operations::build as operation_build;

/// # Add tinted-builder library test since tinted-builder-rust is
/// exporting the structs
/// Add tinted-builder library test since tinted-builder-rust is exporting the structs
///
/// ```
/// use tinted_builder_rust::{Scheme, Template};
Expand Down Expand Up @@ -40,15 +40,14 @@ pub use crate::operations::build as operation_build;
/// base0D: "6a9eb5"
/// base0E: "78a38f"
/// base0F: "a3a079""#;
/// let scheme: Scheme = serde_yaml::from_str(&scheme_str).unwrap();
/// let template = Template::new(template, scheme.system.clone());
/// let scheme = Scheme::Base16(serde_yaml::from_str(&scheme_str).unwrap());
/// let template = Template::new(template, scheme);
/// let output = template
/// .render(&scheme)
/// .render()
/// .unwrap();
///
/// assert_eq!(output, r#"/* Some CSS file with UwUnicorn theme */
/// .someCssSelector { background-color: #241b26 }
/// .someOtherCssSelector { background-color: #a3a079 }"#);
/// ```
pub use tinted_builder::Scheme;
pub use tinted_builder::Template;
pub use tinted_builder::{Base16Scheme, Scheme, Template, TintedBuilderError};
23 changes: 16 additions & 7 deletions tinted-builder-rust/src/operations/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use serde::Deserialize;
use std::collections::HashMap;
use std::fs::{self, create_dir_all, read_to_string};
use std::path::{Path, PathBuf};
use tinted_builder::Template;
use tinted_builder::{Scheme, SchemeSystem};
use tinted_builder::{Base16Scheme, Scheme, SchemeSystem, Template};

use crate::utils::write_to_file;

Expand All @@ -20,7 +19,7 @@ fn get_theme_template_path(theme_template_path: &Path) -> Result<PathBuf> {
}

fn generate_theme(
template: &Template,
template_content: &str,
output_dir: &PathBuf,
scheme_path: &PathBuf,
system: SchemeSystem,
Expand All @@ -38,7 +37,7 @@ fn generate_theme(
.and_then(|s| s.to_str())
.unwrap_or_default();
let scheme_str = read_to_string(scheme_path)?;
let scheme: Scheme = serde_yaml::from_str(&scheme_str)?;
let scheme: Base16Scheme = serde_yaml::from_str(&scheme_str)?;
let output_path = output_dir.join(format!("{}-{}.{}", &scheme.system, slug, extension));

if scheme.system != system {
Expand All @@ -49,7 +48,18 @@ fn generate_theme(
fs::create_dir_all(output_dir)?;
}

let output = template.render(&scheme.clone())?;
let scheme = match system {
SchemeSystem::Base16 => Scheme::Base16(scheme.clone()),
SchemeSystem::Base24 => Scheme::Base24(scheme.clone()),
_ => {
return Err(anyhow!(
"Called `unwrap_basex` on a non `Scheme::BaseX` value"
));
}
};
let template = Template::new(template_content.to_string(), scheme);
let output = template.render()?;

write_to_file(&output_path, &output)?;
}

Expand Down Expand Up @@ -133,13 +143,12 @@ pub fn build(theme_template_path: &Path, user_schemes_path: &Path, is_quiet: boo
}

for (system, schemes_path) in scheme_path_vec {
let template = Template::new(template_content.clone(), system.clone());
for item_result in fs::read_dir(schemes_path)? {
let scheme_direntry = item_result?;
let scheme_file_path = scheme_direntry.path();

generate_theme(
&template,
&template_content,
&output_path,
&scheme_file_path,
system.clone(),
Expand Down
12 changes: 12 additions & 0 deletions tinted-builder/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,23 @@

## Unreleased

## Added

- Add basic documentation for docs.rs

## Changed

- Require schemes to be wrapped in `Scheme` enum when creating a
`Template` struct instance to easily extend builder to support
different scheme systems
- Use `SchemeSystem` and `SchemeVariant` enums for scheme `system` and
`variant` properties respectively instead of using string values

## Removed

- `anyhow` crate moved to dev-dependency for tests, but replaced with
`TintedBuilderError` enum with `thiserror` macros in API

## 0.5.1 - 2024-08-24

## Fixed
Expand Down
4 changes: 3 additions & 1 deletion tinted-builder/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,16 @@ categories = ["command-line-utilities", "template-engine"]
rust-version = "1.74.0"

[dependencies]
anyhow = "1.0.80"
clap = "4.5.2"
dirs = "5.0.1"
quick-xml = { version = "0.36.1", features = ["serialize"] }
regex = "1.10.4"
ribboncurls = "0.2.1"
serde = { version = "1.0.197", features = ["derive"] }
serde_yaml = "0.9.32"
thiserror = "1.0.63"
unicode-normalization = "0.1.23"

[dev-dependencies]
anyhow = "1.0.86"
strip-ansi-escapes = "0.2.0"
51 changes: 16 additions & 35 deletions tinted-builder/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ cargo add tinted-builder
## Usage

```rust
use tinted_builder::{Scheme, SchemeType, Template};
use tinted_builder::{Scheme, Template};

let template = String::from(r#"/* Some CSS file with {{scheme-name}} theme */
.someCssSelector { background-color: #{{base00-hex}} }
Expand All @@ -48,48 +48,29 @@ palette:
base0D: "6a9eb5"
base0E: "78a38f"
base0F: "a3a079""#;
let scheme: Scheme = serde_yaml::from_str(&scheme_str).unwrap();
let template = Template::new(template, scheme.system.clone());
let scheme_type = SchemeType::Yaml(scheme);
let scheme = Scheme::Base16(serde_yaml::from_str(&scheme_str).unwrap());
let template = Template::new(template, scheme);
let output = template
.render(&scheme_type)
.render()
.unwrap();

assert_eq!(output, r#"/* Some CSS file with UwUnicorn theme */
.someCssSelector { background-color: #241b26 }
.someOtherCssSelector { background-color: #a3a079 }"#);
```

The Scheme struct is as follows:

```rust
use std::collections::HashMap;
use tinted_builder::{SchemeSystem, SchemeVariant};

pub struct Scheme {
pub system: SchemeSystem,
pub name: String,
pub slug: String,
pub author: String,
pub description: Option<String>,
pub variant: SchemeVariant,
pub palette: HashMap<String, Color>,
}

pub struct Color {
pub hex: (String, String, String),
pub rgb: (u8, u8, u8),
pub dec: (f32, f32, f32),
}
```

`Template::new`
The `Template` struct simply sets the content provided to it via
`Template::new`.

`template.render(&scheme)` takes the scheme, generates the variables
defined in the `0.11.0` [builder specification] and returns a new
string.
1. Create a scheme (`Scheme`) enum variant while providing the
deserialized data into into the variant:
`Scheme::Base16(serde_yaml::from_str(&scheme_str).unwrap())` in this
case
2. Create a template by passing the serialized mustache text and the
`Scheme` variant in step 1 into the `Template` struct:
`Template::new(mustache_text, scheme)`. The `template.render()`
method takes the scheme, generates the variables defined in the
`0.11.0` [builder specification] and returns a new string.
3. Render the template by running a method which returns a
`Result<String, TintedBuilderError>` type:
`let output = template.render().unwrap();`

## Contributing

Expand Down
9 changes: 0 additions & 9 deletions tinted-builder/src/constants.rs

This file was deleted.

53 changes: 53 additions & 0 deletions tinted-builder/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use ribboncurls::RibboncurlsError;
use thiserror::Error;

/// An error type representing the various errors that can occur when using tinted-builder
///
/// This error type is non-exhaustive, meaning additional variants may be added in future versions without
/// it being considered a breaking change. The enum variants cover a range of possible issues that might
/// arise during the processing of color schemes, including missing properties, deserialization errors,
/// and rendering issues.
#[non_exhaustive]
#[derive(Error, Debug)]
pub enum TintedBuilderError {
/// Error indicating that a required property in the scheme is missing.
///
/// This variant is used when a necessary property for the scheme's configuration is not found.
#[error("missing scheme property: {0}")]
SchemeMissingProperty(String),

/// Error that occurs when YAML deserialization fails.
///
/// This variant wraps the `serde_yaml::Error` and is used when there is an issue converting
/// a YAML string into the corresponding Rust data structure.
#[error("unable to deserialize yaml")]
YamlDeserialize(#[from] serde_yaml::Error),

/// Error that occurs during rendering using Ribboncurls.
///
/// This variant wraps the `RibboncurlsError` and is used when an error is encountered while
/// rendering a template or other content using Ribboncurls.
#[error("unable to render")]
RibboncurlsRender(#[from] RibboncurlsError),

/// Error that occurs when a string slice cannot be converted to an integer with the given base.
///
/// This variant wraps `std::num::ParseIntError` and is used when a string slice, such as a color
/// value in hexadecimal format, fails to parse correctly.
#[error("unable to convert string slice to integer with given base")]
ColorRadix(#[from] std::num::ParseIntError),

/// Error indicating that a hex color input is not formatted correctly.
///
/// This variant is used when a color string that is expected to be in hex format does not match
/// the expected format.
#[error("hex input is not formatted correctly")]
HexInputFormat,

/// Error indicating that an invalid scheme variant was provided.
///
/// This variant is used when an input string does not correspond to any valid scheme variant,
/// such as "dark" or "light".
#[error("invalid scheme variant: {0}")]
InvalidSchemeVariant(String),
}
Loading

0 comments on commit a0bde42

Please sign in to comment.