Debian Codegraph @

client.go

raw
1 package main
2
3 import (
4 "bufio"
5 "fmt"
6 "io"
7 "log"
8 "net"
9 "os"
10 "slices"
11 "strings"
12 "sync"
13 "time"
14
15 "github.com/gdamore/tcell/v3"
16 "golang.org/x/term"
17 )
18
19 type State struct {
20 mutex sync.Mutex
21 data map[string]string
22 }
23
24 var gState State
25
26 func init() {
27 gState.data = make(map[string]string)
28 }
29
30 func run() {
31 if gLogPath != "" {
32 f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
33 if err != nil {
34 log.Fatalf("failed to open log file: %s", err)
35 }
36 defer f.Close()
37 log.SetOutput(f)
38 } else {
39 log.SetOutput(io.Discard)
40 }
41
42 log.Printf("*************** starting client, PID: %d ***************", gClientID)
43
44 var screen tcell.Screen
45 var err error
46 if screen, err = tcell.NewScreen(); err != nil {
47 log.Fatalf("creating screen: %s", err)
48 } else if err = screen.Init(); err != nil {
49 log.Fatalf("initializing screen: %s", err)
50 }
51 if gOpts.mouse {
52 screen.EnableMouse()
53 }
54 screen.EnablePaste()
55
56 ui := newUI(screen)
57 nav := newNav(ui)
58 app := newApp(ui, nav)
59
60 if err := nav.sync(); err != nil {
61 app.ui.echoerrf("sync: %s", err)
62 }
63
64 if err := app.readHistory(); err != nil {
65 app.ui.echoerrf("reading history file: %s", err)
66 }
67
68 app.loop()
69
70 app.ui.screen.Fini()
71
72 if gLastDirPath != "" {
73 writeLastDir(gLastDirPath, app.nav.currDir().path)
74 }
75
76 if gSelectionPath != "" && len(app.selectionOut) > 0 {
77 writeSelection(gSelectionPath, app.selectionOut)
78 }
79
80 if gPrintLastDir || gPrintSelection {
81 stdoutIsTerminal := term.IsTerminal(int(os.Stdout.Fd()))
82
83 if gPrintLastDir {
84 printPath("last-dir", app.nav.currDir().path, stdoutIsTerminal)
85 }
86
87 if gPrintSelection {
88 for _, file := range app.selectionOut {
89 printPath("selection", file, stdoutIsTerminal)
90 }
91 }
92 }
93 }
94
95 // printPath prints path for -print-last-dir / -print-selection. Newlines are
96 // rejected unconditionally (frame integrity for line-oriented consumers);
97 // control bytes are stripped only when stdout is a terminal.
98 func printPath(label, path string, stdoutIsTerminal bool) {
99 if strings.ContainsAny(path, "\n\r") {
100 log.Printf("%s: skipping path with newline: %q", label, path)
101 return
102 }
103 if stdoutIsTerminal {
104 path = sanitizeName(path)
105 }
106 fmt.Println(path)
107 }
108
109 func writeLastDir(filename, lastDir string) {
110 if strings.ContainsAny(lastDir, "\n\r") {
111 log.Printf("last-dir: path contains newline: %q", lastDir)
112 return
113 }
114 f, err := os.Create(filename)
115 if err != nil {
116 log.Printf("opening last dir file: %s", err)
117 return
118 }
119 defer f.Close()
120
121 _, err = f.WriteString(lastDir)
122 if err != nil {
123 log.Printf("writing last dir file: %s", err)
124 }
125 }
126
127 func writeSelection(filename string, selection []string) {
128 f, err := os.Create(filename)
129 if err != nil {
130 log.Printf("opening selection file: %s", err)
131 return
132 }
133 defer f.Close()
134
135 filtered := slices.DeleteFunc(slices.Clone(selection), func(s string) bool {
136 if strings.ContainsAny(s, "\n\r") {
137 log.Printf("selection: skipping path with newline: %q", s)
138 return true
139 }
140 return false
141 })
142 _, err = f.WriteString(strings.Join(filtered, "\n"))
143 if err != nil {
144 log.Printf("writing selection file: %s", err)
145 }
146 }
147
148 func readExpr() <-chan expr {
149 ch := make(chan expr)
150
151 go func() {
152 duration := 100 * time.Millisecond
153
154 c, err := net.Dial("unix", gSocketPath)
155 for err != nil {
156 log.Printf("connecting server: %s", err)
157 time.Sleep(duration)
158 duration *= 2
159 c, err = net.Dial("unix", gSocketPath)
160 }
161
162 if _, err := fmt.Fprintf(c, "conn %d\n", gClientID); err != nil {
163 log.Printf("registering with server: %s", err)
164 return
165 }
166
167 ch <- &callExpr{"sync", nil, 1}
168 ch <- &callExpr{"on-init", nil, 1}
169
170 s := bufio.NewScanner(c)
171 for s.Scan() {
172 log.Printf("recv: %s", s.Text())
173
174 // `query` has to be handled outside of the main thread, which is
175 // blocked when running a synchronous shell command ("$" or "!").
176 // This is important since `query` is often the result of the user
177 // running `$lf -remote "query $id <something>"`.
178 if word, rest := splitWord(s.Text()); word == "query" {
179 gState.mutex.Lock()
180 state := gState.data[rest]
181 gState.mutex.Unlock()
182 if _, err := fmt.Fprintln(c, state); err != nil {
183 log.Printf("sending response to server: %s", err)
184 return
185 }
186 } else {
187 p := newParser(strings.NewReader(s.Text()))
188 if p.parse() {
189 ch <- p.expr
190 }
191 }
192 }
193
194 if err := s.Err(); err != nil {
195 log.Printf("reading from server: %s", err)
196 }
197
198 c.Close()
199 }()
200
201 return ch
202 }
203
204 func remote(req string) (string, error) {
205 c, err := net.Dial("unix", gSocketPath)
206 if err != nil {
207 return "", fmt.Errorf("connecting to server: %w", err)
208 }
209 defer c.Close()
210
211 if _, err := fmt.Fprintln(c, req); err != nil {
212 return "", fmt.Errorf("sending command to server: %w", err)
213 }
214
215 // XXX: Standard net.Conn interface does not include a CloseWrite method
216 // but net.UnixConn and net.TCPConn implement it so the following should be
217 // safe as long as we do not use other types of connections. We need
218 // CloseWrite to notify the server that this is not a persistent connection
219 // and it should be closed after the response.
220 switch c := c.(type) {
221 case *net.TCPConn:
222 c.CloseWrite()
223 case *net.UnixConn:
224 c.CloseWrite()
225 }
226
227 resp, err := io.ReadAll(c)
228 if err != nil {
229 return "", fmt.Errorf("reading response from server: %w", err)
230 }
231
232 return string(resp), nil
233 }