Skip to content
1setPublic

About

✨ Yet another Go wrapper for Starlark that simplifies usage, offers data conversion and useful Starlark libraries

Topics

Resources

Security policy

Stars

51 stars

Watchers

1 watching

Forks

Latest commit

 

History

201 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

✨ Starlet - Starlark scripts and libraries for Go

godoc codecov codacy codeclimate goreportcard

Starlet embeds Starlark in Go through a stateful Machine, builtin libraries, and Go/Starlark value conversion. It uses the Starlight bridge by default and also offers explicit native-value helpers in dataconv.

Installation

From a Go module:

go get github.com/1set/starlet

This README describes the checked-out source; available APIs depend on the version selected by your application (go list -m github.com/1set/starlet). GoDoc links may show the latest tagged release. For this checkout, use go doc Machine, source API comments, and the usage guide.

The root library supports Go 1.19 or newer. Use a supported, security-patched toolchain for production; see compatibility and security.

Quick start

This complete program enables JSON loading, passes a Go function to the script, and reads a script result back in Go:

package main

import (
    "fmt"
    "log"

    "github.com/1set/starlet"
)

func main() {
    globals := starlet.StringAnyMap{
        "greet": func(name string) string {
            return fmt.Sprintf("Hello, %s!", name)
        },
    }
    machine := starlet.NewWithNames(globals, nil, []string{"json"})
    result, err := machine.RunScript([]byte(`
load("json", "decode")
data = decode('{"name":"Starlark"}')
message = greet(data["name"])
`), nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result["message"])
}
// Output: Hello, Starlark!

Choosing modules

NewDefault() supplies standard Starlark builtins, with no additional Starlet modules. Select modules explicitly:

Constructor Script access
NewWithNames(globals, []string{"json"}, nil) Preload: call json.decode(...) directly.
NewWithNames(globals, nil, []string{"json"}) Lazy load: load("json", "decode"), then call decode(...).
NewWithBuiltins(globals, nil, nil) All builtin preloads and loaders, including filesystem, network and process effects.

Preloading and enabling load() are separate choices. Most preloaded modules expose a named object; go_idiomatic exposes flat helpers such as eval, and struct exposes the struct(...) constructor. Binding precedence is host globals < preloads < execution extras < explicit load bindings.

Unknown builtin names make NewWithNames panic. For names supplied by callers, use MakeBuiltinModuleLoaderList / MakeBuiltinModuleLoaderMap and NewWithLoaders to handle configuration errors explicitly. Errors while initializing a module are returned by execution.

Execution and state

  • Configure globals, preloads and dialect options before the first execution; use Reset() when changing initialization configuration. Extras and script globals are retained for later executions and Call.
  • Reset() discards runtime bindings and loaded-module state, while retaining configuration and the optional compiled-program cache. It does not undo host-side effects.
  • RunScript executes supplied bytes without the compiled-program cache. For reusable named scripts, use SetScript + Run, or RunFile; enable caching with SetScriptCacheEnabled(true) when needed.
  • Route script print(...) with SetPrintFunc; nil uses stderr and NoopPrintFunc discards output. See file execution, output, and errors.
  • SetMaxPrintBytes(n) optionally limits messages sent through that handler; 0 is unlimited. See print byte budgets.
  • After loading function definitions, use Call, CallWithContext, or CallWithTimeout to invoke them from Go. Context cancellation is cooperative; it cannot preempt arbitrary Go callbacks.
  • SetMaxExecutionSteps bounds VM steps; 0 means unlimited. The counter resets for each Run/Call, and file-loaded module initialization receives a separate thread allowance. This is not a wall-clock or memory limit.

Execution on one Machine is serialized. Host callbacks must not reenter methods on the same Machine, except the nonblocking String method. The lock does not synchronize externally shared Go data or raw handles returned by GetStarlarkThread / GetStarlarkPredeclared; the host must own or synchronize those values.

Value conversion

Global/extra input conversion and result conversion are enabled by default. Go values use Starlight wrappers where appropriate; results are converted back to Go values. This does not promise a detached copy of host data. With input conversion disabled, globals and extras must already implement starlark.Value; Call arguments still use the Starlight bridge. Disabling output conversion retains starlark.Value results.

Use dataconv.Marshal / Unmarshal for explicit conversion of supported common Go/native Starlark types. These helpers are separate from the Machine's default bridge.

Libraries

Each module README lists its functions, parameters, results and boundaries:

Package Go Doc Description
atom godoc Atomic operations for integers, floats, and strings
base64 godoc Base64 encoding & decoding functions
csv godoc Parses and writes comma-separated values (csv) contents
file godoc Functions to interact with the file system
goidiomatic godoc Go-style helpers, values and constructors; read-only expression evaluation
hashlib godoc Hash primitives for Starlark
http godoc HTTP client and server handler implementation for Starlark
json godoc Utilities for converting Starlark values to/from JSON strings
log godoc Functionality for logging messages at various severity levels
net godoc Network reachability checks: TCP/HTTP ping and DNS lookup
path godoc Functions to manipulate directories and file paths
random godoc Functions to generate random values for various distributions
re godoc Regular expression functions for Starlark (legacy, frozen)
regex godoc Python-style regex (RE2) with Match objects, flags, named groups
runtime godoc Provides Go and app runtime information
serial godoc Lossless data-value serialization (bytes/set/tuple/bigint/time)
stats godoc Statistics: mean/median/stddev, correlation, percentiles, etc.
string godoc Constants and functions to manipulate strings

GetAllBuiltinModuleNames() returns the complete sorted registry. The upstream math, struct, and time APIs are also available; they have no lib/ README here. Capability metadata describes builtin host effects for policy consumers; it is not process isolation or a determinism guarantee.

Compatibility and security

The root library keeps the interpreter pin at go.starlark.net v0.0.0-20260324133313-ffb3f39dd27a. Its Go 1.19 compatibility floor is separate from the production compiler.

This interpreter predates the upstream parser recursion limit. Only parse host-selected, reviewed source and modules in the host process. Step limits, timeouts and module selection do not make arbitrary untrusted source safe. Read SECURITY.md for the deployment boundary.

Command-line tools

For the dedicated command-line application, see StarCLI. The older cmd/starlet has separate dependency pins and legacy install/REPL instructions; installing it does not automatically use the root library version described here. For an embedded terminal REPL, see Machine.REPL.

Contributing and license

Issues and pull requests are welcome. Please discuss significant changes before implementation to avoid duplicate work. Starlet is licensed under MIT.

Credits

Inspired by Starlight and Starlib.

About

✨ Yet another Go wrapper for Starlark that simplifies usage, offers data conversion and useful Starlark libraries

Topics

Resources

Security policy

Stars

51 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages