gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/gox/pathx/pathutil.go (about) 1 package pathx 2 3 import ( 4 "errors" 5 "gitee.com/zhongguo168a/gocodes/gox/osx" 6 "os" 7 "os/exec" 8 "path" 9 "path/filepath" 10 "regexp" 11 "strconv" 12 "strings" 13 ) 14 15 // GetWorkingPath 获取当前文件执行的路径 16 func GetWorkingPath() string { 17 file, _ := exec.LookPath(os.Args[0]) 18 19 //得到全路径,比如在windows下E:\\golang\\test\\a.exe 20 path, _ := filepath.Abs(file) 21 22 rst := filepath.Dir(path) 23 24 return rst 25 } 26 27 func S生成不重复的文件路径(path string) (string, error) { 28 count := 0 29 最后的目录 := "" 30 ext := filepath.Ext(path) 31 name := strings.Replace(filepath.Base(path), ext, "", 1) 32 33 re := regexp.MustCompile(`(.*)_\d+$`) 34 if re.MatchString(name) { 35 results := re.FindAllStringSubmatch(name, -1) 36 name = results[0][1] 37 } 38 39 dir := filepath.Dir(path) 40 for { 41 42 if count == 0 { 43 最后的目录 = path 44 } else { 45 最后的目录 = dir + "/" + name + "_" + strconv.Itoa(count) + ext 46 } 47 48 has, oserr := osx.Exists(最后的目录) 49 if oserr != nil { 50 return "", oserr 51 } 52 if has { 53 count++ 54 continue 55 } 56 break 57 } 58 59 return 最后的目录, nil 60 } 61 62 func PathExists(path string) bool { 63 _, err := os.Stat(path) 64 if err == nil { 65 return true 66 } 67 if os.IsNotExist(err) { 68 return false 69 } 70 return false 71 } 72 73 // GetGoPackagePath 获取当前文件执行的路径 74 func GetGoPackagePath(pkg string) (goPath, pkgPath string, err error) { 75 gopath := os.Getenv("GOPATH") 76 arr := strings.Split(gopath, ";") 77 for _, val := range arr { 78 goPath = val 79 pkgPath = val + "/src/" + pkg 80 if PathExists(pkgPath) == true { 81 return 82 } 83 } 84 85 err = errors.New("not found") 86 return 87 } 88 89 // FormatPath 格式化路径, 统一转换为linux路径 90 func FormatPath(p string) string { 91 p = strings.Replace(p, "\\", "/", -1) 92 return p 93 } 94 95 func GetExecutable() string { 96 p, err := os.Executable() 97 if err != nil { 98 panic(err) 99 } 100 101 p = path.Dir(p) 102 p = FormatPath(p) 103 return p 104 }