scripting

package
v0.0.0-...-8b058bf Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2022 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertFromTengoMap

func ConvertFromTengoMap[T any](tengoMap map[string]any) (data T, err error)

ConvertFromTengoMap reverses the process, turning an arbitrary tengo map into a defined struct so that you can pass information back and forth between tengo and your application.

func ConvertToTengoMap

func ConvertToTengoMap(data any) (map[string]any, error)

ConvertToTengoMap is a helper function for intelligently transforming an arbitrary struct into a map[string]any object, which tengo can treat as a basic map. It is aware of both the mapstructure and tympanconfig directives.

Types

type Engine

type Engine struct {
	// The settings for the engine determine its overall behavior
	Settings EngineSettings
	// The importer is used to provide access to dynamic/module libraries and enables caching them on discovery
	Importer *LibraryImporter
	// The array of scripts enables you to cache a script for future use and introspection
	Scripts []*Script
}

The Engine is the main interface between tengo and a Tympan app and is geared towards loading scripts and libraries from a Tympan module.

func NewEngine

func NewEngine() *Engine

Creates a new instance of an engine with no settings except that it prepopulates the list of valid standard libraries from tengo. Note that even though the list of valid names includes the OS library, it is disabled by default and none of the libraries are made available to the engine by default; this just prevents you from having to look them up.

func (*Engine) AddApplicationLibraries

func (engine *Engine) AddApplicationLibraries(libraries ...Library)

AddApplicationLibrary adds the specified Tympan script library to the engine's cache and appends the declaration for using the library to the script header. This method otherwise works just like the AddStandardLibrary method except that it works on library objects and can take zero or more libraries. It is safe to call in a loop when processing a Tympan module for discovering and adding standalone libraries.

func (*Engine) AddApplicationModule

func (engine *Engine) AddApplicationModule(module Module)

AddApplicationModule adds the specified Tympan script module to the engine's cache and appends the declaration for using the module to the script header. This method otherwise works just like the AddStandardLibrary method except that it works on Module objects only. Note that it does not append the submodules in the script header, as the module should itself be the interface to any submodules. If the submodule should be available outside of its parent module, it should probably be included as a standalone library instead.

func (*Engine) AddScript

func (engine *Engine) AddScript(name string, scriptString string) error

Adds a new script to the engine from a given name and script body as string. At the time the script is added, all necessary actions are taken to ensure the script can be run immediately after. This means that you want to be sure to configure the engine with desired libraries and settings before adding any scripts. The script is not automatically compiled on creation, so it is possible to update/set new variables and reuse the script.

func (*Engine) AddStandardLibrary

func (engine *Engine) AddStandardLibrary(libraryName string) error

AddStandardLibrary adds the specified tengo standard library to the engine's cache and appends the declaration for using the standard library to the script header. For example, when adding the text standard library:

myengine.AddStandardLibrary("text")

That call will add the text standard library to the StandardLibraries list in the engine's settings and append the string `text := import("text")` to the script header.

Because the library is declared in the script header, any script can then use the text library without having to redeclare it itself.

func (*Engine) AllowedStandardLibraries

func (engine *Engine) AllowedStandardLibraries() (libraries []string)

AllowedStandardLibraries is a helper function for returning the list of tengo's standard libraries that the engine is currently configured to allow scripts to access.

func (*Engine) ApplicationLibraryNames

func (engine *Engine) ApplicationLibraryNames() (names []string)

Returns the list of Tympan scripting libraries the engine is currently configured to be able to load

func (*Engine) ApplicationModuleNames

func (engine *Engine) ApplicationModuleNames() (names []string)

Returns the list of Tympan scripting modules the engine is currently configured to be able to load

func (*Engine) GetScript

func (engine *Engine) GetScript(name string) *Script

Retrieves a cached script from the engine by name.

func (*Engine) InitializeLibraryImporter

func (engine *Engine) InitializeLibraryImporter()

The InitializeLibraryImporter method is used to create and add the LibraryImporter to the engine so you don't have to do it manually; it is configured by default to add all of the configured standard libraries and handle importing the Tympan scripting libraries and modules as well. The importer is what ensures the functions, variables, etc in these libraries are made available to the scripts the engine will run.

func (*Engine) RemoveApplicationLibrary

func (engine *Engine) RemoveApplicationLibrary(libraryName string) error

RemoveApplicationLibrary drops the specified library from the engine's configuration, deleting it from the ApplicationLibraries setting and removing its entry from the ScriptHeader.

func (*Engine) RemoveApplicationModule

func (engine *Engine) RemoveApplicationModule(moduleName string) error

RemoveApplicationModule drops the specified module from the engine's configuration, deleting it from the ApplicationModules setting and removing its entry from the ScriptHeader.

func (*Engine) RemoveStandardLibrary

func (engine *Engine) RemoveStandardLibrary(libraryName string) error

RemoveStandardLibrary drops the specified tengo standard library from the engine's configuration, deleting it from the StandardLibraries setting and removing its entry from the ScriptHeader.

func (*Engine) ScriptWithSameNameExists

func (engine *Engine) ScriptWithSameNameExists(name string) bool

Checks to see whether the specified name matches a script the Engine has already cached.

func (*Engine) SetStandardLibraries

func (engine *Engine) SetStandardLibraries(libraryNames []string) error

SetStandardLibraries is a helper method which replaces the existing list of standard libraries the engine is configured to use. It is functionally equivalent to calling AddStandardLibrary in a loop but with a little more safety and validation, preventing partial updates of the setting.

type EngineSettings

type EngineSettings struct {
	// The ScriptHeader is prepended to every script the engine caches; it ensures that any allowed/added libraries are
	// available to the script without every script needing to redeclare them.
	ScriptHeader string
	// The RandomSeed allows you to specify a seed to initialize for randomization in go instead of in your tengo scripts.
	RandomSeed int64
	// If specified, MaximumObjectAllocations limits the number of objects any one script can create.
	MaximumObjectAllocations int64
	// By default, access to tengo's OS library is forbidden. If you want to enable it, set this to true. The OS library
	// includes functions for modifying the system state, including files, folders, environment, and running arbitrary
	// processes.
	AllowOSLibrary bool
	// The list of tengo's standard libraries that the engine should cache and make available to scripts.
	StandardLibraries []string
	// The list of standalone libraries that the engine should cache and make available to scripts. These can be any tengo
	// file, so long as it exports.
	ApplicationLibraries []Library
	// The list of Tympan scripting modules that the engine should cache and make available to scripts.
	ApplicationModules []Module
	// The list of standard libraries that a script can have utilize.
	ValidStandardLibraryNames []string
}

The EngineSettings configure how the tengo script engine behaves, providing some useful shorthands so you don't need to understand the tengo interop model in detail.

type Library

type Library struct {
	// The engine-unique name of the Library
	Name string
	// The tengo script that makes up the Library
	Body string
}

A Tympan scripting Library is made up of a unique name and the tengo script contents are its body. It is expected that a Library exports.

func GetEmbeddedFolderLibraries

func GetEmbeddedFolderLibraries(folderPath string, efs *embed.FS) (libraries []Library, err error)

GetEmbeddedFolderLibraries requires the path to a folder containing *.tengo files you want to add as libraries and an embedded file system to use. It walks the specified folder, calling GetLibrary on each tengo file it finds, appending found libraries to the list of libraries to return in the order they're found.

If any errors occur while walking the folder, it stops looking for more libraries and returns the successfully parsed libraries and the error that stopped the execution.

func GetEmbeddedLibrary

func GetEmbeddedLibrary(filePath string, efs *embed.FS) (library Library, err error)

GetEmbeddedLibrary requires the path to a *.tengo file you want to add as a library and an embedded file system to use. It looks for the specified path to the file, tries to read it, and returns a Library (with the Name set to the file's name -- without the ".tengo" extension -- and the Body set to the contents of the file) and nil for the error.

If the file can't be read for any reason, it returns an empty Library and the error.

func GetEmbeddedStandaloneLibraries

func GetEmbeddedStandaloneLibraries(folderPath string, efs *embed.FS) (libraries []Library, err error)

GetEmbeddedStandaloneLibraries is a helper function for returning the list of all libraries found in a Tympan module folder. It requires the path to the root folder of a Tympan module and an embedded file system. It figures out the path to the "libraries" subfolder inside the "scripts" folder of the specified module path and then calls GetEmbeddedFolderLibraries on it to return all of the standalone libraries the module provides.

func GetFolderLibraries

func GetFolderLibraries(folderPath string, afs *afero.Afero) (libraries []Library, err error)

GetFolderLibraries requires the path to a folder containing *.tengo files you want to add as libraries and an afero file system to use. It looks for the absolute path to the folder and then walks it, calling GetLibrary on each tengo file it finds, appending found libraries to the list of libraries to return in the order they're found.

If any errors occur while walking the folder, it stops looking for more libraries and returns the successfully parsed libraries and the error that stopped the execution.

func GetLibrary

func GetLibrary(filePath string, afs *afero.Afero) (library Library, err error)

GetLibrary requires the path to a *.tengo file you want to add as a library and an afero file system to use. It looks for the absolute path to the file, tries to read it, and returns a Library (with the Name set to the file's name -- without the ".tengo" extension -- and the Body set to the contents of the file) and nil for the error.

If the file can't be read for any reason, it returns an empty Library and the error.

func GetStandaloneLibraries

func GetStandaloneLibraries(moduleFolderPath string, afs *afero.Afero) (libraries []Library, err error)

GetStandaloneLibraries is a helper function for returning the list of all libraries found in a Tympan module folder. It requires the path to the root folder of a Tympan module and an Afero file system. It looks in the absolute path to the module folder for the "scripts" folder with a "libraries" subfolder. If that folder exists, it calls GetFolderLibraries on it to return all of the standalone libraries the module provides.

type LibraryImporter

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

The LibraryImporter is an implementation of the tengo.ModuleGetter; it allows the engine to import dynamically defined libraries from modules in addition to tengo's in-the-box libraries.

func (*LibraryImporter) Get

func (importer *LibraryImporter) Get(name string) tengo.Importable

?

type MetaConfig

type MetaConfig struct {
	ConfigKey string
	Ignore    bool
}

MetaConfig structs are used when parsing tags on configuration structs; they help turn a mapstructure tag into the name of a viper configuration key and change the behavior of a configuration item via the tympanconfig directive; right now the only supported directive is `tympanconfig:"ignore"` which ensures a struct key is not written to the configuration.

func ParseStructTags

func ParseStructTags(tagEntry reflect.StructTag) (metaConfig MetaConfig)

ParseStructTags() is used to introspect on a struct which is to be converted to a map Tengo can user; it returns the MetaConfig for a given struct field which SetStruct uses to determine behavior.

type Module

type Module struct {
	// The module library itself with an engine-unique name and the tengo script body.
	Library
	// Modules may have zero or more submodules. Submodules are made available to the module library's scope.
	Submodules []Library
}

A Tympan scripting module is a Library with zero or more submodules. This enables you to split your scripting across multiple files for ease of development, testing, and maintenance.

func GetEmbeddedModule

func GetEmbeddedModule(folderPath string, efs *embed.FS) (module Module, err error)

GetModule returns a Module instance with all of its submodules. It requires a path to the root folder of a Tympan module and an embeddedd file system. It looks in the module folder for a "scripts" folder and a ".tengo" file that is named the same as the module folder. If it finds the file, it uses GetLibrary to retrieve it, setting the Module's Name and Body to the appropriate values. If it does not find the file, it returns immediately.

If the module file is found and retrieved without error, it then looks for the "submodules" folder in the same directory as the module script file, calling GetEmbeddedFolderLibraries on it and adding all of the discovered libraries to the Module's Submodules list.

func GetModule

func GetModule(moduleFolderPath string, afs *afero.Afero) (module Module, err error)

GetModule returns a Module instance with all of its submodules. It requires a path to the root folder of a Tympan module and an afero file system. It looks in the absolute path to the module folder for a "scripts" folder and a ".tengo" file that is named the same as the module folder. If it finds the file, it uses GetLibrary to retrieve it, setting the Module's Name and Body to the appropriate values. If it does not find the file, it returns immediately.

If the module file is found and retrieved without error, it then looks for the "submodules" folder in the same directory as the module script file. If that directory exists, it calls GetFolderLibraries on it and adds all of the discovered libraries to the Module's Submodules list.

type Script

type Script struct {
	// The Name of the script. Must be unique to this instance of the Engine.
	Name string
	// The script body as a string for readability and introspection during debug.
	Body string
	// The actual tengo script object
	*tengo.Script
}

The Script is a wrapper around a tengo.Script object, appending the name of the script and the raw string for its body so that a script can be found by name and/or introspected on after compiling.

Jump to

Keyboard shortcuts

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