登录
首页 >  Golang >  Go问答

解决问题并优化结果

来源:stackoverflow

时间:2024-03-04 09:33:27 114浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《解决问题并优化结果》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我正在开发 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\)

_______________________________________________ _______________________________________________

更新,我已经完成了前缀修剪工作,(非常简单) 但现在我正在经历这个问题

package main

import (
    "fmt"
    "log"
    "os"
    "os/exec"
    "path/filepath"
    "regexp"
    "sort"
    "strings"

    "go.coder.com/flog"
)

func main() {
    fmt.println("resolved: ", gitbashwindowsdir(os.args[1]))
    fmt.println("resolved: ", gitbashwindowsdir("c:\\msys64\\workspace"))
}

func gitbashwindowsdir(dir string) string {

    // if dir is left empty, line82:main.go will set it to `~`, this makes it so that
    // if dir is `~`, return `~/` instead of continuing with the gitbashwindowsdir()
    // function.
    if dir == "~" {
        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)

            if strings.hasprefix(resolved, "//") {
                resolved = strings.trimprefix(resolved, "/")
                flog.info("debug: strings.trimprefix")
                flog.info("resolved windows path '%s' to '%s", dir, resolved)
                flog.info("'%s'", resolved)
                return resolved
            }

            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 {
    mountpoints := [][]string{{filepath.toslash(os.getenv("home")), "~"}}

    // load mount points
    out, err := exec.command("mount").output()
    if err != nil {
        //log.error(err)
        log.println(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]})
        }
    }

    // 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
}

当它运行时,它会返回

merith@DESKTOP-BQUQ80R MINGW64 /z/sshcode
$ go run ../debug.go Workspace
2019-11-27 10:49:38 INFO       Resolved windows path 'Workspace' to '/z/sshcode/Workspace
RESOLVED:  /z/sshcode/Workspace
2019-11-27 10:49:38 INFO       DEBUG: strings.TrimPrefix
2019-11-27 10:49:38 INFO       Resolved windows path 'C:\msys64\Workspace' to '/Workspace
2019-11-27 10:49:38 INFO       '/Workspace'
RESOLVED:  /Workspace

现在我需要弄清楚如何检测和删除 /*/ 前缀,以便 /z/sshcode/workspace 变为 workspace/


解决方案


对于确定字符串是否以正斜杠为前缀的第一个问题,您可以使用如下函数:

func ensureslashprefix(path string) string {
    return fmt.sprintf("/%s", strings.replace(path, "/", "", -1))
}

对于你的第二个问题,也许我误解了,但这个函数会返回所提供的相对路径的绝对路径或类似的输出到 echo $pwd/path

func cleanWindowsPath(path string) string {
    base := filepath.Base(strings.Replace(path, "\\", "/", -1))
    return ensureSlashPrefix(base)
}

(Go Playground)

本篇关于《解决问题并优化结果》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>