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