jsonnet

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2025 License: Apache-2.0 Imports: 31 Imported by: 0

README

jsonnet-tracer

This is a fork of http://github.com/google/go-jsonnet. In this fork I've added a command, jsonnet-trace, that helps to trace each property in the built JSON outcome back to its original input file location.

Installation

$ go install github.com/y1hao/go-jsonnet/cmd/jsonnet-trace@latest

Usage

$ jsonnet-trace <root_file.jsonnet>

For example

$ jsonnet-trace examples/bazel/testdata/demo/sours-oo.jsonnet

will build the sours-oo.jsonnet file (including its imports with relative paths), and will show the outcome json content as the following:

The original source file and line number where the property in the highlighted line is set or last modified is displayed on the top.

Documentation

Overview

Package jsonnet implements a parser and evaluator for jsonnet.

Jsonnet is a domain specific configuration language that helps you define JSON data. Jsonnet lets you compute fragments of JSON within the structure, bringing the same benefit to structured data that templating languages bring to plain text.

See http://jsonnet.org/ for a full language description and tutorial.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SnippetToAST

func SnippetToAST(filename string, snippet string) (ast.Node, error)

SnippetToAST parses a snippet and returns the resulting AST.

func Version

func Version() string

Version returns the Jsonnet version number.

Types

type ColorFormatter

type ColorFormatter func(w io.Writer, f string, a ...interface{}) (n int, err error)

ColorFormatter represents a function that writes to the terminal using color.

type Contents

type Contents struct {
	// contains filtered or unexported fields
}

Contents is a representation of imported data. It is a simple byte wrapper, which makes it easier to enforce the caching policy.

func MakeContents

func MakeContents(s string) Contents

MakeContents creates Contents from a string.

func MakeContentsRaw

func MakeContentsRaw(bytes []byte) Contents

MakeContentsRaw creates Contents from (possibly non-utf8) []byte data.

func (Contents) Data

func (c Contents) Data() []byte

Data returns content bytes

func (Contents) String

func (c Contents) String() string

type DebugEvent

type DebugEvent interface {
	// contains filtered or unexported methods
}

A DebugEvent is emitted by the hooks to signal certain events happening in the VM. Examples are: - Hitting a breakpoint - Catching an exception - Program termination

type DebugEventExit

type DebugEventExit struct {
	Output string
	Error  error
}

type DebugEventStop

type DebugEventStop struct {
	Reason         DebugStopReason
	Breakpoint     string
	Current        ast.Node
	LastEvaluation *string
	Error          error
	// contains filtered or unexported fields
}

func (*DebugEventStop) ErrorFmt

func (d *DebugEventStop) ErrorFmt() string

type DebugStopReason

type DebugStopReason int
const (
	StopReasonStep DebugStopReason = iota
	StopReasonBreakpoint
	StopReasonException
)

type Debugger

type Debugger struct {
	// contains filtered or unexported fields
}

func MakeDebugger

func MakeDebugger() *Debugger

func (*Debugger) ActiveBreakpoints

func (d *Debugger) ActiveBreakpoints() []string

func (*Debugger) BreakpointLocations

func (d *Debugger) BreakpointLocations(file string) ([]*ast.LocationRange, error)

func (*Debugger) ClearBreakpoints

func (d *Debugger) ClearBreakpoints(file string)

func (*Debugger) Continue

func (d *Debugger) Continue()

func (*Debugger) ContinueUntilAfter

func (d *Debugger) ContinueUntilAfter(n ast.Node)

func (*Debugger) Events

func (d *Debugger) Events() chan DebugEvent

func (*Debugger) Launch

func (d *Debugger) Launch(filename, snippet string, jpaths []string)

func (*Debugger) ListVars

func (d *Debugger) ListVars() []ast.Identifier

func (*Debugger) LookupValue

func (d *Debugger) LookupValue(val string) (string, error)

func (*Debugger) SetBreakpoint

func (d *Debugger) SetBreakpoint(file string, line int, column int) (string, error)

func (*Debugger) StackTrace

func (d *Debugger) StackTrace() []TraceFrame

func (*Debugger) Step

func (d *Debugger) Step()

func (*Debugger) Terminate

func (d *Debugger) Terminate()

type ErrorFormatter

type ErrorFormatter interface {
	// Format static, runtime, and unexpected errors prior to printing them.
	Format(err error) string

	// Set the the maximum length of stack trace before cropping.
	SetMaxStackTraceSize(size int)

	// Set the color formatter for the location color.
	SetColorFormatter(color ColorFormatter)
}

An ErrorFormatter formats errors with stacktraces and color.

type EvalHook

type EvalHook struct {
	// contains filtered or unexported fields
}

type FileImporter

type FileImporter struct {
	JPaths []string
	// contains filtered or unexported fields
}

FileImporter imports data from the filesystem.

func (*FileImporter) Import

func (importer *FileImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error)

Import imports file from the filesystem.

type Importer

type Importer interface {
	// Import fetches data from a given path. It may be relative
	// to the file where we do the import. What "relative path"
	// means depends on the importer.
	//
	// It is required that:
	// a) for given (importedFrom, importedPath) the same
	//    (contents, foundAt) are returned on subsequent calls.
	// b) for given foundAt, the contents are always the same
	//
	// It is recommended that if there are multiple locations that
	// need to be probed (e.g. relative + multiple library paths)
	// then all results of all attempts will be cached separately,
	// both nonexistence and contents of existing ones.
	// FileImporter may serve as an example.
	//
	// IMPORTANT: The passed importedFrom might be "" (an empty string).
	// It means that the import is coming from an ad-hoc snippet, e.g.
	// code passed on the command line, read from stdin or passed as
	// a snippet to execute. Importer may have a "default" path to use
	// in such case or it may only allow absolute imports from such
	// "anonymous locations".
	//
	// Importing the same file multiple times must be a cheap operation
	// and shouldn't involve copying the whole file - the same buffer
	// should be returned.
	Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error)
}

An Importer imports data from a path. TODO(sbarzowski) caching of errors (may require breaking changes)

type LineReader

type LineReader struct {
	// contains filtered or unexported fields
}

LineReader reads single lines.

func (*LineReader) Read

func (r *LineReader) Read() ([]byte, error)

Read returns a single line (with '\n' ended) from the underlying reader. An error is returned iff there is an error with the underlying reader.

type MemoryImporter

type MemoryImporter struct {
	Data map[string]Contents
}

MemoryImporter "imports" data from an in-memory map.

func (*MemoryImporter) Import

func (importer *MemoryImporter) Import(importedFrom, importedPath string) (contents Contents, foundAt string, err error)

Import fetches data from a map entry. All paths are treated as absolute keys.

type NativeFunction

type NativeFunction struct {
	Name   string
	Func   func([]interface{}) (interface{}, error)
	Params ast.Identifiers
}

NativeFunction represents a function implemented in Go.

type Reader

type Reader interface {
	Read() ([]byte, error)
}

Reader reads bytes

type RuntimeError

type RuntimeError struct {
	Msg        string
	StackTrace []TraceFrame
}

RuntimeError is an error discovered during evaluation of the program

func (RuntimeError) Error

func (err RuntimeError) Error() string

type TraceFrame

type TraceFrame struct {
	Name string
	Loc  ast.LocationRange
}

TraceFrame is tracing information about a single frame of the call stack. TODO(sbarzowski) the difference from traceElement. Do we even need this?

type TraceItem

type TraceItem struct {
	Filename  string
	StartLine int
	EndLine   int
}

type VM

type VM struct {
	MaxStack int

	ErrorFormatter ErrorFormatter
	StringOutput   bool

	EvalHook EvalHook
	// contains filtered or unexported fields
}

VM is the core interpreter and is the touchpoint used to parse and execute Jsonnet.

func MakeTracingVM

func MakeTracingVM() *VM

func MakeVM

func MakeVM() *VM

MakeVM creates a new VM with default parameters.

func (*VM) Evaluate

func (vm *VM) Evaluate(node ast.Node) (val string, err error)

Evaluate evaluates a Jsonnet program given by an Abstract Syntax Tree and returns serialized JSON as string. TODO(sbarzowski) perhaps is should return JSON in standard Go representation

func (*VM) EvaluateAnonymousSnippet

func (vm *VM) EvaluateAnonymousSnippet(filename string, snippet string) (json string, formattedErr error)

EvaluateAnonymousSnippet evaluates a string containing Jsonnet code, return a JSON string.

The filename parameter is only used for error messages.

func (*VM) EvaluateAnonymousSnippetMulti

func (vm *VM) EvaluateAnonymousSnippetMulti(filename string, snippet string) (files map[string]string, formattedErr error)

EvaluateAnonymousSnippetMulti evaluates a string containing Jsonnet code to key-value pairs. The keys are field name strings and the values are JSON strings.

The filename parameter is only used for error messages.

func (*VM) EvaluateAnonymousSnippetStream

func (vm *VM) EvaluateAnonymousSnippetStream(filename string, snippet string) (docs []string, formattedErr error)

EvaluateAnonymousSnippetStream evaluates a string containing Jsonnet code to an array. The array is returned as an array of JSON strings.

The filename parameter is only used for error messages.

func (*VM) EvaluateFile

func (vm *VM) EvaluateFile(filename string) (json string, formattedErr error)

EvaluateFile evaluates Jsonnet code in a file and returns a JSON string.

The importer is used to fetch the contents of the file.

func (*VM) EvaluateFileMulti

func (vm *VM) EvaluateFileMulti(filename string) (files map[string]string, formattedErr error)

EvaluateFileMulti evaluates Jsonnet code in a file to key-value pairs. The keys are field name strings and the values are JSON strings.

The importer is used to fetch the contents of the file.

func (*VM) EvaluateFileStream

func (vm *VM) EvaluateFileStream(filename string) (docs []string, formattedErr error)

EvaluateFileStream evaluates Jsonnet code in a file to an array. The array is returned as an array of JSON strings.

The importer is used to fetch the contents of the file.

func (*VM) EvaluateFileWithTrace

func (vm *VM) EvaluateFileWithTrace(filename string) (json string, trace map[int]*ast.LocationRange, formattedErr error)

func (*VM) EvaluateMulti

func (vm *VM) EvaluateMulti(node ast.Node) (output map[string]string, err error)

EvaluateMulti evaluates a Jsonnet program given by an Abstract Syntax Tree and returns key-value pairs. The keys are strings and the values are JSON strigns (serialized JSON).

func (*VM) EvaluateSnippet deprecated

func (vm *VM) EvaluateSnippet(filename string, snippet string) (json string, formattedErr error)

EvaluateSnippet evaluates a string containing Jsonnet code, return a JSON string.

The filename parameter is used for resolving relative imports and for errors messages.

Deprecated: Use EvaluateFile or EvaluateAnonymousSnippet instead.

func (*VM) EvaluateSnippetMulti deprecated

func (vm *VM) EvaluateSnippetMulti(filename string, snippet string) (files map[string]string, formattedErr error)

EvaluateSnippetMulti evaluates a string containing Jsonnet code to key-value pairs. The keys are field name strings and the values are JSON strings.

The filename parameter is used for resolving relative imports and for errors messages.

Deprecated: Use EvaluateFileMulti or EvaluateAnonymousSnippetMulti instead.

func (*VM) EvaluateSnippetStream deprecated

func (vm *VM) EvaluateSnippetStream(filename string, snippet string) (docs []string, formattedErr error)

EvaluateSnippetStream evaluates a string containing Jsonnet code to an array. The array is returned as an array of JSON strings.

The filename parameter is used for resolving relative imports and for errors messages.

Deprecated: Use EvaluateFileStream or EvaluateAnonymousSnippetStream instead.

func (*VM) EvaluateStream

func (vm *VM) EvaluateStream(node ast.Node) (output []string, err error)

EvaluateStream evaluates a Jsonnet program given by an Abstract Syntax Tree and returns an array of JSON strings.

func (*VM) EvaluateWithTrace

func (vm *VM) EvaluateWithTrace(node ast.Node, trace map[int]*ast.LocationRange) (val string, err error)

func (*VM) ExtCode

func (vm *VM) ExtCode(key string, val string)

ExtCode binds a Jsonnet external code var to the given code.

func (*VM) ExtNode

func (vm *VM) ExtNode(key string, node ast.Node)

ExtNode binds a Jsonnet external code var to the given AST node.

func (*VM) ExtReset

func (vm *VM) ExtReset()

ExtReset rests all external variables registered for this VM.

func (*VM) ExtVar

func (vm *VM) ExtVar(key string, val string)

ExtVar binds a Jsonnet external var to the given value.

func (*VM) FindDependencies

func (vm *VM) FindDependencies(importedFrom string, importedPaths []string) ([]string, error)

FindDependencies returns a sorted array of unique transitive dependencies (via import/importstr/importbin) from all the given `importedPaths` which are themselves excluded from the returned array. The `importedPaths` are parsed as if they were imported from a Jsonnet file located at `importedFrom`.

func (*VM) ImportAST

func (vm *VM) ImportAST(importedFrom, importedPath string) (contents ast.Node, foundAt string, err error)

ImportAST fetches the Jsonnet AST just as if it was imported from a Jsonnet file located at `importedFrom`. It shares the cache with the actual evaluation.

func (*VM) ImportData

func (vm *VM) ImportData(importedFrom, importedPath string) (contents string, foundAt string, err error)

ImportData fetches the data just as if it was imported from a Jsonnet file located at `importedFrom`. It shares the cache with the actual evaluation.

func (*VM) Importer

func (vm *VM) Importer(i Importer)

Importer sets Importer to use during evaluation (import callback).

func (*VM) NativeFunction

func (vm *VM) NativeFunction(f *NativeFunction)

NativeFunction registers a native function.

func (*VM) ResolveImport

func (vm *VM) ResolveImport(importedFrom, importedPath string) (foundAt string, err error)

ResolveImport finds the actual path where the imported file can be found. It will cache the contents of the file immediately as well, to avoid the possibility of the file disappearing after being checked.

func (*VM) SetTraceOut

func (vm *VM) SetTraceOut(traceOut io.Writer)

SetTraceOut sets the output stream for the builtin function std.trace().

func (*VM) TLACode

func (vm *VM) TLACode(key string, val string)

TLACode binds a Jsonnet top level argument to the given code.

func (*VM) TLANode

func (vm *VM) TLANode(key string, node ast.Node)

TLANode binds a Jsonnet top level argument to the given AST node.

func (*VM) TLAReset

func (vm *VM) TLAReset()

TLAReset resets all TLAs registered for this VM.

func (*VM) TLAVar

func (vm *VM) TLAVar(key string, val string)

TLAVar binds a Jsonnet top level argument to the given value.

type YAMLReader

type YAMLReader struct {
	// contains filtered or unexported fields
}

YAMLReader reads YAML

func NewYAMLReader

func NewYAMLReader(r *bufio.Reader) *YAMLReader

NewYAMLReader creates a new YAMLReader

type YAMLToJSONDecoder

type YAMLToJSONDecoder struct {
	// contains filtered or unexported fields
}

YAMLToJSONDecoder decodes YAML documents from an io.Reader by separating individual documents. It first converts the YAML body to JSON, then unmarshals the JSON.

func NewYAMLToJSONDecoder

func NewYAMLToJSONDecoder(r io.Reader) *YAMLToJSONDecoder

NewYAMLToJSONDecoder decodes YAML documents from the provided stream in chunks by converting each document (as defined by the YAML spec) into its own chunk, converting it to JSON via yaml.YAMLToJSON, and then passing it to json.Decoder.

func (*YAMLToJSONDecoder) Decode

func (d *YAMLToJSONDecoder) Decode(into interface{}) error

Decode reads a YAML document as JSON from the stream or returns an error. The decoding rules match json.Unmarshal, not yaml.Unmarshal.

func (*YAMLToJSONDecoder) IsStream

func (d *YAMLToJSONDecoder) IsStream() bool

Directories

Path Synopsis
Package ast provides AST nodes and ancillary structures and algorithms.
Package ast provides AST nodes and ancillary structures and algorithms.
cmd
dumpstdlibast command
internal/cmd
Package cmd provides utilities for parsing and handling command line arguments.
Package cmd provides utilities for parsing and handling command line arguments.
jsonnet command
jsonnet-deps command
jsonnet-lint command
jsonnet-trace command
jsonnetfmt command
wasm command
Package formatter is what powers jsonnetfmt, a Jsonnet formatter.
Package formatter is what powers jsonnetfmt, a Jsonnet formatter.
internal
dump
Package dump can dump a Go data structure to Go source file, so that it can be statically embedded into other code.
Package dump can dump a Go data structure to Go source file, so that it can be statically embedded into other code.
errors
Package errors provides internal representation of errors.
Package errors provides internal representation of errors.
formatter
Package formatter provides API for producing pretty-printed source from AST.
Package formatter provides API for producing pretty-printed source from AST.
parser
Package parser reads Jsonnet files and parses them into AST nodes.
Package parser reads Jsonnet files and parses them into AST nodes.
pass
Package pass provides a visitor framework for source code analysis and transformation.
Package pass provides a visitor framework for source code analysis and transformation.
program
Package program provides API for AST pre-processing (desugaring, static analysis).
Package program provides API for AST pre-processing (desugaring, static analysis).
testutils
Package testutils provides general testing utilities.
Package testutils provides general testing utilities.
Package linter analyses Jsonnet code for code "smells".
Package linter analyses Jsonnet code for code "smells".
internal/common
Package common provides utilities to be used in multiple linter subpackages.
Package common provides utilities to be used in multiple linter subpackages.
internal/traversal
Package traversal provides relatively lightweight checks which can all fit within one traversal of the AST.
Package traversal provides relatively lightweight checks which can all fit within one traversal of the AST.
internal/types
Package types provides type inference functionality.
Package types provides type inference functionality.
internal/variables
Package variables allows collecting the information about how variables are used.
Package variables allows collecting the information about how variables are used.
Package toolutils includes several utilities handy for use in code analysis tools
Package toolutils includes several utilities handy for use in code analysis tools

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL