github.com/webx-top/com@v1.2.12/path.go (about) 1 // Copyright 2013 com authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"): you may 4 // not use this file except in compliance with the License. You may obtain 5 // a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations 13 // under the License. 14 15 package com 16 17 import ( 18 "errors" 19 "os" 20 "path/filepath" 21 "strings" 22 ) 23 24 // GetGOPATHs returns all paths in GOPATH variable. 25 func GetGOPATHs() []string { 26 gopath := os.Getenv("GOPATH") 27 if len(gopath) == 0 { 28 if home, err := HomeDir(); err == nil { 29 userGopath := filepath.Join(home, `go`) 30 if fi, err := os.Stat(userGopath); err == nil && fi.IsDir() { 31 gopath = userGopath 32 } 33 } 34 } 35 var paths []string 36 if IsWindows { 37 gopath = strings.Replace(gopath, "\\", "/", -1) 38 paths = strings.Split(gopath, ";") 39 } else { 40 paths = strings.Split(gopath, ":") 41 } 42 return paths 43 } 44 45 func FixDirSeparator(fpath string) string { 46 if IsWindows { 47 fpath = strings.Replace(fpath, "\\", "/", -1) 48 } 49 return fpath 50 } 51 52 var ErrFolderNotFound = errors.New("unable to locate source folder path") 53 54 // GetSrcPath returns app. source code path. 55 // It only works when you have src. folder in GOPATH, 56 // it returns error not able to locate source folder path. 57 func GetSrcPath(importPath string) (appPath string, err error) { 58 paths := GetGOPATHs() 59 for _, p := range paths { 60 if IsExist(p + "/src/" + importPath + "/") { 61 appPath = p + "/src/" + importPath + "/" 62 break 63 } 64 } 65 66 if len(appPath) == 0 { 67 return "", ErrFolderNotFound 68 } 69 70 appPath = filepath.Dir(appPath) + "/" 71 if IsWindows { 72 // Replace all '\' to '/'. 73 appPath = strings.Replace(appPath, "\\", "/", -1) 74 } 75 76 return appPath, nil 77 } 78 79 // HomeDir returns path of '~'(in Linux) on Windows, 80 // it returns error when the variable does not exist. 81 func HomeDir() (string, error) { 82 return os.UserHomeDir() 83 }