github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/Unknwon/com/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 "runtime" 22 "strings" 23 ) 24 25 // GetGOPATHs returns all paths in GOPATH variable. 26 func GetGOPATHs() []string { 27 gopath := os.Getenv("GOPATH") 28 var paths []string 29 if runtime.GOOS == "windows" { 30 gopath = strings.Replace(gopath, "\\", "/", -1) 31 paths = strings.Split(gopath, ";") 32 } else { 33 paths = strings.Split(gopath, ":") 34 } 35 return paths 36 } 37 38 // GetSrcPath returns app. source code path. 39 // It only works when you have src. folder in GOPATH, 40 // it returns error not able to locate source folder path. 41 func GetSrcPath(importPath string) (appPath string, err error) { 42 paths := GetGOPATHs() 43 for _, p := range paths { 44 if IsExist(p + "/src/" + importPath + "/") { 45 appPath = p + "/src/" + importPath + "/" 46 break 47 } 48 } 49 50 if len(appPath) == 0 { 51 return "", errors.New("Unable to locate source folder path") 52 } 53 54 appPath = filepath.Dir(appPath) + "/" 55 if runtime.GOOS == "windows" { 56 // Replace all '\' to '/'. 57 appPath = strings.Replace(appPath, "\\", "/", -1) 58 } 59 60 return appPath, nil 61 } 62 63 // HomeDir returns path of '~'(in Linux) on Windows, 64 // it returns error when the variable does not exist. 65 func HomeDir() (home string, err error) { 66 if runtime.GOOS == "windows" { 67 home = os.Getenv("USERPROFILE") 68 if len(home) == 0 { 69 home = os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") 70 } 71 } else { 72 home = os.Getenv("HOME") 73 } 74 75 if len(home) == 0 { 76 return "", errors.New("Cannot specify home directory because it's empty") 77 } 78 79 return home, nil 80 }