starlet

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 41 Imported by: 29 modules, 29 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

✨ 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.

Documentation

Overview

Package starlet embeds Starlark scripts in Go with a stateful Machine, builtin libraries, and Go/Starlark value conversion.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DisableGlobalReassign

func DisableGlobalReassign()

DisableGlobalReassign clears the legacy upstream process-global reassignment flag. It does not configure Machine file options; use (*Machine).DisableGlobalReassign. Do not change process-global flags concurrently with evaluation.

func DisableRecursionSupport

func DisableRecursionSupport()

DisableRecursionSupport clears the legacy upstream process-global recursion flag. It does not configure Machine file options; use (*Machine).DisableRecursionSupport. Do not change process-global flags concurrently with evaluation.

func EnableGlobalReassign

func EnableGlobalReassign()

EnableGlobalReassign sets the legacy upstream process-global reassignment flag. It does not configure Machine file options; use (*Machine).EnableGlobalReassign. Do not change process-global flags concurrently with evaluation.

func EnableRecursionSupport

func EnableRecursionSupport()

EnableRecursionSupport sets the legacy upstream process-global recursion flag. It does not configure Machine file options; use (*Machine).EnableRecursionSupport. Do not change process-global flags concurrently with evaluation.

func GetAllBuiltinModuleNames

func GetAllBuiltinModuleNames() []string

GetAllBuiltinModuleNames returns a list of all builtin module names.

func GetBuiltinModuleNamesExcluding added in v0.2.0

func GetBuiltinModuleNamesExcluding(excludes ...string) ([]string, error)

GetBuiltinModuleNamesExcluding returns all builtin module names except the given ones. An unknown name in the exclusion list is an error - fail-closed, because a typo in a denylist must not silently include the module it meant to block.

func GetBuiltinModuleNamesWithoutCapabilities added in v0.2.0

func GetBuiltinModuleNamesWithoutCapabilities(caps ModuleCapability) []string

GetBuiltinModuleNamesWithoutCapabilities returns the builtin module names whose capability sets share nothing with caps - e.g. passing CapNetwork|CapFileSystem yields the modules that can touch neither.

func RunFile

func RunFile(name string, fileSys fs.FS, extras StringAnyMap) (*Machine, StringAnyMap, error)

RunFile initiates a Machine, executes a script from a file with extra variables, and returns the Machine and the execution result.

func RunScript

func RunScript(content []byte, extras StringAnyMap) (*Machine, StringAnyMap, error)

RunScript initiates a Machine, executes a script with extra variables, and returns the Machine and the execution result.

func RunTrustedFile

func RunTrustedFile(name string, fileSys fs.FS, globals, extras StringAnyMap) (*Machine, StringAnyMap, error)

RunTrustedFile initiates a Machine, executes a script from a file with all builtin modules loaded and extra variables, returns the Machine and the result. Use with caution as it allows script access to file system and network.

func RunTrustedScript

func RunTrustedScript(content []byte, globals, extras StringAnyMap) (*Machine, StringAnyMap, error)

RunTrustedScript initiates a Machine, executes a script with all builtin modules loaded and extra variables, returns the Machine and the result. Use with caution as it allows script access to file system and network.

Types

type ByteCache added in v0.0.8

type ByteCache interface {
	Get(key string) ([]byte, bool)
	Set(key string, value []byte) error
}

ByteCache is an interface for caching byte data, used for caching compiled Starlark programs.

type ExecError

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

ExecError is a custom error type for Starlet execution errors.

func (ExecError) Error

func (e ExecError) Error() string

Error returns the error message.

func (ExecError) Unwrap

func (e ExecError) Unwrap() error

Unwrap returns the cause of the error.

type LoadFunc

type LoadFunc func(thread *starlark.Thread, module string) (starlark.StringDict, error)

LoadFunc is a function that tells Starlark how to find and load other scripts using the load() function. If you don't use load() in your scripts, you can pass in nil.

type Machine

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

Machine configures and executes a stateful Starlark environment. Configure globals, preloads and dialect options before execution or after Reset. Preloads inject their exported values; lazy loaders supply load() members. Binding precedence is globals, preloads, execution extras, then explicit load bindings. Extras and script globals remain available to later executions. Reset discards runtime bindings and loaded modules, retaining configuration and the optional compiled-program cache; it does not undo host-side effects.

Machine serializes execution and locks access to its state. A callback must not reenter methods on the same Machine, except the nonblocking String method. Externally shared Go data and raw handles returned by GetStarlarkThread or GetStarlarkPredeclared still require host ownership or synchronization.

func NewDefault

func NewDefault() *Machine

NewDefault creates a Machine with standard Starlark builtins, no additional modules, and input/output conversion enabled.

func NewWithBuiltins

func NewWithBuiltins(globals StringAnyMap, additionalPreload ModuleLoaderList, additionalLazyload ModuleLoaderMap) *Machine

NewWithBuiltins creates a new Starlark runtime environment with given global variables and all preload & lazyload built-in modules.

func NewWithGlobals

func NewWithGlobals(globals StringAnyMap) *Machine

NewWithGlobals creates a new Starlark runtime environment with given global variables.

func NewWithLoaders

func NewWithLoaders(globals StringAnyMap, preload ModuleLoaderList, lazyload ModuleLoaderMap) *Machine

NewWithLoaders creates a new Starlark runtime environment with given global variables and preload & lazyload module loaders.

func NewWithNames

func NewWithNames(globals StringAnyMap, preloads []string, lazyloads []string) *Machine

NewWithNames creates a Machine with globals and named builtin preloads/loaders. It panics on unknown names; module initialization happens during execution. For caller-supplied names, handle errors from MakeBuiltinModuleLoaderList and MakeBuiltinModuleLoaderMap, then pass the loaders to NewWithLoaders.

func (*Machine) AddGlobals

func (m *Machine) AddGlobals(globals StringAnyMap)

AddGlobals adds the globals of the Starlark runtime environment. These variables only take effect before the first run or after a reset.

func (*Machine) AddLazyloadModules

func (m *Machine) AddLazyloadModules(mods ModuleLoaderMap)

AddLazyloadModules adds the modules allowed to be loaded later of the Starlark runtime environment.

func (*Machine) AddPreloadModules

func (m *Machine) AddPreloadModules(mods ModuleLoaderList)

AddPreloadModules adds the preload modules of the Starlark runtime environment. These modules only take effect before the first run or after a reset.

func (*Machine) Call

func (m *Machine) Call(name string, args ...interface{}) (out interface{}, err error)

Call executes a Starlark function or builtin saved in the thread and returns the result. The function runs without a context: it cannot be cancelled or time-bounded; use CallWithContext or CallWithTimeout for that.

func (*Machine) CallWithContext added in v0.2.0

func (m *Machine) CallWithContext(ctx context.Context, name string, args ...interface{}) (out interface{}, err error)

CallWithContext executes like Call, but the function call (and any context-aware library builtin it invokes) is aborted when ctx is cancelled, matching RunWithContext semantics. A nil context behaves like plain Call; an already-cancelled context fails immediately.

func (*Machine) CallWithTimeout added in v0.2.0

func (m *Machine) CallWithTimeout(timeout time.Duration, name string, args ...interface{}) (out interface{}, err error)

CallWithTimeout executes like Call, but the function call (and any context-aware library builtin it invokes) is aborted once the timeout elapses, matching RunWithTimeout semantics.

func (*Machine) DisableGlobalReassign added in v0.0.5

func (m *Machine) DisableGlobalReassign()

DisableGlobalReassign disables global reassignment, top-level control flow and while loops in this Machine's file options.

func (*Machine) DisableRecursionSupport added in v0.0.5

func (m *Machine) DisableRecursionSupport()

DisableRecursionSupport disables recursion in this Machine's file options.

func (*Machine) EnableGlobalReassign added in v0.0.5

func (m *Machine) EnableGlobalReassign()

EnableGlobalReassign enables global reassignment, top-level control flow and while loops in this Machine's file options.

func (*Machine) EnableRecursionSupport added in v0.0.5

func (m *Machine) EnableRecursionSupport()

EnableRecursionSupport enables recursion in this Machine's file options.

func (*Machine) Export

func (m *Machine) Export() StringAnyMap

Export returns the current variables of the Starlark runtime environment.

func (*Machine) GetGlobals

func (m *Machine) GetGlobals() StringAnyMap

GetGlobals gets the globals of the Starlark runtime environment.

func (*Machine) GetLazyloadModules

func (m *Machine) GetLazyloadModules() ModuleLoaderMap

GetLazyloadModules gets the modules allowed to be loaded later of the Starlark runtime environment.

func (*Machine) GetPreloadModules

func (m *Machine) GetPreloadModules() ModuleLoaderList

GetPreloadModules gets the preload modules of the Starlark runtime environment.

func (*Machine) GetStarlarkPredeclared added in v0.0.8

func (m *Machine) GetStarlarkPredeclared() starlark.StringDict

GetStarlarkPredeclared returns the live runtime dictionary, not a copy, or nil before initialization. Advanced callers must synchronize access with all Machine operations.

func (*Machine) GetStarlarkThread added in v0.0.8

func (m *Machine) GetStarlarkThread() *starlark.Thread

GetStarlarkThread returns the live runtime Thread, or nil before initialization. Advanced callers must synchronize access with all Machine operations.

func (*Machine) GetThreadLocal added in v0.0.11

func (m *Machine) GetThreadLocal(key string) interface{}

GetThreadLocal returns the local value of the Starlark thread of the Starlark runtime environment. It returns nil if the thread is not set or the key is not found. Please ensure the machine already runs before calling this method.

func (*Machine) REPL

func (m *Machine) REPL()

REPL is a Read-Eval-Print-Loop for Starlark. It loads the predeclared symbols and modules into the global environment and reads from the terminal.

This lives in a terminal-target file because go.starlark.net/repl pulls in chzyer/readline, a terminal library that does not compile for browser js/wasm or WASI; see run_repl_stub.go for the no-terminal stub.

func (*Machine) Reset

func (m *Machine) Reset()

Reset resets the machine to initial state before the first run. Attention: It does not reset the compiled program cache.

It takes the write lock like the other mutators: it clears the very fields (thread, runTimes, predeclared) that Run and the accessors read, so an unlocked Reset would race with them however carefully the readers lock.

func (*Machine) Run

func (m *Machine) Run() (StringAnyMap, error)

Run executes a preset script and returns the output.

func (*Machine) RunFile

func (m *Machine) RunFile(name string, fileSys fs.FS, extras StringAnyMap) (StringAnyMap, error)

RunFile executes a script from a file with additional variables, which take precedence over global variables and modules, returns the result.

func (*Machine) RunScript

func (m *Machine) RunScript(content []byte, extras StringAnyMap) (StringAnyMap, error)

RunScript executes a script with additional variables, which take precedence over global variables and modules, returns the result.

func (*Machine) RunWithContext

func (m *Machine) RunWithContext(ctx context.Context, extras StringAnyMap) (StringAnyMap, error)

RunWithContext executes a preset script within a specified context and additional variables, which take precedence over global variables and modules, returns the result.

func (*Machine) RunWithTimeout

func (m *Machine) RunWithTimeout(timeout time.Duration, extras StringAnyMap) (StringAnyMap, error)

RunWithTimeout executes a preset script with a timeout and additional variables, which take precedence over global variables and modules, returns the result.

func (*Machine) SetCustomTag added in v0.0.6

func (m *Machine) SetCustomTag(tag string)

SetCustomTag sets the custom annotation tag of Go struct fields for Starlark.

func (*Machine) SetGlobals

func (m *Machine) SetGlobals(globals StringAnyMap)

SetGlobals sets global variables in the Starlark runtime environment. These variables only take effect before the first run or after a reset.

func (*Machine) SetInputConversionEnabled added in v0.0.4

func (m *Machine) SetInputConversionEnabled(enabled bool)

SetInputConversionEnabled controls Go-to-Starlark conversion of globals and execution extras through Starlight. It is enabled by default; when disabled, those inputs must already implement starlark.Value. Call arguments always use the Starlight bridge, independently of this setting.

func (*Machine) SetLazyloadModules

func (m *Machine) SetLazyloadModules(mods ModuleLoaderMap)

SetLazyloadModules sets the modules allowed to be loaded later of the Starlark runtime environment.

func (*Machine) SetMaxExecutionSteps added in v0.2.0

func (m *Machine) SetMaxExecutionSteps(steps uint64)

SetMaxExecutionSteps sets the per-execution budget of Starlark steps (an abstract measure of interpreter work); 0 (the default) means unlimited. When the budget is exhausted, the Run or Call fails with a MaxStepsExceededError, reachable host-side via errors.As. The step counter resets at the start of every Run/Call, so the budget applies per execution, not cumulatively.

func (*Machine) SetMaxPrintBytes added in v0.2.5

func (m *Machine) SetMaxPrintBytes(limit uint64)

SetMaxPrintBytes limits the total bytes of messages delivered to the print handler during each Run or Call, including messages from modules loaded by the Machine. Zero, the default, means unlimited. It counts UTF-8 message bytes, excluding any newline or formatting added by the host handler. An oversized message is withheld in full and execution fails with PrintLimitExceededError. A REPL session shares one budget; exceeding it ends the session. Changes apply to the next Machine execution. Setting zero also restores the configured handler on an initialized main thread.

This limits the print channel, not loggers, direct stderr writes such as eprint, returned values, or memory allocated while constructing a message.

func (*Machine) SetOutputConversionEnabled added in v0.0.4

func (m *Machine) SetOutputConversionEnabled(enabled bool)

SetOutputConversionEnabled controls Starlark-to-Go conversion of execution, Call and Export results. It is enabled by default; when disabled, result entries retain their starlark.Value types.

func (*Machine) SetPreloadModules

func (m *Machine) SetPreloadModules(mods ModuleLoaderList)

SetPreloadModules sets the preload modules of the Starlark runtime environment. These modules only take effect before the first run or after a reset.

func (*Machine) SetPrintFunc

func (m *Machine) SetPrintFunc(printFunc PrintFunc)

SetPrintFunc sets the print function of the Starlark runtime environment. To disable printing, you can set it to NoopPrintFunc. Setting it to nil will invoke the default `fmt.Fprintln(os.Stderr, msg)` instead. The handler applies to subsequent Machine executions. When printing is unlimited, an initialized main thread is also updated immediately.

func (*Machine) SetScript

func (m *Machine) SetScript(name string, content []byte, fileSys fs.FS)

SetScript sets the script related things of the Starlark runtime environment.

func (*Machine) SetScriptCache added in v0.0.8

func (m *Machine) SetScriptCache(cache ByteCache)

SetScriptCache sets the cache for compiled Starlark programs.

func (*Machine) SetScriptCacheEnabled added in v0.0.8

func (m *Machine) SetScriptCacheEnabled(enabled bool)

SetScriptCacheEnabled controls the cache for compiled Starlark programs with the default in-memory cache. If enabled is true, it creates the default in-memory cache instance, otherwise it uses no cache.

func (*Machine) SetScriptContent added in v0.0.7

func (m *Machine) SetScriptContent(content []byte)

SetScriptContent sets the script content of the Starlark runtime environment. It differs from SetScript in that it does not change the script name and filesystem.

func (*Machine) String

func (m *Machine) String() string

String returns a state summary without blocking. If the Machine is locked, it returns a running marker, allowing safe formatting from a host callback.

type MaxStepsExceededError added in v0.2.0

type MaxStepsExceededError struct {
	Limit uint64
}

MaxStepsExceededError marks an execution aborted because it exhausted the step budget configured with Machine.SetMaxExecutionSteps. Detect it with errors.As through the execution error chain.

func (MaxStepsExceededError) Error added in v0.2.0

func (e MaxStepsExceededError) Error() string

Error returns the error message.

type MemoryCache added in v0.0.8

type MemoryCache struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

MemoryCache is a simple in-memory map-based ByteCache, serves as a default cache for Starlark programs.

func NewMemoryCache added in v0.0.8

func NewMemoryCache() *MemoryCache

NewMemoryCache creates a new MemoryCache instance.

func (*MemoryCache) Get added in v0.0.8

func (c *MemoryCache) Get(key string) ([]byte, bool)

Get returns the value for the given key, and whether the key exists.

func (*MemoryCache) Set added in v0.0.8

func (c *MemoryCache) Set(key string, value []byte) error

Set sets the value for the given key.

type ModuleCapability added in v0.2.0

type ModuleCapability uint

ModuleCapability is a bit set classifying what a builtin module can touch on the host. Policy layers use it to derive module sets instead of maintaining hand-written name lists that silently rot as modules are added.

The bits model host *effects* (filesystem, network, process, log) only. They deliberately say nothing about determinism or reproducibility: e.g. random is CapPure (it has no host side effects) yet is non-deterministic by design. A consumer that needs a "replayable / pure-function" set must define it on its own side (excluding entropy/clock sources such as random and time) rather than reading it off these capability bits.

const (
	// CapLog marks modules that write to the host's logging or console
	// facilities (including stderr helpers).
	CapLog ModuleCapability = 1 << iota
	// CapProcess marks modules that read or mutate process-level state:
	// working directory, host identity, runtime information.
	CapProcess
	// CapFileSystem marks modules that read or write the real filesystem.
	CapFileSystem
	// CapNetwork marks modules that open network connections.
	CapNetwork

	// CapPure is the empty set: pure computation with no host effects.
	CapPure ModuleCapability = 0
)

func GetBuiltinModuleCapability added in v0.2.0

func GetBuiltinModuleCapability(name string) (cap ModuleCapability, ok bool)

GetBuiltinModuleCapability returns the capability set of a builtin module; ok is false for names that are not builtin modules.

func (ModuleCapability) Has added in v0.2.0

func (c ModuleCapability) Has(other ModuleCapability) bool

Has reports whether c includes every capability in other.

func (ModuleCapability) Intersects added in v0.2.0

func (c ModuleCapability) Intersects(other ModuleCapability) bool

Intersects reports whether c shares any capability with other.

func (ModuleCapability) String added in v0.2.0

func (c ModuleCapability) String() string

String returns a "+"-joined list of capability names, or "pure".

type ModuleLoader

type ModuleLoader func() (starlark.StringDict, error)

ModuleLoader is a function that loads a Starlark module and returns the module's string dict.

func GetBuiltinModule

func GetBuiltinModule(name string) ModuleLoader

GetBuiltinModule returns the builtin module with the given name.

func MakeModuleLoaderFromFile

func MakeModuleLoaderFromFile(name string, fileSys fs.FS, predeclared starlark.StringDict) ModuleLoader

MakeModuleLoaderFromFile creates a module loader from the given file.

Like MakeModuleLoaderFromString, the returned loader executes the file on a bare thread and does NOT inherit a Machine's step budget or run-context cancellation. To have a Machine bound a loaded file with its guards, register the filesystem via SetScript and load(name) the file so it runs on the guarded load thread instead of registering it through this constructor.

func MakeModuleLoaderFromMap

func MakeModuleLoaderFromMap(m StringAnyMap) ModuleLoader

MakeModuleLoaderFromMap creates a module loader from the given map, it converts the map to a string dict when loading.

func MakeModuleLoaderFromReader

func MakeModuleLoaderFromReader(name string, rd io.Reader, predeclared starlark.StringDict) ModuleLoader

MakeModuleLoaderFromReader creates a module loader from the given IO reader.

Like MakeModuleLoaderFromString, the returned loader executes the source on a bare thread and does NOT inherit a Machine's step budget or run-context cancellation; load host-supplied source through the file path when it must be bounded by the Machine's guards.

func MakeModuleLoaderFromString

func MakeModuleLoaderFromString(name, source string, predeclared starlark.StringDict) ModuleLoader

MakeModuleLoaderFromString creates a module loader from the given source code.

The returned loader executes the source on its own bare thread, so the module body does NOT inherit a Machine's step budget or run-context cancellation. The source is host-supplied (not script input), so this is a robustness caveat, not a script-reachable DoS; but for a module whose body must be bounded by the Machine's guards, load it through the file path instead (SetScript's scriptFS plus a load(name) of the file), which runs on the guarded load thread.

func MakeModuleLoaderFromStringDict

func MakeModuleLoaderFromStringDict(d starlark.StringDict) ModuleLoader

MakeModuleLoaderFromStringDict creates a module loader from the given string dict.

type ModuleLoaderList

type ModuleLoaderList []ModuleLoader

ModuleLoaderList is a list of Starlark module loaders, usually used to load a list of modules in order.

func GetAllBuiltinModules

func GetAllBuiltinModules() ModuleLoaderList

GetAllBuiltinModules returns a list of all builtin modules.

func MakeBuiltinModuleLoaderList

func MakeBuiltinModuleLoaderList(names ...string) (ModuleLoaderList, error)

MakeBuiltinModuleLoaderList creates a list of module loaders from a list of module names. It returns an error as second return value if any module is not found.

func (ModuleLoaderList) Clone

func (l ModuleLoaderList) Clone() []ModuleLoader

Clone returns a copy of the list.

func (ModuleLoaderList) LoadAll

LoadAll loads all modules in the list into the given StringDict. It returns an error for a nil dictionary/loader or a failed module load.

type ModuleLoaderMap

type ModuleLoaderMap map[string]ModuleLoader

ModuleLoaderMap is a map of Starlark module loaders, usually used to load a map of modules by name.

func GetBuiltinModuleMap

func GetBuiltinModuleMap() ModuleLoaderMap

GetBuiltinModuleMap returns a map of all builtin modules.

func MakeBuiltinModuleLoaderMap

func MakeBuiltinModuleLoaderMap(names ...string) (ModuleLoaderMap, error)

MakeBuiltinModuleLoaderMap creates a map of module loaders from a list of module names. It returns an error as second return value if any module is not found.

func (ModuleLoaderMap) Clone

func (m ModuleLoaderMap) Clone() ModuleLoaderMap

Clone returns a copy of the map.

func (ModuleLoaderMap) GetLazyLoader

func (m ModuleLoaderMap) GetLazyLoader() NamedModuleLoader

GetLazyLoader returns a lazy loader that loads the module with the given name. It returns an error as second return value if the module is found but fails to load. Otherwise, the first return value is nil if the module is not found. Note that the loader is usually used by the Starlark thread, so that the errors should not be wrapped.

func (ModuleLoaderMap) Keys

func (m ModuleLoaderMap) Keys() []string

Keys returns the keys of the map, sorted in ascending order of the keys.

func (ModuleLoaderMap) Merge

func (m ModuleLoaderMap) Merge(other ModuleLoaderMap)

Merge merges the given map into the map. It does nothing if the current map is nil.

func (ModuleLoaderMap) Values

func (m ModuleLoaderMap) Values() []ModuleLoader

Values returns the elements of the map, sorted in ascending order of the keys.

type ModuleNotFoundError added in v0.2.0

type ModuleNotFoundError struct {
	Name string
}

ModuleNotFoundError is returned by load() when the named module is not present in any source available to the machine: it is neither a builtin or custom loader configured for this machine, nor a script file on the configured filesystem. Hosts can detect it with errors.As through the Starlark error chain.

func (ModuleNotFoundError) Error added in v0.2.0

func (e ModuleNotFoundError) Error() string

Error returns the error message.

type ModuleWithheldError added in v0.2.0

type ModuleWithheldError struct {
	Name string
}

ModuleWithheldError marks a module that exists but is deliberately not made available to the current machine: a known builtin that was not enabled, or a module blocked by a host-side policy layer (which can return this type from its own loaders). It lets hosts and script authors tell a misspelled module apart from a forbidden one; detect it with errors.As through the Starlark error chain.

func (ModuleWithheldError) Error added in v0.2.0

func (e ModuleWithheldError) Error() string

Error returns the error message.

type NamedModuleLoader

type NamedModuleLoader func(string) (starlark.StringDict, error)

NamedModuleLoader is a function that loads a Starlark module with the given name and returns the module's string dict. If the module is not found, it returns nil as the first and second return value.

type PrintFunc

type PrintFunc func(thread *starlark.Thread, msg string)

PrintFunc is a function that tells Starlark how to print messages. If nil, the default `fmt.Fprintln(os.Stderr, msg)` will be used instead.

var (
	// NoopPrintFunc is a no-op print function for the Starlark runtime environment, it does nothing.
	NoopPrintFunc PrintFunc = func(thread *starlark.Thread, msg string) {}
)

type PrintLimitExceededError added in v0.2.5

type PrintLimitExceededError struct {
	Limit uint64
}

PrintLimitExceededError marks an execution stopped by SetMaxPrintBytes. Detect it with errors.As through the execution error chain.

func (PrintLimitExceededError) Error added in v0.2.5

func (e PrintLimitExceededError) Error() string

Error returns the error message.

type StringAnyMap

type StringAnyMap map[string]interface{}

StringAnyMap type is a map of string to interface{} and is used to store global variables like StringDict of Starlark, but not a Starlark type.

func (StringAnyMap) Clone

func (d StringAnyMap) Clone() StringAnyMap

Clone returns a copy of the data store. It returns an empty map if the current data store is nil.

func (StringAnyMap) Merge

func (d StringAnyMap) Merge(other StringAnyMap)

Merge merges the given data store into the current data store. It does nothing if the current data store is nil.

func (StringAnyMap) MergeDict

func (d StringAnyMap) MergeDict(other starlark.StringDict)

MergeDict merges the given string dict into the current data store.

Directories

Path Synopsis
cmd
starlet module
Package dataconv provides helper functions to convert between Starlark and Go types.
Package dataconv provides helper functions to convert between Starlark and Go types.
types
Package types provides wrappers for Starlark types that can be unpacked by the Unpack helper functions to interpret call arguments.
Package types provides wrappers for Starlark types that can be unpacked by the Unpack helper functions to interpret call arguments.
Package internal contains types and utilities that are not part of the public API, and may change without notice.
Package internal contains types and utilities that are not part of the public API, and may change without notice.
jsonrepair
Package jsonrepair is a vendored copy of github.com/kaptinlin/jsonrepair at v0.2.2 (MIT License — see the LICENSE file in this directory, Copyright (c) 2024 KaptinLin).
Package jsonrepair is a vendored copy of github.com/kaptinlin/jsonrepair at v0.2.2 (MIT License — see the LICENSE file in this directory, Copyright (c) 2024 KaptinLin).
replacecr
Package replacecr defines a wrapper for replacing solo carriage return characters (\r) with carriage-return + line feed (\r\n).
Package replacecr defines a wrapper for replacing solo carriage return characters (\r) with carriage-return + line feed (\r\n).
lib
atom
Package atom provides atomic operations for integers, floats and strings.
Package atom provides atomic operations for integers, floats and strings.
base64
Package base64 defines base64 encoding & decoding functions for Starlark.
Package base64 defines base64 encoding & decoding functions for Starlark.
csv
Package csv reads comma-separated values from strings and writes CSV data to strings.
Package csv reads comma-separated values from strings and writes CSV data to strings.
file
Package file defines functions that manipulate files, it's inspired by file helpers from Amoy.
Package file defines functions that manipulate files, it's inspired by file helpers from Amoy.
goidiomatic
The expression helpers provide data-only, read-only Starlark evaluation.
The expression helpers provide data-only, read-only Starlark evaluation.
hashlib
Package hashlib defines hash primitives for Starlark.
Package hashlib defines hash primitives for Starlark.
http
Package http provides tools for integrating HTTP request handling within Go-based web servers and clients with Starlark scripting capabilities.
Package http provides tools for integrating HTTP request handling within Go-based web servers and clients with Starlark scripting capabilities.
json
Package json defines utilities for converting Starlark values to/from JSON strings based on go.starlark.net/lib/json.
Package json defines utilities for converting Starlark values to/from JSON strings based on go.starlark.net/lib/json.
log
Package log provides functionality for logging messages at various severity levels in the Starlark environment.
Package log provides functionality for logging messages at various severity levels in the Starlark environment.
net
Package net provides network-related functions for Starlark, inspired by Go's net package and Python's socket module.
Package net provides network-related functions for Starlark, inspired by Go's net package and Python's socket module.
path
Package path provides path manipulation for Starlark.
Package path provides path manipulation for Starlark.
random
Package random defines functions that generate random values for various distributions, it's intended to be a drop-in subset of Python's random module for Starlark.
Package random defines functions that generate random values for various distributions, it's intended to be a drop-in subset of Python's random module for Starlark.
re
Package re defines regular expression functions, it's intended to be a drop-in subset of Python's re module for Starlark.
Package re defines regular expression functions, it's intended to be a drop-in subset of Python's re module for Starlark.
regex
Package regex provides regular expression functions for Starlark, intended as a subset of Python's re module backed by Go's RE2 engine.
Package regex provides regular expression functions for Starlark, intended as a subset of Python's re module backed by Go's RE2 engine.
runtime
Package runtime implements the Starlark module for Go and app runtime information.
Package runtime implements the Starlark module for Go and app runtime information.
serial
Package serial defines a Starlark module that serializes data values to and from a JSON envelope, round-tripping the types plain JSON cannot: bytes, set, tuple, big integers, time, and dicts with non-string keys.
Package serial defines a Starlark module that serializes data values to and from a JSON envelope, round-tripping the types plain JSON cannot: bytes, set, tuple, big integers, time, and dicts with non-string keys.
stats
Package stats provides a Starlark module for comprehensive statistics functions.
Package stats provides a Starlark module for comprehensive statistics functions.
string
Package string defines functions that manipulate strings, it's intended to be a drop-in subset of Python's string module for Starlark.
Package string defines functions that manipulate strings, it's intended to be a drop-in subset of Python's string module for Starlark.

Jump to

Keyboard shortcuts

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