-
Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathclient.go
More file actions
233 lines (195 loc) · 5.21 KB
/
client.go
File metadata and controls
233 lines (195 loc) · 5.21 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
package main
import (
"bufio"
"fmt"
"io"
"log"
"net"
"os"
"slices"
"strings"
"sync"
"time"
"github.com/gdamore/tcell/v3"
"golang.org/x/term"
)
type State struct {
mutex sync.Mutex
data map[string]string
}
var gState State
func init() {
gState.data = make(map[string]string)
}
func run() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
if err != nil {
log.Fatalf("failed to open log file: %s", err)
}
defer f.Close()
log.SetOutput(f)
} else {
log.SetOutput(io.Discard)
}
log.Printf("*************** starting client, PID: %d ***************", gClientID)
var screen tcell.Screen
var err error
if screen, err = tcell.NewScreen(); err != nil {
log.Fatalf("creating screen: %s", err)
} else if err = screen.Init(); err != nil {
log.Fatalf("initializing screen: %s", err)
}
if gOpts.mouse {
screen.EnableMouse()
}
screen.EnablePaste()
ui := newUI(screen)
nav := newNav(ui)
app := newApp(ui, nav)
if err := nav.sync(); err != nil {
app.ui.echoerrf("sync: %s", err)
}
if err := app.readHistory(); err != nil {
app.ui.echoerrf("reading history file: %s", err)
}
app.loop()
app.ui.screen.Fini()
if gLastDirPath != "" {
writeLastDir(gLastDirPath, app.nav.currDir().path)
}
if gSelectionPath != "" && len(app.selectionOut) > 0 {
writeSelection(gSelectionPath, app.selectionOut)
}
if gPrintLastDir || gPrintSelection {
stdoutIsTerminal := term.IsTerminal(int(os.Stdout.Fd()))
if gPrintLastDir {
printPath("last-dir", app.nav.currDir().path, stdoutIsTerminal)
}
if gPrintSelection {
for _, file := range app.selectionOut {
printPath("selection", file, stdoutIsTerminal)
}
}
}
}
// printPath prints path for -print-last-dir / -print-selection. Newlines are
// rejected unconditionally (frame integrity for line-oriented consumers);
// control bytes are stripped only when stdout is a terminal.
func printPath(label, path string, stdoutIsTerminal bool) {
if strings.ContainsAny(path, "\n\r") {
log.Printf("%s: skipping path with newline: %q", label, path)
return
}
if stdoutIsTerminal {
path = sanitizeName(path)
}
fmt.Println(path)
}
func writeLastDir(filename, lastDir string) {
if strings.ContainsAny(lastDir, "\n\r") {
log.Printf("last-dir: path contains newline: %q", lastDir)
return
}
f, err := os.Create(filename)
if err != nil {
log.Printf("opening last dir file: %s", err)
return
}
defer f.Close()
_, err = f.WriteString(lastDir)
if err != nil {
log.Printf("writing last dir file: %s", err)
}
}
func writeSelection(filename string, selection []string) {
f, err := os.Create(filename)
if err != nil {
log.Printf("opening selection file: %s", err)
return
}
defer f.Close()
filtered := slices.DeleteFunc(slices.Clone(selection), func(s string) bool {
if strings.ContainsAny(s, "\n\r") {
log.Printf("selection: skipping path with newline: %q", s)
return true
}
return false
})
_, err = f.WriteString(strings.Join(filtered, "\n"))
if err != nil {
log.Printf("writing selection file: %s", err)
}
}
func readExpr() <-chan expr {
ch := make(chan expr)
go func() {
duration := 100 * time.Millisecond
c, err := net.Dial("unix", gSocketPath)
for err != nil {
log.Printf("connecting server: %s", err)
time.Sleep(duration)
duration *= 2
c, err = net.Dial("unix", gSocketPath)
}
if _, err := fmt.Fprintf(c, "conn %d\n", gClientID); err != nil {
log.Printf("registering with server: %s", err)
return
}
ch <- &callExpr{"sync", nil, 1}
ch <- &callExpr{"on-init", nil, 1}
s := bufio.NewScanner(c)
for s.Scan() {
log.Printf("recv: %s", s.Text())
// `query` has to be handled outside of the main thread, which is
// blocked when running a synchronous shell command ("$" or "!").
// This is important since `query` is often the result of the user
// running `$lf -remote "query $id <something>"`.
if word, rest := splitWord(s.Text()); word == "query" {
gState.mutex.Lock()
state := gState.data[rest]
gState.mutex.Unlock()
if _, err := fmt.Fprintln(c, state); err != nil {
log.Printf("sending response to server: %s", err)
return
}
} else {
p := newParser(strings.NewReader(s.Text()))
if p.parse() {
ch <- p.expr
}
}
}
if err := s.Err(); err != nil {
log.Printf("reading from server: %s", err)
}
c.Close()
}()
return ch
}
func remote(req string) (string, error) {
c, err := net.Dial("unix", gSocketPath)
if err != nil {
return "", fmt.Errorf("connecting to server: %w", err)
}
defer c.Close()
if _, err := fmt.Fprintln(c, req); err != nil {
return "", fmt.Errorf("sending command to server: %w", err)
}
// XXX: Standard net.Conn interface does not include a CloseWrite method
// but net.UnixConn and net.TCPConn implement it so the following should be
// safe as long as we do not use other types of connections. We need
// CloseWrite to notify the server that this is not a persistent connection
// and it should be closed after the response.
switch c := c.(type) {
case *net.TCPConn:
c.CloseWrite()
case *net.UnixConn:
c.CloseWrite()
}
resp, err := io.ReadAll(c)
if err != nil {
return "", fmt.Errorf("reading response from server: %w", err)
}
return string(resp), nil
}