Skip to content

Commit

Permalink
expand env vars ci (#63)
Browse files Browse the repository at this point in the history
* expand env vars

* Expand mount paths

1 Introduce config_utils to expand paths using Go's utility.
2. Handle '~' separately in the expansion logic, as this is not handled by os.ExpandEnv.
3. Add unit tests.

* Remove Os.ExpandEnv() from rebuilder
  • Loading branch information
Aishwarya-Lad authored Nov 20, 2023
1 parent e604755 commit f332f67
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
17 changes: 17 additions & 0 deletions internal/plugin/config_utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package plugin

import (
"os"
"strings"
)

// For all mounts, map the `~` symbol to `$HOME` and expand it.
func expandConfigPath(mounts []string) []string {
expandedPaths := make([]string, len(mounts))
for i, mount := range mounts {
// As `~` is not handled by `ExpandEnv()`, replace it with `$HOME`.
mount = strings.Replace(mount, "~", "$HOME", 1)
expandedPaths[i] = os.ExpandEnv(mount)
}
return expandedPaths
}
32 changes: 32 additions & 0 deletions internal/plugin/config_utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package plugin

import (
"fmt"
"github.com/meltwater/drone-cache/test"
"log"
"os"
"testing"
)

func TestExpandConfigPath_Tilde(t *testing.T) {
testMountTilde := []string{"~/test/path"}
wantExpandedMountTilde := []string{fmt.Sprintf("%s/test/path", osExpand("$HOME"))}
gotExpandedMountTilde := expandConfigPath(testMountTilde)
test.Equals(t, wantExpandedMountTilde, gotExpandedMountTilde)

}

func TestExpandConfigPath_EnvVar(t *testing.T) {
testMount := []string{"$HOME/test/path"}
wantExpandedMount := []string{fmt.Sprintf("%s/test/path", osExpand("$HOME"))}
gotExpandedMount := expandConfigPath(testMount)
test.Equals(t, wantExpandedMount, gotExpandedMount)
}

func osExpand(symbol string) string {
absolutePath := os.ExpandEnv(symbol)
if absolutePath == "" {
log.Fatalf("Could not find the absolute path for symbol/envVar: %s", symbol)
}
return absolutePath
}
5 changes: 4 additions & 1 deletion internal/plugin/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ func (p *Plugin) Exec() error { // nolint:funlen
options...,
)

// 4. Select mode
// 4. Expand the mount paths.
p.Config.Mount = expandConfigPath(p.Config.Mount)

// 5. Select mode
if cfg.Rebuild {
if err := c.Rebuild(p.Config.Mount); err != nil {
level.Debug(p.logger).Log("err", fmt.Sprintf("%+v\n", err))
Expand Down

0 comments on commit f332f67

Please sign in to comment.