github.com/cyverse/go-irodsclient@v0.13.2/irods/util/path.go (about) 1 package util 2 3 import ( 4 "os" 5 "path/filepath" 6 "strings" 7 8 "golang.org/x/xerrors" 9 ) 10 11 // GetCorrectLocalPath corrects the path 12 func GetCorrectLocalPath(p string) string { 13 return filepath.Clean(p) 14 } 15 16 func GetBasename(p string) string { 17 p = strings.TrimRight(p, string(os.PathSeparator)) 18 p = strings.TrimRight(p, "/") 19 20 idx1 := strings.LastIndex(p, string(os.PathSeparator)) 21 idx2 := strings.LastIndex(p, "/") 22 23 if idx1 < 0 && idx2 < 0 { 24 return p 25 } 26 27 if idx1 >= idx2 { 28 return p[idx1+1:] 29 } 30 return p[idx2+1:] 31 } 32 33 func GetDir(p string) string { 34 idx1 := strings.LastIndex(p, string(os.PathSeparator)) 35 idx2 := strings.LastIndex(p, "/") 36 37 if idx1 < 0 && idx2 < 0 { 38 return "/" 39 } 40 41 if idx1 >= idx2 { 42 return p[:idx1] 43 } 44 return p[:idx2] 45 } 46 47 func Join(p1 string, p2 ...string) string { 48 sep := "/" 49 50 if strings.Contains(p1, string(os.PathSeparator)) { 51 sep = string(os.PathSeparator) 52 } else if strings.Contains(p1, "/") { 53 sep = "/" 54 } 55 56 p := []string{} 57 p = append(p, p1) 58 p = append(p, p2...) 59 60 return strings.Join(p, sep) 61 } 62 63 func ExpandHomeDir(path string) (string, error) { 64 if len(path) == 0 { 65 return "", nil 66 } 67 68 if path[0] != '~' { 69 return path, nil 70 } 71 72 homedir, err := os.UserHomeDir() 73 if err != nil { 74 return "", xerrors.Errorf("failed to get user home dir: %w", err) 75 } 76 77 // resolve "~" 78 if len(path) == 1 { 79 return homedir, nil 80 } 81 82 // resolve "~/" 83 if path[1] == '/' { 84 path = filepath.Join(homedir, path[2:]) 85 return filepath.Clean(path), nil 86 } 87 88 return path, nil 89 } 90 91 func ExistFile(path string) bool { 92 st, err := os.Stat(path) 93 if err != nil { 94 return false 95 } 96 97 if !st.IsDir() { 98 return true 99 } 100 return false 101 }