-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
545 lines (494 loc) · 15.2 KB
/
main.go
File metadata and controls
545 lines (494 loc) · 15.2 KB
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package main
import (
"errors"
"flag"
"fmt"
"io"
"maps"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
"github.com/atomicstack/tmux-popup-control/internal/app"
"github.com/atomicstack/tmux-popup-control/internal/config"
"github.com/atomicstack/tmux-popup-control/internal/logging"
"github.com/atomicstack/tmux-popup-control/internal/logging/events"
"github.com/atomicstack/tmux-popup-control/internal/plugin"
"github.com/atomicstack/tmux-popup-control/internal/resurrect"
"github.com/atomicstack/tmux-popup-control/internal/shquote"
"github.com/atomicstack/tmux-popup-control/internal/tmux"
"golang.org/x/term"
)
// Version is set at build time via ldflags.
var Version = "dev"
type MainDeps struct {
ResolveSocketPath func(string) (string, error)
ResolveSaveDir func(string) (string, error)
ResolvePaneContents func(string) bool
ResolveAutosaveIntervalMinutes func(string) int
ResolveAutosaveMax func(string) int
ResolveAutosaveIcon func(string) string
ResolveAutosaveIconSeconds func(string) int
RunAutoSaveCommand func(resurrect.StatusConfig, io.Writer) error
}
var mainDeps = MainDeps{
ResolveSocketPath: tmux.ResolveSocketPath,
ResolveSaveDir: resurrect.ResolveDir,
ResolvePaneContents: resurrect.ResolvePaneContents,
ResolveAutosaveIntervalMinutes: resurrect.ResolveAutosaveIntervalMinutes,
ResolveAutosaveMax: resurrect.ResolveAutosaveMax,
ResolveAutosaveIcon: resurrect.ResolveAutosaveIcon,
ResolveAutosaveIconSeconds: resurrect.ResolveAutosaveIconSeconds,
RunAutoSaveCommand: resurrect.RunAutoSaveCommand,
}
var (
ensureZeroExitOnHangupFn = ensureZeroExitOnHangup
loadConfigFn = config.Load
validateConfigFn = config.Validate
configureLoggingFn = logging.Configure
setTraceEnabledFn = logging.SetTraceEnabled
enableSQLiteDebugFn = logging.EnableSQLiteDebug
closeLoggingFn = logging.Close
traceStartupFn = traceStartup
appRunFn = app.Run
logErrorFn = logging.Error
)
type commandHandler struct {
ErrorLabel string
Run func(config.Config, MainDeps) error
}
func main() {
os.Exit(run())
}
func run() (exitCode int) {
return runWithDeps(mainDeps)
}
func runWithDeps(deps MainDeps) (exitCode int) {
ensureZeroExitOnHangupFn()
var exitStatus = "ok"
var exitErr error
defer func() {
closeLoggingFn(logging.RunResult{
ExitCode: exitCode,
ExitStatus: exitStatus,
Error: exitErr,
})
}()
runtimeCfg, err := loadConfigFn()
if errors.Is(err, config.ErrVersionRequested) {
fmt.Println(Version)
return 0
}
if err != nil {
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
exitStatus = "config_error"
exitErr = err
return 2
}
if err := validateConfigFn(runtimeCfg); err != nil {
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
exitStatus = "config_error"
exitErr = err
return 2
}
configureLoggingFn(runtimeCfg.Logging.FilePath)
setTraceEnabledFn(runtimeCfg.Logging.Trace)
if runtimeCfg.Logging.DebugToSQLite {
if err := enableSQLiteDebugFn(buildSQLiteRunInfo(runtimeCfg)); err != nil {
fmt.Fprintf(os.Stderr, "Configuration error: %v\n", err)
exitStatus = "sqlite_debug_error"
exitErr = err
return 2
}
}
traceStartupFn(runtimeCfg)
cmd := subcommand(runtimeCfg)
if handler, ok := commandHandlers()[cmd]; ok {
if err := handler.Run(runtimeCfg, deps); err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", handler.ErrorLabel, err)
exitStatus = "error"
exitErr = err
return 1
}
return 0
}
if err := appRunFn(runtimeCfg.App); err != nil {
logErrorFn(err)
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
exitStatus = "error"
exitErr = err
return 1
}
return 0
}
func commandHandlers() map[string]commandHandler {
return map[string]commandHandler{
"save-sessions": {
ErrorLabel: "save-sessions",
Run: func(cfg config.Config, _ MainDeps) error {
return runSaveSessions(cfg)
},
},
"restore-sessions": {
ErrorLabel: "restore-sessions",
Run: func(cfg config.Config, _ MainDeps) error {
return runRestoreSessions(cfg)
},
},
"autosave": {
ErrorLabel: "autosave",
Run: runAutosave,
},
"autosave-status": {
ErrorLabel: "autosave",
Run: runAutosave,
},
"install-and-init-plugins": {
ErrorLabel: "Error",
Run: func(cfg config.Config, _ MainDeps) error {
return runInstallAndInitPlugins(cfg)
},
},
"deferred-install": {
ErrorLabel: "Error",
Run: func(cfg config.Config, _ MainDeps) error {
return runDeferredInstall(cfg)
},
},
}
}
func runInstallAndInitPlugins(cfg config.Config) error {
socketPath, err := tmux.ResolveSocketPath(cfg.App.SocketPath)
if err != nil {
return fmt.Errorf("resolving socket: %w", err)
}
plugins, err := plugin.ParseConfig(socketPath)
if err != nil {
return fmt.Errorf("reading plugin config: %w", err)
}
pluginDir := plugin.PluginDir()
events.Plugins.InitPlugins(len(plugins))
// Source already-installed plugins immediately.
if err := plugin.Source(pluginDir, plugins); err != nil {
return fmt.Errorf("sourcing plugins: %w", err)
}
// If any plugins need installing, schedule a deferred popup so the user
// sees the interactive install UI once tmux finishes starting.
for _, p := range plugins {
if !p.Installed {
return deferPluginInstall(socketPath)
}
}
return nil
}
// deferPluginInstall schedules a background tmux command that waits for
// startup to complete, then opens the install TUI in a display-popup.
// Uses a plain CLI call rather than gotmuxcc control-mode to avoid creating
// phantom sessions during server startup.
func deferPluginInstall(socketPath string) error {
cmd, err := buildSelfCommand("deferred-install", "-socket", socketPath)
if err != nil {
return err
}
args := []string{"run-shell", "-b", cmd}
if socketPath != "" {
args = append([]string{"-S", socketPath}, args...)
}
return exec.Command("tmux", args...).Run()
}
// runDeferredInstall is invoked via run-shell -b after the main
// install-and-init-plugins command completes. It waits for tmux to be
// fully ready, then opens the install TUI in a display-popup.
func runDeferredInstall(cfg config.Config) error {
socketPath, err := tmux.ResolveSocketPath(cfg.App.SocketPath)
if err != nil {
return fmt.Errorf("resolving socket: %w", err)
}
plugins, err := plugin.ParseConfig(socketPath)
if err != nil {
return fmt.Errorf("reading plugin config: %w", err)
}
var needInstall bool
for _, p := range plugins {
if !p.Installed {
needInstall = true
break
}
}
if !needInstall {
return nil
}
// Wait for tmux to finish starting so display-popup has a client.
time.Sleep(500 * time.Millisecond)
// Find the real terminal client — display-popup must target it rather
// than the control-mode connection gotmuxcc uses.
clientName, err := tmux.FindTerminalClient(socketPath)
if err != nil {
return fmt.Errorf("finding terminal client: %w", err)
}
return showPopup(socketPath, clientName, "--root-menu", "plugins:install", "-socket", socketPath)
}
func ensureZeroExitOnHangup() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGHUP)
go func() {
for range ch {
logging.Close(logging.RunResult{
ExitCode: 0,
ExitStatus: "sighup",
})
os.Exit(0)
}
}()
}
func traceStartup(cfg config.Config) {
events.App.Start(startupTracePayload(cfg))
}
// startupTracePayload bundles runtime context for trace logging.
func startupTracePayload(cfg config.Config) map[string]any {
flags := make(map[string]any, len(cfg.Flags))
for k, v := range cfg.Flags {
flags[k] = v
}
flags["trace"] = cfg.Logging.Trace
flags["logFile"] = cfg.Logging.FilePath
flags["debugToSQLite"] = cfg.Logging.DebugToSQLite
payload := map[string]any{
"argv": cfg.Args,
"flags": flags,
"config": cfg,
}
if exe, err := os.Executable(); err == nil {
payload["executable"] = exe
} else {
payload["executableError"] = err.Error()
}
if cwd, err := os.Getwd(); err == nil {
payload["cwd"] = cwd
} else {
payload["cwdError"] = err.Error()
}
payload["tty"] = collectTTYDetails()
return payload
}
func buildSQLiteRunInfo(cfg config.Config) logging.SQLiteRunInfo {
info := logging.SQLiteRunInfo{
Version: Version,
Args: append([]string(nil), cfg.Args...),
Flags: cloneStringMap(cfg.Flags),
SocketPath: cfg.App.SocketPath,
RootMenu: cfg.App.RootMenu,
MenuArgs: cfg.App.MenuArgs,
ClientID: cfg.App.ClientID,
SessionName: cfg.App.SessionName,
}
if exe, err := os.Executable(); err == nil {
info.ExecutablePath = exe
}
if cwd, err := os.Getwd(); err == nil {
info.CWD = cwd
}
return info
}
func cloneStringMap(values map[string]string) map[string]string {
if len(values) == 0 {
return nil
}
cloned := make(map[string]string, len(values))
maps.Copy(cloned, values)
return cloned
}
func subcommand(cfg config.Config) string {
if len(cfg.Command) == 0 {
return ""
}
return strings.TrimSpace(cfg.Command[0])
}
func subcommandArgs(cfg config.Config) []string {
if len(cfg.Command) <= 1 {
return nil
}
return append([]string(nil), cfg.Command[1:]...)
}
type ttyDetails struct {
Detected *ttyDetected `json:"detected,omitempty"`
Probes []ttyProbeResult `json:"probes"`
}
type ttyDetected struct {
Source string `json:"source"`
Width int `json:"width"`
Height int `json:"height"`
}
type ttyProbeResult struct {
Name string `json:"name"`
IsTerminal bool `json:"is_terminal"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Error string `json:"error,omitempty"`
}
// collectTTYDetails inspects standard descriptors for terminal support and dimensions.
func collectTTYDetails() ttyDetails {
probes := []struct {
name string
fd uintptr
}{
{"stdin", os.Stdin.Fd()},
{"stdout", os.Stdout.Fd()},
{"stderr", os.Stderr.Fd()},
}
results := make([]ttyProbeResult, 0, len(probes))
var detected *ttyDetected
for _, probe := range probes {
entry := ttyProbeResult{Name: probe.name}
fd := int(probe.fd)
if fd >= 0 && term.IsTerminal(fd) {
entry.IsTerminal = true
if width, height, err := term.GetSize(fd); err == nil {
entry.Width = width
entry.Height = height
if detected == nil {
detected = &ttyDetected{Source: probe.name, Width: width, Height: height}
}
} else {
entry.Error = err.Error()
}
} else {
entry.IsTerminal = false
}
results = append(results, entry)
}
return ttyDetails{Detected: detected, Probes: results}
}
// runSaveSessions handles the "save-sessions" subcommand.
// Without --resurrect-popup it launches a display-popup; with it, it enters
// the progress UI directly.
func runSaveSessions(cfg config.Config) error {
fs := flag.NewFlagSet("save-sessions", flag.ContinueOnError)
name := fs.String("name", os.Getenv("TMUX_POPUP_CONTROL_RESURRECT_NAME"), "snapshot name")
popup := fs.Bool("resurrect-popup", false, "run inside popup (internal)")
socket := fs.String("socket", cfg.App.SocketPath, "tmux socket path")
if err := fs.Parse(subcommandArgs(cfg)); err != nil {
return err
}
if *popup {
cfg.App.SocketPath = *socket
cfg.App.ResurrectOp = "save"
cfg.App.ResurrectName = *name
return app.Run(cfg.App)
}
// outer invocation: launch popup
socketPath, err := tmux.ResolveSocketPath(*socket)
if err != nil {
return fmt.Errorf("resolving socket: %w", err)
}
clientName, err := tmux.FindTerminalClient(socketPath)
if err != nil {
return fmt.Errorf("finding terminal client: %w", err)
}
args := []string{"save-sessions", "--resurrect-popup", "-socket", socketPath}
if *name != "" {
args = append(args, "-name", *name)
}
return showPopup(socketPath, clientName, args...)
}
// runRestoreSessions handles the "restore-sessions" subcommand.
func runRestoreSessions(cfg config.Config) error {
fs := flag.NewFlagSet("restore-sessions", flag.ContinueOnError)
from := fs.String("from", os.Getenv("TMUX_POPUP_CONTROL_RESURRECT_FROM"), "save file name or path")
popup := fs.Bool("resurrect-popup", false, "run inside popup (internal)")
socket := fs.String("socket", cfg.App.SocketPath, "tmux socket path")
if err := fs.Parse(subcommandArgs(cfg)); err != nil {
return err
}
if *popup {
cfg.App.SocketPath = *socket
cfg.App.ResurrectOp = "restore"
cfg.App.ResurrectFrom = *from
return app.Run(cfg.App)
}
// outer invocation: launch popup
socketPath, err := tmux.ResolveSocketPath(*socket)
if err != nil {
return fmt.Errorf("resolving socket: %w", err)
}
clientName, err := tmux.FindTerminalClient(socketPath)
if err != nil {
return fmt.Errorf("finding terminal client: %w", err)
}
args := []string{"restore-sessions", "--resurrect-popup", "-socket", socketPath}
if *from != "" {
args = append(args, "-from", *from)
}
return showPopup(socketPath, clientName, args...)
}
func runAutosave(cfg config.Config, deps MainDeps) error {
autoSaveCfg, err := buildAutoSaveConfig(cfg, deps)
if err != nil {
return err
}
return deps.RunAutoSaveCommand(autoSaveCfg, os.Stdout)
}
func autoSaveOutput(cfg config.Config) (string, error) {
return autoSaveOutputWithDeps(cfg, mainDeps)
}
func autoSaveOutputWithDeps(cfg config.Config, deps MainDeps) (string, error) {
autoSaveCfg, err := buildAutoSaveConfig(cfg, deps)
if err != nil {
return "", err
}
var output strings.Builder
if err := deps.RunAutoSaveCommand(autoSaveCfg, &output); err != nil {
return "", err
}
return output.String(), nil
}
func buildAutoSaveConfig(cfg config.Config, deps MainDeps) (resurrect.StatusConfig, error) {
socketPath := cfg.App.SocketPath
if parsed := autoSaveSocketFlag(cfg); parsed != "" {
socketPath = parsed
}
resolvedSocketPath, err := deps.ResolveSocketPath(socketPath)
if err != nil {
return resurrect.StatusConfig{}, fmt.Errorf("resolving socket: %w", err)
}
saveDir, err := deps.ResolveSaveDir(resolvedSocketPath)
if err != nil {
return resurrect.StatusConfig{}, fmt.Errorf("resolving save dir: %w", err)
}
serverStart, _ := tmux.ServerStartTime(resolvedSocketPath)
return resurrect.StatusConfig{
SocketPath: resolvedSocketPath,
SaveDir: saveDir,
CapturePaneContents: deps.ResolvePaneContents(resolvedSocketPath),
IntervalMinutes: deps.ResolveAutosaveIntervalMinutes(resolvedSocketPath),
Max: deps.ResolveAutosaveMax(resolvedSocketPath),
Icon: deps.ResolveAutosaveIcon(resolvedSocketPath),
IconSeconds: deps.ResolveAutosaveIconSeconds(resolvedSocketPath),
ServerStart: serverStart,
}, nil
}
func autoSaveSocketFlag(cfg config.Config) string {
fs := flag.NewFlagSet("autosave", flag.ContinueOnError)
socket := fs.String("socket", cfg.App.SocketPath, "tmux socket path")
if err := fs.Parse(subcommandArgs(cfg)); err != nil {
return cfg.App.SocketPath
}
return *socket
}
func buildSelfCommand(args ...string) (string, error) {
binary, err := os.Executable()
if err != nil {
return "", fmt.Errorf("resolving executable: %w", err)
}
return shquote.JoinCommand(append([]string{binary}, args...)...), nil
}
func showPopup(socketPath, clientName string, args ...string) error {
popupCmd, err := buildSelfCommand(args...)
if err != nil {
return err
}
_, err = tmux.RunCommand(socketPath, "display-popup", "-c", clientName, "-E", popupCmd)
return err
}