/
sys.go
93 lines (75 loc) 路 2.01 KB
/
sys.go
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
package sys
import (
"os"
"path/filepath"
"strings"
"github.com/skratchdot/open-golang/open"
)
const (
srcDirName = "src"
gopathEnv = "GOPATH"
gopathSeperator = ":"
)
var (
// CanOpenTerminal indicates if the current platform supports opening
// Terminal/command-line applications to a specific directory.
CanOpenTerminal bool
defaultGoPath = os.ExpandEnv("$HOME/go")
)
// OpenFileExplorer opens the system file explorer application to the
// specified package.
func OpenFileExplorer(pkg string) {
open.Run(AbsPath(pkg))
}
// OpenTerminal opens the system terminal (command line) application to the
// specified package.
func OpenTerminal(pkg string) {
openTerminal(pkg)
}
// OpenBrowser opens the default browser to the url provided.
func OpenBrowser(url string) {
if !strings.HasPrefix(url, "http") {
url = "http://" + url
}
open.Run(url)
}
// AbsPath returns the absolute path to a package from it's name.
func AbsPath(pkg string) string {
srcDirs := Srcdir()
for _, d := range srcDirs {
info, err := os.Stat(filepath.Join(d, pkg))
if err != nil || !info.IsDir() {
continue
}
return filepath.Join(d, pkg)
}
return ""
}
// Srcdir returns the source directory(s) for go packages.
func Srcdir() []string {
gopaths := Gopath()
srcDirs := make([]string, len(gopaths), len(gopaths))
for i, p := range gopaths {
srcDirs[i] = filepath.Join(p, srcDirName)
}
return srcDirs
}
// Gopath returns the system GOPATH(s), defaulting to $HOME/go
// if the environment variable is not set.
func Gopath() []string {
return strings.Split(RawGopath(), gopathSeperator)
}
// RawGopath returns the system GOPATH, defaulting to $HOME/go
// if the environment variable is not set, as a string regardless
// of how many GOPATHs are actually set.
func RawGopath() string {
gopath := os.Getenv(gopathEnv)
if len(gopath) == 0 {
gopath = defaultGoPath
}
return gopath
}
// SetGopath sets the $GOPATH environment variable to the value provided.
func SetGopath(gopath string) {
os.Setenv(gopathEnv, gopath)
}