/
segment_language.go
100 lines (89 loc) · 2.56 KB
/
segment_language.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
94
95
96
97
98
99
100
package main
import "errors"
type language struct {
props *properties
env environmentInfo
extensions []string
commands []string
executable string
versionParam string
versionRegex string
version string
exitCode int
}
const (
// DisplayModeProperty sets the display mode (always, when_in_context, never)
DisplayModeProperty Property = "display_mode"
// DisplayModeAlways displays the segment always
DisplayModeAlways string = "always"
// DisplayModeContext displays the segment when the current folder contains certain extensions
DisplayModeContext string = "context"
// MissingCommandTextProperty sets the text to display when the command is not present in the system
MissingCommandTextProperty Property = "missing_command_text"
// MissingCommandText displays empty string by default
MissingCommandText string = ""
)
func (l *language) string() string {
// check if one of the defined commands exists in the system
if !l.hasCommand() {
return l.props.getString(MissingCommandTextProperty, MissingCommandText)
}
// call getVersion if displayVersion set in config
if l.props.getBool(DisplayVersion, true) && l.getVersion() {
return l.version
}
return ""
}
func (l *language) enabled() bool {
displayMode := l.props.getString(DisplayModeProperty, DisplayModeContext)
displayVersion := l.props.getBool(DisplayVersion, true)
switch displayMode {
case DisplayModeAlways:
return (!displayVersion || l.hasCommand())
case DisplayModeContext:
fallthrough
default:
return l.isInContext() && (!displayVersion || l.hasCommand())
}
}
// isInContext will return true at least one file matching the extensions is found
func (l *language) isInContext() bool {
for i, extension := range l.extensions {
if l.env.hasFiles(extension) {
break
}
if i == len(l.extensions)-1 {
return false
}
}
return true
}
// getVersion returns the version and exit code returned by the executable
func (l *language) getVersion() bool {
versionInfo, err := l.env.runCommand(l.executable, l.versionParam)
var exerr *commandError
if err == nil {
values := findNamedRegexMatch(l.versionRegex, versionInfo)
l.exitCode = 0
l.version = values["version"]
} else {
l.version = ""
if errors.As(err, &exerr) {
l.exitCode = exerr.exitCode
}
}
return true
}
// hasCommand checks if one of the commands exists and sets it as executable
func (l *language) hasCommand() bool {
for i, command := range l.commands {
if l.env.hasCommand(command) {
l.executable = command
break
}
if i == len(l.commands)-1 {
return false
}
}
return true
}