From 7e6b566d21d375b2ba20326f4591794809200c83 Mon Sep 17 00:00:00 2001 From: Anjan Nath Date: Wed, 20 Sep 2023 14:18:53 +0530 Subject: [PATCH] Test change windows drive letter to uppercase always --- pkg/os/util_test.go | 21 +++++++++++++++++++++ pkg/os/util_unix.go | 8 ++++++++ pkg/os/util_windows.go | 21 +++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/pkg/os/util_test.go b/pkg/os/util_test.go index baa8ab8315..b49503cb31 100644 --- a/pkg/os/util_test.go +++ b/pkg/os/util_test.go @@ -94,3 +94,24 @@ func TestFileExists(t *testing.T) { filename = filepath.Join(dirname, "nonexistent") assert.False(t, FileExists(filename)) } + +func TestUppercaseDriveLetter(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("Test only works for windows") + } + + tests := []struct { + got string + expected string + }{ + {"c:\\crc\\crc-org", "C:\\crc\\crc-org"}, + {"d:\\happy\\world", "D:\\happy\\world"}, + {"D:\\happy\\world", "D:\\happy\\world"}, + {":\\crc\\snc", ":\\crc\\snc"}, + {"\\crc\\snc", "\\crc\\snc"}, + } + + for _, tt := range tests { + assert.Equal(t, tt.expected, uppercaseDriveLetterInPath(tt.got), "test failed") + } +} diff --git a/pkg/os/util_unix.go b/pkg/os/util_unix.go index 0d1528166d..72d7bd7279 100644 --- a/pkg/os/util_unix.go +++ b/pkg/os/util_unix.go @@ -46,3 +46,11 @@ func GetCurrentUsername() (string, error) { } return u.Username, nil } + +func GetCurrentExecutablePath() (string, error) { + return os.Executable() +} + +func uppercaseDriveLetterInPath(binPath string) string { + return binPath +} diff --git a/pkg/os/util_windows.go b/pkg/os/util_windows.go index 7d8f0e8313..fd8f4c4f29 100644 --- a/pkg/os/util_windows.go +++ b/pkg/os/util_windows.go @@ -6,8 +6,10 @@ import ( "io" "os" "os/user" + "path/filepath" "strings" + "github.com/crc-org/crc/v2/pkg/crc/logging" "golang.org/x/text/encoding/unicode" "golang.org/x/text/transform" ) @@ -44,3 +46,22 @@ func GetCurrentUsername() (string, error) { } return "", errors.New("unable to find the username of current user") } + +func GetCurrentExecutable() (string, error) { + binPath, err := os.Executable() + if err != nil { + return "", err + } + return uppercaseDriveLetterInPath(binPath), nil +} + +func uppercaseDriveLetterInPath(binPath string) string { + drive := filepath.VolumeName(binPath) + if drive != "" { + driveUpperCase := strings.ToUpper(drive) + normalizedBinPath := strings.Replace(binPath, drive, driveUpperCase, 1) + logging.Debugf("Original path: %s. Normalized path: %s", binPath, normalizedBinPath) + return strings.Replace(binPath, drive, driveUpperCase, 1) + } + return binPath +}