| 1 | // Copyright (c) Bartłomiej Płotka @bwplotka |
| 2 | // Licensed under the Apache License 2.0. |
| 3 | |
| 4 | package envars |
| 5 | |
| 6 | import ( |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "os" |
| 12 | "sort" |
| 13 | "strings" |
| 14 | "text/scanner" |
| 15 | |
| 16 | "github.com/efficientgo/core/errors" |
| 17 | "mvdan.cc/sh/v3/expand" |
| 18 | "mvdan.cc/sh/v3/interp" |
| 19 | "mvdan.cc/sh/v3/syntax" |
| 20 | ) |
| 21 | |
| 22 | // EvalVariables evaluates dot env file in similar way `bash source` would do and returns all environment variables available at end of the |
| 23 | // execution of the script. |
| 24 | // Currently it supports any bash script and can cause side effects. |
| 25 | // TODO(bwplotka): Walk over syntax and allow list few syntax elements only? |
| 26 | func EvalVariables(ctx context.Context, r io.Reader, envSlice ...string) (ret EnvSlice, _ error) { |
| 27 | const prefix = "[[dotenv.EvalVariables]]:" |
| 28 | |
| 29 | s, err := syntax.NewParser().Parse(r, "") |
| 30 | if err != nil { |
| 31 | return nil, errors.Wrap(err, "parse") |
| 32 | } |
| 33 | |
| 34 | vars := listVarNames(s) |
| 35 | if len(vars) == 0 { |
| 36 | return nil, nil |
| 37 | } |
| 38 | |
| 39 | // sh does not implement the declaration clauses like `declare` or `export`. Let's set to ignore it and get variable |
| 40 | // values manually. |
| 41 | trimDeclStmts(s) |
| 42 | |
| 43 | // Add env print at the end to get all environment variables that would be available at this point! |
| 44 | // Create env slice to print at the end of script. |
| 45 | var parts []syntax.WordPart |
| 46 | for _, v := range vars { |
| 47 | parts = append(parts, |
| 48 | &syntax.Lit{Value: fmt.Sprintf("%v \"", v)}, |
| 49 | &syntax.ParamExp{Param: &syntax.Lit{Value: v}}, |
| 50 | &syntax.Lit{Value: "\" "}, |
| 51 | ) |
| 52 | } |
| 53 | |
| 54 | s.Stmts = append( |
| 55 | s.Stmts, &syntax.Stmt{Cmd: &syntax.CallExpr{ |
| 56 | Args: []*syntax.Word{ |
| 57 | {Parts: []syntax.WordPart{&syntax.Lit{Value: "echo"}}}, |
| 58 | {Parts: []syntax.WordPart{&syntax.DblQuoted{Parts: append([]syntax.WordPart{&syntax.Lit{Value: prefix}}, parts...)}}}, |
| 59 | }}}, |
| 60 | ) |
| 61 | |
| 62 | b := bytes.Buffer{} |
| 63 | ru, err := interp.New(interp.StdIO(os.Stdin, &b, &b), interp.Env(expand.ListEnviron(envSlice...))) |
| 64 | if err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | |
| 68 | if err := ru.Run(ctx, s); err != nil { |
| 69 | return nil, err |
| 70 | } |
| 71 | |
| 72 | var sc scanner.Scanner |
| 73 | sc.Init(strings.NewReader(b.String()[strings.Index(b.String(), prefix)+len(prefix):])) |
| 74 | tok := sc.Scan() |
| 75 | for tok != scanner.EOF { |
| 76 | k := sc.TokenText() |
| 77 | _ = sc.Scan() |
| 78 | v := sc.TokenText() |
| 79 | ret = append(ret, fmt.Sprintf("%s=%s", k, strings.Trim(v, "\""))) |
| 80 | tok = sc.Scan() |
| 81 | } |
| 82 | return ret, nil |
| 83 | } |
| 84 | |
| 85 | func listVarNames(ast *syntax.File) (vars []string) { |
| 86 | dup := map[string]struct{}{} |
| 87 | for _, s := range ast.Stmts { |
| 88 | syntax.Walk(s, func(node syntax.Node) bool { |
| 89 | switch n := node.(type) { |
| 90 | case *syntax.Assign: |
| 91 | if n.Name == nil { |
| 92 | return false |
| 93 | } |
| 94 | if _, ok := dup[n.Name.Value]; ok { |
| 95 | return false |
| 96 | } |
| 97 | dup[n.Name.Value] = struct{}{} |
| 98 | vars = append(vars, n.Name.Value) |
| 99 | return false |
| 100 | } |
| 101 | return true |
| 102 | }) |
| 103 | } |
| 104 | return vars |
| 105 | } |
| 106 | |
| 107 | func trimDeclStmts(ast *syntax.File) { |
| 108 | for _, s := range ast.Stmts { |
| 109 | syntax.Walk(s, func(node syntax.Node) bool { |
| 110 | switch node.(type) { |
| 111 | case *syntax.DeclClause: |
| 112 | // TODO(bwplotka): Right not just trim them, but in future pull out assignments to statements on the parent level. |
| 113 | node = nil // nolint |
| 114 | return false |
| 115 | } |
| 116 | return true |
| 117 | }) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | // MergeEnvSlices merges two slices into single, sorted, deduplicated slice by applying `over` slice into `base`. |
| 122 | // The `over` slice will be used if the key overlaps. |
| 123 | // See https://golang.org/pkg/os/exec/#Cmd `Env` field to read more about slice format. |
| 124 | func MergeEnvSlices(base []string, over ...string) (merged []string) { |
| 125 | sort.Strings(base) |
| 126 | sort.Strings(over) |
| 127 | |
| 128 | var b, o int |
| 129 | for b < len(base) || o < len(over) { |
| 130 | |
| 131 | if b >= len(base) { |
| 132 | appendOrReplaceDup(&merged, over[o]) |
| 133 | o++ |
| 134 | continue |
| 135 | } |
| 136 | |
| 137 | if o >= len(over) { |
| 138 | appendOrReplaceDup(&merged, base[b]) |
| 139 | b++ |
| 140 | continue |
| 141 | } |
| 142 | |
| 143 | switch strings.Compare(strings.Split(base[b], "=")[0], strings.Split(over[o], "=")[0]) { |
| 144 | case 0: |
| 145 | // Same keys. Instead of picking over element, ignore base one. This ensure correct behaviour if base |
| 146 | // has duplicate elements. |
| 147 | b++ |
| 148 | case 1: |
| 149 | appendOrReplaceDup(&merged, over[o]) |
| 150 | o++ |
| 151 | case -1: |
| 152 | appendOrReplaceDup(&merged, base[b]) |
| 153 | b++ |
| 154 | } |
| 155 | } |
| 156 | return merged |
| 157 | } |
| 158 | |
| 159 | func appendOrReplaceDup(appendable *[]string, item string) { |
| 160 | if len(*appendable) == 0 { |
| 161 | *appendable = append(*appendable, item) |
| 162 | return |
| 163 | } |
| 164 | |
| 165 | lastI := len(*appendable) - 1 |
| 166 | if strings.Compare(strings.Split((*appendable)[lastI], "=")[0], strings.Split(item, "=")[0]) == 0 { |
| 167 | (*appendable)[lastI] = item |
| 168 | return |
| 169 | } |
| 170 | *appendable = append(*appendable, item) |
| 171 | } |