forked from JanDeDobbeleer/oh-my-posh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgolang.go
More file actions
89 lines (72 loc) · 2.13 KB
/
Copy pathgolang.go
File metadata and controls
89 lines (72 loc) · 2.13 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
package segments
import (
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/segments/options"
)
type Golang struct {
Language
}
const (
ParseModFile options.Option = "parse_mod_file"
ParseGoWorkFile options.Option = "parse_go_work_file"
)
func (g *Golang) Template() string {
return languageTemplate
}
func (g *Golang) Enabled() bool {
g.extensions = []string{"*.go", "go.mod", "go.sum", "go.work", "go.work.sum"}
g.tooling = map[string]*cmd{
"mod": {
regex: `(?P<version>((?P<major>[0-9]+).(?P<minor>[0-9]+)(.(?P<patch>[0-9]+))?))`,
getVersion: g.getVersion,
},
"go": {
executable: "go",
args: []string{versionArg},
regex: `(?:go(?P<version>((?P<major>[0-9]+).(?P<minor>[0-9]+)(.(?P<patch>[0-9]+))?)))`,
},
}
g.defaultTooling = []string{"mod", "go"}
g.versionURLTemplate = "https://golang.org/doc/go{{ .Major }}.{{ .Minor }}"
return g.Language.Enabled()
}
func (g *Golang) getVersion() (string, error) {
if g.options.Bool(ParseModFile, false) {
return g.parseModFile()
}
if g.options.Bool(ParseGoWorkFile, false) {
return g.parseWorkFile()
}
return "", nil
}
func (g *Golang) parseModFile() (string, error) {
gomod, err := g.env.HasParentFilePath("go.mod", false)
if err != nil {
return "", err
}
contents := g.env.FileContent(gomod.Path)
// the go directive is a top-level "go <version>" line; module paths in
// require blocks always contain a slash or dot so they never match
for line := range strings.Lines(contents) {
fields := strings.Fields(line)
if len(fields) >= 2 && fields[0] == "go" && fields[1][0] >= '0' && fields[1][0] <= '9' {
return fields[1], nil
}
}
// ignore when no version is found in go.mod file
return "", nil
}
func (g *Golang) parseWorkFile() (string, error) {
goWork, err := g.env.HasParentFilePath("go.work", false)
if err != nil {
return "", err
}
contents := g.env.FileContent(goWork.Path)
version, _ := regex.FindStringMatch(`go (\d(\.\d{1,2})?(\.\d{1,2})?)`, contents, 1)
if len(version) > 0 {
return version, nil
}
// ignore when no version is found in go.work file
return "", nil
}