-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
553 lines (485 loc) · 13.8 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
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
546
547
548
549
550
551
552
553
package main
import (
"bufio"
"bytes"
"encoding/base64"
"fmt"
"io"
"log"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"time"
"github.com/gdamore/tcell/v2"
"github.com/mattn/go-isatty"
"runtime/debug"
"github.com/spf13/cobra"
)
const (
ESC = '\x1b'
BEL = '\a'
BS = '\\'
OSC = string(ESC) + "]52;"
DCS_OPEN = string(ESC) + "P"
DCS_CLOSE = string(ESC) + string(BS)
CLIPBOARD_REGEX = `^[cpqs0-7]*$`
)
var (
oscOpen string
oscClose string
isScreen bool
isTmux bool
isZellij bool
verboseFlag bool
logfileFlag string
deviceFlag string
clipboardFlag string
timeoutFlag float64
debugLog *log.Logger
errorLog *log.Logger
)
type debugWriter struct {
prefix string
w io.Writer
}
func (dw *debugWriter) Write(p []byte) (int, error) {
n, err := dw.w.Write(p)
debugLog.Printf("%s: %v %v %q", dw.prefix, n, err, p[:n])
return n, err
}
type debugReader struct {
prefix string
r io.Reader
}
func (dr *debugReader) Read(p []byte) (int, error) {
n, err := dr.r.Read(p)
debugLog.Printf("%s: %v %v %q", dr.prefix, n, err, p[:n])
return n, err
}
func closetty(tty tcell.Tty) {
_ = tty.Drain()
_ = tty.Stop()
tty.Close()
}
// log levels to handle:
// debug
// error
// discarding logger: myLogger = log.New(io.Discard, "", 0)
// printing methods:
// Print: multiple args, adds space between non-string arguments
// Printf: first arg format, rest args
// Println multiple args, always adds space between args and a newline
// all print functions add a new line if absent
// File io.Writer is 'safe for concurrent use'
// Lmsgefix // move the "prefix" from the beginning of the line to before the message
func initLogging() (*os.File, error) {
var (
err error
logfile *os.File
)
logOutput := os.Stdout
if logfileFlag != "" {
if logOutput, err = os.OpenFile(logfileFlag, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0644); err != nil {
return nil, fmt.Errorf("Failed to open file %v: %v", logfileFlag, err)
} else {
logfile = logOutput
}
}
log.SetOutput(logOutput)
errorLog = log.New(logOutput, "ERROR ", log.LstdFlags|log.Lmsgprefix)
if verboseFlag {
debugLog = log.New(logOutput, "DEBUG ", log.LstdFlags|log.Lmsgprefix)
} else {
debugLog = log.New(io.Discard, "", 0)
}
debugLog.Println("logging started")
return logfile, nil
}
func identifyTerm() error {
if os.Getenv("ZELLIJ") != "" {
isZellij = true
}
if os.Getenv("TMUX") != "" {
isTmux = true
} else if ti, err := tcell.LookupTerminfo(os.Getenv("TERM")); err != nil {
if runtime.GOOS != "windows" {
return fmt.Errorf("Failed to lookup terminfo: %w", err)
} else {
debugLog.Println("On Windows, failed to lookup terminfo:", err)
}
} else {
debugLog.Printf("term name: %s, aliases: %q", ti.Name, ti.Aliases)
if strings.HasPrefix(ti.Name, "screen") {
isScreen = true
}
}
oscOpen = OSC + clipboardFlag + ";"
oscClose = string(ESC) + string(BS)
if isScreen {
debugLog.Println("Setting screen dcs passthrough")
oscOpen = DCS_OPEN + oscOpen
oscClose = oscClose + DCS_CLOSE
} else if isTmux {
debugLog.Println("Setting tmux dcs passthrough")
oscOpen = DCS_OPEN + "tmux;" + string(ESC) + oscOpen
oscClose = oscClose + DCS_CLOSE
}
return nil
}
// Inserts screen dcs end + start sequence into long sequences
// Based on: https://github.com/chromium/hterm/blob/6846a85f9579a8dfdef4405cc50d9fb17d8944aa/etc/osc52.sh#L23
const chunkSize = 76
type chunkingWriter struct {
bytesWritten int64
writer io.Writer
}
func (w *chunkingWriter) Write(p []byte) (n int, err error) {
debugLog.Println("chunkingWriter got", len(p), "bytes")
for err == nil && len(p) > 0 {
bytesWritten := 0
chunksWritten := w.bytesWritten / chunkSize
nextChunkBoundary := (chunksWritten + 1) * chunkSize
if w.bytesWritten+int64(len(p)) < nextChunkBoundary {
bytesWritten, err = w.writer.Write(p)
} else {
bytesWritten, err = w.writer.Write(p[:nextChunkBoundary-w.bytesWritten])
if err == nil {
_, err = w.writer.Write([]byte(DCS_CLOSE + DCS_OPEN))
}
}
w.bytesWritten += int64(bytesWritten)
n += bytesWritten
p = p[bytesWritten:]
}
return
}
func copy(fnames []string) error {
// copy
if isTmux {
if out, err := exec.Command("tmux", "show", "-v", "allow-passthrough").Output(); err != nil {
return fmt.Errorf("Error running 'tmux show -v allow-passthrough': %w", err)
} else {
outStr := strings.TrimSpace(string(out))
debugLog.Println("'tmux show -v allow-passthrough':", outStr)
if outStr != "on" && outStr != "all" {
return fmt.Errorf("tmux allow-passthrough must be set to 'on' or 'all'")
}
}
}
var data []byte
if len(fnames) == 0 {
if isatty.IsTerminal(os.Stdin.Fd()) || isatty.IsCygwinTerminal(os.Stdin.Fd()) {
return fmt.Errorf("Nothing on stdin")
}
var err error
if data, err = io.ReadAll(os.Stdin); err != nil {
return fmt.Errorf("Error reading stdin: %w", err)
} else {
debugLog.Printf("Read %d bytes from stdin", len(data))
}
} else {
var dataBuff bytes.Buffer
for _, fname := range fnames {
if f, err := os.Open(fname); err != nil {
return fmt.Errorf("Error opening file %s: %w", fname, err)
} else if n, err := io.Copy(&dataBuff, f); err != nil {
return fmt.Errorf("Error reading file %s: %w", fname, err)
} else if err := f.Close(); err != nil {
return fmt.Errorf("Error closing file %s: %w", fname, err)
} else {
debugLog.Printf("Read %d bytes from %s", n, fname)
}
}
data = dataBuff.Bytes()
}
debugLog.Println("Beginning osc52 copy operation")
tty, err := opentty()
if err != nil {
return fmt.Errorf("Error opening tty: %w", err)
}
defer closetty(tty)
// Open buffered output
var ttyWriter *bufio.Writer
if verboseFlag {
ttyWriter = bufio.NewWriter(&debugWriter{
prefix: "tty write",
w: tty,
})
} else {
ttyWriter = bufio.NewWriter(tty)
}
// Start OSC52
if _, err := fmt.Fprint(ttyWriter, oscOpen); err != nil {
return fmt.Errorf("Error writing osc open: %w", err)
}
var b64 io.WriteCloser
if !isScreen {
b64 = base64.NewEncoder(base64.StdEncoding, ttyWriter)
} else {
b64 = base64.NewEncoder(base64.StdEncoding, &chunkingWriter{writer: ttyWriter})
}
if _, err := b64.Write(data); err != nil {
return fmt.Errorf("Error writing data: %w", err)
}
if err := b64.Close(); err != nil {
return fmt.Errorf("Error closing encoder: %w", err)
}
// End OSC52
if _, err := fmt.Fprint(ttyWriter, oscClose); err != nil {
return fmt.Errorf("Error writing osc close: %w", err)
}
if err := ttyWriter.Flush(); err != nil {
return fmt.Errorf("Error flushing bufio: %w", err)
}
return nil
}
func tmux_paste() error {
if out, err := exec.Command("tmux", "show", "-v", "set-clipboard").Output(); err != nil {
return fmt.Errorf("Error running 'tmux show -v set-clipboard': %w", err)
} else {
outStr := strings.TrimSpace(string(out))
debugLog.Println("'tmux show -v set-clipboard':", outStr)
if outStr != "on" && outStr != "external" {
return fmt.Errorf("tmux set-clipboard must be set to 'on' or 'external'")
}
}
// refresh client list
if out, err := exec.Command("tmux", "refresh-client", "-l").Output(); err != nil {
return fmt.Errorf("Error running 'tmux refresh-client -l': %v", err)
} else {
debugLog.Println("tmux refresh-client output:", string(out))
}
// give terminal time to sync
// https://github.com/rumpelsepp/oscclip/blob/6a4847ed5497baa9a9357b389f492f5d52c6867c/oscclip/__init__.py#L73
time.Sleep(50 * time.Millisecond)
if out, err := exec.Command("tmux", "save-buffer", "-").Output(); err != nil {
return fmt.Errorf("error running 'tmux save-buffer -': %v", err)
} else if _, err := os.Stdout.Write(out); err != nil {
errorLog.Println("Error writing to stdout:", err)
return err
}
return nil
}
// wraps an io.Reader, reads until it encounters an ESC or BEL
type pasteReader struct {
r io.Reader
}
func (pr *pasteReader) Read(p []byte) (int, error) {
n, err := pr.r.Read(p)
if i := bytes.IndexByte(p, BEL); i >= 0 {
return i, io.EOF
}
if i := bytes.IndexByte(p, ESC); i >= 0 {
if i+1 == n {
// closing sequence is ESC+BS
// read and discard one more byte
b := make([]byte, 1)
if _, err = pr.r.Read(b); err != nil {
return i, err
}
}
return i, io.EOF
}
return n, err
}
func paste() error {
if isTmux {
return tmux_paste()
} else if isZellij {
return fmt.Errorf("paste unsupported under zellij, unset ZELLIJ env var to force")
}
timeout := time.Duration(timeoutFlag*1_000_000_000) * time.Nanosecond
debugLog.Println("Beginning osc52 paste operation, timeout:", timeout)
if data, err := func() ([]byte, error) {
tty, err := opentty()
if err != nil {
return nil, fmt.Errorf("Error opening tty: %w", err)
}
defer closetty(tty)
var ttyWriter io.Writer
if verboseFlag {
ttyWriter = &debugWriter{
prefix: "tty write",
w: tty,
}
} else {
ttyWriter = tty
}
// Start OSC52
if _, err := fmt.Fprint(ttyWriter, oscOpen+"?"+oscClose); err != nil {
return nil, fmt.Errorf("Error writing osc open: %w", err)
}
var ttyReader *bufio.Reader
if verboseFlag {
ttyReader = bufio.NewReader(&debugReader{
prefix: "tty read",
r: tty,
})
} else {
ttyReader = bufio.NewReader(tty)
}
// Define a struct to hold the read bytes and any error
type readResult struct {
data []byte
err error
}
// Time out initial read
readChan := make(chan readResult, 1)
go func() {
b, e := ttyReader.ReadSlice(';')
readChan <- readResult{data: b, err: e}
close(readChan)
}()
select {
case res := <-readChan:
if res.err != nil {
return nil, fmt.Errorf("Initial ReadSlice error: %w", res.err)
} else if !bytes.Equal(res.data, []byte(OSC)) {
return nil, fmt.Errorf("osc header mismatch: %q", res.data)
}
case <-time.After(timeout):
return nil, fmt.Errorf("tty read timeout")
}
// ignore clipboard info
if _, e := ttyReader.ReadSlice(';'); e != nil {
return nil, fmt.Errorf("Clipboard metadata ReadSlice error: %w", e)
}
pr := pasteReader{r: ttyReader}
decoder := base64.NewDecoder(base64.StdEncoding, &pr)
if data, err := io.ReadAll(decoder); err != nil {
return nil, fmt.Errorf("Error reading from decoder: %w", err)
} else {
return data, nil
}
}(); err != nil {
return err
} else if _, err := os.Stdout.Write(data); err != nil {
return fmt.Errorf("Error writing to stdout: %w", err)
}
debugLog.Println("Ended osc52")
return nil
}
func closeSilently(f *os.File) {
if f != nil {
f.Close()
}
}
var copyCmd = &cobra.Command{
Use: "copy",
Short: "Copies input to the system clipboard",
Long: `Copies input to the system clipboard. Usage:
osc copy [file1 [...fileN]]
With no arguments, will read from stdin.`,
RunE: func(cmd *cobra.Command, args []string) error {
if matched, err := regexp.MatchString(CLIPBOARD_REGEX, clipboardFlag); err != nil {
return fmt.Errorf("Invalid clipboard flag: %w", err)
} else if !matched {
return fmt.Errorf("Invalid clipboard flag: %s", clipboardFlag)
}
rc := func() int {
if logfile, err := initLogging(); err != nil {
errorLog.Println(err)
fmt.Println(err)
return 1
} else {
defer closeSilently(logfile)
}
if err := identifyTerm(); err != nil {
errorLog.Println(err)
fmt.Println(err)
return 1
}
if err := copy(args); err != nil {
errorLog.Println(err)
fmt.Println(err)
return 1
}
return 0
}()
os.Exit(rc)
return nil
},
}
var pasteCmd = &cobra.Command{
Use: "paste",
Short: "Outputs system clipboard contents to stdout",
Long: `Outputs system clipboard contents to stdout. Usage:
osc paste`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
if matched, err := regexp.MatchString(CLIPBOARD_REGEX, clipboardFlag); err != nil {
return fmt.Errorf("Invalid clipboard flag: %w", err)
} else if !matched {
return fmt.Errorf("Invalid clipboard flag: %s", clipboardFlag)
}
rc := func() int {
if logfile, err := initLogging(); err != nil {
errorLog.Println(err)
fmt.Println(err)
return 1
} else {
defer closeSilently(logfile)
}
if err := identifyTerm(); err != nil {
errorLog.Println(err)
fmt.Println(err)
return 1
}
if err := paste(); err != nil {
errorLog.Println(err)
fmt.Println(err)
return 1
}
return 0
}()
os.Exit(rc)
return nil
},
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Outputs version information",
Long: `Outputs version information`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
if info, ok := debug.ReadBuildInfo(); !ok {
fmt.Println(`Unable to obtain build info.`)
} else {
fmt.Println(info.Main.Version)
}
},
}
var rootCmd = &cobra.Command{
Use: "osc",
Short: "Reads or writes the system clipboard using the ANSI OSC52 escape sequence",
Long: `Reads or writes the system clipboard using the ANSI OSC52 escape sequence.`,
}
func ttyDevice() string {
if deviceFlag != "" {
return deviceFlag
} else if isScreen {
return "/dev/tty"
} else if sshtty := os.Getenv("SSH_TTY"); sshtty != "" {
return sshtty
} else {
return "/dev/tty"
}
}
func init() {
rootCmd.PersistentFlags().BoolVarP(&verboseFlag, "verbose", "v", false, "verbose logging")
rootCmd.PersistentFlags().StringVarP(&logfileFlag, "log", "l", "", "write logs to file")
rootCmd.PersistentFlags().StringVarP(&deviceFlag, "device", "d", "", "use specific tty device")
rootCmd.PersistentFlags().Float64VarP(&timeoutFlag, "timeout", "t", 5, "tty read timeout in seconds")
rootCmd.PersistentFlags().StringVarP(&clipboardFlag, "clipboard", "c", "c", "target clipboard, can be empty or one or more of c, p, q, s, or 0-7")
rootCmd.AddCommand(copyCmd)
rootCmd.AddCommand(pasteCmd)
rootCmd.AddCommand(versionCmd)
}
func main() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}