oh-my-posh/src/segment_session.go

83 lines
1.6 KiB
Go
Raw Normal View History

2019-03-13 04:14:30 -07:00
package main
2021-12-03 14:44:58 -08:00
import "strings"
2019-03-13 04:14:30 -07:00
type session struct {
2022-01-01 11:08:08 -08:00
props Properties
2022-01-01 11:09:52 -08:00
env Environment
2021-12-03 14:44:58 -08:00
text string
UserName string
ComputerName string
SSHSession bool
Root bool
2021-12-04 01:22:38 -08:00
// Deprecated
DefaultUserName string
2019-03-13 04:14:30 -07:00
}
func (s *session) enabled() bool {
s.SSHSession = s.activeSSHSession()
segmentTemplate := s.props.getString(SegmentTemplate, "")
2021-12-03 14:44:58 -08:00
if segmentTemplate == "" {
return s.legacyEnabled()
}
s.UserName = s.getUserName()
s.ComputerName = s.getComputerName()
s.Root = s.env.isRunningAsRoot()
template := &textTemplate{
Template: segmentTemplate,
Context: s,
Env: s.env,
}
2021-12-03 14:44:58 -08:00
var err error
s.text, err = template.render()
if err != nil {
s.text = err.Error()
}
2021-12-03 14:44:58 -08:00
return len(s.text) > 0
2019-03-13 04:14:30 -07:00
}
func (s *session) string() string {
2021-12-03 14:44:58 -08:00
if len(s.text) != 0 {
return s.text
}
2019-03-13 04:14:30 -07:00
return s.getFormattedText()
}
2022-01-01 11:09:52 -08:00
func (s *session) init(props Properties, env Environment) {
2019-03-13 04:14:30 -07:00
s.props = props
s.env = env
}
func (s *session) getUserName() string {
user := s.env.getCurrentUser()
username := strings.TrimSpace(user)
2019-03-13 04:14:30 -07:00
if s.env.getRuntimeGOOS() == "windows" && strings.Contains(username, "\\") {
username = strings.Split(username, "\\")[1]
}
return username
}
2021-12-03 14:44:58 -08:00
func (s *session) getComputerName() string {
computername, err := s.env.getHostName()
if err != nil {
computername = "unknown"
}
2021-12-03 14:44:58 -08:00
return strings.TrimSpace(computername)
}
func (s *session) activeSSHSession() bool {
keys := []string{
"SSH_CONNECTION",
"SSH_CLIENT",
}
for _, key := range keys {
content := s.env.getenv(key)
if content != "" {
return true
}
}
return false
}