nix-mod-to-go
Tool to parse and generate Go struct definitions from Nix modules.
Usage
# Print help message
nixmod2go --help
# Generate Go code to stdout for module.nix
nixmod2go -f go module.nix
For more information, see the help message and the below example.
Example
Quick Start
Given a very simple Nix module module.nix:
{ lib, ... }: {
options.services.xyz = {
enable = lib.mkEnableOption "XYZ service";
host = lib.mkOption {
type = lib.types.str;
default = "127.0.0.1";
description = "Host to listen on.";
};
port = lib.mkOption {
type = lib.types.int;
default = 8080;
description = "Port to listen on.";
};
};
}
Running nixmod2go -f go -O services.xyz module.nix will output the following Go code:
// Code generated by nixmod2go. DO NOT EDIT.
package main
// Config is the struct type for `config`.
type Config struct {
// Enable: whether to enable XYZ service.
Enable bool `json:"enable"`
// Host: host to listen on.
Host string `json:"host"`
// Port: port to listen on.
Port int `json:"port"`
}
Complete Example
example/module.nix contains an example Nix module that
contains a lot of different option types. Using this file, 2 more files are
generated:
- module.gen.json contains the
generated JSON representation of the module.
- module.gen.go contains the
generated Go structs code that the module config can be unmarshalled into.
module_test.go ensures that the generated Go
types can be properly unmarshaled onto and marshaled from.
The command to generate these files is listed below in the
update-example section.
Tasks
This README file can be executed using xc.
update-example
Update the generated example files.
go run . -f json ./example/module.nix ./example/module.gen.json
go run . -f go --go-package example ./example/module.nix ./example/module.gen.go
go test ./example