From 9931590d801dd14b3bffb192c3e0f385d8cd2cfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 14 Oct 2022 13:46:33 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=9E=84=E5=BB=BAwenjian?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- project.go | 42 +++++++++++++++++++++++++++++++++++++++++- project_test.go | 6 ++++++ 2 files changed, 47 insertions(+), 1 deletion(-) 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\\")) +}