Documentation
¶
Index ¶
- Constants
- Variables
- func FormatLogMessage(level, message, frameUri string) string
- func RegisterMapping(name string, value any)
- func RegisterStrictMapping(name string, value any)
- func Unmarshal(data []byte, v any) error
- type Checksums
- type Class
- type DataSize
- type DataSizeUnit
- type Duration
- type DurationUnit
- type EvalError
- type Evaluator
- func NewEvaluator(ctx context.Context, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
- func NewEvaluatorWithCommand(ctx context.Context, pklCmd []string, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
- func NewProjectEvaluator(ctx context.Context, projectBaseUrl *url.URL, ...) (Evaluator, error)
- func NewProjectEvaluatorWithCommand(ctx context.Context, projectBaseUrl *url.URL, pklCmd []string, ...) (Evaluator, error)
- type EvaluatorManager
- type EvaluatorOptions
- type ExternalReader
- type ExternalReaderClient
- type ExternalReaderClientOptions
- type Http
- type IntSeq
- type InternalError
- type Logger
- type ModuleReader
- type ModuleSource
- type Object
- type Pair
- type PathElement
- type Project
- type ProjectDependencies
- type ProjectEvaluatorSettingExternalReader
- type ProjectEvaluatorSettings
- type ProjectEvaluatorSettingsHttp
- type ProjectEvaluatorSettingsProxy
- type ProjectLocalDependency
- type ProjectPackage
- type ProjectRemoteDependency
- type Proxy
- type Reader
- type Regex
- type ResourceReader
- type TraceMode
- type TypeAlias
Constants ¶
const ( Nanosecond DurationUnit = 1 Microsecond = Nanosecond * 1000 Millisecond = Microsecond * 1000 Second = Millisecond * 1000 Minute = Second * 60 Hour = Minute * 60 Day = Hour * 24 )
const ( Bytes DataSizeUnit = 1 Kilobytes = 1000 Kibibytes = 1024 Megabytes = Kilobytes * 1000 Mebibytes = Kibibytes * 1024 Gigabytes = Megabytes * 1000 Gibibytes = Mebibytes * 1024 Terabytes = Gigabytes * 1000 Tebibytes = Gibibytes * 1024 Petabytes = Terabytes * 1000 Pebibytes = Tebibytes * 1024 )
const StructTag = "pkl"
Variables ¶
var MaybePreconfiguredOptions = func(opts *EvaluatorOptions) { if len(opts.AllowedResources) == 0 { WithDefaultAllowedResources(opts) } if len(opts.Env) == 0 { WithOsEnv(opts) } if len(opts.AllowedModules) == 0 { WithDefaultAllowedModules(opts) } if opts.CacheDir == "" { WithDefaultCacheDir(opts) } if opts.Logger == nil { opts.Logger = NoopLogger } }
MaybePreconfiguredOptions is like PreconfiguredOptions, except it only applies options if they have not already been set.
It panics if the home directory cannot be determined.
var NoopLogger = NewLogger(io.Discard)
NoopLogger is a logger that discards all messages.
var PreconfiguredOptions = func(opts *EvaluatorOptions) { WithDefaultAllowedResources(opts) WithOsEnv(opts) WithDefaultAllowedModules(opts) WithDefaultCacheDir(opts) opts.Logger = NoopLogger }
PreconfiguredOptions configures an evaluator with:
- allowance for "file", "http", "https", "env", "prop", "package resource schemes
- allowance for "repl", "file", "http", "https", "pkl", "package" module schemes
- environment variables from the host environment
- ~/.pkl/cache as the cache directory
- no-op logging
It panics if the home directory cannot be determined.
var StderrLogger = NewLogger(os.Stdout)
StderrLogger is a logger that writes to standard error.
var WithDefaultAllowedModules = func(opts *EvaluatorOptions) { opts.AllowedModules = append(opts.AllowedModules, "pkl:", "repl:", "file:", "http:", "https:", "modulepath:", "package:", "projectpackage:") }
WithDefaultAllowedModules enables reading stdlib, repl, file, http, https, modulepath, and package modules.
var WithDefaultAllowedResources = func(opts *EvaluatorOptions) { opts.AllowedResources = append(opts.AllowedResources, "http:", "https:", "file:", "env:", "prop:", "modulepath:", "package:", "projectpackage:") }
WithDefaultAllowedResources enables reading http, https, file, env, prop, modulepath, and package resources.
var WithDefaultCacheDir = func(opts *EvaluatorOptions) { dirname, err := os.UserHomeDir() if err != nil { panic(err) } opts.CacheDir = filepath.Join(dirname, ".pkl/cache") }
WithDefaultCacheDir sets the cache directory to Pkl's default location. It panics if the home directory cannot be determined.
var WithExternalClientFs = func(fs fs.FS, scheme string) func(opts *ExternalReaderClientOptions) { return func(opts *ExternalReaderClientOptions) { reader := &fsReader{fs: fs, scheme: scheme} WithExternalClientModuleReader(&fsModuleReader{reader})(opts) WithExternalClientResourceReader(&fsResourceReader{reader})(opts) } }
WithExternalClientFs sets up a ModuleReader and ResourceReader to the ExternalReaderClient that associates the provided scheme with files from fs.
var WithExternalClientModuleReader = func(reader ModuleReader) func(*ExternalReaderClientOptions) { return func(options *ExternalReaderClientOptions) { options.ModuleReaders = append(options.ModuleReaders, reader) } }
WithExternalClientModuleReader adds an additional ModuleReader to the ExternalReaderClient.
var WithExternalClientResourceReader = func(reader ResourceReader) func(*ExternalReaderClientOptions) { return func(options *ExternalReaderClientOptions) { options.ResourceReaders = append(options.ResourceReaders, reader) } }
WithExternalClientResourceReader adds an additional ResourceReader to the ExternalReaderClient.
var WithExternalClientStreams = func(requestReader io.Reader, responseWriter io.Writer) func(*ExternalReaderClientOptions) { return func(options *ExternalReaderClientOptions) { options.RequestReader = requestReader options.ResponseWriter = responseWriter } }
WithExternalClientStreams sets the input and output interfaces the ExternalReaderClient will use to communicate with the Pkl evaluator.
var WithExternalModuleReader = func(scheme string, spec ExternalReader) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { if opts.ExternalModuleReaders == nil { opts.ExternalModuleReaders = map[string]ExternalReader{} } opts.ExternalModuleReaders[scheme] = spec opts.AllowedModules = append(opts.AllowedModules, regexp.QuoteMeta(scheme+":")) } }
var WithExternalResourceReader = func(scheme string, spec ExternalReader) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { if opts.ExternalResourceReaders == nil { opts.ExternalResourceReaders = map[string]ExternalReader{} } opts.ExternalResourceReaders[scheme] = spec opts.AllowedResources = append(opts.AllowedResources, regexp.QuoteMeta(scheme+":")) } }
var WithFs = func(fs fs.FS, scheme string) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { reader := &fsReader{fs: fs, scheme: scheme} WithModuleReader(&fsModuleReader{reader})(opts) WithResourceReader(&fsResourceReader{reader})(opts) } }
WithFs sets up a ModuleReader and ResourceReader that associates the provided scheme with files from fs.
For example, this may come from files within embed.FS.
In Pkl terms, files within this file system are interpreted as based off the root path "/". For example, the path "foo.txt" within the provided file system is matched to path "/foo.txt" in Pkl code.
If on Pkl 0.22 or lower, triple-dot imports and globbing are not supported.
Modules and resources may be globbed within Pkl via `import*` and `read*`. Modules may be imported via triple-dot imports.
Pkl has a built-in file system that reads from the host disk. This behavior may be overwritten by setting the scheme as `file`.
var WithModuleReader = func(reader ModuleReader) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { opts.ModuleReaders = append(opts.ModuleReaders, reader) opts.AllowedModules = append(opts.AllowedModules, regexp.QuoteMeta(reader.Scheme()+":")) } }
WithModuleReader sets up the given module reader, and also adds the reader's scheme to the evaluator's allowed modules list.
var WithOsEnv = func(opts *EvaluatorOptions) { if opts.Env == nil { opts.Env = make(map[string]string) } for _, e := range os.Environ() { if i := strings.Index(e, "="); i >= 0 { opts.Env[e[:i]] = e[i+1:] } } }
WithOsEnv enables reading `env` values from the current environment.
var WithProject = func(project *Project) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { WithProjectEvaluatorSettings(project)(opts) WithProjectDependencies(project)(opts) } }
var WithProjectDependencies = func(project *Project) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { opts.ProjectBaseURI = strings.TrimSuffix(project.ProjectFileUri, "/PklProject") opts.DeclaredProjectDependencies = project.Dependencies() } }
WithProjectDependencies configures the evaluator with dependencies from the specified project.
var WithProjectEvaluatorSettings = func(project *Project) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { evaluatorSettings := project.EvaluatorSettings opts.Properties = evaluatorSettings.ExternalProperties opts.Env = evaluatorSettings.Env if evaluatorSettings.AllowedModules != nil { opts.AllowedModules = *evaluatorSettings.AllowedModules } if evaluatorSettings.AllowedResources != nil { opts.AllowedResources = *evaluatorSettings.AllowedResources } if evaluatorSettings.NoCache != nil && *evaluatorSettings.NoCache { opts.CacheDir = "" } else { opts.CacheDir = evaluatorSettings.ModuleCacheDir } opts.RootDir = evaluatorSettings.RootDir if evaluatorSettings.Http != nil { opts.Http = &Http{} if evaluatorSettings.Http.Proxy != nil { opts.Http.Proxy = &Proxy{NoProxy: opts.Http.Proxy.NoProxy} if evaluatorSettings.Http.Proxy.Address != nil { opts.Http.Proxy.Address = *evaluatorSettings.Http.Proxy.Address } } if evaluatorSettings.Http.Rewrites != nil { opts.Http.Rewrites = *evaluatorSettings.Http.Rewrites } } if evaluatorSettings.ExternalModuleReaders != nil { opts.ExternalModuleReaders = make(map[string]ExternalReader, len(evaluatorSettings.ExternalModuleReaders)) for scheme, reader := range evaluatorSettings.ExternalModuleReaders { opts.ExternalModuleReaders[scheme] = ExternalReader(reader) if evaluatorSettings.AllowedModules == nil { WithDefaultAllowedModules(opts) opts.AllowedModules = append(opts.AllowedModules, regexp.QuoteMeta(scheme+":")) } } } if evaluatorSettings.ExternalResourceReaders != nil { opts.ExternalResourceReaders = make(map[string]ExternalReader, len(evaluatorSettings.ExternalResourceReaders)) for scheme, reader := range evaluatorSettings.ExternalResourceReaders { opts.ExternalResourceReaders[scheme] = ExternalReader(reader) if evaluatorSettings.AllowedResources == nil { WithDefaultAllowedResources(opts) opts.AllowedResources = append(opts.AllowedResources, regexp.QuoteMeta(scheme+":")) } } } if evaluatorSettings.TraceMode != nil { opts.TraceMode = *evaluatorSettings.TraceMode } } }
WithProjectEvaluatorSettings configures the evaluator with settings from the given ProjectEvaluatorSettings.
var WithResourceReader = func(reader ResourceReader) func(opts *EvaluatorOptions) { return func(opts *EvaluatorOptions) { opts.ResourceReaders = append(opts.ResourceReaders, reader) opts.AllowedResources = append(opts.AllowedResources, regexp.QuoteMeta(reader.Scheme()+":")) } }
WithResourceReader sets up the given resource reader, and also adds the reader's scheme to the evaluator's allowed resources list.
Functions ¶
func FormatLogMessage ¶
FormatLogMessage returns the default formatter for log messages.
func RegisterMapping ¶
RegisterMapping is like RegisterStrictMapping, but casts it to a pointer.
This method exists to preserve compatibility with legacy generated code, where object types were generated as pointers.
func RegisterStrictMapping ¶ added in v0.11.0
RegisterStrictMapping associates the type given the Pkl name to the corresponding Go type.
Types ¶
type Class ¶
type Class struct {
// ModuleUri of the Pkl module containing the class.
// Will be an empty string for values encoded by Pkl versions older than 0.30.
ModuleUri string
// Name of the Pkl class.
// Will be an empty string for values encoded by Pkl versions older than 0.30.
Name string
}
Class is the Go representation of `pkl.base#Class`.
type DataSize ¶
type DataSize struct {
// Value is the value of this data size.
Value float64
// Unit is the unit of this data size.
Unit DataSizeUnit
}
DataSize is the Go representation of `pkl.base#DataSize`.
It represents a quantity of binary data, represented by Value (e.g. 30.5) and Unit (e.g. Megabytes).
func (*DataSize) ToUnit ¶
func (d *DataSize) ToUnit(unit DataSizeUnit) DataSize
ToUnit converts this DataSize to the specified unit.
type DataSizeUnit ¶
type DataSizeUnit int64
DataSizeUnit represents unit of a DataSize.
func ToDataSizeUnit ¶
func ToDataSizeUnit(str string) (DataSizeUnit, error)
ToDataSizeUnit converts to a DataSizeUnit from its string representation.
func (DataSizeUnit) String ¶
func (d DataSizeUnit) String() string
String returns the string representation of this DataSizeUnit.
func (*DataSizeUnit) UnmarshalBinary ¶
func (d *DataSizeUnit) UnmarshalBinary(data []byte) error
type Duration ¶
type Duration struct {
Value float64
Unit DurationUnit
}
func (*Duration) GoDuration ¶
GoDuration returns the duration as a time.Duration.
type DurationUnit ¶
type DurationUnit int64
DurationUnit represents unit of a Duration.
func ToDurationUnit ¶
func ToDurationUnit(str string) (DurationUnit, error)
ToDurationUnit converts to a DurationUnit from its string representation.
func (DurationUnit) String ¶
func (d DurationUnit) String() string
String returns the string representation of this DataSizeUnit.
func (*DurationUnit) UnmarshalBinary ¶
func (d *DurationUnit) UnmarshalBinary(data []byte) error
type EvalError ¶
type EvalError struct {
ErrorOutput string
}
EvalError is an error that occurs during the normal evaluation of Pkl code.
This means that Pkl evaluation occurred, and the Pkl runtime produced an error.
type Evaluator ¶
type Evaluator interface {
// EvaluateModule evaluates the given module, and writes it to the value pointed by
// out.
//
// This method is designed to work with Go modules that have been code generated from Pkl
// sources.
EvaluateModule(ctx context.Context, source *ModuleSource, out any) error
// EvaluateOutputText evaluates the `output.text` property of the given module.
EvaluateOutputText(ctx context.Context, source *ModuleSource) (string, error)
// EvaluateOutputBytes evaluates the `output.bytes` property of the given module.
//
// Supported on Pkl 0.29 and higher.
EvaluateOutputBytes(ctx context.Context, source *ModuleSource) ([]byte, error)
// EvaluateOutputValue evaluates the `output.value` property of the given module,
// and writes to the value pointed by out.
EvaluateOutputValue(ctx context.Context, source *ModuleSource, out any) error
// EvaluateOutputFiles evaluates the `output.files` property of the given module, giving the text of each file.
EvaluateOutputFiles(ctx context.Context, source *ModuleSource) (map[string]string, error)
// EvaluateOutputFilesBytes evaluates the `output.files` property of the given module, giving the bytes of each file.
//
// Supported on Pkl 0.29 and higher.
EvaluateOutputFilesBytes(ctx context.Context, source *ModuleSource) (map[string][]byte, error)
// EvaluateExpression evaluates the provided expression on the given module source, and writes
// the result into the value pointed by out.
EvaluateExpression(ctx context.Context, source *ModuleSource, expr string, out any) error
// EvaluateExpressionRaw evaluates the provided module, and returns the underlying value's raw
// bytes.
//
// This is a low level API.
EvaluateExpressionRaw(ctx context.Context, source *ModuleSource, expr string) ([]byte, error)
// Close closes the evaluator and releases any underlying resources.
Close() error
// Closed tells if this evaluator is closed.
Closed() bool
}
Evaluator is an interface for evaluating Pkl modules.
func NewEvaluator ¶
func NewEvaluator(ctx context.Context, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
NewEvaluator returns an evaluator backed by a single EvaluatorManager. Its manager gets closed when the evaluator is closed.
If creating multiple evaluators, prefer using EvaluatorManager.NewEvaluator instead, because it lessens the overhead of each successive evaluator.
func NewEvaluatorWithCommand ¶
func NewEvaluatorWithCommand(ctx context.Context, pklCmd []string, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
NewEvaluatorWithCommand is like NewEvaluator, but also accepts the Pkl command to run.
The first element in pklCmd is treated as the command to run. Any additional elements are treated as arguments to be passed to the process. pklCmd is treated as the base command that spawns Pkl. For example, the below snippet spawns the command /opt/bin/pkl.
NewEvaluatorWithCommand(context.Background(), []string{"/opt/bin/pkl"})
If creating multiple evaluators, prefer using EvaluatorManager.NewEvaluator instead, because it lessens the overhead of each successive evaluator.
func NewProjectEvaluator ¶
func NewProjectEvaluator(ctx context.Context, projectBaseUrl *url.URL, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
NewProjectEvaluator is an easy way to create an evaluator that is configured by the specified projectBaseUrl.
It is similar to running the `pkl eval` or `pkl test` CLI command with a set `--project-dir`.
When using project dependencies, they must first be resolved using the `pkl project resolve` CLI command.
func NewProjectEvaluatorWithCommand ¶
func NewProjectEvaluatorWithCommand(ctx context.Context, projectBaseUrl *url.URL, pklCmd []string, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
NewProjectEvaluatorWithCommand is like NewProjectEvaluator, but also accepts the Pkl command to run.
The first element in pklCmd is treated as the command to run. Any additional elements are treated as arguments to be passed to the process. pklCmd is treated as the base command that spawns Pkl. For example, the below snippet spawns the command /opt/bin/pkl.
NewProjectEvaluatorWithCommand(context.Background(), "/path/to/my/project", []string{"/opt/bin/pkl"})
If creating multiple evaluators, prefer using EvaluatorManager.NewProjectEvaluator instead, because it lessens the overhead of each successive evaluator.
type EvaluatorManager ¶
type EvaluatorManager interface {
// Close closes the evaluator manager and all of its evaluators.
//
// If running Pkl as a child process, closes all evaluators as well as the child process.
// If calling into Pkl through the C API, close all existing evaluators.
Close() error
// GetVersion returns the version of Pkl backing this evaluator manager.
GetVersion() (string, error)
// NewEvaluator constructs an evaluator instance.
//
// If calling into Pkl as a child process, the first time NewEvaluator is called, this will
// start the child process.
NewEvaluator(ctx context.Context, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
// NewProjectEvaluator is an easy way to create an evaluator whose project directory is determined
// by `projectBaseUrl`.
// It loads the project from the `PklProject` and `PklProject.deps.json` files within `projectBaseUrl`.
//
// It is similar to running the `pkl eval` or `pkl test` CLI command with a set `--project-dir`.
//
// When using project dependencies, they must first be resolved using the `pkl project resolve`
// CLI command.
NewProjectEvaluator(ctx context.Context, projectBaseUrl *url.URL, opts ...func(options *EvaluatorOptions)) (Evaluator, error)
}
EvaluatorManager provides a way to minimize the overhead of multiple evaluators. For example, if calling into Pkl as a child process, using the manager will share the same process for all created evaluators. In contrast, constructing multiple evaluators through NewEvaluator will spawn one process per evaluator.
func NewEvaluatorManager ¶
func NewEvaluatorManager() EvaluatorManager
NewEvaluatorManager creates a new EvaluatorManager.
func NewEvaluatorManagerWithCommand ¶
func NewEvaluatorManagerWithCommand(pklCommand []string) EvaluatorManager
NewEvaluatorManagerWithCommand creates a new EvaluatorManager using the given pkl command.
The first element in pklCmd is treated as the command to run. Any additional elements are treated as arguments to be passed to the process. pklCmd is treated as the base command that spawns Pkl. For example, the below snippet spawns the command /opt/bin/pkl.
NewEvaluatorManagerWithCommand([]string{"/opt/bin/pkl"})
type EvaluatorOptions ¶
type EvaluatorOptions struct {
// Properties is the set of properties available to the `prop:` resource reader.
Properties map[string]string
// Env is the set of environment variables available to the `env:` resource reader.
Env map[string]string
// ModulePaths is the set of directories, ZIP archives, or JAR archives to search when
// resolving `modulepath`: resources and modules.
//
// This option must be non-emptyMirror if ModuleReaderModulePath or ResourceModulePath are used.
ModulePaths []string
// Logger is the logging interface for messages emitted by the Pkl evaluator.
Logger Logger
// OutputFormat controls the renderer to be used when rendering the `output.text`
// property of a module.
//
// The supported built-in values are:
// - `"json"`
// - `"jsonnet"`
// - `"pcf"` (default)
// - `"plist"`
// - `"properties"`
// - `"textproto"`
// - `"xml"`
// - `"yaml"`
// - `"pkl-binary"`
OutputFormat string
// AllowedModules defines URI patterns that determine which modules are permitted to be loaded and evaluated.
// Patterns are regular expressions in the dialect understood by [java.util.regex.Pattern].
//
// [java.util.regex.Pattern]: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html
AllowedModules []string
// AllowedResources defines URI patterns that determine which resources are permitted to be loaded and evaluated.
// Patterns are regular expressions in the dialect understood by [java.util.regex.Pattern].
//
// [java.util.regex.Pattern]: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html
AllowedResources []string
// ResourceReaders are the resource readers to be used by the evaluator.
ResourceReaders []ResourceReader
// ModuleReaders are the set of custom module readers to be used by the evaluator.
ModuleReaders []ModuleReader
// CacheDir is the directory where `package:` modules are cached.
//
// If empty, no caching is performed.
CacheDir string
// RootDir is the root directory for file-based reads within a Pkl program.
//
// Attempting to read past the root directory is an error.
RootDir string
// ProjectBaseURI sets the project base path for the evaluator.
//
// Setting this determines how Pkl resolves dependency notation imports.
// It causes Pkl to look for the resolved dependencies relative to this base URI,
// and load resolved dependencies from `PklProject.deps.json` within the base path represented.
//
// NOTE:
// Setting this option is not equivalent to setting the `--project-dir` flag from the CLI.
// When the `--project-dir` flag is set, the CLI will evaluate the PklProject file,
// and then applies any evaluator settings and dependencies set in the PklProject file
// for the main evaluation.
//
// In contrast, this option only determines how Pkl considers whether files are part of a
// project.
// It is meant to be set by lower level logic in Go that first evaluates the PklProject,
// which then configures EvaluatorOptions accordingly.
//
// To emulate the CLI's `--project-dir` flag, create an evaluator with NewProjectEvaluator,
// or EvaluatorManager.NewProjectEvaluator.
ProjectBaseURI string
// DeclaredProjectDependencies is set of dependencies available to modules within ProjectBaseURI.
//
// When importing dependencies, a PklProject.deps.json file must exist within ProjectBaseURI
// that contains the project's resolved dependencies.
DeclaredProjectDependencies *ProjectDependencies
// Settings for controlling how Pkl talks over HTTP(S).
//
// Added in Pkl 0.26.
// If the underlying Pkl does not support HTTP options, NewEvaluator will return with an error.
Http *Http
// ExternalModuleReaders registers external commands that implement module reader schemes.
//
// Added in Pkl 0.27.
// If the underlying Pkl does not support external readers, evaluation will fail when a registered scheme is used.
ExternalModuleReaders map[string]ExternalReader
// ExternalResourceReaders registers external commands that implement resource reader schemes.
//
// Added in Pkl 0.27.
// If the underlying Pkl does not support external readers, evaluation will fail when a registered scheme is used.
ExternalResourceReaders map[string]ExternalReader
// TraceMode dictates how Pkl will format messages logged by `trace()`.
//
// Added in Pkl 0.30.
// If the underlying Pkl does not support trace modes, this option will be ignored.
TraceMode TraceMode
}
EvaluatorOptions is the set of options available to control Pkl evaluation.
type ExternalReader ¶ added in v0.9.0
type ExternalReaderClient ¶ added in v0.9.0
type ExternalReaderClient interface {
// Run starts the ExternalReaderClient and blocks until the reader is closed by [ExternalReaderClient.Close] or the Pkl evaluator.
Run() error
// Close disconnects the ExternalReaderClient from the Pkl evaluator and cleans up any resources.
Close()
}
ExternalReaderClient is an interface for implementing [external readers](https://pkl-lang.org/main/current/language-reference/index.html#external-readers).
func NewExternalReaderClient ¶ added in v0.9.0
func NewExternalReaderClient(opts ...func(options *ExternalReaderClientOptions)) (ExternalReaderClient, error)
NewExternalReaderClient creates a new ExternalReaderClient.
type ExternalReaderClientOptions ¶ added in v0.9.0
type ExternalReaderClientOptions struct {
// RequestReader is the interface used to read messages from the Pkl evaluator. If omitted, os.Stdin will be used.
RequestReader io.Reader
// ResponseWriter is the interface used to send messages to the Pkl evaluator. If omitted, os.Stdout will be used.
ResponseWriter io.Writer
// ResourceReaders are the resource readers to be used by the evaluator.
ResourceReaders []ResourceReader
// ModuleReaders are the set of custom module readers to be used by the evaluator.
ModuleReaders []ModuleReader
}
ExternalReaderClientOptions is the set of options available to control ExternalReaderClients.
type Http ¶ added in v0.8.0
type Http struct {
// PEM format certificates to trust when making HTTP requests.
//
// If empty, Pkl will trust its own built-in certificates.
CaCertificates []byte
// Configuration of the HTTP proxy to use.
//
// If nil, uses the operating system's proxy configuration.
Proxy *Proxy
// HTTP URI rewrite rules.
//
// Added in Pkl 0.29.
// If the underlying Pkl does not support HTTP rewrites, NewEvaluator will return an error.
//
// Each key-value pair designates a source prefix to a target prefix.
// Each rewrite rule must start with `http://` or `https://`, and end with `/`.
//
// This option is often used for setting up package mirroring.
//
// The following example will rewrite a request https://example.com/foo/bar to https://my.other.website/foo/bar:
//
// Rewrites: map[string]string{
// "https://example.com/": "https://my.other.website/"
// }
Rewrites map[string]string
}
type IntSeq ¶
type IntSeq struct {
// Start is the start of this sequence.
Start int
// End is the end of this sequence.
End int
// Step is the common difference of successive members of this sequence.
Step int
}
IntSeq is the Go representation of `pkl.base#IntSeq`.
This value exists for compatibility. IntSeq should preferably be used as a way to describe logic within a Pkl program, and not passed as data between Pkl and Go.
type InternalError ¶
type InternalError struct {
// contains filtered or unexported fields
}
InternalError indicates that an unexpected error occurred.
func (*InternalError) Error ¶
func (r *InternalError) Error() string
func (*InternalError) Is ¶
func (r *InternalError) Is(err error) bool
Is implements the interface expected by errors.Is.
func (*InternalError) Unwrap ¶
func (r *InternalError) Unwrap() error
Unwrap implements the interface expected by errors.Unwrap.
type Logger ¶
type Logger interface {
// Trace logs the given message on level TRACE.
Trace(message string, frameUri string)
// Warn logs the given message on level WARN.
Warn(message string, frameUri string)
}
Logger is the interface for logging messages emitted by the Pkl evaluator.
To set a logger, register it on EvaluatorOptions.Logger when building an Evaluator.
type ModuleReader ¶
type ModuleReader interface {
Reader
// IsLocal tells if the resources represented by this reader is considered local to the runtime.
// A local module reader enables resolving triple-dot imports.
IsLocal() bool
// Read reads the string contents of this module.
Read(url url.URL) (string, error)
}
ModuleReader is a custom module reader for Pkl.
A ModuleReader registers the scheme that it is responsible for reading via Reader.Scheme. For example, a module reader can declare that it reads a resource at myscheme:myFile.pkl by returning "myscheme" when Reader.Scheme is called.
Modules are cached by Pkl for the lifetime of an Evaluator. Therefore, cacheing is not needed on the Go side as long as the same Evaluator is used.
Modules are read in Pkl via the import declaration:
import "myscheme:/myFile.pkl" import* "myscheme:/*.pkl" // only when the reader is globbable
Or via the import expression:
import("myscheme:myFile.pkl")
import*("myscheme:/myFile.pkl") // only when the reader is globbable
To provide a custom reader, register it on EvaluatorOptions.ModuleReaders when building an Evaluator.
type ModuleSource ¶
type ModuleSource struct {
// Uri is the URL of the resource.
Uri *url.URL
// Contents is the text contents of the resource, if any.
//
// If Contents is empty, it gets resolved by Pkl during evaluation time.
// If the scheme of the Uri matches a ModuleReader, it will be used to resolve the module.
Contents string
}
ModuleSource represents a source for Pkl evaluation.
func FileSource ¶
func FileSource(pathElems ...string) *ModuleSource
FileSource builds a ModuleSource, treating its arguments as paths on the file system.
If the provided path is not an absolute path, it will be resolved against the current working directory.
If multiple path arguments are provided, they are joined as multiple elements of the path.
It panics if the current working directory cannot be resolved.
func TextSource ¶
func TextSource(text string) *ModuleSource
TextSource builds a ModuleSource whose contents are the provided text.
func UriSource ¶
func UriSource(uri string) *ModuleSource
UriSource builds a ModuleSource using the input uri.
It panics if the uri is not valid.
type Object ¶
type Object struct {
// ModuleUri is the URI of the module that holds the definition of this object's class.
ModuleUri string
// Name is the qualified name of Pkl object's class.
//
// Example:
//
// "pkl.base#Dynamic"
Name string
// Properties is the set of name-value pairs in an Object.
Properties map[string]any
// Entries is the set of key-value pairs in an Object.
Entries map[any]any
// Elements is the set of items in an Object
Elements []any
}
Object is the Go representation of `pkl.base#Object`. It is a container for properties, entries, and elements.
type Pair ¶
type Pair[A any, B any] struct { // First is the first element of the pair. First A // Second is the second element of the pair. Second B }
Pair is the Go representation of `pkl.base#Pair`.
It is an ordered pair of elements.
type PathElement ¶
type PathElement interface {
// Name is the name of the path element.
Name() string
// IsDirectory tells if the path element is a directory.
IsDirectory() bool
}
PathElement is an element within a base URI.
For example, a PathElement with name "bar.txt" and is not a directory at base URI "file:///foo/" implies URI resource `file:///foo/bar.txt`.
func NewPathElement ¶
func NewPathElement(name string, isDirectory bool) PathElement
NewPathElement returns an instance of PathElement.
type Project ¶
type Project struct {
ProjectFileUri string `pkl:"projectFileUri"`
Package *ProjectPackage `pkl:"package"`
EvaluatorSettings ProjectEvaluatorSettings `pkl:"evaluatorSettings"`
Tests []string `pkl:"tests"`
Annotations []Object `pkl:"annotations"`
// internal field; use Project.Dependencies instead.
// values are either Project or ProjectRemoteDependency
RawDependencies map[string]any `pkl:"dependencies"`
// contains filtered or unexported fields
}
Project is the go representation of pkl.Project.
func LoadProject ¶
LoadProject loads a project definition from the specified path directory.
func LoadProjectFromEvaluator ¶
func LoadProjectFromEvaluator(context context.Context, ev Evaluator, projectSource *ModuleSource) (*Project, error)
LoadProjectFromEvaluator is like LoadProject, but uses the already provisioned evaluator, and loads the project from a ModuleSource rather than a path string.
func (*Project) Dependencies ¶
func (project *Project) Dependencies() *ProjectDependencies
type ProjectDependencies ¶
type ProjectDependencies struct {
LocalDependencies map[string]*ProjectLocalDependency
RemoteDependencies map[string]*ProjectRemoteDependency
}
type ProjectEvaluatorSettingExternalReader ¶ added in v0.9.0
type ProjectEvaluatorSettingExternalReader struct {
Executable string `pkl:"executable"`
Arguments []string `pkl:"arguments"`
}
ProjectEvaluatorSettingExternalReader is the Go representation of pkl.EvaluatorSettings.ExternalReader
type ProjectEvaluatorSettings ¶
type ProjectEvaluatorSettings struct {
ExternalProperties map[string]string `pkl:"externalProperties"`
Env map[string]string `pkl:"env"`
AllowedModules *[]string `pkl:"allowedModules"`
AllowedResources *[]string `pkl:"allowedResources"`
NoCache *bool `pkl:"noCache"`
ModulePath []string `pkl:"modulePath"`
Timeout Duration `pkl:"timeout"`
ModuleCacheDir string `pkl:"moduleCacheDir"`
RootDir string `pkl:"rootDir"`
Http *ProjectEvaluatorSettingsHttp `pkl:"http"`
Color string `pkl:"color"`
ExternalModuleReaders map[string]ProjectEvaluatorSettingExternalReader `pkl:"externalModuleReaders"`
ExternalResourceReaders map[string]ProjectEvaluatorSettingExternalReader `pkl:"externalResourceReaders"`
TraceMode *TraceMode `pkl:"traceMode"`
}
ProjectEvaluatorSettings is the Go representation of pkl.EvaluatorSettings
type ProjectEvaluatorSettingsHttp ¶ added in v0.8.0
type ProjectEvaluatorSettingsHttp struct {
Proxy *ProjectEvaluatorSettingsProxy `pkl:"proxy"`
Rewrites *map[string]string `pkl:"rewrites"`
}
ProjectEvaluatorSettingsHttp is the Go representation of pkl.EvaluatorSettings.Http
type ProjectEvaluatorSettingsProxy ¶ added in v0.8.0
type ProjectEvaluatorSettingsProxy struct {
Address *string `pkl:"address"`
NoProxy *[]string `pkl:"noProxy"`
}
ProjectEvaluatorSettingsProxy is the Go representation of pkl.EvaluatorSettings.Proxy
type ProjectLocalDependency ¶
type ProjectLocalDependency struct {
PackageUri string
ProjectFileUri string
Dependencies *ProjectDependencies
}
type ProjectPackage ¶
type ProjectPackage struct {
Name string `pkl:"name"`
BaseUri string `pkl:"baseUri"`
Version string `pkl:"version"`
PackageZipUrl string `pkl:"packageZipUrl"`
Description string `pkl:"description"`
Authors []string `pkl:"authors"`
Website string `pkl:"website"`
Documentation string `pkl:"documentation"`
SourceCode string `pkl:"sourceCode"`
SourceCodeUrlScheme string `pkl:"sourceCodeUrlScheme"`
License string `pkl:"license"`
LicenseText string `pkl:"licenseText"`
IssueTracker string `pkl:"issueTracker"`
ApiTests []string `pkl:"apiTests"`
Exclude []string `pkl:"exclude"`
Uri string `pkl:"uri"`
}
ProjectPackage is the go representation of pkl.Project#Package.
type ProjectRemoteDependency ¶
type Proxy ¶ added in v0.8.0
type Proxy struct {
// The proxy to use for HTTP(S) connections.
//
// Only HTTP proxies are supported.
// The address must start with "http://", and cannot contain anything other than a host and an optional port.
//
// Example:
//
// Address: "http://my.proxy.example.com:5080"
Address string
// Hosts to which all connections should bypass a proxy.
//
// Values can be either hostnames, or IP addresses.
// IP addresses can optionally be provided using [CIDR notation].
//
// The only wildcard is `"*"`, which disables all proxying.
//
// A hostname matches all subdomains.
// For example, `example.com` matches `foo.example.com`, but not `fooexample.com`.
// A hostname that is prefixed with a dot matches the hostname itself,
// so `.example.com` matches `example.com`.
//
// Optionally, a port can be specified.
// If a port is omitted, all ports are matched.
//
// Example:
//
// NoProxy: []string{
// "127.0.0.1",
// "169.254.0.0/16",
// "example.com",
// "localhost:5050",
// }
//
// [CIDR notation]: https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation
NoProxy []string
}
type Reader ¶
type Reader interface {
// Scheme returns the scheme part of the URL that this reader can read.
// The value should be the URI scheme up to (not including) ":"
Scheme() string
// IsGlobbable tells if this reader supports globbing via Pkl's `import*` and `glob*` keywords
IsGlobbable() bool
// HasHierarchicalUris tells if the URIs handled by this reader are hierarchical.
// Hierarchical URIs are URIs that have hierarchy elements like host, origin, query, and
// fragment.
//
// A hierarchical URI must start with a "/" in its scheme specific part. For example, consider
// the following two URIS:
//
// flintstone:/persons/fred.pkl
// flintstone:persons/fred.pkl
//
// The first URI conveys name "fred.pkl" within parent "/persons/". The second URI
// conveys the name "persons/fred.pkl" with no hierarchical meaning.
HasHierarchicalUris() bool
// ListElements returns the list of elements at a specified path.
// If HasHierarchicalUris is false, path will be empty and ListElements should return all
// available values.
//
// This method is only called if it is hierarchical and local, or if it is globbable.
ListElements(url url.URL) ([]PathElement, error)
}
Reader is the base implementation shared by a ResourceReader and a ModuleReader.
type Regex ¶
type Regex struct {
// Pattern is the regex pattern expression in string form.
Pattern string
}
Regex is the Go representation of `pkl.base#Regex`.
Regular expressions in Pkl are [Java regular expressions](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) and may not be compatible with [Go's RE2](https://github.com/google/re2/wiki/Syntax) syntax.
type ResourceReader ¶
type ResourceReader interface {
Reader
// Read reads the byte contents of this resource.
Read(url url.URL) ([]byte, error)
}
ResourceReader is a custom resource reader for Pkl.
A ResourceReader registers the scheme that it is responsible for reading via Reader.Scheme. For example, a resource reader can declare that it reads a resource at secrets:MY_SECRET by returning "secrets" when Reader.Scheme is called.
Resources are cached by Pkl for the lifetime of an Evaluator. Therefore, cacheing is not needed on the Go side as long as the same Evaluator is used.
Resources are read via the following Pkl expressions:
read("myscheme:myresourcee")
read?("myscheme:myresource")
read*("myscheme:pattern*") // only if the resource is globabble
To provide a custom reader, register it on EvaluatorOptions.ResourceReaders when building an Evaluator.
type TypeAlias ¶
type TypeAlias struct {
// ModuleUri of the Pkl module containing the typealias.
// Will be an empty string for values encoded by Pkl versions older than 0.30.
ModuleUri string
// Name of the Pkl typealias.
// Will be an empty string for values encoded by Pkl versions older than 0.30.
Name string
}
TypeAlias is the Go representation of `pkl.base#TypeAlias`.
Source Files
¶
- atomic.go
- decode_map.go
- decode_primitives.go
- decode_slice.go
- decode_struct.go
- decoder.go
- errors.go
- evaluator.go
- evaluator_exec.go
- evaluator_manager.go
- evaluator_manager_exec.go
- evaluator_manager_exec_unix.go
- evaluator_options.go
- external_reader.go
- fs_reader.go
- logger.go
- module_source.go
- project.go
- reader.go
- schema.go
- unmarshal.go
- values.go
Directories
¶
| Path | Synopsis |
|---|---|
|
test_fixtures
|
|
|
gen/any
Code generated from Pkl module `any`.
|
Code generated from Pkl module `any`. |
|
gen/classes
Code generated from Pkl module `classes`.
|
Code generated from Pkl module `classes`. |
|
gen/collections
Code generated from Pkl module `collections`.
|
Code generated from Pkl module `collections`. |
|
gen/datasize
Code generated from Pkl module `datasize`.
|
Code generated from Pkl module `datasize`. |
|
gen/duration
Code generated from Pkl module `duration`.
|
Code generated from Pkl module `duration`. |
|
gen/dynamic
Code generated from Pkl module `dynamic`.
|
Code generated from Pkl module `dynamic`. |
|
gen/nullables
Code generated from Pkl module `nullables`.
|
Code generated from Pkl module `nullables`. |
|
gen/primitives
Code generated from Pkl module `primitives`.
|
Code generated from Pkl module `primitives`. |
|
gen/types
Code generated from Pkl module `types`.
|
Code generated from Pkl module `types`. |
|
gen/unions
Code generated from Pkl module `unions`.
|
Code generated from Pkl module `unions`. |
|
gen/unions/number
Code generated from Pkl module `unions`.
|
Code generated from Pkl module `unions`. |
|
gen/unions/othernumbers
Code generated from Pkl module `unions`.
|
Code generated from Pkl module `unions`. |
|
gen/unknown_type
Code generated from Pkl module `unknown_type`.
|
Code generated from Pkl module `unknown_type`. |