Skip to content

Commit

Permalink
gitutil: sanitize root dir on WSL
Browse files Browse the repository at this point in the history
Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
  • Loading branch information
crazy-max committed Dec 15, 2023
1 parent 8484fcd commit 15bf8b9
Show file tree
Hide file tree
Showing 5 changed files with 48 additions and 1 deletion.
6 changes: 5 additions & 1 deletion util/gitutil/gitutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,11 @@ func (c *Git) IsDirty() bool {
}

func (c *Git) RootDir() (string, error) {
return c.clean(c.run("rev-parse", "--show-toplevel"))
root, err := c.clean(c.run("rev-parse", "--show-toplevel"))
if err != nil {
return "", err
}
return sanitizePath(root), nil
}

func (c *Git) GitDir() (string, error) {
Expand Down
23 changes: 23 additions & 0 deletions util/gitutil/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package gitutil

import (
"os"
"path/filepath"
"regexp"
"strings"
)

var windowsPathRegex = regexp.MustCompile(`^[A-Za-z]:[\\/].*$`)

func sanitizePath(path string) string {
// If we're running in WSL, we need to convert Windows paths to Unix paths.
// This is because the git binary can be invoked through `git.exe` and
// therefore returns Windows paths.
if os.Getenv("WSL_DISTRO_NAME") != "" && windowsPathRegex.MatchString(path) {
unixPath := strings.ReplaceAll(path, "\\", "/")
drive := strings.ToLower(string(unixPath[0]))
rest := filepath.Clean(unixPath[3:])
return filepath.Join("/mnt", drive, rest)
}
return path
}
20 changes: 20 additions & 0 deletions util/gitutil/path_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package gitutil

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestSanitizePathUnix(t *testing.T) {
assert.Equal(t, "/home/foobar", sanitizePath("/home/foobar"))
}

func TestSanitizePathWSL(t *testing.T) {
t.Setenv("WSL_DISTRO_NAME", "Ubuntu")
assert.Equal(t, "/mnt/c/Users/foobar", sanitizePath("C:\\Users\\foobar"))
}

func TestSanitizePathWindows(t *testing.T) {
assert.Equal(t, "C:\\Users\\foobar", sanitizePath("C:\\Users\\foobar"))
}
File renamed without changes.
File renamed without changes.

0 comments on commit 15bf8b9

Please sign in to comment.