我正在https://github.com/cdr/sshcode的分支上工作,更具体地说,我正在PR上向程序添加git4win / msys2支持
当前问题源于这两个功能
func gitbashWindowsDir(dir string) string {
if dir == "~" { //Special case
return "~/"
}
mountPoints := gitbashMountPointsAndHome()
// Apply mount points
absDir, _ := filepath.Abs(dir)
absDir = filepath.ToSlash(absDir)
for _, mp := range mountPoints {
if strings.HasPrefix(absDir, mp[0]) {
resolved := strings.Replace(absDir, mp[0], mp[1], 1)
flog.Info("Resolved windows path '%s' to '%s", dir, resolved)
return resolved
}
}
return dir
}
// This function returns an array with MINGW64 mount points including relative home dir
func gitbashMountPointsAndHome() [][]string {
// Initialize mount points with home dir
mountPoints := [][]string{{filepath.ToSlash(os.Getenv("HOME")), "~"}}
// Load mount points
out, err := exec.Command("mount").Output()
if err != nil {
log.Fatal(err)
}
lines := strings.Split(string(out), "\n")
var mountRx = regexp.MustCompile(`^(.*) on (.*) type`)
for _, line := range lines {
extract := mountRx.FindStringSubmatch(line)
if len(extract) > 0 {
mountPoints = append(mountPoints, []string{extract[1], extract[2]})
}
res = strings.TrimPrefix(dir, line)
}
// Sort by size to get more restrictive mount points first
sort.Slice(mountPoints, func(i, j int) bool {
return len(mountPoints[i][0]) > len(mountPoints[j][0])
})
return mountPoints
}
[如何使用它,在msys2 / git4win上,您给gitbashWindowsDir("/Workspace")
它应返回/Workspace
,因为它处理msys2 / git4win处理路径的上下颠倒方式。
并且当您给它gitbashWindowsDir("Workspace/")
时,它返回与echo $PWD/Workspace/
基本相同的输出,但以窗口格式
我正在开发利用strings.Prefix
素材的第一步补丁,这就是我的贴布沙发]
package main
import (
"fmt"
"os"
)
func main() {
mydir, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
fmt.Println(os.Getenv("PWD"))
fmt.Println(mydir)
}
我想检查输入是否具有前缀/
,如果有,只需将其作为字符串返回,这似乎是gitbashWindowsDir("/Workspace")
返回//Workspace
的简单解决方法但是我认为最困难的部分是gitbashWindowsDir("Workspace/")
,因为它返回的输出与echo $PWD/Workspace/
相同,但使用的是Windows格式(Z:\Workspace\
)
关于确定字符串是否以正斜杠作为前缀的第一个问题,可以使用如下函数:
func ensureSlashPrefix(path string) string {
if !strings.HasPrefix(path, "/") {
return fmt.Sprintf("/%s", path)
}
return path
}
关于您的第二个问题,也许我误会了,但是此函数会将绝对路径返回到提供的相对路径,或者将类似的输出返回到echo $PWD/path
。
func cleanWindowsPath(path string) string {
base := filepath.Base(strings.Replace(path, "\\", "/", -1))
return ensureSlashPrefix(base)
}