diff --git a/schemars/Cargo.toml b/schemars/Cargo.toml index 2c5d7903..307e708d 100644 --- a/schemars/Cargo.toml +++ b/schemars/Cargo.toml @@ -24,6 +24,7 @@ either = { version = "1.3", default-features = false, optional = true } uuid = { version = "0.8", default-features = false, optional = true } smallvec = { version = "1.0", optional = true } arrayvec = { version = "0.5", default-features = false, optional = true } +semver = { version = "0.11.0", optional = true } [dev-dependencies] pretty_assertions = "0.6.1" @@ -61,6 +62,10 @@ required-features = ["either"] name = "uuid" required-features = ["uuid"] +[[test]] +name = "semver" +required-features = ["semver"] + [[test]] name = "smallvec" required-features = ["smallvec"] diff --git a/schemars/src/json_schema_impls/mod.rs b/schemars/src/json_schema_impls/mod.rs index d6d6d16c..7abe2da1 100644 --- a/schemars/src/json_schema_impls/mod.rs +++ b/schemars/src/json_schema_impls/mod.rs @@ -60,6 +60,8 @@ mod nonzero_unsigned; mod primitives; mod sequences; mod serdejson; +#[cfg(feature = "semver")] +mod semver; #[cfg(feature = "smallvec")] mod smallvec; mod time; diff --git a/schemars/src/json_schema_impls/semver.rs b/schemars/src/json_schema_impls/semver.rs new file mode 100644 index 00000000..944188b8 --- /dev/null +++ b/schemars/src/json_schema_impls/semver.rs @@ -0,0 +1,25 @@ +use crate::gen::SchemaGenerator; +use crate::schema::*; +use crate::JsonSchema; +use semver::Version; + +impl JsonSchema for Version { + no_ref_schema!(); + + fn schema_name() -> String { + "SemVer".to_string() + } + + fn json_schema(_: &mut SchemaGenerator) -> Schema { + SchemaObject { + instance_type: Some(InstanceType::String.into()), + string: Some(Box::new(StringValidation { + max_length: None, + pattern: Some(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$".to_string()), + min_length: Some(5), + })), + ..Default::default() + } + .into() + } +} diff --git a/schemars/tests/expected/semver.json b/schemars/tests/expected/semver.json new file mode 100644 index 00000000..ce30120f --- /dev/null +++ b/schemars/tests/expected/semver.json @@ -0,0 +1,7 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SemVer", + "type": "string", + "minLength": 5, + "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$" +} \ No newline at end of file diff --git a/schemars/tests/semver.rs b/schemars/tests/semver.rs new file mode 100644 index 00000000..2ddc3e3d --- /dev/null +++ b/schemars/tests/semver.rs @@ -0,0 +1,8 @@ +mod util; +use semver::Version; +use util::*; + +#[test] +fn semver() -> TestResult { + test_default_generated_schema::("semver") +}