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
|
2021-02-24 00:04:04 -08:00
|
|
|
DefaultUserName string
|
2019-03-13 04:14:30 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *session) enabled() bool {
|
2021-02-24 00:04:04 -08:00
|
|
|
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-02-24 00:04:04 -08:00
|
|
|
}
|
2021-12-03 14:44:58 -08:00
|
|
|
var err error
|
|
|
|
s.text, err = template.render()
|
|
|
|
if err != nil {
|
|
|
|
s.text = err.Error()
|
2020-12-02 10:00:46 -08:00
|
|
|
}
|
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 {
|
2020-10-12 03:53:54 -07:00
|
|
|
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
|
|
|
|
}
|
2020-11-03 11:06:11 -08:00
|
|
|
|
2021-12-03 14:44:58 -08:00
|
|
|
func (s *session) getComputerName() string {
|
|
|
|
computername, err := s.env.getHostName()
|
|
|
|
if err != nil {
|
|
|
|
computername = "unknown"
|
2021-02-24 00:04:04 -08:00
|
|
|
}
|
2021-12-03 14:44:58 -08:00
|
|
|
return strings.TrimSpace(computername)
|
2021-02-24 00:04:04 -08:00
|
|
|
}
|
|
|
|
|
2020-11-03 11:06:11 -08:00
|
|
|
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
|
|
|
|
}
|