123456789101112131415161718192021222324252627282930313233343536373839404142 | // Package testenv keeps tests that run commands in a sandbox out of the
// user's home.
package testenv
import (
"os"
"path/filepath"
"strings"
"blinker/internal/policy"
)
// LeaveHome drops the paths in the user's home from every environment
// variable, and the variables left empty, so a test's sandbox, given a
// home of its own, resolves no path in the real one: the policies name
// paths through $XDG_CONFIG_HOME, $CARGO_HOME, $PATH and the like.
func LeaveHome() error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
for _, kv := range os.Environ() {
name, value, _ := strings.Cut(kv, "=")
var keep []string
for _, p := range filepath.SplitList(value) {
if !policy.Under(p, home) {
keep = append(keep, p)
}
}
switch kept := strings.Join(keep, string(os.PathListSeparator)); {
case kept == value:
case kept == "":
err = os.Unsetenv(name)
default:
err = os.Setenv(name, kept)
}
if err != nil {
return err
}
}
return nil
}
|