...

Package load

import "cuelang.org/go/cue/load"
Overview
Index
Examples

Overview ▾

Package load loads CUE instances.

Example

Code:

// Load the package "example" relative to the directory testdata/testmod.
// Akin to loading via: cd testdata/testmod && cue export ./example
insts := load.Instances([]string{"./example"}, &load.Config{
    Dir: filepath.Join("testdata", "testmod"),
    Env: []string{}, // or nil to use os.Environ
})

// testdata/testmod/example just has one file without any build tags,
// so we get a single instance as a result.
fmt.Println("Number of instances:", len(insts))
inst := insts[0]
if err := inst.Err; err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Instance module:", inst.Module)
fmt.Println("Instance import path:", inst.ImportPath)
fmt.Println()

// Inspect the syntax trees.
fmt.Println("Source files:")
for _, file := range inst.Files {
    fmt.Println(filepath.Base(file.Filename), "with", len(file.Decls), "declarations")
}
fmt.Println()

// Build the instance into a value.
// We can also use BuildInstances for many instances at once.
ctx := cuecontext.New()
val := ctx.BuildInstance(inst)
if err := val.Err(); err != nil {
    fmt.Println(err)
    return
}

// Inspect the contents of the value, such as one string field.
fieldStr, err := val.LookupPath(cue.MakePath(cue.Str("output"))).String()
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Field string:", fieldStr)

Output:

Number of instances: 1
Instance module: mod.test/test
Instance import path: mod.test/test/example

Source files:
example.cue with 3 declarations

Field string: Hello Joe

Example (ExternalModules)

Code:

// setUpModulesExample starts a temporary in-memory registry,
// populates it with an example module, and sets CUE_REGISTRY
// to refer to it
env, cleanup := setUpModulesExample()
defer cleanup()

insts := load.Instances([]string{"."}, &load.Config{
    Dir: filepath.Join("testdata", "testmod-external"),
    Env: env, // or nil to use os.Environ
})
inst := insts[0]
if err := inst.Err; err != nil {
    fmt.Println(err)
    return
}
ctx := cuecontext.New()
val := ctx.BuildInstance(inst)
if err := val.Err(); err != nil {
    fmt.Println(err)
    return
}

// Inspect the contents of the value, such as one string field.
fieldStr, err := val.LookupPath(cue.MakePath(cue.Str("output"))).String()
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println("Field string:", fieldStr)

Output:

Field string: hello, world

Constants

FromArgsUsage is a partial usage message that applications calling FromArgs may wish to include in their -help output.

Some of the aspects of this documentation, like flags and handling '--' need to be implemented by the tools.

const FromArgsUsage = `
<args> is a list of arguments denoting a set of instances of the form:

   <package>* <file_args>*

1. A list of source files

   CUE files are parsed, loaded and unified into a single instance. All files
   must have the same package name.

   Data files, like YAML or JSON, are handled in one of two ways:

   a. Explicitly mapped into a single CUE namespace, using the --path, --files
      and --list flags. In this case these are unified into a single instance
      along with any other CUE files.

   b. Treated as a stream of data elements that each is optionally unified with
      a single instance, which either consists of the other CUE files specified
       on the command line or a single package.

   By default, the format of files is derived from the file extension.
   This behavior may be modified with file arguments of the form <qualifiers>:
   For instance,

      cue eval foo.cue json: bar.data

   indicates that the bar.data file should be interpreted as a JSON file.
   A qualifier applies to all files following it until the next qualifier.

   The following qualifiers are available:

      encodings
      cue           CUE definitions and data
      json          JSON data, one value only
      jsonl         newline-separated JSON values
      yaml          a YAML file, may contain a stream
      proto         Protobuf definitions

      interpretations
      jsonschema   data encoding describes JSON Schema
      openapi      data encoding describes Open API

      formats
      data         output as -- or only accept -- data
      graph        data allowing references or anchors
      schema       output as schema; defaults JSON files to JSON Schema
      def          full definitions, including documentation

2. A list of relative directories to denote a package instance.

   Each directory matching the pattern is loaded as a separate instance.
   The instance contains all files in this directory and ancestor directories,
   up to the module root, with the same package name. The package name must
   be either uniquely determined by the files in the given directory, or
   explicitly defined using a package name qualifier. For instance, ./...:foo
   selects all packages named foo in the any subdirectory of the current
   working directory.

3. An import path referring to a directory within the current module

   All CUE files in that directory, and all the ancestor directories up to the
   module root (if applicable), with a package name corresponding to the base
   name of the directory or the optional explicit package name are loaded into
   a single instance.

   Examples, assume a module name of acme.org/root:
      mod.test/foo   package in cue.mod
      ./foo             package corresponding to foo directory
      .:bar             package in current directory with package name bar
`

func DefaultTagVars

func DefaultTagVars() map[string]TagVar

DefaultTagVars creates a new map with a set of supported injection variables.

func GenPath

func GenPath(root string) string

GenPath reports the directory in which to store generated files.

func Instances

func Instances(args []string, c *Config) []*build.Instance

Instances returns the instances named by the command line arguments 'args'. If errors occur trying to load an instance it is returned with Incomplete set. Errors directly related to loading the instance are recorded in this instance, but errors that occur loading dependencies are recorded in these dependencies.

type Config

A Config configures load behavior.

type Config struct {

    // Context specifies the context for the load operation.
    Context *build.Context

    // A Module is a collection of packages and instances that are within the
    // directory hierarchy rooted at the module root. The module root can be
    // marked with a cue.mod file.
    ModuleRoot string

    // Module specifies the module prefix. If not empty, this value must match
    // the module field of an existing cue.mod file.
    Module string

    // Package defines the name of the package to be loaded. If this is not set,
    // the package must be uniquely defined from its context. Special values:
    //    _    load files without a package
    //    *    load all packages. Files without packages are loaded
    //         in the _ package.
    Package string

    // Dir is the base directory for import path resolution.
    // For example, it is used to determine the main module,
    // and rooted import paths starting with "./" are relative to it.
    // If Dir is empty, the current directory is used.
    Dir string

    // Tags defines boolean tags or key-value pairs to select files to build
    // or be injected as values in fields.
    //
    // Each string is of the form
    //
    //     key [ "=" value ]
    //
    // where key is a valid CUE identifier and value valid CUE scalar.
    //
    // The Tags values are used to both select which files get included in a
    // build and to inject values into the AST.
    //
    //
    // File selection
    //
    // Files with an attribute of the form @if(expr) before a package clause
    // are conditionally included if expr resolves to true, where expr refers to
    // boolean values in Tags.
    //
    // It is an error for a file to have more than one @if attribute or to
    // have a @if attribute without or after a package clause.
    //
    //
    // Value injection
    //
    // The Tags values are also used to inject values into fields with a
    // @tag attribute.
    //
    // For any field of the form
    //
    //    field: x @tag(key)
    //
    // and Tags value for which the name matches key, the field will be
    // modified to
    //
    //   field: x & "value"
    //
    // By default, the injected value is treated as a string. Alternatively, a
    // "type" option of the @tag attribute allows a value to be interpreted as
    // an int, number, or bool. For instance, for a field
    //
    //    field: x @tag(key,type=int)
    //
    // an entry "key=2" modifies the field to
    //
    //    field: x & 2
    //
    // Valid values for type are "int", "number", "bool", and "string".
    //
    // A @tag attribute can also define shorthand values, which can be injected
    // into the fields without having to specify the key. For instance, for
    //
    //    environment: string @tag(env,short=prod|staging)
    //
    // the Tags entry "prod" sets the environment field to the value "prod".
    // This is equivalent to a Tags entry of "env=prod".
    //
    // The use of @tag does not preclude using any of the usual CUE constraints
    // to limit the possible values of a field. For instance
    //
    //    environment: "prod" | "staging" @tag(env,short=prod|staging)
    //
    // ensures the user may only specify "prod" or "staging".
    Tags []string

    // TagVars defines a set of key value pair the values of which may be
    // referenced by tags.
    //
    // Use DefaultTagVars to get a pre-loaded map with supported values.
    TagVars map[string]TagVar

    // Include all files, regardless of tags.
    AllCUEFiles bool

    // Deprecated: use Tags
    BuildTags []string

    // If Tests is set, the loader includes not just the packages
    // matching a particular pattern but also any related test packages.
    Tests bool

    // If Tools is set, the loader includes tool files associated with
    // a package.
    Tools bool

    // If DataFiles is set, the loader includes entries for directories that
    // have no CUE files, but have recognized data files that could be converted
    // to CUE.
    DataFiles bool

    // StdRoot specifies an alternative directory for standard libraries.
    // This is mostly used for bootstrapping.
    StdRoot string

    // ParseFile is called to read and parse each file when preparing a
    // package's syntax tree. It must be safe to call ParseFile simultaneously
    // from multiple goroutines. If ParseFile is nil, the loader will uses
    // parser.ParseFile.
    //
    // ParseFile should parse the source from src and use filename only for
    // recording position information.
    //
    // An application may supply a custom implementation of ParseFile to change
    // the effective file contents or the behavior of the parser, or to modify
    // the syntax tree.
    ParseFile func(name string, src interface{}) (*ast.File, error)

    // Overlay provides a mapping of absolute file paths to file contents.  If
    // the file with the given path already exists, the parser will use the
    // alternative file contents provided by the map.
    Overlay map[string]Source

    // Stdin defines an alternative for os.Stdin for the file "-". When used,
    // the corresponding build.File will be associated with the full buffer.
    Stdin io.Reader

    // Registry is used to fetch CUE module dependencies.
    //
    // When nil, if the modules experiment is enabled
    // (CUE_EXPERIMENT=modules), [modconfig.NewRegistry]
    // will be used to create a registry instance using the
    // usual cmd/cue conventions for environment variables
    // (but see the Env field below).
    //
    // THIS IS EXPERIMENTAL. API MIGHT CHANGE.
    Registry modconfig.Registry

    // Env provides environment variables for use in the configuration.
    // Currently this is only used in the construction of the Registry
    // value (see above). If this is nil, the current process's environment
    // will be used.
    Env []string
    // contains filtered or unexported fields
}

type MultiplePackageError

MultiplePackageError describes an attempt to build a package composed of CUE files from different packages.

type MultiplePackageError struct {
    Dir      string   // directory containing files
    Packages []string // package names found
    Files    []string // corresponding files: Files[i] declares package Packages[i]
}

func (*MultiplePackageError) Error

func (e *MultiplePackageError) Error() string

func (*MultiplePackageError) InputPositions

func (e *MultiplePackageError) InputPositions() []token.Pos

func (*MultiplePackageError) Msg

func (e *MultiplePackageError) Msg() (string, []interface{})

func (*MultiplePackageError) Path

func (e *MultiplePackageError) Path() []string

func (*MultiplePackageError) Position

func (e *MultiplePackageError) Position() token.Pos

type NoFilesError

NoFilesError is the error used by Import to describe a directory containing no usable source files. (It may still contain tool files, files hidden by build tags, and so on.)

type NoFilesError struct {
    Package *build.Instance
    // contains filtered or unexported fields
}

func (*NoFilesError) Error

func (e *NoFilesError) Error() string

TODO(localize)

func (*NoFilesError) InputPositions

func (e *NoFilesError) InputPositions() []token.Pos

func (*NoFilesError) Msg

func (e *NoFilesError) Msg() (string, []interface{})

TODO(localize)

func (*NoFilesError) Path

func (e *NoFilesError) Path() []string

func (*NoFilesError) Position

func (e *NoFilesError) Position() token.Pos

type PackageError

A PackageError describes an error loading information about a package.

type PackageError struct {
    ImportStack    []string  // shortest path from package named on command line to this one
    Pos            token.Pos // position of error
    errors.Message           // the error itself
    IsImportCycle  bool      // the error is an import cycle
}

func (*PackageError) Error

func (p *PackageError) Error() string

TODO(localize)

func (*PackageError) InputPositions

func (p *PackageError) InputPositions() []token.Pos

func (*PackageError) Path

func (p *PackageError) Path() []string

func (*PackageError) Position

func (p *PackageError) Position() token.Pos

type Source

A Source represents file contents.

type Source interface {
    // contains filtered or unexported methods
}

func FromBytes

func FromBytes(b []byte) Source

FromBytes creates a Source from the given bytes. The contents are not copied and should not be modified.

func FromFile

func FromFile(f *ast.File) Source

FromFile creates a Source from the given *ast.File. The file should not be modified. It is assumed the file is error-free.

func FromString

func FromString(s string) Source

FromString creates a Source from the given string.

type TagVar

A TagVar represents an injection variable.

type TagVar struct {
    // Func returns an ast for a tag variable. It is only called once
    // per evaluation of a configuration.
    Func func() (ast.Expr, error)

    // Description documents this TagVar.
    Description string
}