增加构建wenjian路径方法

This commit is contained in:
白茶清欢 2022-10-14 13:46:33 +08:00
parent 63f5b99d40
commit 9931590d80
2 changed files with 47 additions and 1 deletions

View File

@ -10,10 +10,11 @@ package util
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"runtime"
"strings"
) )
type project struct { type project struct {
} }
// GetExecutablePath 获取可执行文件的路径 // GetExecutablePath 获取可执行文件的路径
@ -38,3 +39,42 @@ func (p *project) GetFileSystemSeparator() string {
return string(filepath.Separator) return string(filepath.Separator)
} }
// BuildPath 构建路径
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:57 2022/10/14
func (p *project) BuildPath(filePathList ...string) string {
projectRootPath, _ := p.GetExecutablePath()
if len(filePathList) == 0 {
// 降为获取项目根目录
return projectRootPath
}
// 第一个特殊处理
if filePathList[0] == "." || len(filePathList[0]) == 0 {
filePathList[0] = projectRootPath
} else {
if strings.ToLower(runtime.GOOS) == "windows" {
// windows
if strings.HasPrefix(filePathList[0], "."+p.GetFileSystemSeparator()) {
// 相对路径
filePathList[0] = strings.ReplaceAll(filePathList[0], ".", projectRootPath)
} else if !strings.Contains(filePathList[0], ":") {
// 不包含 :, 是 相对路径,拼成绝对路径
filePathList[0] = projectRootPath + p.GetFileSystemSeparator() + strings.TrimLeft(filePathList[0], p.GetFileSystemSeparator())
}
} else {
// unix/ linux
if strings.HasPrefix(filePathList[0], "."+p.GetFileSystemSeparator()) {
filePathList[0] = strings.ReplaceAll(filePathList[0], ".", projectRootPath)
} else if !strings.HasPrefix(filePathList[0], p.GetFileSystemSeparator()) {
filePathList[0] = projectRootPath + p.GetFileSystemSeparator() + filePathList[0]
}
}
}
filePathList[0] = strings.TrimRight(filePathList[0], p.GetFileSystemSeparator())
for idx := 1; idx < len(filePathList); idx++ {
filePathList[idx] = strings.Trim(filePathList[idx], p.GetFileSystemSeparator())
}
return strings.Join(filePathList, p.GetFileSystemSeparator())
}

View File

@ -15,3 +15,9 @@ import (
func Test_project_GetExecutablePath(t *testing.T) { func Test_project_GetExecutablePath(t *testing.T) {
fmt.Println(Project.GetExecutablePath()) fmt.Println(Project.GetExecutablePath())
} }
func Test_project_BuildPath(t *testing.T) {
fmt.Println(Project.GetExecutablePath())
fmt.Println(Project.BuildPath("a", "b", "c"))
fmt.Println(Project.BuildPath("\\a\\", "\\b\\", "\\c\\"))
}