Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,35 @@ jobs:
- name: Run tests
run: cargo test --locked --workspace --no-fail-fast --verbose

# Each date backend is tested on its own. The packages are run one at a time
# so that a feature enabled by one package cannot leak into another through
# feature unification.
date-backends:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- backend: jiff
impl_flags: --no-default-features --features jiff
typify_flags: --no-default-features --features macro,jiff
cli_flags: --no-default-features --features jiff
- backend: none
impl_flags: --no-default-features
typify_flags: --no-default-features --features macro
cli_flags: --no-default-features
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
key: date-${{ matrix.backend }}
- name: Run typify-impl
run: cargo test --locked -p typify-impl ${{ matrix.impl_flags }} --no-fail-fast
- name: Run typify
run: cargo test --locked -p typify ${{ matrix.typify_flags }} --no-fail-fast
- name: Run cargo-typify
run: cargo test --locked -p cargo-typify ${{ matrix.cli_flags }} --no-fail-fast

msrv:
runs-on: ubuntu-latest
env:
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ https://github.com/oxidecomputer/typify/compare/v0.10.1\...HEAD[Full list of com
* Lower the MSRV to 1.88
* A newtype with a schema `default` gets its `Default` impl back, per 0.8
(typespace #74).
* The `date` and `date-time` string formats can map to `jiff` types
(`jiff::civil::Date` and `jiff::Timestamp`) through a new `jiff` feature.
The `chrono` feature, which is on by default, keeps the existing mapping.
When both are enabled, `jiff` takes precedence. Types from `jiff` do not
implement `JsonSchema`.

== 0.10.1 (released 2026-11-16)

Expand Down
18 changes: 18 additions & 0 deletions Cargo.lock

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

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ resolver = "2"
rust-version = "1.88"

[workspace.dependencies]
typify = { version = "0.10.1", path = "typify" }
typify-impl = { version = "0.10.1", path = "typify-impl" }
typify-macro = { version = "0.10.1", path = "typify-macro" }
typify = { version = "0.10.1", path = "typify", default-features = false }
typify-impl = { version = "0.10.1", path = "typify-impl", default-features = false }
typify-macro = { version = "0.10.1", path = "typify-macro", default-features = false }

assert_cmd = "2.2.2"
chrono = { version = "0.4.45", features = ["serde"] }
Expand All @@ -28,6 +28,7 @@ expectorate = "1.2.0"
glob = "0.3.3"
heck = "0.5.0"
ipnetwork = { version = "0.21.1", features = ["schemars"] }
jiff = { version = "0.2.23", features = ["serde"] }
log = "0.4.31"
newline-converter = "0.3.0"
paste = "1.0.15"
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,23 @@ appropriate Rust type. For example `{ "type": "string", "format": "uuid" }` is
represented as a `uuid::Uuid` (which requires the `uuid` crate be included as a
dependency).

The `date` and `date-time` formats are represented by a date library, chosen
with the `chrono` (default) or `jiff` feature:

| Format | `chrono` | `jiff` |
| ----------- | --------------------------------- | -------------------- |
| `date` | `chrono::naive::NaiveDate` | `jiff::civil::Date` |
| `date-time` | `chrono::DateTime<chrono::offset::Utc>` | `jiff::Timestamp` |

Enable `jiff` with `default-features = false` to drop chrono. When both features
are enabled, `jiff` takes precedence. With neither, dates are plain `String`s.
The generated code needs the chosen crate as a dependency; enable its `serde`
feature so the date types deserialize.

Types from `jiff` do not implement `schemars::JsonSchema` (schemars 0.8 has no
`jiff` impl), so a generated type that requires `JsonSchema` cannot contain a
`jiff` date.

### Arrays

JSON Schema arrays can turn into one of three Rust types `Vec<T>`, `HashSet<T>`,
Expand Down
7 changes: 6 additions & 1 deletion cargo-typify/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,14 @@ rust-version.workspace = true

default-run = "cargo-typify"

[features]
default = ["chrono"]
chrono = ["typify/chrono"]
jiff = ["typify/jiff"]

[dependencies]
syn = { workspace = true }
typify = { workspace = true }
typify = { workspace = true, features = ["macro"] }

clap = { workspace = true }
color-eyre = { workspace = true }
Expand Down
8 changes: 8 additions & 0 deletions typify-impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ repository = "https://github.com/oxidecomputer/typify"
readme = "../README.md"
rust-version.workspace = true

[features]
default = ["chrono"]
# Selects the date library that `date` and `date-time` strings map to. These
# are marker features: typify emits paths and never links either crate. When
# both are enabled, jiff takes precedence.
chrono = []
jiff = []

[dependencies]
heck = { workspace = true }
log = { workspace = true }
Expand Down
142 changes: 86 additions & 56 deletions typify-impl/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,68 @@ use crate::util::get_type_name;

use crate::{Error, Name, Result, TypeSpace};

/// The date library that `date` and `date-time` strings map to, chosen by the
/// `chrono` and `jiff` features. jiff takes precedence when both are enabled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DateLibrary {
Chrono,
Jiff,
}

impl DateLibrary {
fn crate_name(self) -> &'static str {
match self {
DateLibrary::Chrono => "chrono",
DateLibrary::Jiff => "jiff",
}
}
}

fn date_library() -> Option<DateLibrary> {
if cfg!(feature = "jiff") {
Some(DateLibrary::Jiff)
} else if cfg!(feature = "chrono") {
Some(DateLibrary::Chrono)
} else {
None
}
}

/// The Rust path a `date` or `date-time` string maps to under `library`.
fn date_path(format: &str, library: DateLibrary) -> &'static str {
match (format, library) {
("date", DateLibrary::Chrono) => "::chrono::naive::NaiveDate",
("date", DateLibrary::Jiff) => "::jiff::civil::Date",
(_, DateLibrary::Chrono) => "::chrono::DateTime<::chrono::offset::Utc>",
(_, DateLibrary::Jiff) => "::jiff::Timestamp",
}
}

/// The traits a date native declares. jiff types have no schemars 0.8 impl,
/// so they omit `JsonSchema`.
fn date_traits(library: DateLibrary) -> TypespaceTraitSet {
let traits = [
TypespaceTrait::Clone,
TypespaceTrait::Debug,
TypespaceTrait::Serialize,
TypespaceTrait::Deserialize,
TypespaceTrait::Display,
TypespaceTrait::FromStr,
TypespaceTrait::Eq,
TypespaceTrait::PartialEq,
TypespaceTrait::Ord,
TypespaceTrait::PartialOrd,
TypespaceTrait::Hash,
];
match library {
DateLibrary::Chrono => traits
.into_iter()
.chain([TypespaceTrait::JsonSchema])
.collect(),
DateLibrary::Jiff => traits.into_iter().collect(),
}
}

impl TypeSpace {
pub(crate) fn convert_schema<'a>(
&mut self,
Expand Down Expand Up @@ -810,69 +872,37 @@ impl TypeSpace {
format: &Option<String>,
validation: Option<&StringValidation>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match format.as_ref().map(String::as_str) {
Some("uuid") => {
self.add_dependency(typespace::codespace::Dependency::new("uuid"));
// ::uuid::Uuid Default, but we ignore it because there's no
// useful value. We assume the uuid feature in schemars.
let date = date_library();
match (format.as_ref().map(String::as_str), date) {
(Some(format @ ("date" | "date-time")), Some(library)) => {
self.add_dependency(typespace::codespace::Dependency::new(library.crate_name()));
Ok((
TypeEntry::new_native(
"::uuid::Uuid",
[
TypespaceTrait::Clone,
TypespaceTrait::Debug,
TypespaceTrait::Serialize,
TypespaceTrait::Deserialize,
TypespaceTrait::Display,
TypespaceTrait::FromStr,
TypespaceTrait::Eq,
TypespaceTrait::PartialEq,
TypespaceTrait::Ord,
TypespaceTrait::PartialOrd,
TypespaceTrait::Hash,
TypespaceTrait::JsonSchema,
]
.into_iter()
.collect::<TypespaceTraitSet>(),
),
TypeEntry::new_native(date_path(format, library), date_traits(library)),
metadata,
))
}

Some("date") => {
self.add_dependency(typespace::codespace::Dependency::new("chrono"));
// ::chrono::naive::NaiveDate implements Default, but there's
// no useful value. We assume the chrono feaeture in schemars.
Ok((
TypeEntry::new_native(
"::chrono::naive::NaiveDate",
[
TypespaceTrait::Clone,
TypespaceTrait::Debug,
TypespaceTrait::Serialize,
TypespaceTrait::Deserialize,
TypespaceTrait::Display,
TypespaceTrait::FromStr,
TypespaceTrait::Eq,
TypespaceTrait::PartialEq,
TypespaceTrait::Ord,
TypespaceTrait::PartialOrd,
TypespaceTrait::Hash,
TypespaceTrait::JsonSchema,
]
.into_iter()
.collect::<TypespaceTraitSet>(),
),
metadata,
))
(format, _) => {
self.convert_format(type_name, original_schema, metadata, format, validation)
}
Some("date-time") => {
self.add_dependency(typespace::codespace::Dependency::new("chrono"));
// ::chrono::DateTime implements Default, but not usefully.
// We assume the chrono feaeture in schemars.
}
}

fn convert_format<'a>(
&mut self,
type_name: Name,
original_schema: &'a Schema,
metadata: &'a Option<Box<Metadata>>,
format: Option<&str>,
validation: Option<&StringValidation>,
) -> Result<(TypeEntry, &'a Option<Box<Metadata>>)> {
match format {
Some("uuid") => {
self.add_dependency(typespace::codespace::Dependency::new("uuid"));
// ::uuid::Uuid Default, but we ignore it because there's no
// useful value. We assume the uuid feature in schemars.
Ok((
TypeEntry::new_native(
"::chrono::DateTime<::chrono::offset::Utc>",
"::uuid::Uuid",
[
TypespaceTrait::Clone,
TypespaceTrait::Debug,
Expand Down
4 changes: 2 additions & 2 deletions typify-impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ pub struct TypeSpace {
name_to_id: BTreeMap<String, TypeId>,
ref_to_id: BTreeMap<RefKey, TypeId>,

/// The crates needed for native types: `chrono` and `uuid` for the string
/// formats it maps to them, and each crate an `x-rust-type` extension
/// The crates needed for native types: `uuid` and the date library
/// (`chrono` or `jiff`) for the string formats they map to, and each crate an `x-rust-type` extension
/// names, at the version [`TypeSpaceSettings::with_crate`] declared for
/// it. Recorded on the `TypespaceBuilder` so the finalized typespace
/// reports them with the crates of what typespace renders itself.
Expand Down
31 changes: 31 additions & 0 deletions typify-impl/tests/test_date_fallback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright 2026 Oxide Computer Company

//! With no date library enabled, `date` and `date-time` are plain strings.

#![cfg(not(any(feature = "chrono", feature = "jiff")))]

use schemars::schema::RootSchema;
use typify_impl::{TypeSpace, TypeSpaceSettings};

#[test]
fn dates_without_a_library_are_strings() {
let schema: RootSchema = serde_json::from_value(serde_json::json!({
"title": "Event",
"type": "object",
"properties": {
"when": { "type": "string", "format": "date-time" },
"day": { "type": "string", "format": "date" }
},
"required": ["when", "day"]
}))
.unwrap();
let mut type_space = TypeSpace::new(&TypeSpaceSettings::default());
type_space.add_root_schema(schema).unwrap();
let rendered = type_space.to_stream().unwrap().to_string();
assert!(
rendered.contains(":: std :: string :: String"),
"{rendered}"
);
assert!(!rendered.contains("chrono"), "{rendered}");
assert!(!rendered.contains("jiff"), "{rendered}");
}
Loading