MSP-8974 up deps
This commit is contained in:
1 parent
0abaaf740f
commit
a0aafd93b9
602 files changed
+47724
-13295
No files matched your search
+27
@@ -0,0 +1,27 @@
|
||||
version: "2"
|
||||
linters:
|
||||
default: none
|
||||
enable:
|
||||
- errcheck
|
||||
- govet
|
||||
- ineffassign
|
||||
- misspell
|
||||
- modernize
|
||||
- paralleltest
|
||||
- staticcheck
|
||||
- thelper
|
||||
- tparallel
|
||||
- unused
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
settings:
|
||||
gofmt:
|
||||
simplify: true
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [v0.2.0] - 2026-11-10
|
||||
|
||||
This release renames the API and hides the parser types. To upgrade, replace `interpolate.Interpolate(env, s)` with `interpolate.Expand(s, env)`, and rename the `Get` method of a custom `Env` to `Lookup`, or use `interpolate.LookupFunc(os.LookupEnv)`.
|
||||
|
||||
### Added
|
||||
|
||||
- `LookupFunc`, an adapter that makes a function such as `os.LookupEnv` an `Env`.
|
||||
- `UnsetVariableError`, the error from `${NAME?message}`, `${NAME:?message}` and `WithNoUnset`, with `Name` and `Message` fields. The error text does not change.
|
||||
- `WithNoUnset`, an option that makes a reference to an unset variable an error, the same as `set -u` in bash.
|
||||
|
||||
### Changed
|
||||
|
||||
- `Interpolate(env, s)` is now `Expand(s, env, opts...)`.
|
||||
- `Identifiers` is now `Variables`, and returns each name only once, in the order of first use.
|
||||
- The `Get` method of `Env` is now `Lookup`.
|
||||
- `NewSliceEnv(slice)` is now `NewListEnv(pairs...)`. Use `NewListEnv(os.Environ()...)` for a slice.
|
||||
|
||||
### Removed
|
||||
|
||||
- The exported parser and expression types, such as `Parser`, `NewParser`, `Expression`, `ExpressionItem`, `Expansion`, and the `*Expansion` types. Use `Expand` and `Variables`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- On Windows, `NewMapEnv` with keys that differ only in case, such as `Path` and `PATH`, gave a random result. The last key in sorted order now wins.
|
||||
|
||||
## [v0.1.0] - 2026-11-10
|
||||
|
||||
### Added
|
||||
|
||||
- `${VAR:?message}`: error if `VAR` is unset or empty ([#2](https://github.com/mfridman/interpolate/issues/2)).
|
||||
- `${VAR+word}` and `${VAR:+word}`: use `word` if `VAR` is set, or set and not empty.
|
||||
- `${#VAR}`: the length of the value in characters.
|
||||
- `\}` in the word of a brace expansion is a literal `}`, for example `${CONFIG:-{"a":1\}}`.
|
||||
- New expansion types: `RequiredNonEmptyExpansion`, `AlternateExpansion`, `AlternateNonEmptyExpansion`, and `LengthExpansion`.
|
||||
- Brace expansions can be nested at most 1000 levels deep. Deeper input returns an error instead of exhausting the stack.
|
||||
|
||||
### Changed
|
||||
|
||||
- Go 1.25 or later is required.
|
||||
- A `$` that is not followed by a letter, `_`, or `{` is literal text. Before, inputs such as `$1`, `$ `, `$5`, `$@`, `'^abc$'`, and `${VAR:-$}` returned an error.
|
||||
- Names follow POSIX: `[A-Za-z_][A-Za-z0-9_]*`. `$_VAR` and `${_VAR}` now expand. Non-ASCII letters are no longer part of a name, so `$é` is literal text, `$FOOé` expands `FOO`, and `${é}` is an error.
|
||||
- `${VAR:+word}` is the alternate value. Before, it was parsed as a substring with offset `+word`, so `${VAR:+1}` was the value after the first character.
|
||||
- Substring offsets and lengths count characters, not bytes.
|
||||
- A negative substring offset before the start of the value gives an empty string, the same as bash. Before, it gave the whole value.
|
||||
- A blank substring offset or length counts as 0, so `${VAR::2}`, `${VAR:2:}`, and `${VAR: }` work. Before, they returned an error.
|
||||
- `Identifiers` includes the names in the word of `${VAR-word}` and `${VAR?word}`, the same as `${VAR:-word}`.
|
||||
- Error messages start with a lowercase letter, and say "end of input" for unterminated expansions. An empty `${}` gives `empty expansion ${}, expected a variable name` ([#1](https://github.com/mfridman/interpolate/issues/1)). The `$VAR: message` errors from required expansions are unchanged.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Substrings with a length near the maximum `int` value no longer panic.
|
||||
- Invalid UTF-8 bytes in the input are kept unchanged. Before, they became U+FFFD.
|
||||
- Calling `Parse` again on the same `Parser` parses the input again. Before, it returned an empty expression.
|
||||
|
||||
## [v0.0.2]
|
||||
|
||||
The last release before the changes above. See [buildkite/interpolate](https://github.com/buildkite/interpolate) for the history before the fork.
|
||||
|
||||
[Unreleased]: https://github.com/mfridman/interpolate/compare/v0.2.0...HEAD
|
||||
[v0.2.0]: https://github.com/mfridman/interpolate/compare/v0.1.0...v0.2.0
|
||||
[v0.1.0]: https://github.com/mfridman/interpolate/compare/v0.0.2...v0.1.0
|
||||
[v0.0.2]: https://github.com/mfridman/interpolate/releases/tag/v0.0.2
|
||||
+88
-46
@@ -1,85 +1,127 @@
|
||||
# Interpolate
|
||||
# interpolate
|
||||
|
||||
[](https://github.com/mfridman/interpolate/actions/workflows/ci.yaml)
|
||||
[](https://pkg.go.dev/github.com/mfridman/interpolate)
|
||||
[](https://goreportcard.com/report/github.com/mfridman/interpolate)
|
||||
|
||||
A Go library for parameter expansion (like `${NAME}` or `$NAME`) in strings from environment
|
||||
variables. An implementation of [POSIX Parameter
|
||||
Expansion](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02),
|
||||
plus some other basic operations that you'd expect in a shell scripting environment [like
|
||||
bash](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html).
|
||||
A Go library that expands shell-style parameters, such as `$NAME` and `${NAME:-default}`, in strings. It implements [POSIX parameter expansion](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02) and some [bash extensions](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html).
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
```sh
|
||||
go get github.com/mfridman/interpolate@latest
|
||||
```
|
||||
|
||||
Requires Go 1.25 or later.
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/mfridman/interpolate"
|
||||
"fmt"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/mfridman/interpolate"
|
||||
)
|
||||
|
||||
func main() {
|
||||
env := interpolate.NewSliceEnv([]string{
|
||||
"NAME=James",
|
||||
})
|
||||
env := interpolate.NewListEnv("NAME=James")
|
||||
|
||||
output, _ := interpolate.Interpolate(env, "Hello... ${NAME} welcome to the ${ANOTHER_VAR:-🏖}")
|
||||
|
||||
fmt.Println(output)
|
||||
// Output: Hello... James welcome to the 🏖
|
||||
output, err := interpolate.Expand("Hello ${NAME}, welcome to the ${PLACE:-🏖}", env)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Println(output) // Hello James, welcome to the 🏖
|
||||
}
|
||||
```
|
||||
|
||||
## Supported Expansions
|
||||
Values come from an `Env`:
|
||||
|
||||
- `${parameter}` or `$parameter`
|
||||
- `interpolate.LookupFunc(os.LookupEnv)` reads the process environment.
|
||||
- `interpolate.NewMapEnv(m)` reads a `map[string]string`.
|
||||
- `interpolate.NewListEnv("A=1", "B=2")` reads `NAME=value` pairs, such as `os.Environ()...`.
|
||||
- Any type with a `Lookup(name string) (string, bool)` method is an `Env`.
|
||||
|
||||
- **Use value.** If parameter is set, then it shall be substituted; otherwise, it will be blank
|
||||
`interpolate.Variables` returns the names of the variables in a string, without repeats, and does not expand it.
|
||||
|
||||
- `${parameter:-[word]}`
|
||||
### Errors and strict mode
|
||||
|
||||
- **Use default values.** If parameter is unset or null, the expansion of word (or an empty string
|
||||
if word is omitted) shall be substituted; otherwise, the value of parameter shall be
|
||||
substituted.
|
||||
`${NAME?message}` and `${NAME:?message}` return an `*interpolate.UnsetVariableError` with the variable `Name` and the `Message`. Its text is `$NAME: message`.
|
||||
|
||||
- `${parameter-[word]}`
|
||||
```go
|
||||
var unsetErr *interpolate.UnsetVariableError
|
||||
if errors.As(err, &unsetErr) {
|
||||
fmt.Println(unsetErr.Name) // PORT
|
||||
}
|
||||
```
|
||||
|
||||
- **Use default values when not set.** If parameter is unset, the expansion of word (or an empty
|
||||
string if word is omitted) shall be substituted; otherwise, the value of parameter shall be
|
||||
substituted.
|
||||
By default, an unset variable expands to an empty string, the same as a shell. Use `interpolate.WithNoUnset()` to make a reference to an unset variable an error, the same as `set -u` in bash. Expansions that handle an unset variable, such as `${NAME:-word}`, do not change.
|
||||
|
||||
- `${parameter:[offset]}`
|
||||
```go
|
||||
output, err := interpolate.Expand(input, env, interpolate.WithNoUnset())
|
||||
// $TYPO -> error: $TYPO: not set
|
||||
```
|
||||
|
||||
- **Use the substring of parameter after offset.** A negative offset must be separated from the
|
||||
colon with a space, and will select from the end of the string. If the value is out of bounds,
|
||||
an empty string will be substituted.
|
||||
## Supported expansions
|
||||
|
||||
- `${parameter:[offset]:[length]}`
|
||||
| Syntax | Result |
|
||||
| --- | --- |
|
||||
| `$NAME` or `${NAME}` | The value of `NAME`, or an empty string if it is unset |
|
||||
| `${NAME:-word}` | `word` if `NAME` is unset or empty, otherwise the value |
|
||||
| `${NAME-word}` | `word` if `NAME` is unset, otherwise the value |
|
||||
| `${NAME:?message}` | An error if `NAME` is unset or empty, otherwise the value |
|
||||
| `${NAME?message}` | An error if `NAME` is unset, otherwise the value |
|
||||
| `${NAME:+word}` | `word` if `NAME` is set and not empty, otherwise an empty string |
|
||||
| `${NAME+word}` | `word` if `NAME` is set, otherwise an empty string |
|
||||
| `${#NAME}` | The length of the value in characters |
|
||||
| `${NAME:offset}` | The value from `offset` to the end |
|
||||
| `${NAME:offset:length}` | At most `length` characters of the value from `offset` |
|
||||
|
||||
- **Use the substring of parameter after offset of given length.** A negative offset must be
|
||||
separated from the colon with a space, and will select from the end of the string. If the offset
|
||||
is out of bounds, an empty string will be substituted. If the length is greater than the length
|
||||
then the entire string will be returned.
|
||||
- A name starts with a letter or an underscore, followed by letters, digits, or underscores (`[A-Za-z_][A-Za-z0-9_]*`).
|
||||
- A `word` or `message` can contain other expansions, such as `${NAME:-${FALLBACK:-default}}`. It is expanded only when it is used. Expansions can be nested up to 1000 levels deep.
|
||||
- Without a message, the error from `?` is `$NAME: not set`, and the error from `:?` is `$NAME: empty or not set`.
|
||||
|
||||
- `${parameter:?[word]}`
|
||||
- **Indicate Error if Null or Unset.** If parameter is unset or null, the expansion of word (or a
|
||||
message indicating it is unset if word is omitted) shall be returned as an error.
|
||||
### Substrings
|
||||
|
||||
## Prior work
|
||||
- Offsets and lengths count characters, not bytes. They are decimal integers; arithmetic is not supported.
|
||||
- A negative offset counts from the end. Put a space before it, as in `${NAME: -2}`, because `${NAME:-2}` is a default value.
|
||||
- An offset past the end, or before the start, gives an empty string.
|
||||
- A length past the end gives the rest of the value. A negative length ends that many characters before the end, so `${NAME:1:-1}` removes the first and last characters.
|
||||
- A blank offset or length counts as 0, so `${NAME::2}` gives the first two characters. `${NAME:}` is an error.
|
||||
|
||||
This repository is a fork of [buildkite/interpolate](https://github.com/buildkite/interpolate). I'd
|
||||
like to thank the authors of that library for their work. I've forked it to make some changes that I
|
||||
needed for my own use cases, and to make it easier to maintain. I've also added some tests and
|
||||
documentation.
|
||||
## Escaping
|
||||
|
||||
| Input | Output |
|
||||
| --- | --- |
|
||||
| `$$NAME` or `\$NAME` | `$NAME` |
|
||||
| `$${NAME}` or `\${NAME}` | `${NAME}` |
|
||||
| `\}` in a `word` or `message` | `}` |
|
||||
| `$` not followed by a letter, `_`, or `{` | Kept as-is, so `$1`, `$(command)`, `price: $5`, and a trailing `$` do not change |
|
||||
| `\\` | Kept as-is |
|
||||
|
||||
A word ends at the first `}`, so write `${CONFIG:-{"a":1\}}` to get `{"a":1}`. Outside of `${...}`, `\}` is kept as-is.
|
||||
|
||||
A double backslash is kept as two backslashes, and it does not escape the `$` after it: `\\$NAME` gives `\\` followed by the value of `NAME`. You cannot put one backslash directly before a literal `$`. In a regular expression, write `[$]` instead of `\$`.
|
||||
|
||||
### SQL
|
||||
|
||||
These rules matter when the input is SQL, for example in [goose](https://github.com/pressly/goose) migrations with `ENVSUB ON`:
|
||||
|
||||
- Write `$$$$` for a `$$` dollar-quoted string, and `$$tag$$` for `$tag$`. Without escaping, `$$` becomes `$`, and `$tag` expands as a variable.
|
||||
- Write `%1$$s` in `format('%1$s', name)`, because `$s` is a variable.
|
||||
- Positional parameters such as `$1`, and a `$` at the end of a regular expression such as `'^abc$'`, are kept as-is.
|
||||
|
||||
## Not supported
|
||||
|
||||
- Pattern removal: `${NAME%word}`, `${NAME%%word}`, `${NAME#word}`, and `${NAME##word}`.
|
||||
- Assignment: `${NAME:=word}` and `${NAME=word}`.
|
||||
- Special and positional parameters, such as `$1`, `$@`, `$*`, `$#`, and `$?`. They are kept as literal text.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
This project started as a fork of [buildkite/interpolate](https://github.com/buildkite/interpolate). Thanks to its authors for their work.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under MIT license, in `LICENSE`.
|
||||
[MIT](LICENSE.txt)
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
// Package interpolate expands shell-style parameters, such as $NAME and ${NAME:-default}, in
|
||||
// strings. It implements POSIX parameter expansion and some bash extensions. [Expand] reads
|
||||
// values from an [Env], and [Variables] lists the variables in a string.
|
||||
//
|
||||
// Supported expansions:
|
||||
//
|
||||
// $NAME or ${NAME} the value of NAME, or an empty string if NAME is unset
|
||||
// ${NAME:-word} word if NAME is unset or empty
|
||||
// ${NAME-word} word if NAME is unset
|
||||
// ${NAME:?message} an error if NAME is unset or empty
|
||||
// ${NAME?message} an error if NAME is unset
|
||||
// ${NAME:+word} word if NAME is set and not empty, otherwise an empty string
|
||||
// ${NAME+word} word if NAME is set, otherwise an empty string
|
||||
// ${#NAME} the length of the value in characters
|
||||
// ${NAME:offset} the value from offset
|
||||
// ${NAME:offset:length} at most length characters of the value from offset
|
||||
//
|
||||
// Write $$ or \$ for a literal dollar sign, and \} for a literal closing brace in a word. A $
|
||||
// that is not followed by a letter, an underscore, or { is kept as-is, so $1 and $(command) do
|
||||
// not change.
|
||||
//
|
||||
// A required expansion that fails returns an [*UnsetVariableError]. Use [WithNoUnset] to make a
|
||||
// reference to an unset variable an error too, the same as set -u in bash.
|
||||
//
|
||||
// [Expand] and [Variables] are safe for concurrent use if the [Env] is.
|
||||
package interpolate
|
||||
+61
-36
@@ -1,53 +1,78 @@
|
||||
package interpolate
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Env is an interface for getting environment variables by name and returning a boolean indicating
|
||||
// whether the variable was found.
|
||||
// Env is a source of variable values.
|
||||
type Env interface {
|
||||
Get(key string) (string, bool)
|
||||
// Lookup returns the value of the variable with the given name, and whether the variable is
|
||||
// set. A variable that is set can have an empty value.
|
||||
Lookup(name string) (value string, ok bool)
|
||||
}
|
||||
|
||||
// NewSliceEnv creates an Env from a slice of environment variables in the form "key=value".
|
||||
// LookupFunc is a function that is an [Env]. For example, LookupFunc(os.LookupEnv) reads the
|
||||
// environment of the process.
|
||||
type LookupFunc func(name string) (value string, ok bool)
|
||||
|
||||
// Lookup returns f(name).
|
||||
func (f LookupFunc) Lookup(name string) (string, bool) {
|
||||
return f(name)
|
||||
}
|
||||
|
||||
// NewMapEnv returns an Env with the variables in m. It copies m.
|
||||
//
|
||||
// This can be used with [os.Environ] to create an Env.
|
||||
func NewSliceEnv(env []string) Env {
|
||||
envMap := mapEnv{}
|
||||
for _, l := range env {
|
||||
parts := strings.SplitN(l, "=", 2)
|
||||
if len(parts) == 2 {
|
||||
envMap[normalizeKeyName(parts[0])] = parts[1]
|
||||
// On Windows, names are case insensitive. If keys in m differ only in case, the last key in
|
||||
// sorted order wins.
|
||||
func NewMapEnv(m map[string]string) Env {
|
||||
return newMapEnv(m, runtime.GOOS == "windows")
|
||||
}
|
||||
|
||||
// NewListEnv returns an Env with the variables in pairs, which use the "NAME=value" form of
|
||||
// [os.Environ]. Pairs without "=" are ignored. If a name occurs more than once, the last pair
|
||||
// wins.
|
||||
//
|
||||
// On Windows, names are case insensitive.
|
||||
func NewListEnv(pairs ...string) Env {
|
||||
return newListEnv(pairs, runtime.GOOS == "windows")
|
||||
}
|
||||
|
||||
func newMapEnv(m map[string]string, foldCase bool) mapEnv {
|
||||
env := mapEnv{values: make(map[string]string, len(m)), foldCase: foldCase}
|
||||
// Sort the keys, so the result does not depend on map order when keys differ only in case.
|
||||
for _, name := range slices.Sorted(maps.Keys(m)) {
|
||||
env.values[env.key(name)] = m[name]
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func newListEnv(pairs []string, foldCase bool) mapEnv {
|
||||
env := mapEnv{values: make(map[string]string, len(pairs)), foldCase: foldCase}
|
||||
for _, pair := range pairs {
|
||||
if name, value, ok := strings.Cut(pair, "="); ok {
|
||||
env.values[env.key(name)] = value
|
||||
}
|
||||
}
|
||||
return envMap
|
||||
return env
|
||||
}
|
||||
|
||||
// NewMapEnv creates an Env from a map of environment variables.
|
||||
func NewMapEnv(env map[string]string) Env {
|
||||
envMap := mapEnv{}
|
||||
for k, v := range env {
|
||||
envMap[normalizeKeyName(k)] = v
|
||||
// mapEnv is an Env with variables in a map. With foldCase, names are case insensitive.
|
||||
type mapEnv struct {
|
||||
values map[string]string
|
||||
foldCase bool
|
||||
}
|
||||
|
||||
func (e mapEnv) Lookup(name string) (string, bool) {
|
||||
value, ok := e.values[e.key(name)]
|
||||
return value, ok
|
||||
}
|
||||
|
||||
func (e mapEnv) key(name string) string {
|
||||
if e.foldCase {
|
||||
return strings.ToUpper(name)
|
||||
}
|
||||
return envMap
|
||||
}
|
||||
|
||||
type mapEnv map[string]string
|
||||
|
||||
func (m mapEnv) Get(key string) (string, bool) {
|
||||
if m == nil {
|
||||
return "", false
|
||||
}
|
||||
val, ok := m[normalizeKeyName(key)]
|
||||
return val, ok
|
||||
}
|
||||
|
||||
// Windows isn't case sensitive for env
|
||||
func normalizeKeyName(key string) string {
|
||||
if runtime.GOOS == "windows" {
|
||||
return strings.ToUpper(key)
|
||||
}
|
||||
return key
|
||||
return name
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
package interpolate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// expandContext holds the values and settings for one call to Expand.
|
||||
type expandContext struct {
|
||||
env Env
|
||||
noUnset bool
|
||||
}
|
||||
|
||||
// value returns the value of name for a plain reference, such as $NAME or ${NAME:1}. With
|
||||
// noUnset, an unset variable is an error.
|
||||
func (c *expandContext) value(name string) (string, error) {
|
||||
value, ok := c.env.Lookup(name)
|
||||
if !ok && c.noUnset {
|
||||
return "", &UnsetVariableError{Name: name, Message: "not set"}
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// unsetError returns the error for a required expansion. It uses the expansion of message, or
|
||||
// defaultMessage if message expands to an empty string.
|
||||
func (c *expandContext) unsetError(name string, message expression, defaultMessage string) error {
|
||||
msg, err := message.expand(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if msg == "" {
|
||||
msg = defaultMessage
|
||||
}
|
||||
return &UnsetVariableError{Name: name, Message: msg}
|
||||
}
|
||||
|
||||
// expression is a list of text and expansions.
|
||||
type expression []expressionItem
|
||||
|
||||
// expand expands all expansions in the expression, and joins the results with the text.
|
||||
func (e expression) expand(c *expandContext) (string, error) {
|
||||
var buf strings.Builder
|
||||
for _, item := range e {
|
||||
if item.Expansion == nil {
|
||||
buf.WriteString(item.Text)
|
||||
continue
|
||||
}
|
||||
result, err := item.Expansion.expand(c)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
buf.WriteString(result)
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
|
||||
// variables returns the variable names referenced by all expansions in the expression, in order.
|
||||
// A name can occur more than once.
|
||||
func (e expression) variables() []string {
|
||||
var names []string
|
||||
for _, item := range e {
|
||||
if item.Expansion != nil {
|
||||
names = append(names, item.Expansion.variables()...)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// expressionItem is either text or an expansion, never both.
|
||||
type expressionItem struct {
|
||||
Text string
|
||||
Expansion expansion
|
||||
}
|
||||
|
||||
func (i expressionItem) String() string {
|
||||
if i.Expansion != nil {
|
||||
return fmt.Sprintf("%#v", i.Expansion)
|
||||
}
|
||||
return fmt.Sprintf("%q", i.Text)
|
||||
}
|
||||
|
||||
// expansion is one parameter expansion, such as $NAME or ${NAME:-word}.
|
||||
type expansion interface {
|
||||
// expand returns the value of the expansion.
|
||||
expand(c *expandContext) (string, error)
|
||||
|
||||
// variables returns the variable names referenced by the expansion, including the names in
|
||||
// its word or message.
|
||||
variables() []string
|
||||
}
|
||||
|
||||
// variableExpansion is $NAME or ${NAME}.
|
||||
type variableExpansion struct {
|
||||
Identifier string
|
||||
}
|
||||
|
||||
func (e variableExpansion) variables() []string {
|
||||
return []string{e.Identifier}
|
||||
}
|
||||
|
||||
func (e variableExpansion) expand(c *expandContext) (string, error) {
|
||||
return c.value(e.Identifier)
|
||||
}
|
||||
|
||||
// emptyValueExpansion is ${NAME:-word}: the value, or word if the variable is unset or empty.
|
||||
type emptyValueExpansion struct {
|
||||
Identifier string
|
||||
Content expression
|
||||
}
|
||||
|
||||
func (e emptyValueExpansion) variables() []string {
|
||||
return append([]string{e.Identifier}, e.Content.variables()...)
|
||||
}
|
||||
|
||||
func (e emptyValueExpansion) expand(c *expandContext) (string, error) {
|
||||
if value, _ := c.env.Lookup(e.Identifier); value != "" {
|
||||
return value, nil
|
||||
}
|
||||
return e.Content.expand(c)
|
||||
}
|
||||
|
||||
// unsetValueExpansion is ${NAME-word}: the value, or word if the variable is unset.
|
||||
type unsetValueExpansion struct {
|
||||
Identifier string
|
||||
Content expression
|
||||
}
|
||||
|
||||
func (e unsetValueExpansion) variables() []string {
|
||||
return append([]string{e.Identifier}, e.Content.variables()...)
|
||||
}
|
||||
|
||||
func (e unsetValueExpansion) expand(c *expandContext) (string, error) {
|
||||
if value, ok := c.env.Lookup(e.Identifier); ok {
|
||||
return value, nil
|
||||
}
|
||||
return e.Content.expand(c)
|
||||
}
|
||||
|
||||
// requiredExpansion is ${NAME?message}: the value, or an error if the variable is unset.
|
||||
type requiredExpansion struct {
|
||||
Identifier string
|
||||
Message expression
|
||||
}
|
||||
|
||||
func (e requiredExpansion) variables() []string {
|
||||
return append([]string{e.Identifier}, e.Message.variables()...)
|
||||
}
|
||||
|
||||
func (e requiredExpansion) expand(c *expandContext) (string, error) {
|
||||
value, ok := c.env.Lookup(e.Identifier)
|
||||
if !ok {
|
||||
return "", c.unsetError(e.Identifier, e.Message, "not set")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// requiredNonEmptyExpansion is ${NAME:?message}: the value, or an error if the variable is unset
|
||||
// or empty.
|
||||
type requiredNonEmptyExpansion struct {
|
||||
Identifier string
|
||||
Message expression
|
||||
}
|
||||
|
||||
func (e requiredNonEmptyExpansion) variables() []string {
|
||||
return append([]string{e.Identifier}, e.Message.variables()...)
|
||||
}
|
||||
|
||||
func (e requiredNonEmptyExpansion) expand(c *expandContext) (string, error) {
|
||||
value, _ := c.env.Lookup(e.Identifier)
|
||||
if value == "" {
|
||||
return "", c.unsetError(e.Identifier, e.Message, "empty or not set")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// alternateExpansion is ${NAME+word}: word if the variable is set, otherwise an empty string.
|
||||
type alternateExpansion struct {
|
||||
Identifier string
|
||||
Content expression
|
||||
}
|
||||
|
||||
func (e alternateExpansion) variables() []string {
|
||||
return append([]string{e.Identifier}, e.Content.variables()...)
|
||||
}
|
||||
|
||||
func (e alternateExpansion) expand(c *expandContext) (string, error) {
|
||||
if _, ok := c.env.Lookup(e.Identifier); !ok {
|
||||
return "", nil
|
||||
}
|
||||
return e.Content.expand(c)
|
||||
}
|
||||
|
||||
// alternateNonEmptyExpansion is ${NAME:+word}: word if the variable is set and not empty,
|
||||
// otherwise an empty string.
|
||||
type alternateNonEmptyExpansion struct {
|
||||
Identifier string
|
||||
Content expression
|
||||
}
|
||||
|
||||
func (e alternateNonEmptyExpansion) variables() []string {
|
||||
return append([]string{e.Identifier}, e.Content.variables()...)
|
||||
}
|
||||
|
||||
func (e alternateNonEmptyExpansion) expand(c *expandContext) (string, error) {
|
||||
if value, _ := c.env.Lookup(e.Identifier); value == "" {
|
||||
return "", nil
|
||||
}
|
||||
return e.Content.expand(c)
|
||||
}
|
||||
|
||||
// lengthExpansion is ${#NAME}: the number of characters in the value.
|
||||
type lengthExpansion struct {
|
||||
Identifier string
|
||||
}
|
||||
|
||||
func (e lengthExpansion) variables() []string {
|
||||
return []string{e.Identifier}
|
||||
}
|
||||
|
||||
func (e lengthExpansion) expand(c *expandContext) (string, error) {
|
||||
value, err := c.value(e.Identifier)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strconv.Itoa(utf8.RuneCountInString(value)), nil
|
||||
}
|
||||
|
||||
// substringExpansion is ${NAME:offset} or ${NAME:offset:length}.
|
||||
type substringExpansion struct {
|
||||
Identifier string
|
||||
Offset int
|
||||
Length int
|
||||
HasLength bool
|
||||
}
|
||||
|
||||
func (e substringExpansion) variables() []string {
|
||||
return []string{e.Identifier}
|
||||
}
|
||||
|
||||
func (e substringExpansion) expand(c *expandContext) (string, error) {
|
||||
value, err := c.value(e.Identifier)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Offsets and lengths count characters, not bytes, the same as bash in a UTF-8 locale. Each
|
||||
// invalid UTF-8 byte counts as one character and is kept unchanged.
|
||||
size := utf8.RuneCountInString(value)
|
||||
|
||||
// A negative offset counts from the end. An offset before the start gives an empty string,
|
||||
// the same as bash. The order of operations prevents integer overflow for extreme offsets
|
||||
// and lengths.
|
||||
from := e.Offset
|
||||
if from < 0 {
|
||||
if from < -size {
|
||||
return "", nil
|
||||
}
|
||||
from += size
|
||||
}
|
||||
from = min(from, size)
|
||||
|
||||
// A positive length counts from the offset. A negative length counts back from the end, and
|
||||
// cannot go before the offset.
|
||||
to := size
|
||||
if e.HasLength {
|
||||
if e.Length >= 0 {
|
||||
to = from + min(e.Length, size-from)
|
||||
} else {
|
||||
to = max(size+e.Length, from)
|
||||
}
|
||||
}
|
||||
|
||||
start := byteOffset(value, from)
|
||||
end := start + byteOffset(value[start:], to-from)
|
||||
return value[start:end], nil
|
||||
}
|
||||
|
||||
// byteOffset returns the byte offset of the character at index in s. Each invalid UTF-8 byte
|
||||
// counts as one character, the same as [utf8.RuneCountInString].
|
||||
func byteOffset(s string, index int) int {
|
||||
offset := 0
|
||||
for range index {
|
||||
_, size := utf8.DecodeRuneInString(s[offset:])
|
||||
offset += size
|
||||
}
|
||||
return offset
|
||||
}
|
||||
+53
-186
@@ -1,213 +1,80 @@
|
||||
package interpolate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Interpolate takes a set of environment and interpolates it into the provided string using shell
|
||||
// script expansions
|
||||
func Interpolate(env Env, str string) (string, error) {
|
||||
if env == nil {
|
||||
env = NewSliceEnv(nil)
|
||||
// Expand returns s with each parameter expansion replaced by its value, and each escape such as
|
||||
// $$ replaced by its text. Values come from env. A nil env has no variables.
|
||||
//
|
||||
// Expand returns an error if s is not valid, and an [*UnsetVariableError] if a variable that must
|
||||
// have a value does not have one.
|
||||
func Expand(s string, env Env, opts ...Option) (string, error) {
|
||||
var cfg config
|
||||
for _, opt := range opts {
|
||||
opt.apply(&cfg)
|
||||
}
|
||||
expr, err := NewParser(str).Parse()
|
||||
if env == nil {
|
||||
env = mapEnv{}
|
||||
}
|
||||
expr, err := newParser(s).Parse()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return expr.Expand(env)
|
||||
return expr.expand(&expandContext{env: env, noUnset: cfg.noUnset})
|
||||
}
|
||||
|
||||
// Indentifiers parses the identifiers from any expansions in the provided string
|
||||
func Identifiers(str string) ([]string, error) {
|
||||
expr, err := NewParser(str).Parse()
|
||||
// Variables returns the names of the variables that s refers to, in the order of their first use,
|
||||
// with no repeats. It includes the variables in the words and messages of expansions, such as
|
||||
// FALLBACK in ${NAME:-$FALLBACK}, and does not include escaped references such as $$NAME.
|
||||
//
|
||||
// Variables returns an error if s is not valid.
|
||||
func Variables(s string) ([]string, error) {
|
||||
expr, err := newParser(s).Parse()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return expr.Identifiers(), nil
|
||||
}
|
||||
|
||||
// An expansion is something that takes in ENV and returns a string or an error
|
||||
type Expansion interface {
|
||||
Expand(env Env) (string, error)
|
||||
Identifiers() []string
|
||||
}
|
||||
|
||||
// VariableExpansion represents either $VAR or ${VAR}, our simplest expansion
|
||||
type VariableExpansion struct {
|
||||
Identifier string
|
||||
}
|
||||
|
||||
func (e VariableExpansion) Identifiers() []string {
|
||||
return []string{e.Identifier}
|
||||
}
|
||||
|
||||
func (e VariableExpansion) Expand(env Env) (string, error) {
|
||||
val, _ := env.Get(e.Identifier)
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// EmptyValueExpansion returns either the value of an env, or a default value if it's unset or null
|
||||
type EmptyValueExpansion struct {
|
||||
Identifier string
|
||||
Content Expression
|
||||
}
|
||||
|
||||
func (e EmptyValueExpansion) Identifiers() []string {
|
||||
return append([]string{e.Identifier}, e.Content.Identifiers()...)
|
||||
}
|
||||
|
||||
func (e EmptyValueExpansion) Expand(env Env) (string, error) {
|
||||
val, _ := env.Get(e.Identifier)
|
||||
if val == "" {
|
||||
return e.Content.Expand(env)
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// UnsetValueExpansion returns either the value of an env, or a default value if it's unset
|
||||
type UnsetValueExpansion struct {
|
||||
Identifier string
|
||||
Content Expression
|
||||
}
|
||||
|
||||
func (e UnsetValueExpansion) Identifiers() []string {
|
||||
return []string{e.Identifier}
|
||||
}
|
||||
|
||||
func (e UnsetValueExpansion) Expand(env Env) (string, error) {
|
||||
val, ok := env.Get(e.Identifier)
|
||||
if !ok {
|
||||
return e.Content.Expand(env)
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
|
||||
// SubstringExpansion returns a substring (or slice) of the env
|
||||
type SubstringExpansion struct {
|
||||
Identifier string
|
||||
Offset int
|
||||
Length int
|
||||
HasLength bool
|
||||
}
|
||||
|
||||
func (e SubstringExpansion) Identifiers() []string {
|
||||
return []string{e.Identifier}
|
||||
}
|
||||
|
||||
func (e SubstringExpansion) Expand(env Env) (string, error) {
|
||||
val, _ := env.Get(e.Identifier)
|
||||
|
||||
from := e.Offset
|
||||
|
||||
// Negative offsets = from end
|
||||
if from < 0 {
|
||||
from += len(val)
|
||||
}
|
||||
|
||||
// Still negative = too far from end? Truncate to start.
|
||||
if from < 0 {
|
||||
from = 0
|
||||
}
|
||||
|
||||
// Beyond end? Truncate to end.
|
||||
if from > len(val) {
|
||||
from = len(val)
|
||||
}
|
||||
|
||||
if !e.HasLength {
|
||||
return val[from:], nil
|
||||
}
|
||||
|
||||
to := e.Length
|
||||
|
||||
if to >= 0 {
|
||||
// Positive length = from offset
|
||||
to += from
|
||||
} else {
|
||||
// Negative length = from end
|
||||
to += len(val)
|
||||
|
||||
// Too far? Truncate to offset.
|
||||
if to < from {
|
||||
to = from
|
||||
names := []string{}
|
||||
seen := make(map[string]bool)
|
||||
for _, name := range expr.variables() {
|
||||
if !seen[name] {
|
||||
seen[name] = true
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
|
||||
// Beyond end? Truncate to end.
|
||||
if to > len(val) {
|
||||
to = len(val)
|
||||
}
|
||||
|
||||
return val[from:to], nil
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// RequiredExpansion returns an env value, or an error if it is unset
|
||||
type RequiredExpansion struct {
|
||||
Identifier string
|
||||
Message Expression
|
||||
// Option configures [Expand].
|
||||
type Option interface {
|
||||
apply(*config)
|
||||
}
|
||||
|
||||
func (e RequiredExpansion) Identifiers() []string {
|
||||
return []string{e.Identifier}
|
||||
// WithNoUnset makes a reference to an unset variable an error, the same as set -u (nounset) in
|
||||
// bash. It applies to $NAME, ${NAME}, ${#NAME}, ${NAME:offset} and ${NAME:offset:length}.
|
||||
// Expansions that handle an unset variable, such as ${NAME:-word} and ${NAME+word}, do not
|
||||
// change. The error is an [*UnsetVariableError] with the message "not set".
|
||||
func WithNoUnset() Option {
|
||||
return noUnsetOption{}
|
||||
}
|
||||
|
||||
func (e RequiredExpansion) Expand(env Env) (string, error) {
|
||||
val, ok := env.Get(e.Identifier)
|
||||
if !ok {
|
||||
msg, err := e.Message.Expand(env)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if msg == "" {
|
||||
msg = "not set"
|
||||
}
|
||||
return "", fmt.Errorf("$%s: %s", e.Identifier, msg)
|
||||
}
|
||||
return val, nil
|
||||
// UnsetVariableError is the error for a variable that must have a value but does not. It comes
|
||||
// from ${NAME?message}, from ${NAME:?message}, and from a reference to an unset variable with
|
||||
// [WithNoUnset].
|
||||
type UnsetVariableError struct {
|
||||
// Name is the name of the variable.
|
||||
Name string
|
||||
// Message is the expanded message from the expansion, or a default message such as "not set".
|
||||
Message string
|
||||
}
|
||||
|
||||
// Expression is a collection of either Text or Expansions
|
||||
type Expression []ExpressionItem
|
||||
|
||||
func (e Expression) Identifiers() []string {
|
||||
identifiers := []string{}
|
||||
for _, item := range e {
|
||||
if item.Expansion != nil {
|
||||
identifiers = append(identifiers, item.Expansion.Identifiers()...)
|
||||
}
|
||||
}
|
||||
return identifiers
|
||||
// Error returns the error in the form "$NAME: message".
|
||||
func (e *UnsetVariableError) Error() string {
|
||||
return "$" + e.Name + ": " + e.Message
|
||||
}
|
||||
|
||||
func (e Expression) Expand(env Env) (string, error) {
|
||||
buf := &bytes.Buffer{}
|
||||
|
||||
for _, item := range e {
|
||||
if item.Expansion != nil {
|
||||
result, err := item.Expansion.Expand(env)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, _ = buf.WriteString(result)
|
||||
} else {
|
||||
_, _ = buf.WriteString(item.Text)
|
||||
}
|
||||
}
|
||||
|
||||
return buf.String(), nil
|
||||
type config struct {
|
||||
noUnset bool
|
||||
}
|
||||
|
||||
// ExpressionItem models either an Expansion or Text. Either/Or, never both.
|
||||
type ExpressionItem struct {
|
||||
Text string
|
||||
// -- or --
|
||||
Expansion Expansion
|
||||
}
|
||||
type noUnsetOption struct{}
|
||||
|
||||
func (i ExpressionItem) String() string {
|
||||
if i.Expansion != nil {
|
||||
return fmt.Sprintf("%#v", i.Expansion)
|
||||
}
|
||||
return fmt.Sprintf("%q", i.Text)
|
||||
func (noUnsetOption) apply(cfg *config) {
|
||||
cfg.noUnset = true
|
||||
}
|
||||
+186
-109
@@ -1,10 +1,10 @@
|
||||
package interpolate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
@@ -23,39 +23,60 @@ import (
|
||||
// functions and structs named the same reading the string bite by bite (peekRune and nextRune)
|
||||
|
||||
/*
|
||||
EscapedBackslash = "\\" EscapedDollar = ( "\$" | "$$") Identifier = letter { letters |
|
||||
digit | "_" } Expansion = "$" ( Identifier | Brace ) Brace = "{" Identifier [
|
||||
Identifier BraceOperation ] "}" Text = { EscapedBackslash | EscapedDollar | all characters except
|
||||
"$" } Expression = { Text | Expansion } EmptyValue = ":-" { Expression } UnsetValue =
|
||||
"-" { Expression } Substring = ":" number [ ":" number ] Required = "?" { Expression }
|
||||
Operation = EmptyValue | UnsetValue | Substring | Required
|
||||
EscapedBackslash = "\\"
|
||||
EscapedDollar = ( "\$" | "$$")
|
||||
Identifier = ( letter | "_" ) { letter | digit | "_" }
|
||||
Expansion = "$" ( Identifier | Brace )
|
||||
LiteralDollar = "$" (not followed by "{" or a letter or "_")
|
||||
Brace = "{" ( Length | Identifier [ Operation ] ) "}"
|
||||
EscapedBrace = "\}" (only in the word of a brace expansion)
|
||||
Text = { EscapedBackslash | EscapedDollar | EscapedBrace | LiteralDollar | all characters except "$" }
|
||||
Expression = { Text | Expansion }
|
||||
Length = "#" Identifier
|
||||
EmptyValue = ":-" { Expression }
|
||||
UnsetValue = "-" { Expression }
|
||||
Substring = ":" number [ ":" number ]
|
||||
RequiredNonEmpty = ":?" { Expression }
|
||||
Required = "?" { Expression }
|
||||
AlternateNonEmpty = ":+" { Expression }
|
||||
Alternate = "+" { Expression }
|
||||
Operation = EmptyValue | UnsetValue | Substring | RequiredNonEmpty | Required | AlternateNonEmpty | Alternate
|
||||
*/
|
||||
|
||||
const (
|
||||
eof = -1
|
||||
|
||||
// maxNestingDepth is the maximum number of brace expansions that can be nested inside each
|
||||
// other, as in ${A:-${B:-${C}}}. The parser is recursive, so the limit protects against stack
|
||||
// exhaustion from untrusted input.
|
||||
maxNestingDepth = 1000
|
||||
)
|
||||
|
||||
// Parser takes a string and parses out a tree of structs that represent text and Expansions
|
||||
type Parser struct {
|
||||
// parser takes a string and parses out a tree of structs that represent text and Expansions
|
||||
type parser struct {
|
||||
input string // the string we are scanning
|
||||
pos int // the current position
|
||||
depth int // the current number of nested brace expansions
|
||||
}
|
||||
|
||||
// NewParser returns a new instance of a Parser
|
||||
func NewParser(str string) *Parser {
|
||||
return &Parser{
|
||||
// newParser returns a new instance of a Parser
|
||||
func newParser(str string) *parser {
|
||||
return &parser{
|
||||
input: str,
|
||||
pos: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Parse expansions out of the internal text and return them as a tree of Expressions
|
||||
func (p *Parser) Parse() (Expression, error) {
|
||||
// Parse expansions out of the internal text and return them as a tree of Expressions. Each call
|
||||
// parses the whole input again.
|
||||
func (p *parser) Parse() (expression, error) {
|
||||
p.pos = 0
|
||||
p.depth = 0
|
||||
return p.parseExpression()
|
||||
}
|
||||
|
||||
func (p *Parser) parseExpression(stop ...rune) (Expression, error) {
|
||||
var expr Expression
|
||||
func (p *parser) parseExpression(stop ...rune) (expression, error) {
|
||||
var expr expression
|
||||
var stopStr = string(stop)
|
||||
|
||||
for {
|
||||
@@ -67,48 +88,50 @@ func (p *Parser) parseExpression(stop ...rune) (Expression, error) {
|
||||
// check for our escaped characters first, as we assume nothing subsequently is escaped
|
||||
if strings.HasPrefix(p.input[p.pos:], `\\`) {
|
||||
p.pos += 2
|
||||
expr = append(expr, ExpressionItem{Text: `\\`})
|
||||
expr = append(expr, expressionItem{Text: `\\`})
|
||||
continue
|
||||
} else if stopStr != "" && strings.HasPrefix(p.input[p.pos:], `\}`) {
|
||||
// Inside a brace expansion, an escaped closing brace is text and does not end the
|
||||
// expansion, the same as bash.
|
||||
p.pos += 2
|
||||
expr = append(expr, expressionItem{Text: `}`})
|
||||
continue
|
||||
} else if strings.HasPrefix(p.input[p.pos:], `\$`) || strings.HasPrefix(p.input[p.pos:], `$$`) {
|
||||
p.pos += 2
|
||||
expr = append(expr, ExpressionItem{Text: `$`})
|
||||
expr = append(expr, expressionItem{Text: `$`})
|
||||
continue
|
||||
}
|
||||
|
||||
// Ignore bash shell expansions
|
||||
if strings.HasPrefix(p.input[p.pos:], `$(`) {
|
||||
p.pos += 2
|
||||
expr = append(expr, ExpressionItem{Text: `$(`})
|
||||
continue
|
||||
}
|
||||
|
||||
// If we run into a dollar sign and it's not the last char, it's an expansion
|
||||
if c == '$' && p.pos < (len(p.input)-1) {
|
||||
// A dollar sign starts an expansion only when a brace or a name follows it. Anything else,
|
||||
// such as "$1", "$ ", "$(" or a trailing "$", is literal text.
|
||||
if c == '$' && p.isExpansionStart() {
|
||||
expansion, err := p.parseExpansion()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
expr = append(expr, ExpressionItem{Expansion: expansion})
|
||||
expr = append(expr, expressionItem{Expansion: expansion})
|
||||
continue
|
||||
}
|
||||
|
||||
// nibble a character, otherwise if it's a \ or a $ we can loop
|
||||
c = p.nextRune()
|
||||
// Nibble a character, otherwise if it's a \ or a $ we can loop. Slice the input instead of
|
||||
// re-encoding runes, so invalid UTF-8 bytes pass through unchanged.
|
||||
start := p.pos
|
||||
_ = p.nextRune()
|
||||
|
||||
// Scan as much as we can into text
|
||||
text := p.scanUntil(func(r rune) bool {
|
||||
p.scanUntil(func(r rune) bool {
|
||||
return (r == '$' || r == '\\' || strings.ContainsRune(stopStr, r))
|
||||
})
|
||||
|
||||
expr = append(expr, ExpressionItem{Text: string(c) + text})
|
||||
expr = append(expr, expressionItem{Text: p.input[start:p.pos]})
|
||||
}
|
||||
|
||||
return expr, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseExpansion() (Expansion, error) {
|
||||
func (p *parser) parseExpansion() (expansion, error) {
|
||||
if c := p.nextRune(); c != '$' {
|
||||
return nil, fmt.Errorf("Expected expansion to start with $, got %c", c)
|
||||
return nil, fmt.Errorf("expected expansion to start with $, got %s", describeRune(c))
|
||||
}
|
||||
|
||||
// if we have an open brace, this is a brace expansion
|
||||
@@ -121,12 +144,28 @@ func (p *Parser) parseExpansion() (Expansion, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return VariableExpansion{Identifier: identifier}, nil
|
||||
return variableExpansion{Identifier: identifier}, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseBraceExpansion() (Expansion, error) {
|
||||
func (p *parser) parseBraceExpansion() (expansion, error) {
|
||||
if c := p.nextRune(); c != '{' {
|
||||
return nil, fmt.Errorf("Expected brace expansion to start with {, got %c", c)
|
||||
return nil, fmt.Errorf("expected brace expansion to start with {, got %s", describeRune(c))
|
||||
}
|
||||
|
||||
p.depth++
|
||||
defer func() { p.depth-- }()
|
||||
if p.depth > maxNestingDepth {
|
||||
return nil, fmt.Errorf("brace expansions nested deeper than %d levels", maxNestingDepth)
|
||||
}
|
||||
|
||||
if c := p.peekRune(); c == '}' {
|
||||
return nil, errors.New("empty expansion ${}, expected a variable name")
|
||||
}
|
||||
|
||||
// ${#parameter} is the length of the value, so it has a prefix and no operator.
|
||||
if c := p.peekRune(); c == '#' {
|
||||
_ = p.nextRune()
|
||||
return p.parseLengthExpansion()
|
||||
}
|
||||
|
||||
identifier, err := p.scanIdentifier()
|
||||
@@ -136,87 +175,100 @@ func (p *Parser) parseBraceExpansion() (Expansion, error) {
|
||||
|
||||
if c := p.peekRune(); c == '}' {
|
||||
_ = p.nextRune()
|
||||
return VariableExpansion{Identifier: identifier}, nil
|
||||
return variableExpansion{Identifier: identifier}, nil
|
||||
}
|
||||
|
||||
var operator string
|
||||
var exp Expansion
|
||||
operator, err := p.scanOperator()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Parse an operator, some trickery is needed to handle : vs :-
|
||||
if op1 := p.nextRune(); op1 == ':' {
|
||||
if op2 := p.peekRune(); op2 == '-' {
|
||||
_ = p.nextRune()
|
||||
operator = ":-"
|
||||
} else {
|
||||
operator = ":"
|
||||
var expansion expansion
|
||||
if operator == ":" {
|
||||
expansion, err = p.parseSubstringExpansion(identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if op1 == '?' || op1 == '-' {
|
||||
operator = string(op1)
|
||||
} else {
|
||||
return nil, fmt.Errorf("Expected an operator, got %c", op1)
|
||||
}
|
||||
|
||||
switch operator {
|
||||
case `:-`:
|
||||
exp, err = p.parseEmptyValueExpansion(identifier)
|
||||
// All other operators take a word: an expression (text and expansions) up until the end
|
||||
// of the brace.
|
||||
word, err := p.parseExpression('}')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case `-`:
|
||||
exp, err = p.parseUnsetValueExpansion(identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case `:`:
|
||||
exp, err = p.parseSubstringExpansion(identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case `?`:
|
||||
exp, err = p.parseRequiredExpansion(identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
switch operator {
|
||||
case ":-":
|
||||
expansion = emptyValueExpansion{Identifier: identifier, Content: word}
|
||||
case "-":
|
||||
expansion = unsetValueExpansion{Identifier: identifier, Content: word}
|
||||
case ":?":
|
||||
expansion = requiredNonEmptyExpansion{Identifier: identifier, Message: word}
|
||||
case "?":
|
||||
expansion = requiredExpansion{Identifier: identifier, Message: word}
|
||||
case ":+":
|
||||
expansion = alternateNonEmptyExpansion{Identifier: identifier, Content: word}
|
||||
case "+":
|
||||
expansion = alternateExpansion{Identifier: identifier, Content: word}
|
||||
}
|
||||
}
|
||||
|
||||
if c := p.nextRune(); c != '}' {
|
||||
return nil, fmt.Errorf("Expected brace expansion to end with }, got %c", c)
|
||||
return nil, fmt.Errorf("expected brace expansion to end with }, got %s", describeRune(c))
|
||||
}
|
||||
|
||||
return exp, nil
|
||||
return expansion, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseEmptyValueExpansion(identifier string) (Expansion, error) {
|
||||
// parse an expression (text and expansions) up until the end of the brace
|
||||
expr, err := p.parseExpression('}')
|
||||
// scanOperator scans the operator after the identifier in a brace expansion. A colon on its own
|
||||
// is a substring operator. A colon followed by "-", "?" or "+" also treats an empty value as
|
||||
// unset.
|
||||
func (p *parser) scanOperator() (string, error) {
|
||||
switch op1 := p.nextRune(); op1 {
|
||||
case ':':
|
||||
if op2 := p.peekRune(); op2 == '-' || op2 == '?' || op2 == '+' {
|
||||
_ = p.nextRune()
|
||||
return string([]rune{op1, op2}), nil
|
||||
}
|
||||
return ":", nil
|
||||
case '-', '?', '+':
|
||||
return string(op1), nil
|
||||
default:
|
||||
return "", fmt.Errorf("expected an operator, got %s", describeRune(op1))
|
||||
}
|
||||
}
|
||||
|
||||
func (p *parser) parseLengthExpansion() (expansion, error) {
|
||||
identifier, err := p.scanIdentifier()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return EmptyValueExpansion{Identifier: identifier, Content: expr}, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseUnsetValueExpansion(identifier string) (Expansion, error) {
|
||||
expr, err := p.parseExpression('}')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if c := p.nextRune(); c != '}' {
|
||||
return nil, fmt.Errorf("expected length expansion to end with }, got %s", describeRune(c))
|
||||
}
|
||||
|
||||
return UnsetValueExpansion{Identifier: identifier, Content: expr}, nil
|
||||
return lengthExpansion{Identifier: identifier}, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseSubstringExpansion(identifier string) (Expansion, error) {
|
||||
func (p *parser) parseSubstringExpansion(identifier string) (expansion, error) {
|
||||
offset := p.scanUntil(func(r rune) bool {
|
||||
return r == ':' || r == '}'
|
||||
})
|
||||
|
||||
offsetInt, err := strconv.Atoi(strings.TrimSpace(offset))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to parse offset: %v", err)
|
||||
// Bash rejects ${VAR:}, but treats a blank offset as 0 when it is followed by a length, as in
|
||||
// ${VAR::2}, or when it has only spaces, as in ${VAR: }.
|
||||
hasLength := p.peekRune() == ':'
|
||||
if offset == "" && !hasLength {
|
||||
return nil, fmt.Errorf("expected substring offset, got %s", describeRune(p.peekRune()))
|
||||
}
|
||||
|
||||
if c := p.peekRune(); c == '}' {
|
||||
return SubstringExpansion{Identifier: identifier, Offset: offsetInt}, nil
|
||||
offsetInt, err := parseSubstringNumber(offset)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse substring offset: %w", err)
|
||||
}
|
||||
|
||||
if !hasLength {
|
||||
return substringExpansion{Identifier: identifier, Offset: offsetInt}, nil
|
||||
}
|
||||
|
||||
_ = p.nextRune()
|
||||
@@ -224,28 +276,28 @@ func (p *Parser) parseSubstringExpansion(identifier string) (Expansion, error) {
|
||||
return r == '}'
|
||||
})
|
||||
|
||||
lengthInt, err := strconv.Atoi(strings.TrimSpace(length))
|
||||
lengthInt, err := parseSubstringNumber(length)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Unable to parse length: %v", err)
|
||||
return nil, fmt.Errorf("parse substring length: %w", err)
|
||||
}
|
||||
|
||||
return SubstringExpansion{Identifier: identifier, Offset: offsetInt, Length: lengthInt, HasLength: true}, nil
|
||||
return substringExpansion{Identifier: identifier, Offset: offsetInt, Length: lengthInt, HasLength: true}, nil
|
||||
}
|
||||
|
||||
func (p *Parser) parseRequiredExpansion(identifier string) (Expansion, error) {
|
||||
expr, err := p.parseExpression('}')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// parseSubstringNumber parses a substring offset or length. A blank value is 0, the same as bash.
|
||||
func parseSubstringNumber(value string) (int, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return RequiredExpansion{Identifier: identifier, Message: expr}, nil
|
||||
return strconv.Atoi(value)
|
||||
}
|
||||
|
||||
func (p *Parser) scanUntil(f func(rune) bool) string {
|
||||
func (p *parser) scanUntil(f func(rune) bool) string {
|
||||
start := p.pos
|
||||
for int(p.pos) < len(p.input) {
|
||||
for p.pos < len(p.input) {
|
||||
c, size := utf8.DecodeRuneInString(p.input[p.pos:])
|
||||
if c == utf8.RuneError || f(c) {
|
||||
if f(c) {
|
||||
break
|
||||
}
|
||||
p.pos += size
|
||||
@@ -253,18 +305,35 @@ func (p *Parser) scanUntil(f func(rune) bool) string {
|
||||
return p.input[start:p.pos]
|
||||
}
|
||||
|
||||
func (p *Parser) scanIdentifier() (string, error) {
|
||||
if c := p.peekRune(); !unicode.IsLetter(c) {
|
||||
return "", fmt.Errorf("Expected identifier to start with a letter, got %c", c)
|
||||
func (p *parser) scanIdentifier() (string, error) {
|
||||
if c := p.peekRune(); !isIdentifierStart(c) {
|
||||
return "", fmt.Errorf("expected identifier to start with a letter or underscore, got %s", describeRune(c))
|
||||
}
|
||||
var notIdentifierChar = func(r rune) bool {
|
||||
return (!unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_')
|
||||
notIdentifierChar := func(r rune) bool {
|
||||
return !isIdentifierChar(r)
|
||||
}
|
||||
return p.scanUntil(notIdentifierChar), nil
|
||||
}
|
||||
|
||||
func (p *Parser) nextRune() rune {
|
||||
if int(p.pos) >= len(p.input) {
|
||||
// isExpansionStart reports whether the dollar sign at the current position starts an expansion.
|
||||
func (p *parser) isExpansionStart() bool {
|
||||
next, _ := utf8.DecodeRuneInString(p.input[p.pos+1:])
|
||||
return next == '{' || isIdentifierStart(next)
|
||||
}
|
||||
|
||||
// isIdentifierStart reports whether r can start a POSIX name: an ASCII letter or an underscore.
|
||||
func isIdentifierStart(r rune) bool {
|
||||
return r == '_' || ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z')
|
||||
}
|
||||
|
||||
// isIdentifierChar reports whether r can continue a POSIX name: an ASCII letter, an ASCII digit,
|
||||
// or an underscore.
|
||||
func isIdentifierChar(r rune) bool {
|
||||
return isIdentifierStart(r) || ('0' <= r && r <= '9')
|
||||
}
|
||||
|
||||
func (p *parser) nextRune() rune {
|
||||
if p.pos >= len(p.input) {
|
||||
return eof
|
||||
}
|
||||
c, size := utf8.DecodeRuneInString(p.input[p.pos:])
|
||||
@@ -272,10 +341,18 @@ func (p *Parser) nextRune() rune {
|
||||
return c
|
||||
}
|
||||
|
||||
func (p *Parser) peekRune() rune {
|
||||
if int(p.pos) >= len(p.input) {
|
||||
func (p *parser) peekRune() rune {
|
||||
if p.pos >= len(p.input) {
|
||||
return eof
|
||||
}
|
||||
c, _ := utf8.DecodeRuneInString(p.input[p.pos:])
|
||||
return c
|
||||
}
|
||||
|
||||
// describeRune returns a description of r for use in error messages.
|
||||
func describeRune(r rune) string {
|
||||
if r == eof {
|
||||
return "end of input"
|
||||
}
|
||||
return fmt.Sprintf("%q", r)
|
||||
}
|
||||
Reference in new issue
Block a user