diff --git a/project.go b/project.go index 502cf56..3bf110b 100644 --- a/project.go +++ b/project.go @@ -10,10 +10,11 @@ package util import ( "os" "path/filepath" + "runtime" + "strings" ) type project struct { - } // GetExecutablePath 获取可执行文件的路径 @@ -38,3 +39,42 @@ func (p *project) GetFileSystemSeparator() string { 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()) +} diff --git a/project_test.go b/project_test.go index 37d984a..940e6cf 100644 --- a/project_test.go +++ b/project_test.go @@ -15,3 +15,9 @@ import ( func Test_project_GetExecutablePath(t *testing.T) { 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\\")) +}