| 1 | |
| 2 | |
| 3 | |
| 4 | package fsutil |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io/fs" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | |
| 15 | "github.com/sirupsen/logrus" |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | func WindowsSubsystemPath(ctx context.Context, orig string) (string, error) { |
| 23 | return WindowsSubsystemPathWithCygpath(ctx, "cygpath", orig) |
| 24 | } |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | func WindowsSubsystemPathWithCygpath(ctx context.Context, cygpathExe, orig string) (string, error) { |
| 33 | out, err := exec.CommandContext(ctx, cygpathExe, filepath.ToSlash(orig)).CombinedOutput() |
| 34 | if err == nil { |
| 35 | return strings.TrimSpace(string(out)), nil |
| 36 | } |
| 37 | if !errors.Is(err, exec.ErrNotFound) && !errors.Is(err, fs.ErrNotExist) { |
| 38 | return "", fmt.Errorf("failed to run %#q on %#q: %#q: %w", cygpathExe, orig, strings.TrimSpace(string(out)), err) |
| 39 | } |
| 40 | |
| 41 | logrus.WithError(err).Debugf("%#q not found for %#q, attempting native conversion", cygpathExe, orig) |
| 42 | |
| 43 | return windowsSubsystemPathWithoutCygpath(orig) |
| 44 | } |
| 45 | |
| 46 | func windowsSubsystemPathWithoutCygpath(orig string) (string, error) { |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | if !filepath.IsAbs(orig) { |
| 53 | return "", fmt.Errorf("cannot convert %#q to an MSYS-style path: input is not an absolute drive-letter path", orig) |
| 54 | } |
| 55 | |
| 56 | |
| 57 | if vol := filepath.VolumeName(orig); len(vol) == 2 && vol[1] == ':' { |
| 58 | |
| 59 | |
| 60 | tail := strings.TrimPrefix(filepath.ToSlash(orig[2:]), "/") |
| 61 | converted := "/" + strings.ToLower(vol[:1]) + "/" + tail |
| 62 | logrus.Debugf("native cygpath fallback: %#q -> %#q", orig, converted) |
| 63 | return converted, nil |
| 64 | } |
| 65 | |
| 66 | return "", fmt.Errorf("cannot convert %#q to an MSYS-style path: input is not an absolute drive-letter path", orig) |
| 67 | } |
| 68 | |
| 69 | |
| 70 | |
| 71 | func WindowsSubsystemPathForLinux(ctx context.Context, orig, distro string) (string, error) { |
| 72 | out, err := exec.CommandContext(ctx, "wsl", "-d", distro, "--exec", "wslpath", filepath.ToSlash(orig)).CombinedOutput() |
| 73 | if err != nil { |
| 74 | logrus.WithError(err).Errorf("failed to convert path to mingw, maybe wsl command is not operational?") |
| 75 | return "", err |
| 76 | } |
| 77 | return strings.TrimSpace(string(out)), nil |
| 78 | } |