oh-my-posh/src/segment_language.go

101 lines
2.5 KiB
Go
Raw Normal View History

2020-11-14 11:04:04 -08:00
package main
import "errors"
2020-11-14 11:04:04 -08:00
type language struct {
props *properties
env environmentInfo
extensions []string
commands []string
executable string
2020-11-14 11:04:04 -08:00
versionParam string
versionRegex string
version string
exitCode int
2020-11-14 11:04:04 -08:00
}
const (
// DisplayMode sets the display mode (always, when_in_context, never)
DisplayMode Property = "display_mode"
2020-12-31 23:00:08 -08:00
// DisplayModeAlways displays the segment always
DisplayModeAlways string = "always"
// DisplayModeFiles displays the segment when the current folder contains certain extensions
DisplayModeFiles string = "files"
2021-01-05 03:28:33 -08:00
// MissingCommandTextProperty sets the text to display when the command is not present in the system
MissingCommandTextProperty Property = "missing_command_text"
2021-01-05 03:28:33 -08:00
// MissingCommandText displays empty string by default
MissingCommandText string = ""
)
2020-11-14 11:04:04 -08:00
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() {
2020-11-14 11:04:04 -08:00
return l.version
}
return ""
}
func (l *language) enabled() bool {
displayMode := l.props.getString(DisplayMode, DisplayModeFiles)
displayVersion := l.props.getBool(DisplayVersion, true)
switch displayMode {
case DisplayModeAlways:
return (!displayVersion || l.hasCommand())
case DisplayModeFiles:
fallthrough
default:
return l.hasLanguageFiles() && (!displayVersion || l.hasCommand())
}
}
// hasLanguageFiles will return true at least one file matching the extensions is found
func (l *language) hasLanguageFiles() bool {
2020-11-14 11:04:04 -08:00
for i, extension := range l.extensions {
if l.env.hasFiles(extension) {
break
}
if i == len(l.extensions)-1 {
return false
}
}
return true
}
2020-12-31 11:07:59 -08:00
// 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
}
2020-12-31 11:07:59 -08:00
// hasCommand checks if one of the commands exists and sets it as executable
func (l *language) hasCommand() bool {
2020-11-14 11:04:04 -08:00
for i, command := range l.commands {
if l.env.hasCommand(command) {
l.executable = command
2020-11-14 11:04:04 -08:00
break
}
if i == len(l.commands)-1 {
return false
}
}
return true
}