Skip to content

Commit

Permalink
cli: pass environment variables to genpolicy
Browse files Browse the repository at this point in the history
  • Loading branch information
burgerdev committed Nov 27, 2024
1 parent ecf5007 commit c375309
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion cli/genpolicy/genpolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ func (r *Runner) Run(ctx context.Context, yamlPath string, logger *slog.Logger)
"--yaml-file=" + yamlPath,
}
genpolicy := exec.CommandContext(ctx, r.genpolicy.Path(), args...)
genpolicy.Env = append(genpolicy.Env, "RUST_LOG=info", "RUST_BACKTRACE=1")
genpolicy.Env = os.Environ()
if _, hasRustLog := os.LookupEnv("RUST_LOG"); !hasRustLog {
genpolicy.Env = append(genpolicy.Env, "RUST_LOG=info")
}
if _, hasRustBacktrace := os.LookupEnv("RUST_BACKTRACE"); !hasRustBacktrace {
genpolicy.Env = append(genpolicy.Env, "RUST_BACKTRACE=1")
}

logFilter := newLogTranslator(logger)
defer logFilter.stop()
Expand Down
20 changes: 20 additions & 0 deletions cli/genpolicy/genpolicy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ while [ $# -gt 0 ]; do
esac
shift
done
echo -e "HOME=${HOME}\nXDG_RUNTIME_DIR=${XDG_RUNTIME_DIR}\nDOCKER_CONFIG=${DOCKER_CONFIG}\nREGISTRY_AUTH_FILE=${REGISTRY_AUTH_FILE}" >env_path
`

func TestRunner(t *testing.T) {
Expand All @@ -47,6 +49,11 @@ func TestRunner(t *testing.T) {
ctx := context.Background()
logger := slog.Default()

t.Setenv("HOME", "/invalid/home")
t.Setenv("XDG_RUNTIME_DIR", "/invalid/xdg")
t.Setenv("DOCKER_CONFIG", "/invalid/docker")
t.Setenv("REGISTRY_AUTH_FILE", "/invalid/registry")

d := t.TempDir()
genpolicyBin := []byte(fmt.Sprintf(scriptTemplate, d))

Expand All @@ -57,6 +64,7 @@ func TestRunner(t *testing.T) {
cachePath := filepath.Join(d, "cache", "cache.json")
expectedYAMLPath := filepath.Join(d, "test.yml")
yamlPathFile := filepath.Join(d, "yaml_path")
envFile := filepath.Join(d, "env_path")

r, err := New(expectedRulesPath, expectedSettingsPath, cachePath, genpolicyBin)
require.NoError(err)
Expand All @@ -75,5 +83,17 @@ func TestRunner(t *testing.T) {
require.NoError(err)
assert.YAMLEq(expectedYAMLPath, string(yamlPath))

env, err := os.ReadFile(envFile)
require.NoError(err)
assert.YAMLEq(expectedYAMLPath, string(yamlPath))
for _, expected := range []string{
"HOME=/invalid/home",
"XDG_RUNTIME_DIR=/invalid/xdg",
"DOCKER_CONFIG=/invalid/docker",
"REGISTRY_AUTH_FILE=/invalid/registry",
} {
assert.Contains(string(env), expected)
}

require.NoError(r.Teardown())
}

0 comments on commit c375309

Please sign in to comment.