feat(tvix/serde): add an example application to the project
This shows how people can use tvix_serde to deserialise configuration structs for their programs from Nix code. Change-Id: I71bf4e03dce19dddafe67dd729b4e4b10719a739 Reviewed-on: https://cl.tvl.fyi/c/depot/+/7945 Reviewed-by: flokli <flokli@flokli.de> Tested-by: BuildkiteCI
This commit is contained in:
parent
7702941dd9
commit
4da1e64c03
3 changed files with 57 additions and 0 deletions
1
tvix/serde/.skip-subtree
Normal file
1
tvix/serde/.skip-subtree
Normal file
|
@ -0,0 +1 @@
|
|||
The foods.nix can not be read by readTree.
|
34
tvix/serde/examples/cfg-demo.rs
Normal file
34
tvix/serde/examples/cfg-demo.rs
Normal file
|
@ -0,0 +1,34 @@
|
|||
//! This program demonstrates how to use tvix_serde to deserialise
|
||||
//! program configuration (or other data) from Nix code.
|
||||
//!
|
||||
//! This makes it possible to use Nix as an embedded config language.
|
||||
//! For greater control over evaluation, and for features like adding
|
||||
//! additional builtins, depending directly on tvix_eval would be
|
||||
//! required.
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
enum Flavour {
|
||||
Tasty,
|
||||
Okay,
|
||||
Eww,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Data {
|
||||
name: String,
|
||||
foods: HashMap<String, Flavour>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Get the content from wherever, read it from a file, receive it
|
||||
// over the network - whatever floats your boat! We'll include it
|
||||
// as a string.
|
||||
let code = include_str!("foods.nix");
|
||||
|
||||
// Now you can use tvix_serde to deserialise the struct:
|
||||
let foods: Data = tvix_serde::from_str(code).expect("deserialisation should succeed");
|
||||
|
||||
println!("These are the foods:\n{:#?}", foods);
|
||||
}
|
22
tvix/serde/examples/foods.nix
Normal file
22
tvix/serde/examples/foods.nix
Normal file
|
@ -0,0 +1,22 @@
|
|||
# This is content for the `Data` struct, written in intentionally
|
||||
# convoluted Nix code.
|
||||
let
|
||||
mkFlavour = flavour: name: {
|
||||
inherit name;
|
||||
value = flavour;
|
||||
};
|
||||
|
||||
tasty = mkFlavour "Tasty";
|
||||
okay = mkFlavour "Okay";
|
||||
eww = mkFlavour "Eww";
|
||||
in
|
||||
{
|
||||
name = "exhaustive list of foods";
|
||||
|
||||
foods = builtins.listToAttrs [
|
||||
(tasty "beef")
|
||||
(okay "tomatoes")
|
||||
(eww "olives")
|
||||
(tasty "coffee")
|
||||
];
|
||||
}
|
Loading…
Reference in a new issue