Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
187 lines (167 loc) · 6.56 KB
/
Copy pathmain.go
File metadata and controls
187 lines (167 loc) · 6.56 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
// Command termdevtools is a terminal-mode Elasticsearch client, inspired by
// Kibana's DevTools view. See SPEC.md for the detail of design choices.
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"runtime/debug"
"syscall"
"time"
"github.com/rivo/tview"
"github.com/gnocent/termdevtools/config"
"github.com/gnocent/termdevtools/i18n"
"github.com/gnocent/termdevtools/refdata"
"github.com/gnocent/termdevtools/ui"
)
// version identifies the build. Release binaries and the install scripts
// stamp it (-ldflags "-X main.version=..."); otherwise buildVersion falls
// back on what Go recorded in the binary.
var version = "dev"
// buildVersion is what --version prints: the stamped version if there is
// one, else the main module's version from the build info — the one asked
// for by "go install github.com/gnocent/termdevtools@v0.7.2", or derived
// from git by a plain "go build" in a checkout — else "dev".
func buildVersion() string {
if version != "dev" {
return version
}
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" && info.Main.Version != "(devel)" {
return info.Main.Version
}
return version
}
func main() {
// Before anything is read or created: asking a binary what it is must
// work on a machine where it has never run.
for _, arg := range os.Args[1:] {
if arg == "--version" || arg == "-version" {
fmt.Println("termdevtools " + buildVersion())
return
}
}
cfg, err := config.Load()
if err != nil {
// cfg (and so cfg.Language) isn't available yet at this point —
// i18n.For("") gives the interface's default language, English.
fmt.Fprintf(os.Stderr, i18n.For("").ErrConfigLoadFmt+"\n", err)
os.Exit(1)
}
msgs := i18n.For(cfg.Language)
exportDir := flag.String("export-defaults", "", msgs.UsageExportDefaults)
flag.Bool("version", false, msgs.UsageVersion) // handled above; declared for the usage text
flag.Parse()
exeDir, err := config.ExecutableDir()
if err != nil {
fmt.Fprintf(os.Stderr, msgs.ErrExecDirFmt+"\n", err)
os.Exit(1)
}
// Where the user's reference files are read from, and where exports and
// crash reports are written. The error is not checked again: config.Load
// above resolves the same directory and has already failed without it.
userDir, _ := config.ConfigDir()
reference := refdata.Sources{TeamDir: exeDir, UserDir: userDir}
if *exportDir != "" {
// Exported where reference files are read from, the built-in recipes
// would all come back as the user's own: frozen copies, hiding the
// corrections of every later version.
if reference.Reads(*exportDir) {
fmt.Fprintf(os.Stderr, msgs.ErrExportIntoSourceFmt+"\n", *exportDir)
os.Exit(1)
}
written, err := refdata.ExportDefaults(*exportDir)
if err != nil {
fmt.Fprintf(os.Stderr, msgs.ErrExportDefaultsFmt+"\n", err)
os.Exit(1)
}
fmt.Printf(msgs.InfoExportedDefaultsFmt+"\n", len(written), *exportDir)
return
}
// Best-effort, like the other self-documenting files (config.yaml,
// variables): without it the user's recipes simply have no template.
_ = refdata.CreateUserTemplate(userDir)
paths := buildPaths(exeDir, userDir, reference)
ui.Version = buildVersion()
tapp := tview.NewApplication()
defer recoverCrash(tapp, userDir, msgs)
// The connection screen, then one screen per cluster connected to, and
// the keyboard shortcuts of all of them — Ctrl+C included, from the
// connection screen on.
sessions := ui.NewSessions(tapp, cfg, paths)
// Best-effort save of the left panels in addition to explicit Ctrl+S
// (SPEC.md §3.2): Ctrl+C is already covered by the sessions' own
// shortcuts (it's just a control byte read by the terminal in raw mode,
// not an OS signal). SIGTERM/SIGHUP cover external shutdowns (kill, a
// dropped SSH session) — SIGKILL, as with any program, remains impossible
// to intercept.
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM, syscall.SIGHUP)
go func() {
<-sig
sessions.SaveOnSignal()
tapp.Stop()
}()
tapp.SetRoot(sessions.Root(), true).EnableMouse(cfg.Mouse)
if err := tapp.Run(); err != nil {
fmt.Fprintf(os.Stderr, msgs.ErrFatalFmt+"\n", err)
os.Exit(1)
}
}
// buildPaths resolves the files the interface reads and writes (SPEC.md
// §9.1). exeDir, the binary's directory, only supplies what an installation
// shares and is read; what the program writes — exports — goes to userDir,
// the user's own configuration directory: in a shared or read-only
// installation the binary's directory can't be written to.
func buildPaths(exeDir, userDir string, reference refdata.Sources) ui.Paths {
return ui.Paths{
Cheatsheet: filepath.Join(exeDir, ui.CheatsheetFileName),
Starter: refdata.Starter(),
Exports: filepath.Join(userDir, ui.ExportsDirName),
Reference: reference,
}
}
// recoverCrash catches a panic in the main goroutine — where
// tview.Application.Run processes events — and writes it, with a full stack
// trace, to a timestamped file in dir, the user's configuration directory:
// the only way to get a real diagnosis for a crash nobody watching can
// reproduce or transcribe by hand. Best-effort only: a panic inside tcell's
// own separate input-reading goroutine, rather than in the application code
// Run() itself processes, would not be caught here — Go's recover only
// catches panics in the same goroutine as the deferred call.
func recoverCrash(tapp *tview.Application, dir string, msgs *i18n.Strings) {
r := recover()
if r == nil {
return
}
// Best-effort attempt to restore the terminal before printing anything —
// guarded so a second panic here (screen state may already be broken)
// doesn't hide the original crash report below.
func() {
defer func() { _ = recover() }()
tapp.Stop()
}()
report := fmt.Sprintf("%v\n\n%s", r, debug.Stack())
fmt.Fprintf(os.Stderr, msgs.ErrCrashedFmt+"\n", r)
if path, err := writeCrashReport(dir, report, time.Now()); err != nil {
fmt.Fprintf(os.Stderr, msgs.ErrCrashReportWriteFailedFmt+"\n", err)
fmt.Fprint(os.Stderr, report)
} else {
fmt.Fprintf(os.Stderr, msgs.InfoCrashReportFmt+"\n", path)
}
os.Exit(1)
}
// writeCrashReport writes report to a timestamped file in dir — created if
// needed: nothing guarantees it still exists by the time a crash happens —
// and returns the path of that file.
func writeCrashReport(dir, report string, now time.Time) (string, error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
path := filepath.Join(dir, fmt.Sprintf("crash-%s.log", now.Format("20060102-150405")))
if err := os.WriteFile(path, []byte(report), 0o600); err != nil {
return "", err
}
return path, nil
}