v2.7.6 Latest Latest

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

Go to latest
Published: Dec 7, 2023 License: Apache-2.0 Imports: 16 Imported by: 823




This section is empty.


This section is empty.


func Format

func Format(input []byte) []byte

Format formats the input Caddyfile to a standard, nice-looking appearance. It works by reading each rune of the input and taking control over all the bracing and whitespace that is written; otherwise, words, comments, placeholders, and escaped characters are all treated literally and written as they appear in the input.

func FormattingDifference added in v2.6.3

func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bool)

FormattingDifference returns a warning and true if the formatted version is any different from the input; empty warning and false otherwise. TODO: also perform this check on imported files


type Adapter

type Adapter struct {
	ServerType ServerType

Adapter adapts Caddyfile to Caddy JSON.

func (Adapter) Adapt

func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconfig.Warning, error)

Adapt converts the Caddyfile config in body to Caddy JSON.

type Dispenser

type Dispenser struct {
	// contains filtered or unexported fields

Dispenser is a type that dispenses tokens, similarly to a lexer, except that it can do so with some notion of structure. An empty Dispenser is invalid; call NewDispenser to make a proper instance.

func NewDispenser

func NewDispenser(tokens []Token) *Dispenser

NewDispenser returns a Dispenser filled with the given tokens.

func NewTestDispenser added in v2.1.0

func NewTestDispenser(input string) *Dispenser

NewTestDispenser parses input into tokens and creates a new Dispenser for test purposes only; any errors are fatal.

func (*Dispenser) AllArgs

func (d *Dispenser) AllArgs(targets ...*string) bool

AllArgs is like Args, but if there are more argument tokens available than there are targets, false is returned. The number of available argument tokens must match the number of targets exactly to return true.

func (*Dispenser) ArgErr

func (d *Dispenser) ArgErr() error

ArgErr returns an argument error, meaning that another argument was expected but not found. In other words, a line break or open curly brace was encountered instead of an argument.

func (*Dispenser) Args

func (d *Dispenser) Args(targets ...*string) bool

Args is a convenience function that loads the next arguments (tokens on the same line) into an arbitrary number of strings pointed to in targets. If there are not enough argument tokens available to fill targets, false is returned and the remaining targets are left unchanged. If all the targets are filled, then true is returned.

func (*Dispenser) CountRemainingArgs added in v2.5.0

func (d *Dispenser) CountRemainingArgs() int

CountRemainingArgs counts the amount of remaining arguments (tokens on the same line) without consuming the tokens.

func (*Dispenser) Delete

func (d *Dispenser) Delete() []Token

Delete deletes the current token and returns the updated slice of tokens. The cursor is not advanced to the next token. Because deletion modifies the underlying slice, this method should only be called if you have access to the original slice of tokens and/or are using the slice of tokens outside this Dispenser instance. If you do not re-assign the slice with the return value of this method, inconsistencies in the token array will become apparent (or worse, hide from you like they did me for 3 and a half freaking hours late one night).

func (*Dispenser) DeleteN added in v2.7.0

func (d *Dispenser) DeleteN(amount int) []Token

DeleteN is the same as Delete, but can delete many tokens at once. If there aren't N tokens available to delete, none are deleted.

func (*Dispenser) EOFErr

func (d *Dispenser) EOFErr() error

EOFErr returns an error indicating that the dispenser reached the end of the input when searching for the next token.

func (*Dispenser) Err

func (d *Dispenser) Err(msg string) error

Err generates a custom parse-time error with a message of msg.

func (*Dispenser) Errf

func (d *Dispenser) Errf(format string, args ...any) error

Errf is like Err, but for formatted error messages

func (*Dispenser) File

func (d *Dispenser) File() string

File gets the filename where the current token originated.

func (*Dispenser) Line

func (d *Dispenser) Line() int

Line gets the line number of the current token. If there is no token loaded, it returns 0.

func (*Dispenser) Nesting

func (d *Dispenser) Nesting() int

Nesting returns the current nesting level. Necessary if using NextBlock()

func (*Dispenser) NewFromNextSegment

func (d *Dispenser) NewFromNextSegment() *Dispenser

NewFromNextSegment returns a new dispenser with a copy of the tokens from the current token until the end of the "directive" whether that be to the end of the line or the end of a block that starts at the end of the line; in other words, until the end of the segment.

func (*Dispenser) Next

func (d *Dispenser) Next() bool

Next loads the next token. Returns true if a token was loaded; false otherwise. If false, all tokens have been consumed.

func (*Dispenser) NextArg

func (d *Dispenser) NextArg() bool

NextArg loads the next token if it is on the same line and if it is not a block opening (open curly brace). Returns true if an argument token was loaded; false otherwise. If false, all tokens on the line have been consumed except for potentially a block opening. It handles imported tokens correctly.

func (*Dispenser) NextBlock

func (d *Dispenser) NextBlock(initialNestingLevel int) bool

NextBlock can be used as the condition of a for loop to load the next token as long as it opens a block or is already in a block nested more than initialNestingLevel. In other words, a loop over NextBlock() will iterate all tokens in the block assuming the next token is an open curly brace, until the matching closing brace. The open and closing brace tokens for the outer-most block will be consumed internally and omitted from the iteration.

Proper use of this method looks like this:

for nesting := d.Nesting(); d.NextBlock(nesting); {

However, in simple cases where it is known that the Dispenser is new and has not already traversed state by a loop over NextBlock(), this will do:

for d.NextBlock(0) {

As with other token parsing logic, a loop over NextBlock() should be contained within a loop over Next(), as it is usually prudent to skip the initial token.

func (*Dispenser) NextLine

func (d *Dispenser) NextLine() bool

NextLine loads the next token only if it is not on the same line as the current token, and returns true if a token was loaded; false otherwise. If false, there is not another token or it is on the same line. It handles imported tokens correctly.

func (*Dispenser) NextSegment

func (d *Dispenser) NextSegment() Segment

NextSegment returns a copy of the tokens from the current token until the end of the line or block that starts at the end of the line.

func (*Dispenser) Prev

func (d *Dispenser) Prev() bool

Prev moves to the previous token. It does the inverse of Next(), except this function may decrement the cursor to -1 so that the next call to Next() points to the first token; this allows dispensing to "start over". This method returns true if the cursor ends up pointing to a valid token.

func (*Dispenser) RemainingArgs

func (d *Dispenser) RemainingArgs() []string

RemainingArgs loads any more arguments (tokens on the same line) into a slice and returns them. Open curly brace tokens also indicate the end of arguments, and the curly brace is not included in the return value nor is it loaded.

func (*Dispenser) RemainingArgsRaw added in v2.5.0

func (d *Dispenser) RemainingArgsRaw() []string

RemainingArgsRaw loads any more arguments (tokens on the same line, retaining quotes) into a slice and returns them. Open curly brace tokens also indicate the end of arguments, and the curly brace is not included in the return value nor is it loaded.

func (*Dispenser) Reset

func (d *Dispenser) Reset()

Reset sets d's cursor to the beginning, as if this was a new and unused dispenser.

func (*Dispenser) ScalarVal added in v2.5.0

func (d *Dispenser) ScalarVal() any

ScalarVal gets value of the current token, converted to the closest scalar type. If there is no token loaded, it returns nil.

func (*Dispenser) SyntaxErr

func (d *Dispenser) SyntaxErr(expected string) error

SyntaxErr creates a generic syntax error which explains what was found and what was expected.

func (*Dispenser) Token

func (d *Dispenser) Token() Token

Token returns the current token.

func (*Dispenser) Val

func (d *Dispenser) Val() string

Val gets the text of the current token. If there is no token loaded, it returns empty string.

func (*Dispenser) ValRaw added in v2.5.0

func (d *Dispenser) ValRaw() string

ValRaw gets the raw text of the current token (including quotes). If the token was a heredoc, then the delimiter is not included, because that is not relevant to any unmarshaling logic at this time. If there is no token loaded, it returns empty string.

func (*Dispenser) WrapErr added in v2.5.0

func (d *Dispenser) WrapErr(err error) error

WrapErr takes an existing error and adds the Caddyfile file and line number.

type Segment

type Segment []Token

Segment is a list of tokens which begins with a directive and ends at the end of the directive (either at the end of the line, or at the end of a block it opens).

func (Segment) Directive

func (s Segment) Directive() string

Directive returns the directive name for the segment. The directive name is the text of the first token.

type ServerBlock

type ServerBlock struct {
	HasBraces    bool
	Keys         []string
	Segments     []Segment
	IsNamedRoute bool

ServerBlock associates any number of keys from the head of the server block with tokens, which are grouped by segments.

func Parse

func Parse(filename string, input []byte) ([]ServerBlock, error)

Parse parses the input just enough to group tokens, in order, by server block. No further parsing is performed. Server blocks are returned in the order in which they appear. Directives that do not appear in validDirectives will cause an error. If you do not want to check for valid directives, pass in nil instead.

Environment variables in {$ENVIRONMENT_VARIABLE} notation will be replaced before parsing begins.

func (ServerBlock) DispenseDirective

func (sb ServerBlock) DispenseDirective(dir string) *Dispenser

DispenseDirective returns a dispenser that contains all the tokens in the server block.

type ServerType

type ServerType interface {
	// Setup takes the server blocks which
	// contain tokens, as well as options
	// (e.g. CLI flags) and creates a Caddy
	// config, along with any warnings or
	// an error.
	Setup([]ServerBlock, map[string]any) (*caddy.Config, []caddyconfig.Warning, error)

ServerType is a type that can evaluate a Caddyfile and set up a caddy config.

type Token

type Token struct {
	File string

	Line int
	Text string
	// contains filtered or unexported fields

Token represents a single parsable unit.

func Tokenize added in v2.2.0

func Tokenize(input []byte, filename string) ([]Token, error)

Tokenize takes bytes as input and lexes it into a list of tokens that can be parsed as a Caddyfile. Also takes a filename to fill the token's File as the source of the tokens, which is important to determine relative paths for `import` directives.

func (Token) NumLineBreaks added in v2.7.0

func (t Token) NumLineBreaks() int

NumLineBreaks counts how many line breaks are in the token text.

func (Token) Quoted added in v2.6.0

func (t Token) Quoted() bool

type Unmarshaler

type Unmarshaler interface {
	UnmarshalCaddyfile(d *Dispenser) error

Unmarshaler is a type that can unmarshal Caddyfile tokens to set itself up for a JSON encoding. The goal of an unmarshaler is not to set itself up for actual use, but to set itself up for being marshaled into JSON. Caddyfile-unmarshaled values will not be used directly; they will be encoded as JSON and then used from that. Implementations must be able to support multiple segments (instances of their directive or batch of tokens); typically this means wrapping all token logic in a loop: `for d.Next() { ... }`.

func UnmarshalModule added in v2.4.0

func UnmarshalModule(d *Dispenser, moduleID string) (Unmarshaler, error)

UnmarshalModule instantiates a module with the given ID and invokes UnmarshalCaddyfile on the new value using the immediate next segment of d as input. In other words, d's next token should be the first token of the module's Caddyfile input.

This function is used when the next segment of Caddyfile tokens belongs to another Caddy module. The returned value is often type-asserted to the module's associated type for practical use when setting up a config.

Jump to

Keyboard shortcuts

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