From 0863cb29ee8085a7a58c9660c2029814153772a5 Mon Sep 17 00:00:00 2001 From: Zeeshan Ali Date: Fri, 20 Dec 2019 17:24:03 +0100 Subject: [PATCH] Add utility function for chown --- pkg/os/util_linux.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pkg/os/util_linux.go b/pkg/os/util_linux.go index b8268ceb6e..33c392ccbf 100644 --- a/pkg/os/util_linux.go +++ b/pkg/os/util_linux.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "os/exec" + "os/user" "strings" "github.com/code-ready/crc/pkg/crc/logging" @@ -53,3 +54,14 @@ func GetFirstExistentPath(paths []string) (string, error) { return readablePath, nil } + +func ChownAsRoot(user *user.User, filepath string) error { + logging.Infof("Will use root access to change owner & group of file %s to %s", filepath, user.Username) + cmd := exec.Command("sudo", "chown", fmt.Sprintf("%s.%s", user.Uid, user.Gid), filepath) // #nosec G204 + buf := new(bytes.Buffer) + cmd.Stderr = buf + if err := cmd.Run(); err != nil { + return fmt.Errorf("Failed to change owner & group of %s to %s: %s: %s: %v", filepath, user.Username, buf.String(), err) + } + return nil +}