merge: the history of schemars-nixgen

This commit is contained in:
LGUG2Z committed 2026-11-05 15:03:27 -08:00
commit 3d33fac0cd
8 files changed
+2878

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
[package]
name = "schemars-nixgen"
version = "0.1.0"
edition = "2024"
license-file = "LICENSE.md"
[lib]
name = "schemars_nixgen"
path = "src/lib.rs"
[[bin]]
name = "schemars-nixgen"
path = "src/main.rs"
[dependencies]
clap = { version = "4", features = ["derive", "wrap_help"] }
color-eyre = "0.6"
schemars = "1.1"
serde = { version = "1", features = ["derive"] }
serde_json = { package = "serde_json_lenient", version = "0.2" }
sha2 = "0.10"
thiserror = "2"
+131
View File
@@ -0,0 +1,131 @@
//! Nix code formatting utilities
/// Generate the Nix module header
pub fn module_header() -> &'static str {
"{ lib, ... }:"
}
/// Generate the opening of an options block
pub fn options_block_open(option_name: &str) -> String {
format!(
r#"{{
options.{} = lib.mkOption {{
type = lib.types.submodule {{
options = {{"#,
option_name
)
}
/// Generate the closing of an options block
pub fn options_block_close(description: &str) -> String {
format!(
r#" }};
}};
default = {{}};
description = "{}";
}};
}}"#,
crate::types::escape_nix_string(description)
)
}
/// Indent a block of text
pub fn indent(text: &str, level: usize) -> String {
let prefix = " ".repeat(level);
text.lines()
.map(|line| {
if line.trim().is_empty() {
String::new()
} else {
format!("{}{}", prefix, line)
}
})
.collect::<Vec<_>>()
.join("\n")
}
/// Convert a JSON value to a Nix literal
pub fn json_to_nix_literal(value: &serde_json::Value) -> String {
match value {
serde_json::Value::Null => "null".to_string(),
serde_json::Value::Bool(b) => b.to_string(),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
i.to_string()
} else if let Some(f) = n.as_f64() {
format!("{:.6}", f)
.trim_end_matches('0')
.trim_end_matches('.')
.to_string()
} else {
n.to_string()
}
}
serde_json::Value::String(s) => {
format!("\"{}\"", crate::types::escape_nix_string(s))
}
serde_json::Value::Array(arr) => {
let items: Vec<String> = arr.iter().map(json_to_nix_literal).collect();
format!("[ {} ]", items.join(" "))
}
serde_json::Value::Object(obj) => {
if obj.is_empty() {
"{}".to_string()
} else {
let attrs: Vec<String> = obj
.iter()
.map(|(k, v)| {
format!(
"{} = {};",
crate::types::escape_nix_attr_name(k),
json_to_nix_literal(v)
)
})
.collect();
format!("{{ {} }}", attrs.join(" "))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_json_to_nix_literal_primitives() {
assert_eq!(json_to_nix_literal(&json!(null)), "null");
assert_eq!(json_to_nix_literal(&json!(true)), "true");
assert_eq!(json_to_nix_literal(&json!(false)), "false");
assert_eq!(json_to_nix_literal(&json!(42)), "42");
assert_eq!(json_to_nix_literal(&json!(2.5)), "2.5");
assert_eq!(json_to_nix_literal(&json!("hello")), "\"hello\"");
}
#[test]
fn test_json_to_nix_literal_array() {
assert_eq!(json_to_nix_literal(&json!([1, 2, 3])), "[ 1 2 3 ]");
assert_eq!(json_to_nix_literal(&json!(["a", "b"])), "[ \"a\" \"b\" ]");
}
#[test]
fn test_json_to_nix_literal_object() {
assert_eq!(json_to_nix_literal(&json!({})), "{}");
// Note: Object ordering may vary, so we just check it produces valid output
let result = json_to_nix_literal(&json!({"x": 1}));
assert!(result.contains("x = 1"));
}
#[test]
fn test_indent() {
let text = "line1\nline2\nline3";
let indented = indent(text, 2);
assert_eq!(indented, " line1\n line2\n line3");
}
#[test]
fn test_module_header() {
assert_eq!(module_header(), "{ lib, ... }:");
}
}
File diff suppressed because it is too large. Load diff
+132
View File
@@ -0,0 +1,132 @@
//! schemars-nixgen: Generate Nix option definitions from JSON Schema
//!
//! This library converts JSON Schema (as generated by schemars) into
//! strongly-typed Nix option definitions for the NixOS module system.
pub mod format;
pub mod generator;
pub mod prepare;
pub mod types;
pub use generator::Generator;
pub use generator::GeneratorError;
pub use generator::GeneratorOptions;
pub use types::NixOption;
pub use types::NixType;
use schemars::JsonSchema;
use serde_json::Value;
/// Extension trait for generating Nix options from types that implement JsonSchema
pub trait SchemaExt: JsonSchema {
/// Generate Nix module code for this type
fn to_nix_options(options: &GeneratorOptions) -> Result<String, GeneratorError> {
let schema = schemars::schema_for!(Self);
let schema_value: Value = serde_json::to_value(&schema)
.map_err(|e| GeneratorError::InvalidSchema(e.to_string()))?;
let mut generator = Generator::new(&schema_value);
generator.generate(&schema_value, options)
}
}
// Implement SchemaExt for all types that implement JsonSchema
impl<T: JsonSchema> SchemaExt for T {}
/// The first line of a generated file: the SHA-256 of the schema file's bytes, in lowercase hex
///
/// This is the same digest as `nix hash file --type sha256 --base16 <schema>`, so a check can compare
/// the header of a generated file with the hash of the schema it says it was made from.
pub fn schema_hash_header(schema_bytes: &[u8]) -> String {
use sha2::Digest;
use std::fmt::Write;
let mut header = String::from("# schema-sha256: ");
for byte in sha2::Sha256::digest(schema_bytes) {
write!(header, "{byte:02x}").expect("writing to a String cannot fail");
}
header.push('\n');
header
}
/// Generate Nix options from a JSON schema value
pub fn generate_from_schema(
schema: &Value,
options: &GeneratorOptions,
) -> Result<String, GeneratorError> {
let mut generator = Generator::new(schema);
generator.generate(schema, options)
}
/// Generate Nix options from a JSON schema string
pub fn generate_from_str(
schema_str: &str,
options: &GeneratorOptions,
) -> Result<String, GeneratorError> {
let schema: Value = serde_json::from_str(schema_str)
.map_err(|e| GeneratorError::InvalidSchema(e.to_string()))?;
generate_from_schema(&schema, options)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_schema_hash_header() {
// the SHA-256 of the empty input and of "abc"
assert_eq!(
schema_hash_header(b""),
"# schema-sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n"
);
assert_eq!(
schema_hash_header(b"abc"),
"# schema-sha256: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\n"
);
}
#[test]
fn test_generate_from_schema() {
let schema = json!({
"type": "object",
"properties": {
"enabled": {
"type": "boolean",
"description": "Whether to enable the feature"
},
"count": {
"type": "integer",
"description": "Number of items"
}
}
});
let options = GeneratorOptions {
root_name: "myapp".to_string(),
root_description: "My application configuration".to_string(),
};
let output = generate_from_schema(&schema, &options).unwrap();
assert!(output.contains("{ lib, ... }:"));
assert!(output.contains("options.myapp"));
assert!(output.contains("lib.types.bool"));
assert!(output.contains("lib.types.int"));
assert!(output.contains("Whether to enable the feature"));
}
#[test]
fn test_generate_from_str() {
let schema_str = r#"{
"type": "object",
"properties": {
"name": {"type": "string"}
}
}"#;
let options = GeneratorOptions::default();
let output = generate_from_str(schema_str, &options).unwrap();
assert!(output.contains("lib.types.str"));
}
}
+66
View File
@@ -0,0 +1,66 @@
use clap::Parser;
use schemars_nixgen::GeneratorOptions;
use schemars_nixgen::generate_from_schema;
use schemars_nixgen::schema_hash_header;
use std::fs;
use std::io::Write;
use std::io::{self};
use std::path::PathBuf;
/// Generate Nix option definitions from JSON Schema
#[derive(Parser, Debug)]
#[command(name = "schemars-nixgen")]
#[command(about = "Generate Nix option definitions from JSON Schema")]
struct Cli {
/// Input JSON Schema file
input: PathBuf,
/// Output Nix file (default: stdout)
#[arg(short, long)]
output: Option<PathBuf>,
/// Root option name (e.g., "komorebi" or "komorebi-bar")
#[arg(short, long, default_value = "config")]
name: String,
/// Description for the root option
#[arg(short, long, default_value = "Configuration options")]
description: String,
}
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let cli = Cli::parse();
// Read the input schema
let schema_str = fs::read_to_string(&cli.input)?;
let schema: serde_json::Value = serde_json::from_str(&schema_str)?;
// Configure generator options
let options = GeneratorOptions {
root_name: cli.name,
root_description: cli.description,
};
// Generate Nix code, with the hash of the schema file first so a check can tell when the options
// are older than the schema
let nix_code = format!(
"{}{}",
schema_hash_header(schema_str.as_bytes()),
generate_from_schema(&schema, &options)?
);
// Write output
if let Some(output_path) = cli.output {
fs::write(&output_path, &nix_code)?;
eprintln!(
"Generated Nix options written to: {}",
output_path.display()
);
} else {
io::stdout().write_all(nix_code.as_bytes())?;
}
Ok(())
}
+503
View File
@@ -0,0 +1,503 @@
//! Schema preparation utilities for normalizing JSON Schema before conversion
use serde_json::Value;
use std::collections::BTreeMap;
/// Result type for mixed enum + object union detection
/// Contains (enum_variants, object_variants) where object_variants are (tag_name, inner_schema) tuples
pub type MixedUnionResult = (Vec<String>, Vec<(String, Value)>);
/// Extract all definitions from the schema's $defs section
pub fn collect_definitions(schema: &Value) -> BTreeMap<String, Value> {
let mut defs = BTreeMap::new();
if let Some(definitions) = schema.get("$defs").and_then(|d| d.as_object()) {
for (name, def) in definitions {
defs.insert(name.clone(), def.clone());
}
}
// Also check "definitions" for older schemas
if let Some(definitions) = schema.get("definitions").and_then(|d| d.as_object()) {
for (name, def) in definitions {
defs.insert(name.clone(), def.clone());
}
}
defs
}
/// Resolve a $ref to its definition name
pub fn resolve_ref_name(ref_str: &str) -> Option<&str> {
// Handle "#/$defs/TypeName" or "#/definitions/TypeName"
if let Some(name) = ref_str.strip_prefix("#/$defs/") {
Some(name)
} else if let Some(name) = ref_str.strip_prefix("#/definitions/") {
Some(name)
} else {
None
}
}
/// Check if a schema represents a nullable type (anyOf with null)
/// Returns Some(inner_schema) if it's a nullable pattern, None otherwise
/// Handles cases with multiple null variants (e.g., from serde Option serialization)
pub fn detect_nullable_anyof(schema: &Value) -> Option<&Value> {
let any_of = schema.get("anyOf")?.as_array()?;
// Collect null and non-null variants
let mut non_null_variants: Vec<&Value> = Vec::new();
let mut has_null = false;
for variant in any_of.iter() {
if is_null_schema(variant) {
has_null = true;
} else {
non_null_variants.push(variant);
}
}
// If we have exactly one non-null variant and at least one null, it's a nullable pattern
if has_null && non_null_variants.len() == 1 {
Some(non_null_variants[0])
} else {
None
}
}
/// Check if a schema is a null type
pub fn is_null_schema(schema: &Value) -> bool {
// Check for {"type": "null"}
schema
.get("type")
.is_some_and(|type_val| type_val == "null")
}
/// Check if a type array includes null: ["string", "null"]
/// Returns Some(non_null_type) if it's a nullable type array
pub fn detect_nullable_type_array(schema: &Value) -> Option<String> {
let type_val = schema.get("type")?;
let type_array = type_val.as_array()?;
if type_array.len() != 2 {
return None;
}
let mut has_null = false;
let mut other_type = None;
for t in type_array {
if let Some(t_str) = t.as_str() {
if t_str == "null" {
has_null = true;
} else {
other_type = Some(t_str.to_string());
}
}
}
if has_null { other_type } else { None }
}
/// Detect enum pattern from oneOf with const variants
/// Returns Some(variants) if all variants are const strings
pub fn detect_const_enum(schema: &Value) -> Option<Vec<String>> {
let one_of = schema.get("oneOf")?.as_array()?;
let mut variants = Vec::new();
for variant in one_of {
// Check for {"const": "value"}
if let Some(const_val) = variant.get("const")
&& let Some(s) = const_val.as_str()
{
variants.push(s.to_string());
continue;
}
// If any variant is not a const string, this isn't a simple enum
return None;
}
if variants.is_empty() {
None
} else {
Some(variants)
}
}
/// Detect simple enum from "enum" array
pub fn detect_simple_enum(schema: &Value) -> Option<Vec<String>> {
let enum_val = schema.get("enum")?.as_array()?;
let variants: Vec<String> = enum_val
.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect();
if variants.len() == enum_val.len() && !variants.is_empty() {
Some(variants)
} else {
None
}
}
/// Get the primary type from a schema
pub fn get_schema_type(schema: &Value) -> Option<&str> {
schema.get("type")?.as_str()
}
/// Get the description from a schema
pub fn get_description(schema: &Value) -> Option<&str> {
schema.get("description")?.as_str()
}
/// Get the default value from a schema
pub fn get_default(schema: &Value) -> Option<&Value> {
schema.get("default")
}
/// Check if schema has a $ref
pub fn get_ref(schema: &Value) -> Option<&str> {
schema.get("$ref")?.as_str()
}
/// Get properties from an object schema
pub fn get_properties(schema: &Value) -> Option<&serde_json::Map<String, Value>> {
schema.get("properties")?.as_object()
}
/// Get the items schema for an array
pub fn get_array_items(schema: &Value) -> Option<&Value> {
schema.get("items")
}
/// Get the prefixItems for a tuple array schema
/// Returns the first item type (for homogeneous tuples like [int, int])
pub fn get_prefix_items_type(schema: &Value) -> Option<&Value> {
let prefix_items = schema.get("prefixItems")?.as_array()?;
// Return the first item's schema - for homogeneous tuples this represents all items
prefix_items.first()
}
/// Get additionalProperties schema
pub fn get_additional_properties(schema: &Value) -> Option<&Value> {
let ap = schema.get("additionalProperties")?;
// additionalProperties can be a boolean or a schema
if ap.is_boolean() { None } else { Some(ap) }
}
/// Get patternProperties schemas (returns first one for simplicity)
pub fn get_pattern_properties(schema: &Value) -> Option<&Value> {
let pp = schema.get("patternProperties")?.as_object()?;
// Return the first pattern's schema
pp.values().next()
}
/// Detect externally tagged union pattern (oneOf with single-property object variants)
/// This is the Serde default representation for Rust enums with data.
/// Example: `oneOf: [{ "Komorebi": {...} }, { "Battery": {...} }]`
/// Returns Some(vec of (tag_name, inner_schema)) if detected
///
/// IMPORTANT: Each variant must have a DIFFERENT tag name. If all variants have the same
/// property name (like "kind"), this is an internally-tagged union, not externally-tagged.
pub fn detect_externally_tagged_union(schema: &Value) -> Option<Vec<(String, Value)>> {
let one_of = schema.get("oneOf")?.as_array()?;
// Need at least 2 variants for a tagged union
if one_of.len() < 2 {
return None;
}
let mut variants = Vec::new();
for variant in one_of {
// Check if this variant is an object with exactly one required property
if let Some(props) = variant.get("properties").and_then(|p| p.as_object())
&& let Some(required) = variant.get("required").and_then(|r| r.as_array())
{
// Must have exactly one property and one required field
if required.len() == 1
&& props.len() == 1
&& let Some(tag) = required[0].as_str()
&& let Some(inner) = props.get(tag)
{
variants.push((tag.to_string(), inner.clone()));
continue;
}
}
// If any variant doesn't match the pattern, this isn't an externally tagged union
return None;
}
if variants.is_empty() {
return None;
}
// Check that all tag names are UNIQUE (externally tagged unions have different keys)
// If all variants have the same key, this is an internally-tagged union
let first_tag = &variants[0].0;
let all_same = variants.iter().all(|(tag, _)| tag == first_tag);
if all_same {
// All variants have the same property name - this is internally tagged, not externally
return None;
}
Some(variants)
}
/// Detect internally tagged union pattern (oneOf with shared discriminator field containing const)
/// Example: `oneOf: [{ "kind": "None" }, { "kind": "Bar", ...config }]`
/// Returns Some((discriminator_field, vec of (discriminator_value, variant_schema)))
pub fn detect_internally_tagged_union(schema: &Value) -> Option<(String, Vec<(String, Value)>)> {
let one_of = schema.get("oneOf")?.as_array()?;
if one_of.len() < 2 {
return None;
}
// Find common discriminator field with const values
let mut discriminator_field: Option<String> = None;
let mut variants = Vec::new();
for variant in one_of {
let props = variant.get("properties")?.as_object()?;
// Look for a property with a const value (the discriminator)
let mut found_discriminator = false;
for (key, prop_schema) in props {
if let Some(const_val) = prop_schema.get("const").and_then(|c| c.as_str()) {
if discriminator_field.is_none() {
discriminator_field = Some(key.clone());
}
if discriminator_field.as_ref() == Some(key) {
variants.push((const_val.to_string(), variant.clone()));
found_discriminator = true;
break;
}
}
}
if !found_discriminator {
return None;
}
}
let disc = discriminator_field?;
if variants.len() == one_of.len() {
Some((disc, variants))
} else {
None
}
}
/// Detect mixed enum + object union (oneOf with string consts AND tagged object variants)
/// Example: DateFormat with "MonthDateYear" (string) OR { "Custom": "..." } (object)
/// Returns Some((enum_variants, object_variants)) if detected
pub fn detect_mixed_enum_object_union(schema: &Value) -> Option<MixedUnionResult> {
let one_of = schema.get("oneOf")?.as_array()?;
let mut enum_variants = Vec::new();
let mut object_variants = Vec::new();
for variant in one_of {
// Check for string const
if variant.get("type").and_then(|t| t.as_str()) == Some("string") {
if let Some(const_val) = variant.get("const").and_then(|c| c.as_str()) {
enum_variants.push(const_val.to_string());
continue;
}
// Also handle enum arrays in string type
if let Some(enum_vals) = variant.get("enum").and_then(|e| e.as_array()) {
for v in enum_vals {
if let Some(s) = v.as_str() {
enum_variants.push(s.to_string());
}
}
continue;
}
}
// Check for object with single required property (externally tagged variant)
if let Some(props) = variant.get("properties").and_then(|p| p.as_object())
&& let Some(required) = variant.get("required").and_then(|r| r.as_array())
&& required.len() == 1
&& props.len() == 1
&& let Some(tag) = required[0].as_str()
&& let Some(inner) = props.get(tag)
{
object_variants.push((tag.to_string(), inner.clone()));
continue;
}
// Variant doesn't match either pattern - could still be valid if we have some of each
}
// Only return if we have BOTH enum variants AND object variants
if !enum_variants.is_empty() && !object_variants.is_empty() {
Some((enum_variants, object_variants))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_resolve_ref_name() {
assert_eq!(resolve_ref_name("#/$defs/MyType"), Some("MyType"));
assert_eq!(resolve_ref_name("#/definitions/OldType"), Some("OldType"));
assert_eq!(resolve_ref_name("invalid"), None);
}
#[test]
fn test_detect_nullable_anyof() {
let schema = json!({
"anyOf": [
{"$ref": "#/$defs/Color"},
{"type": "null"}
]
});
let inner = detect_nullable_anyof(&schema).unwrap();
assert_eq!(inner.get("$ref").unwrap(), "#/$defs/Color");
}
#[test]
fn test_detect_nullable_type_array() {
let schema = json!({
"type": ["string", "null"]
});
assert_eq!(
detect_nullable_type_array(&schema),
Some("string".to_string())
);
}
#[test]
fn test_detect_const_enum() {
let schema = json!({
"oneOf": [
{"const": "Left"},
{"const": "Right"},
{"const": "Center"}
]
});
let variants = detect_const_enum(&schema).unwrap();
assert_eq!(variants, vec!["Left", "Right", "Center"]);
}
#[test]
fn test_detect_simple_enum() {
let schema = json!({
"enum": ["Red", "Green", "Blue"]
});
let variants = detect_simple_enum(&schema).unwrap();
assert_eq!(variants, vec!["Red", "Green", "Blue"]);
}
#[test]
fn test_collect_definitions() {
let schema = json!({
"$defs": {
"Color": {"type": "string"},
"Size": {"type": "integer"}
}
});
let defs = collect_definitions(&schema);
assert_eq!(defs.len(), 2);
assert!(defs.contains_key("Color"));
assert!(defs.contains_key("Size"));
}
#[test]
fn test_detect_externally_tagged_union() {
// Pattern like WidgetConfig: { "Komorebi": {...} } | { "Battery": {...} }
let schema = json!({
"oneOf": [
{
"type": "object",
"properties": {
"Komorebi": {"$ref": "#/$defs/KomorebiConfig"}
},
"required": ["Komorebi"]
},
{
"type": "object",
"properties": {
"Battery": {"$ref": "#/$defs/BatteryConfig"}
},
"required": ["Battery"]
}
]
});
let variants = detect_externally_tagged_union(&schema).unwrap();
assert_eq!(variants.len(), 2);
assert_eq!(variants[0].0, "Komorebi");
assert_eq!(variants[1].0, "Battery");
}
#[test]
fn test_detect_externally_tagged_union_not_matching() {
// Not a tagged union - just const enums
let schema = json!({
"oneOf": [
{"type": "string", "const": "Left"},
{"type": "string", "const": "Right"}
]
});
assert!(detect_externally_tagged_union(&schema).is_none());
}
#[test]
fn test_detect_internally_tagged_union() {
// Pattern like Grouping: { "kind": "None" } | { "kind": "Bar", ...config }
let schema = json!({
"oneOf": [
{
"type": "object",
"properties": {
"kind": {"type": "string", "const": "None"}
},
"required": ["kind"]
},
{
"type": "object",
"properties": {
"kind": {"type": "string", "const": "Bar"},
"transparency": {"type": "number"}
},
"required": ["kind"]
}
]
});
let (disc, variants) = detect_internally_tagged_union(&schema).unwrap();
assert_eq!(disc, "kind");
assert_eq!(variants.len(), 2);
assert_eq!(variants[0].0, "None");
assert_eq!(variants[1].0, "Bar");
}
#[test]
fn test_detect_mixed_enum_object_union() {
// Pattern like DateFormat: "MonthDateYear" | { "Custom": "..." }
let schema = json!({
"oneOf": [
{"type": "string", "const": "MonthDateYear"},
{"type": "string", "const": "YearMonthDate"},
{
"type": "object",
"properties": {
"Custom": {"type": "string"}
},
"required": ["Custom"]
}
]
});
let (enums, objects) = detect_mixed_enum_object_union(&schema).unwrap();
assert_eq!(enums, vec!["MonthDateYear", "YearMonthDate"]);
assert_eq!(objects.len(), 1);
assert_eq!(objects[0].0, "Custom");
}
}
+332
View File
@@ -0,0 +1,332 @@
/// Represents a Nix type expression
#[derive(Debug, Clone, PartialEq)]
pub enum NixType {
/// lib.types.str
Str,
/// lib.types.int
Int,
/// lib.types.bool
Bool,
/// lib.types.float (actually lib.types.number in Nix)
Float,
/// lib.types.path
Path,
/// lib.types.nullOr <inner>
NullOr(Box<NixType>),
/// lib.types.listOf <inner>
ListOf(Box<NixType>),
/// lib.types.attrsOf <inner>
AttrsOf(Box<NixType>),
/// lib.types.enum [ "A" "B" ... ]
Enum(Vec<String>),
/// lib.types.oneOf [ ... ]
OneOf(Vec<NixType>),
/// lib.types.submodule { options = { ... }; }
Submodule(Vec<NixOption>),
/// Tagged union: submodule where each variant is an optional field
/// Generated from externally tagged unions like WidgetConfig
/// Each tuple is (tag_name, inner_type)
TaggedUnion(Vec<(String, NixType)>),
/// Reference to a named type defined in a let binding
TypeRef(String),
/// lib.types.anything - fallback for complex types
Anything,
/// Raw Nix expression for edge cases
Raw(String),
}
/// Represents a Nix option definition
#[derive(Debug, Clone, PartialEq)]
pub struct NixOption {
pub name: String,
pub nix_type: NixType,
pub description: Option<String>,
pub default: Option<String>,
pub example: Option<String>,
}
impl NixType {
/// Convert this type to a Nix expression string
pub fn to_nix_expr(&self) -> String {
match self {
NixType::Str => "lib.types.str".to_string(),
NixType::Int => "lib.types.int".to_string(),
NixType::Bool => "lib.types.bool".to_string(),
NixType::Float => "lib.types.number".to_string(),
NixType::Path => "lib.types.path".to_string(),
NixType::NullOr(inner) => {
format!("(lib.types.nullOr {})", inner.to_nix_expr())
}
NixType::ListOf(inner) => {
format!("(lib.types.listOf {})", inner.to_nix_expr())
}
NixType::AttrsOf(inner) => {
format!("(lib.types.attrsOf {})", inner.to_nix_expr())
}
NixType::Enum(variants) => {
let variants_str: Vec<String> = variants
.iter()
.map(|v| format!("\"{}\"", escape_nix_string(v)))
.collect();
format!("(lib.types.enum [ {} ])", variants_str.join(" "))
}
NixType::OneOf(types) => {
let types_str: Vec<String> = types.iter().map(|t| t.to_nix_expr()).collect();
format!("(lib.types.oneOf [ {} ])", types_str.join(" "))
}
NixType::Submodule(options) => {
if options.is_empty() {
"(lib.types.attrsOf lib.types.anything)".to_string()
} else {
let opts: Vec<String> =
options.iter().map(|opt| opt.to_nix_option_def(2)).collect();
format!(
"(lib.types.submodule {{\n options = {{\n{}\n }};\n }})",
opts.join("\n")
)
}
}
NixType::TaggedUnion(variants) => {
// Generate submodule with each variant as nullOr option with default = null
// This transforms externally-tagged unions into a single submodule where
// users specify exactly one variant (the others remain null)
if variants.is_empty() {
"(lib.types.attrsOf lib.types.anything)".to_string()
} else {
let opts: Vec<String> = variants
.iter()
.map(|(tag, inner_type)| {
// Each variant becomes: Tag = lib.mkOption { type = lib.types.nullOr <inner>; default = null; };
let inner_expr = inner_type.to_nix_expr();
let tag_escaped = escape_nix_attr_name(tag);
format!(
" {} = lib.mkOption {{ type = (lib.types.nullOr {}); default = null; }};",
tag_escaped,
inner_expr
)
})
.collect();
format!(
"(lib.types.submodule {{\n options = {{\n{}\n }};\n }})",
opts.join("\n")
)
}
}
NixType::TypeRef(name) => name.clone(),
NixType::Anything => "lib.types.anything".to_string(),
NixType::Raw(expr) => expr.clone(),
}
}
/// Check if this type is nullable (NullOr)
pub fn is_nullable(&self) -> bool {
matches!(self, NixType::NullOr(_))
}
/// Wrap this type in NullOr if not already nullable
pub fn make_nullable(self) -> NixType {
if self.is_nullable() {
self
} else {
NixType::NullOr(Box::new(self))
}
}
}
impl NixOption {
/// Create a new NixOption
pub fn new(name: impl Into<String>, nix_type: NixType) -> Self {
Self {
name: name.into(),
nix_type,
description: None,
default: None,
example: None,
}
}
/// Set the description
pub fn with_description(mut self, desc: impl Into<String>) -> Self {
self.description = Some(desc.into());
self
}
/// Set the default value
pub fn with_default(mut self, default: impl Into<String>) -> Self {
self.default = Some(default.into());
self
}
/// Generate the Nix option definition code
pub fn to_nix_option_def(&self, indent_level: usize) -> String {
let indent = " ".repeat(indent_level);
let inner_indent = " ".repeat(indent_level + 1);
let mut parts = vec![format!(
"{}type = {};",
inner_indent,
self.nix_type.to_nix_expr()
)];
// Add default if present, otherwise use null for nullable types
if let Some(ref default) = self.default {
parts.push(format!("{}default = {};", inner_indent, default));
} else if self.nix_type.is_nullable() {
parts.push(format!("{}default = null;", inner_indent));
}
// Add description if present
if let Some(ref desc) = self.description {
parts.push(format!(
"{}description = \"{}\";",
inner_indent,
escape_nix_string(desc)
));
}
format!(
"{}{} = lib.mkOption {{\n{}\n{}}};",
indent,
escape_nix_attr_name(&self.name),
parts.join("\n"),
indent
)
}
}
/// Escape a string for use in Nix string literals
pub fn escape_nix_string(s: &str) -> String {
s.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\t', "\\t")
.replace("${", "\\${")
}
/// Escape an attribute name if it contains special characters
pub fn escape_nix_attr_name(name: &str) -> String {
// Nix attribute names that contain hyphens or start with numbers need quoting
if name.chars().all(|c| c.is_alphanumeric() || c == '_')
&& name.chars().next().is_some_and(|c| !c.is_ascii_digit())
{
name.to_string()
} else {
format!("\"{}\"", escape_nix_string(name))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_primitive_types() {
assert_eq!(NixType::Str.to_nix_expr(), "lib.types.str");
assert_eq!(NixType::Int.to_nix_expr(), "lib.types.int");
assert_eq!(NixType::Bool.to_nix_expr(), "lib.types.bool");
assert_eq!(NixType::Float.to_nix_expr(), "lib.types.number");
}
#[test]
fn test_nullable_type() {
let nullable_str = NixType::NullOr(Box::new(NixType::Str));
assert_eq!(
nullable_str.to_nix_expr(),
"(lib.types.nullOr lib.types.str)"
);
}
#[test]
fn test_list_type() {
let list_of_int = NixType::ListOf(Box::new(NixType::Int));
assert_eq!(
list_of_int.to_nix_expr(),
"(lib.types.listOf lib.types.int)"
);
}
#[test]
fn test_attrs_type() {
let attrs_of_str = NixType::AttrsOf(Box::new(NixType::Str));
assert_eq!(
attrs_of_str.to_nix_expr(),
"(lib.types.attrsOf lib.types.str)"
);
}
#[test]
fn test_enum_type() {
let enum_type = NixType::Enum(vec!["Left".to_string(), "Right".to_string()]);
assert_eq!(
enum_type.to_nix_expr(),
"(lib.types.enum [ \"Left\" \"Right\" ])"
);
}
#[test]
fn test_escape_nix_string() {
assert_eq!(escape_nix_string("hello"), "hello");
assert_eq!(escape_nix_string("line1\nline2"), "line1\\nline2");
assert_eq!(escape_nix_string("say \"hi\""), "say \\\"hi\\\"");
assert_eq!(escape_nix_string("${var}"), "\\${var}");
}
#[test]
fn test_escape_attr_name() {
assert_eq!(escape_nix_attr_name("foo"), "foo");
assert_eq!(escape_nix_attr_name("foo_bar"), "foo_bar");
assert_eq!(escape_nix_attr_name("foo-bar"), "\"foo-bar\"");
assert_eq!(escape_nix_attr_name("123start"), "\"123start\"");
}
#[test]
fn test_make_nullable() {
let str_type = NixType::Str;
let nullable = str_type.make_nullable();
assert!(nullable.is_nullable());
assert_eq!(nullable.to_nix_expr(), "(lib.types.nullOr lib.types.str)");
// Already nullable should not double-wrap
let already_nullable = NixType::NullOr(Box::new(NixType::Int));
let still_nullable = already_nullable.clone().make_nullable();
assert_eq!(still_nullable, already_nullable);
}
#[test]
fn test_tagged_union_type() {
let tagged = NixType::TaggedUnion(vec![
("Komorebi".to_string(), NixType::Str),
("Battery".to_string(), NixType::Int),
]);
let expr = tagged.to_nix_expr();
// Should produce a submodule with optional fields
assert!(expr.contains("lib.types.submodule"));
assert!(expr.contains("Komorebi = lib.mkOption"));
assert!(expr.contains("Battery = lib.mkOption"));
assert!(expr.contains("lib.types.nullOr lib.types.str"));
assert!(expr.contains("lib.types.nullOr lib.types.int"));
assert!(expr.contains("default = null"));
}
#[test]
fn test_tagged_union_empty() {
let tagged = NixType::TaggedUnion(vec![]);
assert_eq!(
tagged.to_nix_expr(),
"(lib.types.attrsOf lib.types.anything)"
);
}
#[test]
fn test_tagged_union_with_submodule() {
// Test that tagged union can contain submodule types
let inner_submodule = NixType::Submodule(vec![NixOption::new("enable", NixType::Bool)]);
let tagged = NixType::TaggedUnion(vec![("Widget".to_string(), inner_submodule)]);
let expr = tagged.to_nix_expr();
assert!(expr.contains("Widget = lib.mkOption"));
assert!(expr.contains("lib.types.nullOr"));
assert!(expr.contains("lib.types.submodule"));
}
}
+137
View File
@@ -0,0 +1,137 @@
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
flake-parts.url = "github:hercules-ci/flake-parts";
crane.url = "github:ipetkov/crane";
rust-overlay.url = "github:oxalica/rust-overlay";
rust-overlay.inputs.nixpkgs.follows = "nixpkgs";
treefmt-nix.url = "github:numtide/treefmt-nix";
treefmt-nix.inputs.nixpkgs.follows = "nixpkgs";
git-hooks-nix.url = "github:cachix/git-hooks.nix";
git-hooks-nix.inputs.nixpkgs.follows = "nixpkgs";
};
outputs =
inputs@{
nixpkgs,
flake-parts,
crane,
rust-overlay,
...
}:
flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.treefmt-nix.flakeModule
inputs.git-hooks-nix.flakeModule
];
systems = [
"x86_64-linux"
"aarch64-linux"
"aarch64-darwin"
];
perSystem =
{
config,
system,
...
}:
let
pkgs = import nixpkgs {
inherit system;
overlays = [ rust-overlay.overlays.default ];
};
rustToolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml;
nightlyRustfmt = pkgs.rust-bin.nightly.latest.rustfmt;
rustToolchainWithNightlyRustfmt = pkgs.symlinkJoin {
name = "rust-toolchain-with-nightly-rustfmt";
paths = [
nightlyRustfmt
rustToolchain
];
};
nightlyToolchain = pkgs.rust-bin.nightly.latest.default;
cargo-udeps = pkgs.writeShellScriptBin "cargo-udeps" ''
export PATH="${nightlyToolchain}/bin:$PATH"
exec ${pkgs.cargo-udeps}/bin/cargo-udeps "$@"
'';
craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;
src = pkgs.lib.cleanSourceWith {
src = ./.;
filter = craneLib.filterCargoSources;
};
commonArgs = {
inherit src;
strictDeps = true;
};
cargoArtifacts = craneLib.buildDepsOnly commonArgs;
schemars-nixgen = craneLib.buildPackage (
commonArgs
// {
inherit cargoArtifacts;
}
);
in
{
checks = {
clippy = craneLib.cargoClippy (
commonArgs
// {
inherit cargoArtifacts;
}
);
tests = craneLib.cargoTest (
commonArgs
// {
inherit cargoArtifacts;
}
);
};
packages = {
inherit schemars-nixgen;
default = schemars-nixgen;
};
devShells.default = pkgs.mkShell {
inputsFrom = [ schemars-nixgen ];
packages = [
rustToolchainWithNightlyRustfmt
cargo-udeps
pkgs.cargo-outdated
pkgs.bacon
];
};
pre-commit = {
check.enable = true;
settings.hooks.treefmt = {
enable = true;
package = config.treefmt.build.wrapper;
pass_filenames = false;
};
};
treefmt = {
projectRootFile = "flake.nix";
programs = {
rustfmt = {
enable = true;
package = nightlyRustfmt;
};
taplo.enable = true;
nixfmt.enable = true;
deadnix.enable = true;
};
};
};
};
}