risor

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: Apache-2.0 Imports: 26 Imported by: 5

README

Risor logo Risor

CircleCI Apache-2.0 license Go.Dev reference Go Report Card Releases

Risor is a fast and flexible scripting language for Go developers and DevOps.

Its modules integrate the Go standard library, making it easy to use functions that you're already familiar with as a Go developer.

Scripts are compiled to bytecode and then run on a lightweight virtual machine. Risor is written in pure Go.

Documentation

Documentation is available at risor.io.

You might also want to try evaluating Risor scripts from your browser.

Syntax Example

Here's a short example of how Risor feels like a hybrid of Go and Python. This demonstrates using Risor's pipe expressions to apply a series of transformations:

array := ["gophers", "are", "burrowing", "rodents"]

sentence := array | strings.join(" ") | strings.to_upper

print(sentence)

Output:

GOPHERS ARE BURROWING RODENTS

Getting Started

You might want to head over to Getting Started in the documentation. That said, here are tips for both the CLI and the Go library.

Risor CLI and REPL

If you use Homebrew, you can install the Risor CLI as follows:

brew install risor

Having done that, just run risor to start the CLI or risor -h to see usage information.

Execute a code snippet directly using the -c option:

risor -c "time.now()"

Start the REPL by running risor with no options.

Build and Install the CLI from Source

Build the CLI from source as follows:

git clone git@github.com:risor-io/risor.git
cd risor/cmd/risor
go install -tags aws,k8s,vault .

Go Library

Use go get to add Risor as a dependency of your Go program:

go get github.com/risor-io/risor@v1.6.0

Here's an example of using the risor.Eval API to evaluate some code:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/risor-io/risor"
)

func main() {
	ctx := context.Background()
	script := "math.sqrt(input)"
	result, err := risor.Eval(ctx, script, risor.WithGlobal("input", 4))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("The square root of 4 is:", result)
}

Built-in Functions and Modules

30+ built-in functions are included and are documented here.

Modules are included that generally wrap the equivalent Go package. For example, there is direct correspondence between base64, bytes, filepath, json, math, os, rand, regexp, strconv, strings, and time Risor modules and the Go standard library.

Risor modules that are beyond the Go standard library currently include aws, pgx, uuid, vault, and k8s.

Go Interface

It is trivial to embed Risor in your Go program in order to evaluate scripts that have access to arbitrary Go structs and other types.

The simplest way to use Risor is to call the Eval function and provide the script source code. The result is returned as a Risor object:

result, err := risor.Eval(ctx, "math.min([5, 2, 7])")
// result is 2, as an *object.Int

Provide input to the script using Risor options:

result, err := risor.Eval(ctx, "input | strings.to_upper", risor.WithGlobal("input", "hello"))
// result is "HELLO", as an *object.String

Use the same mechanism to inject a struct. You can then access fields or call methods on the struct from the Risor script:

type Example struct {
    Message string
}
example := &Example{"abc"}
result, err := risor.Eval(ctx, "len(ex.Message)", risor.WithGlobal("ex", example))
// result is 3, as an *object.Int

Dependencies and Build Options

Risor is designed to have minimal external dependencies in its core libraries. You can choose to opt into various add-on modules if they are of value in your application. The modules are present in this same Git repository, but must be installed with go get as separate dependencies:

Name Path Go Get Command
aws modules/aws go get github.com/risor-io/risor/modules/aws@v1.6.0
bcrypt modules/bcrypt go get github.com/risor-io/risor/modules/bcrypt@v1.6.0
carbon modules/carbon go get github.com/risor-io/risor/modules/carbon@v1.6.0
cli modules/cli go get github.com/risor-io/risor/modules/cli@v1.6.0
image modules/image go get github.com/risor-io/risor/modules/image@v1.6.0
jmespath modules/jmespath go get github.com/risor-io/risor/modules/jmespath@v1.6.0
k8s modules/kubernetes go get github.com/risor-io/risor/modules/kubernetes@v1.6.0
pgx modules/pgx go get github.com/risor-io/risor/modules/pgx@v1.6.0
s3fs os/s3fs go get github.com/risor-io/risor/os/s3fs@v1.6.0
sql modules/sql go get github.com/risor-io/risor/modules/sql@v1.6.0
template modules/template go get github.com/risor-io/risor/modules/template@v1.6.0
uuid modules/uuid go get github.com/risor-io/risor/modules/uuid@v1.6.0
vault modules/vault go get github.com/risor-io/risor/modules/vault@v1.6.0

These add-ons are included by default when using the Risor CLI. However, when building Risor into your own program, you'll need to opt-in using go get as described above and then add the modules as globals in Risor scripts as follows:

import (
    "github.com/risor-io/risor"
    "github.com/risor-io/risor/modules/aws"
    "github.com/risor-io/risor/modules/image"
    "github.com/risor-io/risor/modules/pgx"
    "github.com/risor-io/risor/modules/uuid"
)

func main() {
    source := `"nice modules!"`
    result, err := risor.Eval(ctx, source,
        risor.WithGlobals(map[string]any{
            "aws":   aws.Module(),
            "image": image.Module(),
            "pgx":   pgx.Module(),
            "uuid":  uuid.Module(),
        }))
    // ...
}

Syntax Highlighting

A Risor VSCode extension is already available which currently only offers syntax highlighting.

You can also make use of the Risor TextMate grammar.

Contributing

Risor is intended to be a community project. You can lend a hand in various ways:

  • Please ask questions and share ideas in GitHub discussions
  • Share Risor on any social channels that may appreciate it
  • Open GitHub issue or a pull request for any bugs you find
  • Star the project on GitHub

Contributing New Modules

Adding modules to Risor is a great way to get involved with the project. See this guide for details.

Discuss the Project

Please visit the GitHub discussions page to share thoughts and questions.

There is also a #risor Slack channel on the Gophers Slack.

Credits

Check CREDITS.md.

License

Released under the Apache License, Version 2.0.

Copyright Curtis Myzie / github.com/myzie.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Call added in v0.14.0

func Call(
	ctx context.Context,
	main *compiler.Code,
	functionName string,
	args []object.Object,
	options ...Option,
) (object.Object, error)

Call evaluates the precompiled code and then calls the named function. The supplied arguments are passed in the function call. The result of the function call is returned.

func Eval

func Eval(ctx context.Context, source string, options ...Option) (object.Object, error)

Eval evaluates the given source code and returns the result.

func EvalCode added in v0.14.0

func EvalCode(ctx context.Context, main *compiler.Code, options ...Option) (object.Object, error)

EvalCode evaluates the precompiled code and returns the result.

Types

type Config added in v1.1.0

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

Config assists in configuring Risor evaluations.

func NewConfig added in v1.1.0

func NewConfig(opts ...Option) *Config

NewConfig returns a new Risor Config. Use the Risor options functions to customize the configuration.

func (*Config) CombinedGlobals deprecated added in v1.1.0

func (cfg *Config) CombinedGlobals() map[string]any

CombinedGlobals returns a map of all global variables that should be available in a Risor evaluation.

Deprecated: Use Globals instead.

func (*Config) CompilerOpts added in v1.1.0

func (cfg *Config) CompilerOpts() []compiler.Option

CompilerOpts returns compiler options derived from this configuration.

func (*Config) GlobalNames added in v1.1.0

func (cfg *Config) GlobalNames() []string

GlobalNames returns a list of all global variables names that should be available in a Risor evaluation.

func (*Config) Globals added in v1.1.0

func (cfg *Config) Globals() map[string]any

Globals returns a map of all global variables that should be available in a Risor evaluation.

func (*Config) VMOpts added in v1.1.0

func (cfg *Config) VMOpts() []vm.Option

VMOpts returns virtual machine options derived from this configuration.

type Option

type Option func(*Config)

Option describes a function used to configure a Risor evaluation.

func WithConcurrency added in v1.4.0

func WithConcurrency() Option

WithConcurrency enables the use of concurrency in Risor evaluations.

func WithGlobal added in v0.14.0

func WithGlobal(name string, value any) Option

WithGlobal supplies a single named global variable to the Risor evaluation.

func WithGlobalOverride added in v1.3.0

func WithGlobalOverride(name string, value any) Option

WithGlobalOverride replaces the a global or module builtin with the given value

func WithGlobals added in v0.14.0

func WithGlobals(globals map[string]any) Option

WithGlobals provides global variables that are made available to Risor evaluations. This option is additive, so multiple WithGlobals options may be supplied. If the same key is supplied multiple times, the last supplied value is used.

func WithImporter

func WithImporter(i importer.Importer) Option

WithImporter supplies an Importer that will be used to execute import statements.

func WithListenersAllowed added in v1.4.0

func WithListenersAllowed() Option

WithListenersAllowed allows opening sockets for listening.

func WithLocalImporter added in v0.8.0

func WithLocalImporter(path string) Option

WithLocalImporter enables importing Risor modules from the given directory.

func WithoutDefaultGlobals added in v0.14.0

func WithoutDefaultGlobals() Option

WithoutDefaultGlobals opts out of all default global builtins and modules.

func WithoutGlobal added in v1.3.0

func WithoutGlobal(name string) Option

WithoutGlobal opts out of a given global builtin or module. If the name can't be resolved, this is a no-op. This does operate on nested modules.

func WithoutGlobals added in v1.3.0

func WithoutGlobals(names ...string) Option

WithoutGlobals removes multiple global builtins or modules.

Directories

Path Synopsis
Package ast defines the abstract syntax tree representation of Risor code.
Package ast defines the abstract syntax tree representation of Risor code.
Package builtins defines a default set of built-in functions.
Package builtins defines a default set of built-in functions.
cmd
risor Module
risor-api Module
risor-docs Module
risor-lsp Module
risor-modgen Module
Package compiler is used to compile a Risor abstract syntax tree (AST) into the corresponding bytecode.
Package compiler is used to compile a Risor abstract syntax tree (AST) into the corresponding bytecode.
Package dis supports analysis of Risor bytecode by disassembling it.
Package dis supports analysis of Risor bytecode by disassembling it.
Package errz defines a FriendlyError interface for errors that have a human friendly message in addition to the default error message.
Package errz defines a FriendlyError interface for errors that have a human friendly message in addition to the default error message.
examples
go/struct Module
Package importer provides a common interface used to import Risor modules.
Package importer provides a common interface used to import Risor modules.
internal
arg
tmpl
Package tmpl is used to parse Risor string templates.
Package tmpl is used to parse Risor string templates.
Package lexer provides a Lexer that takes Risor source code as input and outputs a stream of tokens to be consumed by a parser.
Package lexer provides a Lexer that takes Risor source code as input and outputs a stream of tokens to be consumed by a parser.
Package limits provides an interface and helpers for restricting resource usage during Risor evaluations.
Package limits provides an interface and helpers for restricting resource usage during Risor evaluations.
modules
all
dns
fmt
net
os
aws Module
bcrypt Module
carbon Module
cli Module
gha Module
image Module
jmespath Module
kubernetes Module
pgx Module
sql Module
template Module
uuid Module
vault Module
Package object provides the standard set of Risor object types.
Package object provides the standard set of Risor object types.
Package op defines opcodes used by the Risor compiler and virtual machine.
Package op defines opcodes used by the Risor compiler and virtual machine.
os
s3fs Module
Package parser is used to generate the abstract syntax tree (AST) for a program.
Package parser is used to generate the abstract syntax tree (AST) for a program.
tests
Package token defines language keywords and tokens used when lexing source code.
Package token defines language keywords and tokens used when lexing source code.
Package vm provides a VirtualMachine that executes compiled Risor code.
Package vm provides a VirtualMachine that executes compiled Risor code.

Jump to

Keyboard shortcuts

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