Files
util/project.go
2026-01-03 21:34:13 +08:00

71 lines
1.6 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 获取可执行文件的路径
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 获取当前文件系统的路径分隔符
func (p *project) GetFileSystemSeparator() string {
return string(filepath.Separator)
}
// BuildPath 构建路径
func (p *project) BuildPath(filePathList ...string) string {
projectRootPath, _ := p.GetExecutablePath()
if len(filePathList) == 0 {
// 降为获取项目根目录
return projectRootPath
}
// 第一个特殊处理
if strings.ToLower(runtime.GOOS) == "windows" {
// windows
if !strings.Contains(filePathList[0], ":") {
// 不包含 :, 是 相对路径,拼成绝对路径
filePathList[0] = filepath.Join(projectRootPath, filePathList[0])
}
} else {
// unix/ linux
if !strings.HasPrefix(filePathList[0], p.GetFileSystemSeparator()) {
// 不是绝对路径
filePathList[0] = filepath.Join(projectRootPath, filePathList[0])
}
}
return filepath.Join(filePathList...)
}
// GetWorkDir 获取工作目录
func (p *project) GetWorkDir() string {
dir, _ := os.Getwd()
return dir
}
// GetHomeDir 获取家目录
func (p *project) GetHomeDir() string {
homePath, _ := homedir.Dir()
return homePath
}