pkl

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2024 License: Apache-2.0 Imports: 24 Imported by: 32

Documentation

Overview

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ===----------------------------------------------------------------------===//

Index

Constants

View Source
const (
	Nanosecond  DurationUnit = 1
	Microsecond              = Nanosecond * 1000
	Millisecond              = Microsecond * 1000
	Second                   = Millisecond * 1000
	Minute                   = Second * 60
	Hour                     = Minute * 60
	Day                      = Hour * 24
)
View Source
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
)
View Source
const StructTag = "pkl"

Variables

View Source
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.

View Source
var NoopLogger = NewLogger(io.Discard)

NoopLogger is a logger that discards all messages.

View Source
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.

View Source
var StderrLogger = NewLogger(os.Stdout)

StderrLogger is a logger that writes to standard error.

View Source
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.

View Source
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.

View Source
var WithDefaultCacheDir = func(opts *EvaluatorOptions) {
	dirname, err := os.UserHomeDir()
	if err != nil {
		panic(err)
	}
	opts.CacheDir = path.Join(dirname, ".pkl/cache")
}

WithDefaultCacheDir sets the cache directory to Pkl's default location. It panics if the home directory cannot be determined.

View Source
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`.

View Source
var WithModuleReader = func(reader ModuleReader) func(opts *EvaluatorOptions) {
	return func(opts *EvaluatorOptions) {
		opts.ModuleReaders = append(opts.ModuleReaders, reader)
		opts.AllowedModules = append(opts.AllowedModules, reader.Scheme())
	}
}

WithModuleReader sets up the given module reader, and also adds the reader's scheme to the] evaluator's allowed modules list.

View Source
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.

View Source
var WithProject = func(project *Project) func(opts *EvaluatorOptions) {
	return func(opts *EvaluatorOptions) {
		WithProjectEvaluatorSettings(project)(opts)
		WithProjectDependencies(project)(opts)
	}
}
View Source
var WithProjectDependencies = func(project *Project) func(opts *EvaluatorOptions) {
	return func(opts *EvaluatorOptions) {
		opts.ProjectDir = strings.TrimPrefix(strings.TrimSuffix(project.ProjectFileUri, "/PklProject"), "file://")
		opts.DeclaredProjectDepenedencies = project.Dependencies()
	}
}

WithProjectDependencies configures the evaluator with dependencies from the specified project.

View Source
var WithProjectEvaluatorSettings = func(project *Project) func(opts *EvaluatorOptions) {
	return func(opts *EvaluatorOptions) {
		evaluatorSettings := project.EvaluatorSetings
		if evaluatorSettings == nil {
			return
		}
		opts.Properties = evaluatorSettings.ExternalProperties
		opts.Env = evaluatorSettings.Env
		opts.AllowedModules = evaluatorSettings.AllowedModules
		opts.AllowedResources = evaluatorSettings.AllowedResources
		if evaluatorSettings.NoCache != nil && *evaluatorSettings.NoCache {
			opts.CacheDir = ""
		} else {
			opts.CacheDir = evaluatorSettings.ModuleCacheDir
		}
		opts.RootDir = evaluatorSettings.RootDir
	}
}

WithProjectEvaluatorSettings configures the evaluator with settings from the given ProjectEvaluatorSettings.

View Source
var WithResourceReader = func(reader ResourceReader) func(opts *EvaluatorOptions) {
	return func(opts *EvaluatorOptions) {
		opts.ResourceReaders = append(opts.ResourceReaders, reader)
		opts.AllowedResources = append(opts.AllowedResources, 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

func FormatLogMessage(level, message, frameUri string) string

FormatLogMessage returns the default formatter for log messages.

func RegisterMapping

func RegisterMapping(name string, value any)

RegisterMapping associates the type given the Pkl name to the corresponding Go type.

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal parses Pkl-encoded data and stores the result into the value pointed by v.

This is a low-level API. Most users should be using Evaluator.Evaluate instead.

The following struct tags are supported:

pkl:"Field"     Overrides the field's name to map to.

Types

type Checksums

type Checksums struct {
	Sha256 string `pkl:"sha256"`
}

type Class

type Class struct{}

Class is the Go representation of `pkl.base#Class`.

This value is purposefully opaque, and only exists for compatibilty.

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) String

func (d *DataSize) String() string

String implementers the fmt.Stringer interface for DataSize.

func (*DataSize) ToUnit

func (d *DataSize) ToUnit(unit DataSizeUnit) DataSize

ToUnit converts this DataSize to the specified unit.

type DataSizeUnit

type DataSizeUnit int

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

func (d *Duration) GoDuration() time.Duration

GoDuration returns the duration as a time.Duration.

type DurationUnit

type DurationUnit int

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.

func (*EvalError) Error

func (r *EvalError) Error() string

func (*EvalError) Is

func (r *EvalError) Is(err error) bool

Is implements the interface expected by errors.Is.

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)

	// 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.
	EvaluateOutputFiles(ctx context.Context, source *ModuleSource) (map[string]string, 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 interface{}) 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, projectDir string, opts ...func(options *EvaluatorOptions)) (Evaluator, error)

NewProjectEvaluator is an easy way to create an evaluator that is configured by the specified projectDir.

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, projectDir string, 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(), []string{"/opt/bin/pkl"}, "/path/to/my/project")

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 that is configured by the specified
	// projectDir.
	//
	// 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, projectDir string, 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"`
	OutputFormat string

	// AllowedModules is the URI patterns that determine which modules can be loaded and evaluated.
	AllowedModules []string

	// AllowedResources is the URI patterns that determine which resources can be loaded and evaluated.
	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 cacheing 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

	// ProjectDir is the project directory for the evaluator.
	//
	// Setting this determines how Pkl resolves dependency notation imports.
	// It causes Pkl to look for the resolved dependencies relative to this directory,
	// and load resolved dependencies from a PklProject.deps.json file inside this directory.
	//
	// 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.
	ProjectDir string

	// DeclaredProjectDepenedencies is set of dependencies available to modules within ProjectDir.
	//
	// When importing dependencies, a PklProject.deps.json file must exist within ProjectDir
	// that contains the project's resolved dependencies.
	DeclaredProjectDepenedencies *ProjectDependencies
}

EvaluatorOptions is the set of options available to control Pkl evaluation.

type IntSeq

type IntSeq struct {
	// Start is the start of this seqeunce.
	Start int

	// End is the end of this seqeunce.
	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 preferrably 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 occured.

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.

func NewLogger

func NewLogger(out io.Writer) Logger

NewLogger builds a logger that writes to the provided output stream, using the default formatting.

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"`
	EvaluatorSetings *ProjectEvaluatorSettings `pkl:"evaluatorSettings"`
	Tests            []string                  `pkl:"tests"`

	// 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

func LoadProject(context context.Context, path string) (*Project, error)

LoadProject loads a project definition from the specified path directory.

func LoadProjectFromEvaluator

func LoadProjectFromEvaluator(context context.Context, ev Evaluator, path string) (*Project, error)

func (*Project) Dependencies

func (project *Project) Dependencies() *ProjectDependencies

type ProjectDependencies

type ProjectDependencies struct {
	LocalDependencies map[string]*ProjectLocalDependency

	RemoteDependencies map[string]*ProjectRemoteDependency
}

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"`
}

ProjectEvaluatorSettings is the Go representation of pkl.Project#EvaluatorSettings

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 ProjectRemoteDependency struct {
	PackageUri string     `pkl:"uri"`
	Checksums  *Checksums `pkl:"checksums"`
}

type Reader

type Reader interface {
	// Scheme returns the scheme part of the URL that this reader can read.
	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`.

Regulard experssions in Pkl are

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{}

TypeAlias is the Go representation of `pkl.base#TypeAlias`.

This value is purposefully opaque, and only exists for compatibilty.

Directories

Path Synopsis
===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc.
===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc.
msgapi
===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc.
===----------------------------------------------------------------------===// Copyright © 2024 Apple Inc.
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/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`.

Jump to

Keyboard shortcuts

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