gitutil: sanitize root dir on WSL

Signed-off-by: CrazyMax <1951866+crazy-max@users.noreply.github.com>
This commit is contained in:
CrazyMax 2023-12-15 15:33:10 +01:00
parent 8484fcdd57
commit ac5b3241b1
No known key found for this signature in database
GPG Key ID: ADE44D8C9D44FBE4
5 changed files with 57 additions and 1 deletions

View File

@ -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) {

View File

@ -7,6 +7,8 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/moby/sys/mountinfo"
)
@ -40,3 +42,18 @@ func gitPath(wd string) (string, error) {
}
return exec.LookPath("git")
}
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 filepath.Clean(path)
}

View File

@ -0,0 +1,19 @@
//go:build !windows
// +build !windows
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"))
}

View File

@ -2,8 +2,13 @@ package gitutil
import (
"os/exec"
"path/filepath"
)
func gitPath(wd string) (string, error) {
return exec.LookPath("git.exe")
}
func sanitizePath(path string) string {
return filepath.ToSlash(filepath.Clean(path))
}

View File

@ -0,0 +1,11 @@
package gitutil
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSanitizePathWindows(t *testing.T) {
assert.Equal(t, "C:\\Users\\foobar", sanitizePath("C:/Users/foobar"))
}