starlight

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2024 License: MIT Imports: 9 Imported by: 0

README

🌟 Starlight Enhanced - Bridging Go and Starlark

Go Reference codecov codacy codeclimate goreportcard

Welcome to Starlight Enhanced, a sophisticated fork of the original Starlight project. Our version builds upon the Starlight wrapper for Starlark in Go to facilitate smoother data conversion between Go and Starlark.

Due to the lack of ongoing maintenance of the original Starlight project, we saw an opportunity to breathe new life into it. We've optimized it to work seamlessly with the latest versions of Starlark in Go while addressing and rectifying bugs present in the original repository.

The objectives of this enhanced fork include:

  • Identification and resolution of bugs and corner cases that were present in the original repository.
  • Extension of the library's capabilities by exposing additional functions, thereby enriching functionality.
  • Ensuring compatibility and support for the latest versions of Starlark in Go.

We hope that this improved iteration of Starlight will contribute to your projects and enhance your experience with Starlark. Your contributions and feedback are always welcome.

Features

A set of powerful features is provided to facilitate the integration of Starlark scripts into Go applications:

Seamless Data Conversion

Starlight offers robust support for seamless data conversion between Go and Starlark types. Conversion functions are provided through the convert package.

Leveraging the convert.ToValue and convert.FromValue utilities, Starlight enables the smooth transition of Go's rich data types and methods into the Starlark scripting environment. This feature supports a wide array of Go types, including structs, slices, maps, and functions, making them readily accessible and manipulable within Starlark scripts. The only exceptions are Go channels and complexes, which are not supported due to their concurrency nature.

Efficient Caching Mechanism

Starlight introduces an efficient caching mechanism that significantly optimizes script execution performance. By caching scripts upon their first execution, Starlight minimizes the overhead associated with re-reading and re-parsing files in subsequent runs. This caching is compliant with the Starlark Thread.Load standards, ensuring that scripts are efficiently loaded and executed while adhering to Starlark's loading semantics. This feature is particularly beneficial for applications that frequently execute Starlark scripts, as it dramatically reduces execution times and resource consumption.

Simplified Script Execution

The Eval function encapsulates the complexities of setting up and executing Starlark scripts, providing a streamlined interface for developers. This encapsulation allows for easy execution of Starlark scripts with full access to the script's global variables, enhancing script interoperability and flexibility. Additionally, Starlight supports the Starlark load() function, enabling scripts to load and execute other scripts seamlessly. This feature simplifies the integration of Starlark scripting into Go applications, reducing the need for repetitive boilerplate code and fostering a more efficient development process.

Installation

To install Starlight Enhanced, use the following Go command under your project directory:

go get github.com/1set/starlight

Usage

Starlight can be used to easily integrate Starlark scripting into your Go applications. Here's a quick example:

import "github.com/1set/starlight"

// Define your Go function
name := "Starlight"
globals := map[string]interface{}{
    "target": name,
    "greet": func(name string) string {
        return fmt.Sprintf("Hello, %s!", name)
    },
}

// Run a Starlark script with the global variables
script := `text = greet(target); print("Starlark:", text)`
res, err := starlight.Eval([]byte(script), globals, nil)

// Check for errors and results
if err != nil {
    fmt.Println("Error executing script:", err)
    return
}
fmt.Println("Go:", res["text"].(string))

The convert package can be used to convert data between Go and Starlark, making it simpler to pass data and functions back and forth between the two contexts. Here's an example of converting a Go struct to a Starlark value and modifying it in a script:

import (
	"github.com/1set/starlight"
	"github.com/1set/starlight/convert"
)

// Define your Go data structure
type Contact struct {
    Name  string
    Email string
    Age   uint
}
contact := Contact{Name: "Bob", Email: "bob@example.com", Age: 30}

// Convert Go data structure to Starlark value
starlarkValue, err := convert.ToValue(&contact)
if err != nil {
    panic(err)
}
globals := map[string]interface{}{
    "candidate": "Leon",
    "contact":   starlarkValue,
}

// Run a Starlark script with the global variables
script := `
contact.Name = "".join(reversed(candidate.codepoints())).title()
contact.Age += 2
summary = "%s [%d] %s" % (contact.Name, contact.Age, contact.Email)
`
res, err := starlight.Eval([]byte(script), globals, nil)

// Check for errors, results and modified data
if err != nil {
    fmt.Println("Error executing script:", err)
    return
}
fmt.Println("Updated:", contact)
fmt.Println("Summary:", res["summary"].(string))

Contributing

We welcome contributions to the Starlight Enhanced project. If you encounter any issues or have suggestions for improvements, please feel free to open an issue or submit a pull request. Before undertaking any significant changes, please let us know by filing an issue or claiming an existing one to ensure there is no duplication of effort.

License

Starlight Enhanced is licensed under the MIT License.

Credits

This project is a fork of the original Starlight project, authored by Nate Finch (@natefinch). We would like to thank Nate and all the original authors and contributors for laying the foundation upon which this project builds, Starlight Enhanced would not have been possible without the original creation and development by Nate Finch 🎉

For historical reference, the original README from the Starlight project is preserved as README-old.md in this repository.

Documentation

Overview

Package starlight provides a convenience wrapper around go.starlark.net/starlark.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Eval

func Eval(src interface{}, globals map[string]interface{}, load LoadFunc) (map[string]interface{}, error)

Eval evaluates the starlark source with the given global variables. The type of the argument for the src parameter must be string (filename), []byte, or io.Reader.

Types

type Cache

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

Cache is a cache of scripts to avoid re-reading files and reparsing them.

func New

func New(dirs ...string) *Cache

New returns a Starlight Cache that looks in the given directories for plugin files to run. The directories are searched in order for files when Run is called. Calls to the script function load() will also look in these directories. This function will panic if you give it no directories.

func WithGlobals

func WithGlobals(globals map[string]interface{}, dirs ...string) (*Cache, error)

WithGlobals returns a new Starlight cache that passes the listed global values to scripts loaded with the load() script function. Note that these globals will *not* be passed to individual scripts you run unless you explicitly pass them in the Run call.

func (*Cache) Forget

func (c *Cache) Forget(filename string)

Forget clears the cached script for the given filename.

func (*Cache) Load added in v0.0.2

func (c *Cache) Load(_ *starlark.Thread, module string) (starlark.StringDict, error)

Load loads a module using the cache's configured directories.

func (*Cache) Reset

func (c *Cache) Reset()

Reset clears all cached scripts.

func (*Cache) Run

func (c *Cache) Run(filename string, globals map[string]interface{}) (map[string]interface{}, error)

Run looks for a file with the given filename, and runs it with the given globals passed to the script's global namespace. The return value is all convertible global variables from the script, which may include the passed-in globals.

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.

Directories

Path Synopsis
Package convert provides functions for converting data and functions between Go and Starlark.
Package convert provides functions for converting data and functions between Go and Starlark.

Jump to

Keyboard shortcuts

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