-
Notifications
You must be signed in to change notification settings - Fork 7
/
selectsession.go
231 lines (198 loc) · 7.09 KB
/
selectsession.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package selectsession
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/manifoldco/promptui"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/c8ysession"
createCmd "github.com/reubenmiller/go-c8y-cli/v2/pkg/cmd/sessions/create"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/config"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/iostreams"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/logger"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/utilities/bellskipper"
)
const (
esc = "\033["
noLineWrap = esc + "\x1b[?7l"
doLineWrap = esc + "\x1b[?7h"
)
func customStyle(attr ...color.Attribute) func(interface{}) string {
return func(v interface{}) string {
return color.New(attr...).Sprintf("%v", v)
}
}
func matchSession(session c8ysession.CumulocitySession, input string) bool {
// strip url scheme
uri := strings.ReplaceAll(session.Host, "https://", "")
uri = strings.ReplaceAll(uri, "http://", "")
name := strings.ToLower(fmt.Sprintf("#%02d %s %s %s %s",
session.Index,
filepath.Base(session.Path),
uri,
session.Tenant,
session.Username,
))
input = strings.ToLower(input)
searchTerms := strings.Split(input, " ")
match := true
for _, term := range searchTerms {
if !strings.Contains(name, term) {
match = false
}
}
return match || input == ""
}
// SelectSession select a Cumulocity session interactively
func SelectSession(io *iostreams.IOStreams, cfg *config.Config, log *logger.Logger, filter string) (sessionFile string, err error) {
sessions := &c8ysession.CumulocitySessions{}
sessions.Sessions = make([]c8ysession.CumulocitySession, 0)
subDirToSkip := strings.ToLower(":ignore:" + config.ActivityLogDirName + ":")
files := make([]string, 0)
srcdir := cfg.GetSessionHomeDir()
log.Infof("using c8y session folder: %s", srcdir)
err = filepath.Walk(srcdir, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Printf("Prevent panic by handling failure accessing a path %q: %v", path, err)
return err
}
if info.IsDir() && strings.Contains(subDirToSkip, ":"+strings.ToLower(info.Name())+":") {
log.Printf("Ignoring dir: %+v", info.Name())
return filepath.SkipDir
}
if info.IsDir() && info.Name() == ".git" {
log.Printf("Ignoring dir: %+v", info.Name())
return filepath.SkipDir
}
if info.IsDir() && path == cfg.ExtensionsDataDir() {
log.Printf("Ignoring extensions dir: %+v", info.Name())
return filepath.SkipDir
}
// extensions is a reserved word (in case the user has older extensions folder which is not the current setting, but left overs from a previous location)
if info.IsDir() && strings.EqualFold(info.Name(), "extensions") {
log.Printf("Ignoring reserved dir names: %+v", info.Name())
return filepath.SkipDir
}
if info.IsDir() {
return nil
}
// skip settings file
if strings.HasPrefix(info.Name(), config.SettingsGlobalName+".") ||
strings.HasPrefix(info.Name(), ".") {
return nil
}
log.Infof("Walking folder/file: %s", path)
files = append(files, path)
if session, err := createCmd.NewCumulocitySessionFromFile(path, log, cfg); err == nil {
sessions.Sessions = append(sessions.Sessions, *session)
} else {
log.Infof("Failed to read file: file=%s, err=%s", path, err)
}
return nil
})
if err != nil {
return "", err
}
// Add index numbers
for i := range sessions.Sessions {
sessions.Sessions[i].Index = i + 1
}
funcMap := promptui.FuncMap
funcMap["highlight"] = customStyle()
funcMap["hide"] = func(v interface{}) string {
if cfg.HideSensitive() {
return "*****"
}
return fmt.Sprintf("%v", v)
}
funcMap["hideUser"] = func(v interface{}) string {
msg := fmt.Sprintf("%v", v)
if !cfg.HideSensitive() {
return msg
}
if os.Getenv("USERNAME") != "" {
msg = strings.ReplaceAll(msg, os.Getenv("USERNAME"), "******")
}
return msg
}
templates := &promptui.SelectTemplates{
Active: `▶ {{ printf "#%02d %4.4s" .Index .Extension | highlight }} {{ printf "%-30.29s" .Name | highlight }} {{ .Host | hide | highlight }} {{ printf "(%s/" .Tenant | hide | highlight }}{{ printf "%s)" .Username | hide | highlight }}`,
Inactive: ` {{ printf "#%02d %4.4s" .Index .Extension | faint }} {{ printf "%-30.29s" .Name | cyan }} {{ .Host | hide | magenta }} {{ printf "(%s/" .Tenant | hide | red }}{{ printf "%s)" .Username | hide | red }}`,
Selected: "{{ .Path | hideUser }}",
FuncMap: funcMap,
Details: `
--------- Details ----------
{{ printf "%10s" "File:" | faint }} {{ .Path | hideUser }}
{{ printf "%10s" "Host:" | faint }} {{ .Host | hide }}
{{ printf "%10s" "Tenant:" | faint }} {{ .Tenant | hide }}
{{ printf "%10s" "Username:" | faint }} {{ .Username | hide }}
`,
}
templates.Help = `{{ "Use arrow keys (holding shift) to navigate" | faint }} {{ .NextKey | faint }} ` +
`{{ .PrevKey | faint }} {{ .PageDownKey | faint }} {{ .PageUpKey | faint }} ` +
`{{ if .Search }} {{ "and" | faint }} {{ .SearchKey | faint }} {{ "toggles search" | faint }}{{ end }}`
filteredSessions := make([]c8ysession.CumulocitySession, 0)
sessionIndex := 1
for _, session := range sessions.Sessions {
if session.Host == "" && session.Username == "" && session.Tenant == "" {
continue
}
if matchSession(session, filter) {
session.Index = sessionIndex
filteredSessions = append(filteredSessions, session)
sessionIndex++
}
}
searcher := func(input string, index int) bool {
session := filteredSessions[index]
return matchSession(session, input)
}
// always enable color
color.NoColor = false
prompt := promptui.Select{
Stdout: bellskipper.NewBellSkipper(os.Stderr), // Workaround to pervent the terminal bell on MacOS
HideSelected: true,
IsVimMode: false,
StartInSearchMode: false,
Label: "Select a Cumulocity Session",
Items: filteredSessions,
Templates: templates,
Size: 10,
Searcher: searcher,
}
// Customize select keys
prompt.Keys = &promptui.SelectKeys{
Prev: promptui.Key{Code: promptui.KeyPrev, Display: promptui.KeyPrevDisplay + ""},
Next: promptui.Key{Code: promptui.KeyNext, Display: promptui.KeyNextDisplay + ""},
PageUp: promptui.Key{Code: promptui.KeyBackward, Display: promptui.KeyBackwardDisplay + ""},
PageDown: promptui.Key{Code: promptui.KeyForward, Display: promptui.KeyForwardDisplay + ""},
Search: promptui.Key{Code: '/', Display: "/"},
}
var idx int
var result string
switch len(filteredSessions) {
case 0:
return "", fmt.Errorf("no sessions found")
case 1:
log.Info("Only 1 session found. Selecting it automatically")
idx = 0
result = filteredSessions[0].Path
err = nil
default:
// Prevent wrapping errors as promptui expects all templates to only take
// up one line. When multiline templates are supported by promptui, then this can be removed
// https://github.com/manifoldco/promptui/issues/92
fmt.Fprint(os.Stderr, noLineWrap)
idx, result, err = prompt.Run()
fmt.Fprint(os.Stderr, doLineWrap)
}
if err != nil {
log.Warnf("Prompt failed %v\n", err)
return "", err
}
if result != "" && idx >= 0 && idx < len(filteredSessions) {
sessionFile = filteredSessions[idx].Path
}
return
}