-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
373 lines (318 loc) · 8.94 KB
/
main.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"slices"
"strings"
"github.com/BurntSushi/toml"
"github.com/adrg/xdg"
"github.com/stilesdev/sessionizer/internal/fzf"
"github.com/stilesdev/sessionizer/internal/tmux"
"github.com/urfave/cli/v2"
)
var showDebug bool
func debugLog(message ...any) {
if showDebug {
fmt.Println(message...)
}
}
func main() {
var configFile string
var config Config
var sessionOverride string
defaultConfigFile, err := xdg.ConfigFile("sessionizer/config.toml")
if err != nil {
log.Fatalln(err)
}
cli := cli.App{
Name: "sessionizer",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Usage: "Load configuration from `FILE`",
Value: defaultConfigFile,
Destination: &configFile,
},
&cli.BoolFlag{
Name: "debug",
Usage: "Print debug messages to stdout",
Destination: &showDebug,
},
&cli.StringFlag{
Name: "open",
Usage: "Open the provided session immediately instead of prompting to select a session with fzf",
Destination: &sessionOverride,
},
},
Action: func(ctx *cli.Context) error {
if _, err := toml.DecodeFile(configFile, &config); err == nil {
debugLog("Using config file:", configFile)
} else {
if configFile != defaultConfigFile {
// user specified config file but we couldn't decode it
return err
}
debugLog("Using default config, error loading file:", err)
// not able to load default config, set defaults for anything required here:
defaultSessionConfig := SessionsConfig{
Path: filepath.Join(xdg.Home, "*"),
}
config.Sessions = append(config.Sessions, defaultSessionConfig)
}
var sessions []Session
if !tmux.IsTmuxAvailable() {
return errors.New("tmux is not installed or could not be found in $PATH")
}
if !fzf.IsAvailable() {
return errors.New("fzf is not installed or could not be found in $PATH")
}
debugLog(fmt.Sprintf("Loaded config: %+v", config))
existingTmuxSessions, err := tmux.ListExistingSessions()
if err != nil {
return err
}
for _, sessionConfig := range config.Sessions {
if sessionConfig.Path != "" {
for _, path := range parseGlobToPaths(sessionConfig.Path) {
session := parseSession(path, sessionConfig, existingTmuxSessions)
if !session.IsAttached || !config.Tmux.HideAttachedSessions || sessionOverride != "" {
if found, index := findSessionIndex(session, sessions); found {
sessions[index] = session
} else {
sessions = append(sessions, session)
}
}
}
}
if len(sessionConfig.Paths) > 0 {
for _, glob := range sessionConfig.Paths {
for _, path := range parseGlobToPaths(glob) {
session := parseSession(path, sessionConfig, existingTmuxSessions)
if !session.IsAttached || !config.Tmux.HideAttachedSessions || sessionOverride != "" {
if found, index := findSessionIndex(session, sessions); found {
sessions[index] = session
} else {
sessions = append(sessions, session)
}
}
}
}
}
}
// look for any scratch sessions - existing sessions in tmux but not associated with any paths from config file
// TODO: add scratch path as config opt, and explicitly match scratch sessions to that path
for _, existingSession := range existingTmuxSessions {
excludeSession := false
// exclude if attached and configured to hide attached sessions
if (config.Tmux.HideAttachedSessions && existingSession.Attached) || sessionOverride != "" {
excludeSession = true
}
// exclude if already included via paths - only looking for scratch sessions here
for _, session := range sessions {
if existingSession.Name == session.Name && existingSession.Path == session.Path {
excludeSession = true
break
}
}
if !excludeSession {
sessions = append(sessions, Session{
Path: existingSession.Path,
Name: existingSession.Name,
FzfEntry: fmt.Sprintf("scratch: %s", existingSession.Name),
Exists: true,
IsAttached: existingSession.Attached,
IsScratch: true,
})
}
}
var selectedIndex int
var enteredQuery string
sortSessions(&sessions)
if sessionOverride == "" {
fzfEntries := make([]string, len(sessions))
for idx, session := range sessions {
fzfEntries[idx] = session.FzfEntry
}
selectedIndex, _, enteredQuery, err = fzf.Prompt(fzfEntries)
if err != nil {
return err
} else if selectedIndex < 0 && enteredQuery == "" {
// not an error, but no valid selection made
debugLog("user exited")
return nil
}
} else {
for index, session := range sessions {
if session.Name == sessionOverride || session.Path == sessionOverride {
selectedIndex = index
break
}
}
}
var tmuxSession tmux.TmuxSession
if selectedIndex >= 0 {
debugLog(fmt.Sprintf("Selected: %#v", sessions[selectedIndex]))
if sessions[selectedIndex].Exists {
for _, existingTmuxSession := range existingTmuxSessions {
if existingTmuxSession.Name == sessions[selectedIndex].Name {
tmuxSession = existingTmuxSession
}
}
} else {
// session does not exist, create it now
tmuxSession = tmux.TmuxSession{
Name: sessions[selectedIndex].Name,
Path: sessions[selectedIndex].Path,
Env: sessions[selectedIndex].Env,
Command: sessions[selectedIndex].Command,
Split: sessions[selectedIndex].Split,
Windows: sessions[selectedIndex].Windows,
}
tmux.CreateNewSession(tmuxSession)
}
} else if enteredQuery != "" {
// no selection, create scratch
tmuxSession = tmux.TmuxSession{
Name: enteredQuery,
Path: xdg.Home,
}
tmux.CreateNewSession(tmuxSession)
} else {
debugLog("no session selected and no query returned from fzf")
return nil
}
if tmux.IsInTmux() {
tmux.SwitchToSession(tmuxSession)
} else {
tmux.AttachToSession(tmuxSession)
}
return nil
},
}
if err := cli.Run(os.Args); err != nil {
log.Fatalln(err)
}
}
type SessionsConfig struct {
Path string
Paths []string
Env map[string]string
Command string
Split tmux.PaneSplit
Windows []tmux.TmuxWindow
}
type TmuxConfig struct {
HideAttachedSessions bool
}
type Config struct {
Sessions []SessionsConfig
Tmux TmuxConfig
}
type Session struct {
Path string
Name string
FzfEntry string
Exists bool
IsScratch bool
IsAttached bool
Env map[string]string
Command string
Split tmux.PaneSplit
Windows []tmux.TmuxWindow
}
func parseGlobToPaths(glob string) []string {
var paths []string
matches, err := filepath.Glob(expandHome(glob))
if err != nil {
debugLog("Unable to parse glob:", glob)
return paths
}
for _, path := range matches {
if fileInfo, err := os.Stat(path); err == nil && fileInfo.IsDir() {
paths = append(paths, path)
}
}
return paths
}
func findSessionIndex(target Session, sessions []Session) (bool, int) {
for index, session := range sessions {
if session.Path == target.Path {
return true, index
}
}
return false, 0
}
func tmuxSessionExists(path string, existingSessions []tmux.TmuxSession) bool {
for _, existingSession := range existingSessions {
if existingSession.Path == path {
return true
}
}
return false
}
func expandHome(path string) string {
if strings.HasPrefix(path, "~"+string(os.PathSeparator)) {
return filepath.Join(xdg.Home, path[2:])
}
return path
}
func unexpandHome(path string) string {
if strings.HasPrefix(path, xdg.Home) {
return filepath.Join("~", path[len(xdg.Home):])
}
return path
}
func parseSession(path string, sessionConfig SessionsConfig, existingTmuxSessions []tmux.TmuxSession) Session {
session := Session{
Path: path,
Name: filepath.Base(path),
FzfEntry: unexpandHome(path),
Env: sessionConfig.Env,
Command: sessionConfig.Command,
Split: sessionConfig.Split,
Windows: sessionConfig.Windows,
}
for key, val := range session.Env {
session.Env[key] = expandHome(val)
}
for _, tmuxSession := range existingTmuxSessions {
if tmuxSession.Path == path && tmuxSession.Name == session.Name {
session.FzfEntry = fmt.Sprintf("tmux: %s [%s]", session.Name, unexpandHome(path))
session.Exists = true
session.IsAttached = tmuxSession.Attached
break
}
}
if session.Split.Path != "" {
session.Split.Path = expandHome(session.Split.Path)
}
for i, window := range session.Windows {
if window.Path != "" {
session.Windows[i].Path = expandHome(window.Path)
}
}
return session
}
func sortSessions(sessions *[]Session) {
slices.SortStableFunc(*sessions, func(a Session, b Session) int {
if a.IsScratch != b.IsScratch {
if a.IsScratch {
return 1
} else {
return -1
}
}
if a.Exists != b.Exists {
if a.Exists {
return 1
} else {
return -1
}
}
return 0
})
}