interpolate

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 6 Imported by: 14 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Interpolate

Build Status Go Reference

A Go library for parameter expansion (like ${NAME} or $NAME) in strings from environment variables. An implementation of POSIX Parameter Expansion, plus some other basic operations that you'd expect in a shell scripting environment like bash.

Installation

go get github.com/mfridman/interpolate@latest

Requires Go 1.25 or later.

Usage

package main

import (
  "github.com/mfridman/interpolate"
  "fmt"
)

func main() {
  env := interpolate.NewSliceEnv([]string{
    "NAME=James",
  })

  output, _ := interpolate.Interpolate(env, "Hello... ${NAME} welcome to the ${ANOTHER_VAR:-🏖}")

  fmt.Println(output)
  // Output: Hello... James welcome to the 🏖
}

Supported Expansions

  • ${parameter} or $parameter

    • Use value. If parameter is set, then it shall be substituted; otherwise, it will be blank.
  • ${parameter:-[word]}

    • 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.
  • ${parameter-[word]}

    • 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.
  • ${parameter:?[word]}

    • Indicate error if null or unset. If parameter is unset or null, the expansion of word (or a message indicating it is empty or unset if word is omitted) shall be returned as an error.
  • ${parameter?[word]}

    • Indicate error if unset. If parameter is unset, the expansion of word (or a message indicating it is unset if word is omitted) shall be returned as an error.
  • ${parameter:+[word]}

    • Use alternative value. If parameter is unset or null, an empty string shall be substituted; otherwise, the expansion of word shall be substituted.
  • ${parameter+[word]}

    • Use alternative value when set. If parameter is unset, an empty string shall be substituted; otherwise, the expansion of word shall be substituted.
  • ${#parameter}

    • String length. The length in characters of the value of parameter shall be substituted. An unset parameter has a length of 0.
  • ${parameter:offset}

    • Use the substring of parameter after offset. A negative offset counts from the end of the value, and must be separated from the colon with a space, as in ${parameter: -2}. An offset past the end, or before the start, gives an empty string.
  • ${parameter:[offset]:[length]}

    • Use the substring of parameter after offset, of at most length characters. A length past the end gives the rest of the value after the offset. A negative length ends that many characters before the end of the value, so ${parameter:1:-1} removes the first and the last character. A blank offset or length counts as 0, so ${parameter::2} is the first two characters.

    Offsets and lengths count characters, not bytes, and are decimal integers; arithmetic expressions are not supported. The offset is required unless a length follows it, so ${parameter:} is an error.

A parameter name starts with a letter or an underscore, followed by letters, digits, or underscores ([A-Za-z_][A-Za-z0-9_]*).

Escaping and literal dollar signs

  • $$parameter, \$parameter, $${expression}, or \${expression}

    • Escaped expansion. The expansion is not interpolated. Interpolate removes one level of escaping, so $$NAME becomes $NAME.
  • $ not followed by a letter, an underscore, or {

    • Literal dollar sign. The $ is kept as-is. For example, $1, $(command), price: $5, and a trailing $ are not changed.
  • \} in the word of a brace expansion

    • Escaped closing brace. The word stops at the first }, so write \} for a literal }. For example, ${CONFIG:-{"a":1\}} gives {"a":1} when CONFIG is unset or empty. Outside a brace expansion, \} is kept as-is.
  • \\

    • Backslashes are kept. A double backslash is kept as two backslashes, and it does not escape the $ that follows it. For example, \\$NAME gives \\ followed by the value of NAME. This keeps SQL strings such as E'\\n' unchanged. Because \$ is an escape, you cannot write 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 migrations with ENVSUB ON:

  • Dollar-quoted strings need escaping. $$ becomes $, and the $tag in $tag$ expands as a variable. Write $$$$ for $$ and $$tag$$ for $tag$.
  • A $ followed by a letter or _ is always a variable. For example, in format('%1$s', name), the $s expands. Write %1$$s.
  • Positional parameters such as $1, and $ in regular expressions such as '^abc$', are kept as-is.

Not supported

  • Pattern removal: ${parameter%word}, ${parameter%%word}, ${parameter#word}, and ${parameter##word}.
  • Assignment: ${parameter:=word} and ${parameter=word}.
  • Special and positional parameters, such as $1, $@, $*, $#, and $?. These are kept as literal text.

Prior work

This repository is a fork of 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.

This fork does not track upstream. It has the same behavior for bare $ signs, but it does not have upstream's EscapedExpansion type. In this fork, Identifiers("$$NAME") returns no identifiers, while upstream returns $NAME. See CHANGELOG.md for the changes in this fork.

License

Licensed under MIT license, in LICENSE.

Documentation

Overview

Package interpolate expands shell-style parameters, such as $NAME and ${NAME:-default}, in strings. It implements POSIX parameter expansion and some bash extensions, and reads values from an Env.

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.

Interpolate and Identifiers are safe for concurrent use if the Env is. A Parser is not.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Identifiers

func Identifiers(str string) ([]string, error)

Identifiers parses the identifiers from any expansions in the provided string

Example
package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	identifiers, err := interpolate.Identifiers("${HOST:-localhost}:${PORT:?port is required} $1")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(identifiers)

}
Output:
[HOST PORT]

func Interpolate

func Interpolate(env Env, str string) (string, error)

Interpolate takes a set of environment and interpolates it into the provided string using shell script expansions

Example
package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.NewSliceEnv([]string{
		"NAME=James",
	})

	output, err := interpolate.Interpolate(env, "Hello... ${NAME} welcome to the ${ANOTHER_VAR:-🏖}")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output)

}
Output:
Hello... James welcome to the 🏖

Types

type AlternateExpansion added in v0.1.0

type AlternateExpansion struct {
	Identifier string
	Content    Expression
}

AlternateExpansion returns the expansion of Content if the env is set, and an empty string otherwise. This is ${VAR+word}.

func (AlternateExpansion) Expand added in v0.1.0

func (e AlternateExpansion) Expand(env Env) (string, error)

func (AlternateExpansion) Identifiers added in v0.1.0

func (e AlternateExpansion) Identifiers() []string

type AlternateNonEmptyExpansion added in v0.1.0

type AlternateNonEmptyExpansion struct {
	Identifier string
	Content    Expression
}

AlternateNonEmptyExpansion returns the expansion of Content if the env is set and not empty, and an empty string otherwise. This is ${VAR:+word}.

func (AlternateNonEmptyExpansion) Expand added in v0.1.0

func (e AlternateNonEmptyExpansion) Expand(env Env) (string, error)

func (AlternateNonEmptyExpansion) Identifiers added in v0.1.0

func (e AlternateNonEmptyExpansion) Identifiers() []string

type EmptyValueExpansion

type EmptyValueExpansion struct {
	Identifier string
	Content    Expression
}

EmptyValueExpansion returns either the value of an env, or a default value if it's unset or null

func (EmptyValueExpansion) Expand

func (e EmptyValueExpansion) Expand(env Env) (string, error)

func (EmptyValueExpansion) Identifiers

func (e EmptyValueExpansion) Identifiers() []string

type Env

type Env interface {
	Get(key string) (string, bool)
}

Env is an interface for getting environment variables by name and returning a boolean indicating whether the variable was found.

func NewMapEnv

func NewMapEnv(env map[string]string) Env

NewMapEnv creates an Env from a map of environment variables.

Example
package main

import (
	"fmt"
	"log"

	"github.com/mfridman/interpolate"
)

func main() {
	env := interpolate.NewMapEnv(map[string]string{
		"USER":  "llama",
		"EMPTY": "",
	})

	output, err := interpolate.Interpolate(env, "${USER:+--user=$USER} ${EMPTY:-default} ${#USER}")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(output)

}
Output:
--user=llama default 5

func NewSliceEnv

func NewSliceEnv(env []string) Env

NewSliceEnv creates an Env from a slice of environment variables in the form "key=value".

This can be used with os.Environ to create an Env.

type Expansion

type Expansion interface {
	// Expand expands the expansion using variables from env.
	Expand(env Env) (string, error)

	// Identifiers returns any variable names referenced within the expansion.
	Identifiers() []string
}

An expansion is something that takes in ENV and returns a string or an error

type Expression

type Expression []ExpressionItem

Expression is a collection of either Text or Expansions

func (Expression) Expand

func (e Expression) Expand(env Env) (string, error)

Expand expands all expansions in the expression using variables from env, and joins the results with the text.

func (Expression) Identifiers

func (e Expression) Identifiers() []string

Identifiers returns the variable names referenced by all expansions in the expression, in order. A name can occur more than once.

type ExpressionItem

type ExpressionItem struct {
	Text string
	// -- or --
	Expansion Expansion
}

ExpressionItem models either an Expansion or Text. Either/Or, never both.

func (ExpressionItem) String

func (i ExpressionItem) String() string

type LengthExpansion added in v0.1.0

type LengthExpansion struct {
	Identifier string
}

LengthExpansion returns the number of characters in an env value, or 0 if it is unset. This is ${#VAR}.

func (LengthExpansion) Expand added in v0.1.0

func (e LengthExpansion) Expand(env Env) (string, error)

func (LengthExpansion) Identifiers added in v0.1.0

func (e LengthExpansion) Identifiers() []string

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser takes a string and parses out a tree of structs that represent text and Expansions

func NewParser

func NewParser(str string) *Parser

NewParser returns a new instance of a Parser

func (*Parser) Parse

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.

type RequiredExpansion

type RequiredExpansion struct {
	Identifier string
	Message    Expression
}

RequiredExpansion returns an env value, or an error if it is unset. This is ${VAR?message}.

func (RequiredExpansion) Expand

func (e RequiredExpansion) Expand(env Env) (string, error)

func (RequiredExpansion) Identifiers

func (e RequiredExpansion) Identifiers() []string

type RequiredNonEmptyExpansion added in v0.1.0

type RequiredNonEmptyExpansion struct {
	Identifier string
	Message    Expression
}

RequiredNonEmptyExpansion returns an env value, or an error if it is unset or empty. This is ${VAR:?message}.

func (RequiredNonEmptyExpansion) Expand added in v0.1.0

func (e RequiredNonEmptyExpansion) Expand(env Env) (string, error)

func (RequiredNonEmptyExpansion) Identifiers added in v0.1.0

func (e RequiredNonEmptyExpansion) Identifiers() []string

type SubstringExpansion

type SubstringExpansion struct {
	Identifier string
	Offset     int
	Length     int
	HasLength  bool
}

SubstringExpansion returns a substring (or slice) of the env. This is ${VAR:offset} or ${VAR:offset:length}.

func (SubstringExpansion) Expand

func (e SubstringExpansion) Expand(env Env) (string, error)

func (SubstringExpansion) Identifiers

func (e SubstringExpansion) Identifiers() []string

type UnsetValueExpansion

type UnsetValueExpansion struct {
	Identifier string
	Content    Expression
}

UnsetValueExpansion returns either the value of an env, or a default value if it's unset

func (UnsetValueExpansion) Expand

func (e UnsetValueExpansion) Expand(env Env) (string, error)

func (UnsetValueExpansion) Identifiers

func (e UnsetValueExpansion) Identifiers() []string

type VariableExpansion

type VariableExpansion struct {
	Identifier string
}

VariableExpansion represents either $VAR or ${VAR}, our simplest expansion

func (VariableExpansion) Expand

func (e VariableExpansion) Expand(env Env) (string, error)

func (VariableExpansion) Identifiers

func (e VariableExpansion) Identifiers() []string

Jump to

Keyboard shortcuts

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