Skip to content

Commit

Permalink
context: envsubst
Browse files Browse the repository at this point in the history
  • Loading branch information
rsteube committed May 6, 2022
1 parent 46086f1 commit a4f810f
Show file tree
Hide file tree
Showing 13 changed files with 1,835 additions and 0 deletions.
23 changes: 23 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"path/filepath"
"strings"

"github.com/rsteube/carapace/third_party/github.com/drone/envsubst"
"github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs"
)

Expand All @@ -23,6 +24,24 @@ type Context struct {
Dir string
}

// LookupEnv retrieves the value of the environment variable named by the key.
func (c *Context) LookupEnv(key string) (string, bool) {
prefix := key + "="
for i := len(c.Env) - 1; i >= 0; i-- {
if env := c.Env[i]; strings.HasPrefix(env, prefix) {
return strings.SplitN(env, "=", 2)[1], true
}
}
return "", false

}

// Getenv retrieves the value of the environment variable named by the key.
func (c *Context) Getenv(key string) string {
v, _ := c.LookupEnv(key)
return v
}

// Setenv sets the value of the environment variable named by the key.
func (c *Context) Setenv(key, value string) {
if c.Env == nil {
Expand All @@ -31,6 +50,10 @@ func (c *Context) Setenv(key, value string) {
c.Env = append(c.Env, fmt.Sprintf("%v=%v", key, value))
}

func (c *Context) Envsubst(s string) (string, error) {
return envsubst.Eval(s, c.Getenv)
}

// Command returns the Cmd struct to execute the named program with the given arguments.
// Env and Dir are set using the Context.
// See exec.Command for most details.
Expand Down
47 changes: 47 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,50 @@ func TestContextAbs(t *testing.T) {
}

}

func TestEnv(t *testing.T) {
c := Context{}
if c.Getenv("example") != "" {
t.Fail()
}
if v, exist := c.LookupEnv("example"); v != "" || exist {
t.Fail()
}

c.Setenv("example", "value")
if c.Getenv("example") != "value" {
t.Fail()
}
if v, exist := c.LookupEnv("example"); v != "value" || !exist {
t.Fail()
}

c.Setenv("example", "newvalue")
if c.Getenv("example") != "newvalue" {
t.Fail()
}
if v, exist := c.LookupEnv("example"); v != "newvalue" || !exist {
t.Fail()
}
}

func TestEnvsubst(t *testing.T) {
c := Context{}

if s, err := c.Envsubst("start${example}end"); s != "startend" || err != nil {
t.Fail()
}

if s, err := c.Envsubst("start${example:-default}end"); s != "startdefaultend" || err != nil {
t.Fail()
}

c.Setenv("example", "value")
if s, err := c.Envsubst("start${example}end"); s != "startvalueend" || err != nil {
t.Fail()
}

if s, err := c.Envsubst("start${example:-default}end"); s != "startvalueend" || err != nil {
t.Fail()
}
}
21 changes: 21 additions & 0 deletions third_party/github.com/drone/envsubst/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 drone.io

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
19 changes: 19 additions & 0 deletions third_party/github.com/drone/envsubst/eval.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package envsubst

import "os"

// Eval replaces ${var} in the string based on the mapping function.
func Eval(s string, mapping func(string) string) (string, error) {
t, err := Parse(s)
if err != nil {
return s, err
}
return t.Execute(mapping)
}

// EvalEnv replaces ${var} in the string according to the values of the
// current environment variables. References to undefined variables are
// replaced by the empty string.
func EvalEnv(s string) (string, error) {
return Eval(s, os.Getenv)
}
228 changes: 228 additions & 0 deletions third_party/github.com/drone/envsubst/eval_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
package envsubst

import "testing"

// test cases sourced from tldp.org
// http://www.tldp.org/LDP/abs/html/parameter-substitution.html

func TestExpand(t *testing.T) {
var expressions = []struct {
params map[string]string
input string
output string
}{
// text-only
{
params: map[string]string{},
input: "abcdEFGH28ij",
output: "abcdEFGH28ij",
},
// length
{
params: map[string]string{"var01": "abcdEFGH28ij"},
input: "${#var01}",
output: "12",
},
// uppercase first
{
params: map[string]string{"var01": "abcdEFGH28ij"},
input: "${var01^}",
output: "AbcdEFGH28ij",
},
// uppercase
{
params: map[string]string{"var01": "abcdEFGH28ij"},
input: "${var01^^}",
output: "ABCDEFGH28IJ",
},
// lowercase first
{
params: map[string]string{"var01": "ABCDEFGH28IJ"},
input: "${var01,}",
output: "aBCDEFGH28IJ",
},
// lowercase
{
params: map[string]string{"var01": "ABCDEFGH28IJ"},
input: "${var01,,}",
output: "abcdefgh28ij",
},
// substring with position
{
params: map[string]string{"path_name": "/home/bozo/ideas/thoughts.for.today"},
input: "${path_name:11}",
output: "ideas/thoughts.for.today",
},
// substring with position and length
{
params: map[string]string{"path_name": "/home/bozo/ideas/thoughts.for.today"},
input: "${path_name:11:5}",
output: "ideas",
},
// default not used
{
params: map[string]string{"var": "abc"},
input: "${var=xyz}",
output: "abc",
},
// default used
{
params: map[string]string{},
input: "${var=xyz}",
output: "xyz",
},
{
params: map[string]string{"default_var": "foo"},
input: "something ${var=${default_var}}",
output: "something foo",
},
{
params: map[string]string{"default_var": "foo1"},
input: `foo: ${var=${default_var}-suffix}`,
output: "foo: foo1-suffix",
},
{
params: map[string]string{"default_var": "foo1"},
input: `foo: ${var=prefix${default_var}-suffix}`,
output: "foo: prefixfoo1-suffix",
},
{
params: map[string]string{},
input: "${var:=xyz}",
output: "xyz",
},
// replace suffix
{
params: map[string]string{"stringZ": "abcABC123ABCabc"},
input: "${stringZ/%abc/XYZ}",
output: "abcABC123ABCXYZ",
},
// replace prefix
{
params: map[string]string{"stringZ": "abcABC123ABCabc"},
input: "${stringZ/#abc/XYZ}",
output: "XYZABC123ABCabc",
},
// replace all
{
params: map[string]string{"stringZ": "abcABC123ABCabc"},
input: "${stringZ//abc/xyz}",
output: "xyzABC123ABCxyz",
},
// replace first
{
params: map[string]string{"stringZ": "abcABC123ABCabc"},
input: "${stringZ/abc/xyz}",
output: "xyzABC123ABCabc",
},
// delete shortest match prefix
{
params: map[string]string{"filename": "bash.string.txt"},
input: "${filename#*.}",
output: "string.txt",
},
{
params: map[string]string{"filename": "path/to/file"},
input: "${filename#*/}",
output: "to/file",
},
{
params: map[string]string{"filename": "/path/to/file"},
input: "${filename#*/}",
output: "path/to/file",
},
// delete longest match prefix
{
params: map[string]string{"filename": "bash.string.txt"},
input: "${filename##*.}",
output: "txt",
},
{
params: map[string]string{"filename": "path/to/file"},
input: "${filename##*/}",
output: "file",
},
{
params: map[string]string{"filename": "/path/to/file"},
input: "${filename##*/}",
output: "file",
},
// delete shortest match suffix
{
params: map[string]string{"filename": "bash.string.txt"},
input: "${filename%.*}",
output: "bash.string",
},
// delete longest match suffix
{
params: map[string]string{"filename": "bash.string.txt"},
input: "${filename%%.*}",
output: "bash",
},

// nested parameters
{
params: map[string]string{"var01": "abcdEFGH28ij"},
input: "${var=${var01^^}}",
output: "ABCDEFGH28IJ",
},
// escaped
{
params: map[string]string{"var01": "abcdEFGH28ij"},
input: "$${var01}",
output: "${var01}",
},
{
params: map[string]string{"var01": "abcdEFGH28ij"},
input: "some text ${var01}$${var$${var01}$var01${var01}",
output: "some text abcdEFGH28ij${var${var01}$var01abcdEFGH28ij",
},
{
params: map[string]string{"default_var": "foo"},
input: "something $${var=${default_var}}",
output: "something ${var=foo}",
},
// some common escaping use cases
{
params: map[string]string{"stringZ": "foo/bar"},
input: `${stringZ/\//-}`,
output: "foo-bar",
},
{
params: map[string]string{"stringZ": "foo/bar/baz"},
input: `${stringZ//\//-}`,
output: "foo-bar-baz",
},
// escape outside of expansion shouldn't be processed
{
params: map[string]string{"default_var": "foo"},
input: "\\\\something ${var=${default_var}}",
output: "\\\\something foo",
},
// substitute with a blank string
{
params: map[string]string{"stringZ": "foo.bar"},
input: `${stringZ/./}`,
output: "foobar",
},
}

for _, expr := range expressions {
t.Run(expr.input, func(t *testing.T) {
t.Logf(expr.input)
output, err := Eval(expr.input, func(s string) string {
return expr.params[s]
})
if err != nil {
t.Errorf("Want %q expanded but got error %q", expr.input, err)
}

if output != expr.output {
t.Errorf("Want %q expanded to %q, got %q",
expr.input,
expr.output,
output)
}
})
}
}
Loading

0 comments on commit a4f810f

Please sign in to comment.