util/project.go

103 lines
2.8 KiB
Go

// Package util ...
//
// Description : util ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-10-14 12:39
package util
import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/mitchellh/go-homedir"
)
type project struct {
}
// GetExecutablePath 获取可执行文件的路径
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:41 2022/10/14
func (p *project) GetExecutablePath() (string, error) {
dir, err := filepath.Abs(filepath.Dir(os.Args[0])) //返回绝对路径 filepath.Dir(os.Args[0])去除最后一个元素的路径
if err != nil {
return "", err
}
return dir, nil
}
// GetFileSystemSeparator 获取当前文件系统的路径分隔符
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:51 2022/10/14
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())
}
// GetProjectPath 获取项目目录
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:39 2023/1/13
func (p *project) GetProjectPath() string {
dir, _ := os.Getwd()
return dir
}
// GetHomeDir 获取家目录
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 22:31 2023/4/18
func (p *project) GetHomeDir() string {
homePath, _ := homedir.Dir()
return homePath
}