Skip to content

Commit

Permalink
Expand environment variables in modeline options.
Browse files Browse the repository at this point in the history
  • Loading branch information
doru1004 authored and nicolaferraro committed Dec 9, 2020
1 parent a9c595b commit 0910b2d
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
33 changes: 33 additions & 0 deletions pkg/cmd/modeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import (
"fmt"
"path"
"path/filepath"
"strings"

"github.com/apache/camel-k/pkg/util"
"github.com/apache/camel-k/pkg/util/modeline"
"github.com/pkg/errors"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -169,6 +171,11 @@ func extractModelineOptions(ctx context.Context, sources []string) ([]modeline.O
return opts, err
}

ops, err = expandModelineEnvVarOptions(ops)
if err != nil {
return opts, err
}

opts = append(opts, ops...)
}

Expand Down Expand Up @@ -198,3 +205,29 @@ func extractModelineOptionsFromSource(resolvedSource Source) ([]modeline.Option,

return ops, nil
}

func expandModelineEnvVarOptions(ops []modeline.Option) ([]modeline.Option, error) {
listWithExpandedOptions := []modeline.Option{}
for _, opt := range ops {
// Check if the value contains an environment variable.
for strings.Contains(opt.Value, "${") {
// Split value into 2 substrings, first contains the start of the string,
// second contains the remainder of the string.
splitOptBeforeEV := strings.SplitN(opt.Value, "${", 2)

// Remainer of the string is split into the environment variable we want
// to replace with its value, and the tail of the string.
splitOptAfterEV := strings.SplitN(splitOptBeforeEV[1], "}", 2)
envVarValue, err := util.GetEnvironmentVariable(splitOptAfterEV[0])
if err != nil {
return nil, err
}
opt.Value = splitOptBeforeEV[0] + envVarValue + splitOptAfterEV[1]
}

// Add option to list whether it contained environment variables or not.
listWithExpandedOptions = append(listWithExpandedOptions, opt)
}

return listWithExpandedOptions, nil
}
14 changes: 14 additions & 0 deletions pkg/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,17 @@ func CreateLocalRoutesDirectory() error {
}
return nil
}

// GetEnvironmentVariable --
func GetEnvironmentVariable(variable string) (string, error) {
value, isPresent := os.LookupEnv(variable)
if !isPresent {
return "", errors.Errorf("environment variable %v does not exist", variable)
}

if value == "" {
return "", errors.Errorf("environment variable %v is not set", variable)
}

return value, nil
}

0 comments on commit 0910b2d

Please sign in to comment.