Skip to content

Commit

Permalink
pkgs-lib.formats: add mkStructuredType
Browse files Browse the repository at this point in the history
  • Loading branch information
Stunkymonkey committed Jan 8, 2025
1 parent bff640b commit c817d7f
Showing 1 changed file with 21 additions and 34 deletions.
55 changes: 21 additions & 34 deletions pkgs/pkgs-lib/formats.nix
Original file line number Diff line number Diff line change
Expand Up @@ -49,35 +49,49 @@ rec {
inherit (lib.types) nullOr oneOf coercedTo listOf nonEmptyListOf attrsOf either;
inherit (lib.types) bool int float str path;

json = {}: {
/* Creates a structured value type suitable for serialization formats.
type = let
valueType = nullOr (oneOf [
Parameters:
- typeName: String describing the format (e.g. "JSON", "YAML", "XML")
Returns a type suitable for structured data formats that supports:
- Basic types: boolean, integer, float, string, path
- Complex types: attribute sets and lists
*/
mkStructuredType = { typeName }: let
baseType = oneOf [
bool
int
float
str
path
(attrsOf valueType)
(listOf valueType)
]) // {
description = "JSON value";
];
valueType = (nullOr baseType) // {
description = "${typeName} value";
};
in valueType;

json = {}: {

type = mkStructuredType { typeName = "JSON"; };

generate = name: value: pkgs.callPackage ({ runCommand, jq }: runCommand name {
nativeBuildInputs = [ jq ];
value = builtins.toJSON value;
passAsFile = [ "value" ];
preferLocalBuild = true;
} ''
jq . "$valuePath"> $out
jq . "$valuePath" > $out
'') {};

};

yaml = {}: {

type = mkStructuredType { typeName = "YAML"; };

generate = name: value: pkgs.callPackage ({ runCommand, remarshal }: runCommand name {
nativeBuildInputs = [ remarshal ];
value = builtins.toJSON value;
Expand All @@ -86,21 +100,6 @@ rec {
} ''
json2yaml "$valuePath" "$out"
'') {};

type = let
valueType = nullOr (oneOf [
bool
int
float
str
path
(attrsOf valueType)
(listOf valueType)
]) // {
description = "YAML value";
};
in valueType;

};

# the ini formats share a lot of code
Expand Down Expand Up @@ -484,19 +483,7 @@ rec {
# Outputs a succession of Python variable assignments
# Useful for many Django-based services
pythonVars = {}: {
type = let
valueType = nullOr(oneOf [
bool
float
int
path
str
(attrsOf valueType)
(listOf valueType)
]) // {
description = "Python value";
};
in attrsOf valueType;
type = attrsOf (mkStructuredType { typeName = "Python"; });
generate = name: value: pkgs.callPackage ({ runCommand, python3, black }: runCommand name {
nativeBuildInputs = [ python3 black ];
value = builtins.toJSON value;
Expand Down

0 comments on commit c817d7f

Please sign in to comment.