Package hcl contains the main modelling types and general utility functions for HCL.
For a simple entry point into HCL, see the package in the subdirectory "hclsimple", which has an opinionated function Decode that can decode HCL configurations in either native HCL syntax or JSON syntax into a Go struct type:
package main import ( "log" "github.com/hashicorp/hcl/v2/hclsimple" ) type Config struct { LogLevel string `hcl:"log_level"` } func main() { var config Config err := hclsimple.DecodeFile("config.hcl", nil, &config) if err != nil { log.Fatalf("Failed to load configuration: %s", err) } log.Printf("Configuration is %#v", config) }
If your application needs more control over the evaluation of the configuration, you can use the functions in the subdirectories hclparse, gohcl, hcldec, etc. Splitting the handling of configuration into multiple phases allows for advanced patterns such as allowing expressions in one part of the configuration to refer to data defined in another part.
This section is empty.
InitialPos is a suitable position to use to mark the start of a file.
AbsTraversalForExpr attempts to interpret the given expression as an absolute traversal, or returns error diagnostic(s) if that is not possible for the given expression.
A particular Expression implementation can support this function by offering a method called AsTraversal that takes no arguments and returns either a valid absolute traversal or nil to indicate that no traversal is possible. Alternatively, an implementation can support UnwrapExpression to delegate handling of this function to a wrapped Expression object.
In most cases the calling application is interested in the value that results from an expression, but in rarer cases the application needs to see the name of the variable and subsequent attributes/indexes itself, for example to allow users to give references to the variables themselves rather than to their values. An implementer of this function should at least support attribute and index steps.
DiagnosticExtra attempts to retrieve an "extra value" of type T from the given diagnostic, if either the diag.Extra field directly contains a value of that type or the value implements DiagnosticExtraUnwrapper and directly or indirectly returns a value of that type.
Type T should typically be an interface type, so that code which generates diagnostics can potentially return different implementations of the same interface dynamically as needed.
If a value of type T is found, returns that value and true to indicate success. Otherwise, returns the zero value of T and false to indicate failure.
ExprAsKeyword attempts to interpret the given expression as a static keyword, returning the keyword string if possible, and the empty string if not.
A static keyword, for the sake of this function, is a single identifier. For example, the following attribute has an expression that would produce the keyword "foo":
example = foo
This function is a variant of AbsTraversalForExpr, which uses the same interface on the given expression. This helper constrains the result further by requiring only a single root identifier.
This function is intended to be used with the following idiom, to recognize situations where one of a fixed set of keywords is required and arbitrary expressions are not allowed:
switch hcl.ExprAsKeyword(expr) { case "allow": // (take suitable action for keyword "allow") case "deny": // (take suitable action for keyword "deny") default: diags = append(diags, &hcl.Diagnostic{ // ... "invalid keyword" diagnostic message ... }) }
The above approach will generate the same message for both the use of an unrecognized keyword and for not using a keyword at all, which is usually reasonable if the message specifies that the given value must be a keyword from that fixed list.
Note that in the native syntax the keywords "true", "false", and "null" are recognized as literal values during parsing and so these reserved words cannot not be accepted as keywords by this function.
Since interpreting an expression as a keyword bypasses usual expression evaluation, it should be used sparingly for situations where e.g. one of a fixed set of keywords is used in a structural way in a special attribute to affect the further processing of a block.
ExprCall tests if the given expression is a function call and, if so, extracts the function name and the expressions that represent the arguments. If the given expression is not statically a function call, error diagnostics are returned.
A particular Expression implementation can support this function by offering a method called ExprCall that takes no arguments and returns *StaticCall. This method should return nil if a static call cannot be extracted. Alternatively, an implementation can support UnwrapExpression to delegate handling of this function to a wrapped Expression object.
ExprList tests if the given expression is a static list construct and, if so, extracts the expressions that represent the list elements. If the given expression is not a static list, error diagnostics are returned.
A particular Expression implementation can support this function by offering a method called ExprList that takes no arguments and returns []Expression. This method should return nil if a static list cannot be extracted. Alternatively, an implementation can support UnwrapExpression to delegate handling of this function to a wrapped Expression object.
ExprMap tests if the given expression is a static map construct and, if so, extracts the expressions that represent the map elements. If the given expression is not a static map, error diagnostics are returned.
A particular Expression implementation can support this function by offering a method called ExprMap that takes no arguments and returns []KeyValuePair. This method should return nil if a static map cannot be extracted. Alternatively, an implementation can support UnwrapExpression to delegate handling of this function to a wrapped Expression object.
RelTraversalForExpr is similar to AbsTraversalForExpr but it returns a relative traversal instead. Due to the nature of HCL expressions, the first element of the returned traversal is always a TraverseAttr, and then it will be followed by zero or more other expressions.
Any expression accepted by AbsTraversalForExpr is also accepted by RelTraversalForExpr.
Attribute represents an attribute from within a body.
type AttributeSchema struct { Name string Required bool }
AttributeSchema represents the requirements for an attribute, and is used for matching attributes within bodies.
Attributes is a set of attributes keyed by their names.
Block represents a nested block within a Body.
type BlockHeaderSchema struct { }
BlockHeaderSchema represents the shape of a block header, and is used for matching blocks within bodies.
Blocks is a sequence of Block.
ByType transforms the receiving block sequence into a map from type name to block sequences of only that type.
OfType filters the receiving block sequence by block type name, returning a new block sequence including only the blocks of the requested type.
type Body ¶Body is a container for attributes and blocks. It serves as the primary unit of hierarchical structure within configuration.
The content of a body cannot be meaningfully interpreted without a schema, so Body represents the raw body content and has methods that allow the content to be extracted in terms of a given schema.
func EmptyBody ¶EmptyBody returns a body with no content. This body can be used as a placeholder when a body is required but no body content is available.
MergeBodies is like MergeFiles except it deals directly with bodies, rather than with entire files.
MergeFiles combines the given files to produce a single body that contains configuration from all of the given files.
The ordering of the given files decides the order in which contained elements will be returned. If any top-level attributes are defined with the same name across multiple files, a diagnostic will be produced from the Content and PartialContent methods describing this error in a user-friendly way.
type BodyContent ¶BodyContent is the result of applying a BodySchema to a Body.
type BodySchema ¶BodySchema represents the desired shallow structure of a body.
Diagnostic represents information to be presented to a user about an error or anomaly in parsing or evaluating configuration.
error implementation, so that diagnostics can be returned via APIs that normally deal in vanilla Go errors.
This presents only minimal context about the error, for compatibility with usual expectations about how errors will present as strings.
type DiagnosticExtraUnwrapper interface { UnwrapDiagnosticExtra() interface{} }
DiagnosticExtraUnwrapper is an interface implemented by values in the Extra field of Diagnostic when they are wrapping another "Extra" value that was generated downstream.
Diagnostic recipients which want to examine "Extra" values to sniff for particular types of extra data can either type-assert this interface directly and repeatedly unwrap until they recieve nil, or can use the helper function DiagnosticExtra.
type DiagnosticSeverity int
DiagnosticSeverity represents the severity of a diagnostic.
A DiagnosticWriter emits diagnostics somehow.
NewDiagnosticTextWriter creates a DiagnosticWriter that writes diagnostics to the given writer as formatted text.
It is designed to produce text appropriate to print in a monospaced font in a terminal of a particular width, or optionally with no width limit.
The given width may be zero to disable word-wrapping of the detail text and truncation of source code snippets.
If color is set to true, the output will include VT100 escape sequences to color-code the severity indicators. It is suggested to turn this off if the target writer is not a terminal.
Diagnostics is a list of Diagnostic instances.
ApplyPath is a helper function that applies a cty.Path to a value using the indexing and attribute access operations from HCL.
This is similar to calling the path's own Apply method, but ApplyPath uses the more relaxed typing rules that apply to these operations in HCL, rather than cty's relatively-strict rules. ApplyPath is implemented in terms of Index and GetAttr, and so it has the same behavior for individual steps but will stop and return any errors returned by intermediate steps.
Diagnostics are produced if the given path cannot be applied to the given value. Therefore a pointer to a source range must be provided to use in diagnostics, though nil can be provided if the calling application is going to ignore the subject of the returned diagnostics anyway.
GetAttr is a helper function that performs the same operation as the attribute access in the HCL expression language. That is, the result is the same as it would be for obj.attr in a configuration expression.
This is exported so that applications can access attributes in a manner consistent with how the language does it, including handling of null and unknown values, etc.
Diagnostics are produced if the given combination of values is not valid. Therefore a pointer to a source range must be provided to use in diagnostics, though nil can be provided if the calling application is going to ignore the subject of the returned diagnostics anyway.
Index is a helper function that performs the same operation as the index operator in the HCL expression language. That is, the result is the same as it would be for collection[key] in a configuration expression.
This is exported so that applications can perform indexing in a manner consistent with how the language does it, including handling of null and unknown values, etc.
Diagnostics are produced if the given combination of values is not valid. Therefore a pointer to a source range must be provided to use in diagnostics, though nil can be provided if the calling application is going to ignore the subject of the returned diagnostics anyway.
Append appends a new error to a Diagnostics and return the whole Diagnostics.
This is provided as a convenience for returning from a function that collects and then returns a set of diagnostics:
return nil, diags.Append(&hcl.Diagnostic{ ... })
Note that this modifies the array underlying the diagnostics slice, so must be used carefully within a single codepath. It is incorrect (and rude) to extend a diagnostics created by a different subsystem.
error implementation, so that sets of diagnostics can be returned via APIs that normally deal in vanilla Go errors.
Extend concatenates the given Diagnostics with the receiver and returns the whole new Diagnostics.
This is similar to Append but accepts multiple diagnostics to add. It has all the same caveats and constraints.
HasErrors returns true if the receiver contains any diagnostics of severity DiagError.
An EvalContext provides the variables and functions that should be used to evaluate an expression.
NewChild returns a new EvalContext that is a child of the receiver.
Parent returns the parent of the receiver, or nil if the receiver has no parent.
Expression is a literal value or an expression provided in the configuration, which can be evaluated within a scope to produce a value.
StaticExpr returns an Expression that always evaluates to the given value.
This is useful to substitute default values for expressions that are not explicitly given in configuration and thus would otherwise have no Expression to return.
Since expressions are expected to have a source range, the caller must provide one. Ideally this should be a real source range, but it can be a synthetic one (with an empty-string filename) if no suitable range is available.
UnwrapExpression removes any "wrapper" expressions from the given expression, to recover the representation of the physical expression given in source code.
Sometimes wrapping expressions are used to modify expression behavior, e.g. in extensions that need to make some local variables available to certain sub-trees of the configuration. This can make it difficult to reliably type-assert on the physical AST types used by the underlying syntax.
Unwrapping an expression may modify its behavior by stripping away any additional constraints or capabilities being applied to the Value and Variables methods, so this function should generally only be used prior to operations that concern themselves with the static syntax of the input configuration, and not with the effective value of the expression.
Wrapper expression types must support unwrapping by implementing a method called UnwrapExpression that takes no arguments and returns the embedded Expression. Implementations of this method should peel away only one level of wrapping, if multiple are present. This method may return nil to indicate _dynamically_ that no wrapped expression is available, for expression types that might only behave as wrappers in certain cases.
UnwrapExpressionUntil is similar to UnwrapExpression except it gives the caller an opportunity to test each level of unwrapping to see each a particular expression is accepted.
This could be used, for example, to unwrap until a particular other interface is satisfied, regardless of wrap wrapping level it is satisfied at.
The given callback function must return false to continue wrapping, or true to accept and return the proposed expression given. If the callback function rejects even the final, physical expression then the result of this function is nil.
type File struct { Body Body Bytes []byte Nav interface{} }
File is the top-level node that results from parsing a HCL file.
AttributeAtPos attempts to find an attribute definition in the receiving file that contains the given position. This is a best-effort method that may not be able to produce a result for all positions or for all HCL syntaxes.
The result is nil if no single attribute could be selected for any reason.
BlocksAtPos attempts to find all of the blocks that contain the given position, ordered so that the outermost block is first and the innermost block is last. This is a best-effort method that may not be able to produce a complete result for all positions or for all HCL syntaxes.
If the returned slice is non-empty, the first element is guaranteed to represent the same block as would be the result of OutermostBlockAtPos and the last element the result of InnermostBlockAtPos. However, the implementation may return two different objects describing the same block, so comparison by pointer identity is not possible.
The result is nil if no blocks at all contain the given position.
InnermostBlockAtPos attempts to find the most deeply-nested block in the receiving file that contains the given position. This is a best-effort method that may not be able to produce a result for all positions or for all HCL syntaxes.
The result is nil if no single block could be selected for any reason.
OutermostBlockAtPos attempts to find a top-level block in the receiving file that contains the given position. This is a best-effort method that may not be able to produce a result for all positions or for all HCL syntaxes.
The result is nil if no single block could be selected for any reason.
OutermostExprAtPos attempts to find an expression in the receiving file that contains the given position. This is a best-effort method that may not be able to produce a result for all positions or for all HCL syntaxes.
Since expressions are often nested inside one another, this method returns the outermost "root" expression that is not contained by any other.
The result is nil if no single expression could be selected for any reason.
KeyValuePair represents a pair of expressions that serve as a single item within a map or object definition construct.
type Pos struct { Line int Column int Byte int }
Pos represents a single position in a source file, by addressing the start byte of a unicode character encoded in UTF-8.
Pos is generally used only in the context of a Range, which then defines which source file the position is within.
type Range struct { Filename string Start, End Pos }
Range represents a span of characters between two positions in a source file.
This struct is usually used by value in types that represent AST nodes, but by pointer in types that refer to the positions of other objects, such as in diagnostics.
RangeBetween returns a new range that spans from the beginning of the start range to the end of the end range.
The result is meaningless if the two ranges do not belong to the same source file or if the end range appears before the start range.
RangeOver returns a new range that covers both of the given ranges and possibly additional content between them if the two ranges do not overlap.
If either range is empty then it is ignored. The result is empty if both given ranges are empty.
The result is meaningless if the two ranges to not belong to the same source file.
CanSliceBytes returns true if SliceBytes could return an accurate sub-slice of the given slice.
This effectively tests whether the start and end offsets of the range are within the bounds of the slice, and thus whether SliceBytes can be trusted to produce an accurate start and end position within that slice.
ContainsOffset returns true if and only if the given byte offset is within the receiving Range.
ContainsPos returns true if and only if the given position is contained within the receiving range.
In the unlikely case that the line/column information disagree with the byte offset information in the given position or receiving range, the byte offsets are given priority.
Overlap finds a range that is either identical to or a sub-range of both the receiver and the other given range. It returns an empty range within the receiver if there is no overlap between the two ranges.
A non-empty result is either identical to or a subset of the receiver.
Overlaps returns true if the receiver and the other given range share any characters in common.
PartitionAround finds the portion of the given range that overlaps with the reciever and returns three ranges: the portion of the reciever that precedes the overlap, the overlap itself, and then the portion of the reciever that comes after the overlap.
If the two ranges do not overlap then all three returned ranges are empty.
If the given range aligns with or extends beyond either extent of the reciever then the corresponding outer range will be empty.
Ptr returns a pointer to a copy of the receiver. This is a convenience when ranges in places where pointers are required, such as in Diagnostic, but the range in question is returned from a method. Go would otherwise not allow one to take the address of a function call.
SliceBytes returns a sub-slice of the given slice that is covered by the receiving range, assuming that the given slice is the source code of the file indicated by r.Filename.
If the receiver refers to any byte offsets that are outside of the slice then the result is constrained to the overlapping portion only, to avoid a panic. Use CanSliceBytes to determine if the result is guaranteed to be an accurate span of the requested range.
String returns a compact string representation of the receiver. Callers should generally prefer to present a range more visually, e.g. via markers directly on the relevant portion of source code.
type RangeScanner struct { }
RangeScanner is a helper that will scan over a buffer using a bufio.SplitFunc and visit a source range for each token matched.
For example, this can be used with bufio.ScanLines to find the source range for each line in the file, skipping over the actual newline characters, which may be useful when printing source code snippets as part of diagnostic messages.
The line and column information in the returned ranges is produced by counting newline characters and grapheme clusters respectively, which mimics the behavior we expect from a parser when producing ranges.
NewRangeScanner creates a new RangeScanner for the given buffer, producing ranges for the given filename.
Since ranges have grapheme-cluster granularity rather than byte granularity, the scanner will produce incorrect results if the given SplitFunc creates tokens between grapheme cluster boundaries. In particular, it is incorrect to use RangeScanner with bufio.ScanRunes because it will produce tokens around individual UTF-8 sequences, which will split any multi-sequence grapheme clusters.
NewRangeScannerFragment is like NewRangeScanner but the ranges it produces will be offset by the given starting position, which is appropriate for sub-slices of a file, whereas NewRangeScanner assumes it is scanning an entire file.
Bytes returns the slice of the input buffer that is covered by the range that would be returned by Range.
Err can be called after Scan returns false to determine if the latest read resulted in an error, and obtain that error if so.
Range returns a range that covers the latest token obtained after a call to Scan returns true.
StaticCall represents a function call that was extracted statically from an expression using ExprCall.
A Traversal is a description of traversing through a value through a series of operations such as attribute lookup, index lookup, etc.
It is used to look up values in scopes, for example.
The traversal operations are implementations of interface Traverser. This is a closed set of implementations, so the interface cannot be implemented from outside this package.
A traversal can be absolute (its first value is a symbol name) or relative (starts from an existing value).
TraversalJoin appends a relative traversal to an absolute traversal to produce a new absolute traversal.
IsRelative returns true if the receiver is a relative traversal, or false otherwise.
RootName returns the root name for a absolute traversal. Will panic if called on a relative traversal.
SimpleSplit returns a TraversalSplit where the name lookup is the absolute part and the remainder is the relative part. Supported only for absolute traversals, and will panic if applied to a relative traversal.
This can be used by applications that have a relatively-simple variable namespace where only the top-level is directly populated in the scope, with everything else handled by relative lookups from those initial values.
SourceRange returns the source range for the traversal.
TraverseAbs applies the receiving traversal to the given eval context, returning the resulting value. This is supported only for absolute traversals, and will panic if applied to a relative traversal.
TraverseRel applies the receiving traversal to the given value, returning the resulting value. This is supported only for relative traversals, and will panic if applied to an absolute traversal.
TraversalSplit represents a pair of traversals, the first of which is an absolute traversal and the second of which is relative to the first.
This is used by calling applications that only populate prefixes of the traversals in the scope, with Abs representing the part coming from the scope and Rel representing the remaining steps once that part is retrieved.
Join concatenates together the Abs and Rel parts to produce a single absolute traversal.
RootName returns the root name for the absolute part of the split.
Traverse is a convenience function to apply TraverseAbs followed by TraverseRel.
TraverseAbs traverses from a scope to the value resulting from the absolute traversal.
TraverseRel traverses from a given value, assumed to be the result of TraverseAbs on some scope, to a final result for the entire split traversal.
type TraverseAttr struct { Name string SrcRange Range }
TraverseAttr looks up an attribute in its initial value.
TraverseIndex applies the index operation to its initial value.
type TraverseRoot struct { Name string SrcRange Range }
TraverseRoot looks up a root name in a scope. It is used as the first step of an absolute Traversal, and cannot itself be traversed directly.
TraversalStep on a TraverseName immediately panics, because absolute traversals cannot be directly traversed.
TraverseSplat applies the splat operation to its initial value.
A Traverser is a step within a Traversal.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4