path.go 2.0 KB

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