Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for #[required] fields #11

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

Conversation

hnefatl
Copy link

@hnefatl hnefatl commented Nov 9, 2024

Hey! Love the library, I use it a lot for embedding configuration and credentials into embedded devices.

The failing-config example I've added basically describes the use-case that motivated this: I wanted a config that requires some fields (e.g. wifi_ssid) to be set but doesn't necessarily need other fields (e.g. wifi_passkey, ...). I could provide defaults for everything then check for non-default values at runtime, but that's verbose and negates the awesomeness of this crate: being able to control the config at compile-time.

#[toml_cfg::toml_config]
pub struct Config {
    #[required]  // this is new
    wifi_ssid: &'static str,
    #[default("")]
    wifi_passkey: &'static str,
}
[failing-config]
# Oops, I forgot to set `wifi_ssid`.
wifi_passkey = "my_password"
$ cd ../failing-config
$ cargo build --quiet
error: custom attribute panicked
 --> src/lib.rs:3:1
  |
3 | #[toml_cfg::toml_config]
  | ^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: message: Field `wifi_ssid`: required but no value was provided in the config file.

error: could not compile `failing-config` (lib) due to 1 previous error

This is backwards compatible except for error messages: #[default(...)] behaves identically, users have to add #[required] to see any new behaviour.

First two commits are just housekeeping, 3rd commit is implementation+documentation.

@hnefatl hnefatl marked this pull request as ready for review November 9, 2024 12:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant