24 unstable releases (5 breaking)

0.7.0 Apr 10, 2024
0.6.0 Feb 6, 2024
0.5.5 Feb 4, 2024
0.4.10 Nov 30, 2023
0.4.0 Jul 3, 2023

#1053 in Encoding

Download history 588/week @ 2023-12-25 621/week @ 2024-01-01 875/week @ 2024-01-08 554/week @ 2024-01-15 705/week @ 2024-01-22 837/week @ 2024-01-29 811/week @ 2024-02-05 455/week @ 2024-02-12 427/week @ 2024-02-19 841/week @ 2024-02-26 712/week @ 2024-03-04 512/week @ 2024-03-11 980/week @ 2024-03-18 446/week @ 2024-03-25 767/week @ 2024-04-01 705/week @ 2024-04-08

2,942 downloads per month
Used in 16 crates (via schematic)

MIT license

32KB
871 lines

Schematic

Schematic is a library that provides:

  • A layered serde-driven configuration system with support for merge strategies, validation rules, environment variables, and more!
  • A schema modeling system that can be used to generate TypeScript types, JSON schemas, and more!

Both of these features can be used independently or together.

cargo add schematic

Get started: https://moonrepo.github.io/schematic

Configuration

  • Supports JSON, TOML, and YAML based configs via serde.
  • Load sources from the file system or secure URLs.
  • Source layering that merge into a final configuration.
  • Extend additional files through an annotated setting.
  • Field-level merge strategies with built-in merge functions.
  • Aggregated validation with built-in validate functions (provided by garde).
  • Environment variable parsing and overrides.
  • Beautiful parsing and validation errors (powered by miette).
  • Generates schemas that can be rendered to TypeScript types, JSON schemas, and more!

Define a struct or enum and derive the Config trait.

use schematic::Config;

#[derive(Config)]
struct AppConfig {
	#[setting(default = 3000, env = "PORT")]
	port: usize,

	#[setting(default = true)]
	secure: bool,

	#[setting(default = vec!["localhost".into()])]
	allowed_hosts: Vec<String>,
}

Then load, parse, merge, and validate the configuration from one or many sources. A source is either a file path, secure URL, or code block.

use schematic::{ConfigLoader, Format};

let result = ConfigLoader::<AppConfig>::new()
	.code("secure: false", Format::Yaml)?
	.file("path/to/config.yml")?
	.url("https://ordomain.com/to/config.yaml")?
	.load()?;

result.config;
result.layers;

Schemas

Define a struct or enum and derive or implement the Schematic trait.

use schematic::Schematic;

#[derive(Schematic)]
struct Task {
	command: String,
	args: Vec<String>,
	env: HashMap<String, String>,
}

Then generate output in multiple formats, like JSON schemas or TypeScript types, using the schema type information.

use schematic::schema::{SchemaGenerator, TypeScriptRenderer};

let mut generator = SchemaGenerator::default();
generator.add::<Task>();
generator.generate(output_dir.join("types.ts"), TypeScriptRenderer::default())?;

Dependencies

~0–1.8MB
~38K SLoC