Convert Figma logo to code with AI

google logogo-jsonnet

No description available

1,600
230
1,600
152

Top Related Projects

Starlark in Go: the Starlark configuration language, implemented in Go

5,227

HCL is the HashiCorp configuration language.

16,259

Simple and flexible tool for managing secrets

Quick Overview

Google's go-jsonnet is a Go implementation of the Jsonnet data templating language. It provides a library and command-line tools for parsing, evaluating, and formatting Jsonnet code, allowing users to generate complex JSON or YAML configurations from simpler, more maintainable Jsonnet templates.

Pros

  • Native Go implementation, offering better performance and easier integration with Go projects
  • Supports both library usage and command-line tools for flexibility
  • Maintains compatibility with the original C++ implementation of Jsonnet
  • Actively maintained and supported by Google

Cons

  • Learning curve for those unfamiliar with Jsonnet language syntax
  • May introduce additional complexity for simple configuration tasks
  • Limited ecosystem compared to more established templating languages
  • Potential for increased build times in large projects due to template evaluation

Code Examples

  1. Basic Jsonnet evaluation:
import "github.com/google/go-jsonnet"

jsonnetCode := `{
    person: {
        name: "Alice",
        age: 30,
    },
    greeting: "Hello " + self.person.name + "!",
}`

vm := jsonnet.MakeVM()
result, err := vm.EvaluateSnippet("example.jsonnet", jsonnetCode)
if err != nil {
    // Handle error
}
fmt.Println(result)
  1. Using external variables:
vm := jsonnet.MakeVM()
vm.ExtVar("color", "blue")

jsonnetCode := `{
    favorite_color: std.extVar("color"),
}`

result, err := vm.EvaluateSnippet("example.jsonnet", jsonnetCode)
if err != nil {
    // Handle error
}
fmt.Println(result)
  1. Importing and using Jsonnet libraries:
vm := jsonnet.MakeVM()
vm.Importer(&jsonnet.FileImporter{
    JPaths: []string{"path/to/jsonnet/libs"},
})

jsonnetCode := `
local mylib = import "mylib.libsonnet";
{
    result: mylib.someFunction(42),
}`

result, err := vm.EvaluateSnippet("example.jsonnet", jsonnetCode)
if err != nil {
    // Handle error
}
fmt.Println(result)

Getting Started

To use go-jsonnet in your Go project:

  1. Install the library:

    go get github.com/google/go-jsonnet
    
  2. Import the library in your Go code:

    import "github.com/google/go-jsonnet"
    
  3. Create a Jsonnet VM and evaluate a snippet:

    vm := jsonnet.MakeVM()
    result, err := vm.EvaluateSnippet("example.jsonnet", `{message: "Hello, Jsonnet!"}`)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result)
    

This will output the evaluated JSON: {"message": "Hello, Jsonnet!"}

Competitor Comparisons

Starlark in Go: the Starlark configuration language, implemented in Go

Pros of Starlark-go

  • More flexible and expressive language, supporting loops and conditionals
  • Better integration with Go programs, allowing for easier embedding
  • Designed for configuration and scripting tasks beyond just data templating

Cons of Starlark-go

  • Less focused on JSON output, which may require additional processing
  • Steeper learning curve for users familiar with JSON-like syntax
  • Potentially slower execution compared to Jsonnet's specialized JSON handling

Code Comparison

Starlark-go:

def greet(name):
    return "Hello, " + name + "!"

result = greet("World")

Jsonnet:

{
  greet(name):: "Hello, " + name + "!",
  result: self.greet("World")
}

Summary

Starlark-go offers a more versatile scripting language suitable for various configuration tasks, while Jsonnet focuses specifically on JSON templating. Starlark-go provides better integration with Go programs but may require more effort for JSON output. Jsonnet excels in JSON-specific tasks but has limited expressiveness compared to Starlark-go. The choice between the two depends on the specific requirements of the project, with Starlark-go being more suitable for complex configuration scenarios and Jsonnet for straightforward JSON templating.

5,227

HCL is the HashiCorp configuration language.

Pros of HCL

  • More human-readable syntax, designed for configuration files
  • Native support for complex data structures like maps and lists
  • Integrated with HashiCorp ecosystem (Terraform, Vault, etc.)

Cons of HCL

  • Less flexible for general-purpose data manipulation
  • Limited built-in functions compared to Jsonnet
  • Steeper learning curve for users unfamiliar with HashiCorp tools

Code Comparison

HCL:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "ExampleInstance"
  }
}

Jsonnet:

{
  resource: {
    aws_instance: {
      example: {
        ami: "ami-0c55b159cbfafe1f0",
        instance_type: "t2.micro",
        tags: {
          Name: "ExampleInstance",
        },
      },
    },
  },
}

Both HCL and go-jsonnet serve different purposes. HCL is primarily designed for configuration files, especially within the HashiCorp ecosystem, while go-jsonnet is a more general-purpose data templating language. HCL offers a more readable syntax for configuration, while go-jsonnet provides greater flexibility for complex data transformations and manipulations.

16,259

Simple and flexible tool for managing secrets

Pros of sops

  • Focuses on secure encryption of configuration files, supporting multiple formats (YAML, JSON, ENV, INI)
  • Integrates with various key management services (AWS KMS, GCP KMS, Azure Key Vault)
  • Provides fine-grained access control and key rotation capabilities

Cons of sops

  • Limited to encryption/decryption operations, not a general-purpose configuration language
  • Requires additional setup and key management infrastructure
  • May introduce complexity for simple configuration scenarios

Code comparison

sops:

myapp:
    db_password: ENC[AES256_GCM,data:...] # Encrypted value

go-jsonnet:

{
  myapp: {
    db_password: std.extVar('DB_PASSWORD')
  }
}

Summary

sops is specialized for secure configuration management, offering robust encryption features and integration with cloud key management services. go-jsonnet, on the other hand, is a data templating language that provides powerful configuration generation capabilities but lacks built-in encryption features. The choice between them depends on specific security requirements and the complexity of configuration needs in a project.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

go-jsonnet

GoDoc Widget Travis Widget Coverage Status Widget

This an implementation of Jsonnet in pure Go. It is a feature complete, production-ready implementation. It is compatible with the original Jsonnet C++ implementation. Bindings to C and Python are available (but not battle-tested yet).

This code is known to work on Go 1.12 and above. We recommend always using the newest stable release of Go.

Installation instructions

# Using `go get` to install binaries is deprecated.
# The version suffix is mandatory.
go install github.com/google/go-jsonnet/cmd/jsonnet@latest

# Or other tools in the 'cmd' directory
go install github.com/google/go-jsonnet/cmd/jsonnet-lint@latest

It's also available on Homebrew:

brew install go-jsonnet

jsonnetfmt and jsonnet-lint are also available as pre-commit hooks. Example .pre-commit-config.yaml:

- repo: https://github.com/google/go-jsonnet
  rev: # ref you want to point at, e.g. v0.17.0
  hooks:
    - id: jsonnet-format
    - id: jsonnet-lint

It can also be embedded in your own Go programs as a library:

package main

import (
	"fmt"
	"log"

	"github.com/google/go-jsonnet"
)

func main() {
	vm := jsonnet.MakeVM()

	snippet := `{
		person1: {
		    name: "Alice",
		    welcome: "Hello " + self.name + "!",
		},
		person2: self.person1 { name: "Bob" },
	}`

	jsonStr, err := vm.EvaluateAnonymousSnippet("example1.jsonnet", snippet)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(jsonStr)
	/*
	   {
	     "person1": {
	         "name": "Alice",
	         "welcome": "Hello Alice!"
	     },
	     "person2": {
	         "name": "Bob",
	         "welcome": "Hello Bob!"
	     }
	   }
	*/
}

Build instructions (go 1.12+)

git clone git@github.com:google/go-jsonnet.git
cd go-jsonnet
go build ./cmd/jsonnet
go build ./cmd/jsonnetfmt
go build ./cmd/jsonnet-deps

To build with Bazel instead:

git clone git@github.com:google/go-jsonnet.git
cd go-jsonnet
git submodule init
git submodule update
bazel build //cmd/jsonnet
bazel build //cmd/jsonnetfmt
bazel build //cmd/jsonnet-deps

The resulting jsonnet program will then be available at a platform-specific path, such as bazel-bin/cmd/jsonnet/darwin_amd64_stripped/jsonnet for macOS.

Bazel also accommodates cross-compiling the program. To build the jsonnet program for various popular platforms, run the following commands:

Target platformBuild command
Current hostbazel build //cmd/jsonnet
Linuxbazel build --platforms=@io_bazel_rules_go//go/toolchain:linux_amd64 //cmd/jsonnet
macOSbazel build --platforms=@io_bazel_rules_go//go/toolchain:darwin_amd64 //cmd/jsonnet
Windowsbazel build --platforms=@io_bazel_rules_go//go/toolchain:windows_amd64 //cmd/jsonnet

For additional target platform names, see the per-Go release definitions here in the rules_go Bazel package.

Additionally if any files were moved around, see the section Keeping the Bazel files up to date.

Building libjsonnet.wasm

GOOS=js GOARCH=wasm go build -o libjsonnet.wasm ./cmd/wasm 

Or if using bazel:

bazel build //cmd/wasm:libjsonnet.wasm

Running tests

./tests.sh  # Also runs `go test ./...`

Running Benchmarks

Method 1

go get golang.org/x/tools/cmd/benchcmp
  1. Make sure you build a jsonnet binary prior to making changes.
go build -o jsonnet-old ./cmd/jsonnet
  1. Make changes (iterate as needed), and rebuild new binary
go build ./cmd/jsonnet
  1. Run benchmark:
# e.g. ./benchmark.sh Builtin
./benchmark.sh <TestNameFilter>

Method 2

  1. get benchcmp
go get golang.org/x/tools/cmd/benchcmp
  1. Make sure you build a jsonnet binary prior to making changes.
make build-old
  1. iterate with (which will also automatically rebuild the new binary ./jsonnet)

replace the FILTER with the name of the test you are working on

FILTER=Builtin_manifestJsonEx make benchmark

Update cpp-jsonnet sub-repo

This repo depends on the original Jsonnet repo. Shared parts include the standard library, headers files for C API and some tests.

You can update the submodule and regenerate dependent files with one command:

./update_cpp_jsonnet.sh

Note: It needs to be run from repo root.

Updating and modifying the standard library

Standard library source code is kept in cpp-jsonnet submodule, because it is shared with Jsonnet C++ implementation.

For performance reasons we perform preprocessing on the standard library, so for the changes to be visible, regeneration is necessary:

go run cmd/dumpstdlibast/dumpstdlibast.go cpp-jsonnet/stdlib/std.jsonnet > astgen/stdast.go

**The

The above command creates the astgen/stdast.go file which puts the desugared standard library into the right data structures, which lets us avoid the parsing overhead during execution. Note that this step is not necessary to perform manually when building with Bazel; the Bazel target regenerates the astgen/stdast.go (writing it into Bazel's build sandbox directory tree) file when necessary.

Keeping the Bazel files up to date

Note that we maintain the Go-related Bazel targets with the Gazelle tool. The Go module (go.mod in the root directory) remains the primary source of truth. Gazelle analyzes both that file and the rest of the Go files in the repository to create and adjust appropriate Bazel targets for building Go packages and executable programs.

After changing any dependencies within the files covered by this Go module, it is helpful to run go mod tidy to ensure that the module declarations match the state of the Go source code. In order to synchronize the Bazel rules with material changes to the Go module, run the following command to invoke Gazelle's update-repos command:

bazel run //:gazelle -- update-repos -from_file=go.mod -to_macro=bazel/deps.bzl%jsonnet_go_dependencies

Similarly, after adding or removing Go source files, it may be necessary to synchronize the Bazel rules by running the following command:

bazel run //:gazelle