summaryrefslogtreecommitdiffstats
path: root/up.go
blob: d3f733a818f016a07bec6a249ba4fc91e71b9d39 (plain)
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
// Copyright 2018 The up Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// up is the Ultimate Plumber, a tool for writing Linux pipes in a
// terminal-based UI interactively, with instant live preview of command
// results.
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"sync"
	"unicode/utf8"

	"github.com/gdamore/tcell"
	"github.com/mattn/go-isatty"
)

func main() {
	// TODO: Without below block, we'd hang with no piped input (see github.com/peco/peco, mattn/gof, fzf, etc.)
	if isatty.IsTerminal(os.Stdin.Fd()) {
		fmt.Fprintln(os.Stderr, "error: up requires some data piped on standard input, e.g.: `echo hello world | up`")
		os.Exit(1)
	}

	// Init TUI code
	// TODO: maybe try gocui or tcell?
	tui, err := tcell.NewScreen()
	if err != nil {
		panic(err)
	}
	err = tui.Init()
	if err != nil {
		panic(err)
	}
	defer tui.Fini()

	var (
		editor      = NewEditor("| ")
		lastCommand = ""
		subprocess  *Subprocess
		inputBuf    = NewBuf()
		buf         = inputBuf
		bufView     = BufView{}
		bufY        = 1
	)
	const (
		xscroll = 8
	)

	// In background, start collecting input from stdin to internal buffer of size 40 MB, then pause it
	go inputBuf.Collect(os.Stdin, func() {
		tui.PostEvent(tcell.NewEventInterrupt(nil))
	})

	log.SetOutput(ioutil.Discard)
	if len(os.Args) > 1 && os.Args[1] == "--debug" {
		debug, err := os.Create("up.debug")
		if err != nil {
			panic(err)
		}
		log.SetOutput(debug)
	}

	// Main loop
main_loop:
	for {
		// Run command automatically in background if user edited it (and kill previous command)
		// TODO: allow stopping/restarting this behavior via Ctrl-Enter
		// TODO: allow stopping this behavior via Ctrl-C (and killing current command), but invent some nice way to quit then
		command := editor.String()
		if command != lastCommand {
			lastCommand = command
			subprocess.Kill()
			if command != "" {
				subprocess = StartSubprocess(inputBuf, command, func() {
					tui.PostEvent(tcell.NewEventInterrupt(nil))
				})
				buf = subprocess.Buf
			} else {
				// If command is empty, show original input data again (~ equivalent of typing `cat`)
				subprocess = nil
				buf = inputBuf
			}
		}

		// Draw command input line
		editor.Draw(tui, 0, 0, true)
		buf.Draw(tui, bufY, bufView)
		tui.Show()

		// Handle events
		switch ev := tui.PollEvent().(type) {
		case *tcell.EventKey:
			// handle command-line editing keys
			if editor.HandleKey(ev) {
				continue main_loop
			}
			// handle other keys
			switch (keymod{ev.Key(), ev.Modifiers()}) {
			case keymod{tcell.KeyCtrlC, 0},
				keymod{tcell.KeyCtrlC, tcell.ModCtrl}:
				// quit
				return
			case keymod{tcell.KeyCtrlX, 0},
				keymod{tcell.KeyCtrlX, tcell.ModCtrl}:
				// write script and quit
				writeScript(editor.String(), tui)
				return
			// TODO: move buf scroll handlers to Buf or BufView struct
			case keymod{tcell.KeyUp, 0}:
				bufView.Y--
				bufView.NormalizeY(buf.Lines())
			case keymod{tcell.KeyDown, 0}:
				bufView.Y++
				bufView.NormalizeY(buf.Lines())
			case keymod{tcell.KeyPgDn, 0}:
				// TODO: in top-right corner of Buf area, draw current line number & total # of lines
				_, h := tui.Size()
				bufView.Y += h - bufY - 1
				bufView.NormalizeY(buf.Lines())
			case keymod{tcell.KeyPgUp, 0}:
				_, h := tui.Size()
				bufView.Y -= h - bufY - 1
				bufView.NormalizeY(buf.Lines())
			case keymod{tcell.KeyLeft, tcell.ModAlt},
				keymod{tcell.KeyLeft, tcell.ModCtrl}:
				bufView.X -= xscroll
				if bufView.X < 0 {
					bufView.X = 0
				}
			case keymod{tcell.KeyRight, tcell.ModAlt},
				keymod{tcell.KeyRight, tcell.ModCtrl}:
				bufView.X += xscroll
			case keymod{tcell.KeyHome, tcell.ModAlt},
				keymod{tcell.KeyHome, tcell.ModCtrl}:
				bufView.X = 0
			}
		}
	}

	// TODO: properly handle fully consumed buffers, to enable piping into `wc -l` or `uniq -c` etc.
	// TODO: readme, asciinema
	// TODO: on github: add issues, incl. up-for-grabs / help-wanted
	// TODO: [LATER] make it work on Windows; maybe with mattn/go-shellwords ?
	// TODO: [LATER] Ctrl-O shows input via `less` or $PAGER
	// TODO: properly show all licenses of dependencies on --version
	// TODO: [LATER] allow increasing size of input buffer with some key
	// TODO: [LATER] on ^X, leave TUI and run the command through buffered input, then unpause rest of input
	// TODO: [LATER] allow adding more elements of pipeline (initially, just writing `foo | bar` should work)
	// TODO: [LATER] allow invocation with partial command, like: `up grep -i`
	// TODO: [LATER][MAYBE] allow reading upN.sh scripts
	// TODO: [LATER] auto-save and/or save on Ctrl-S or something
	// TODO: [MUCH LATER] readline-like rich editing support? and completion?
	// TODO: [MUCH LATER] integration with fzf? and pindexis/marker?
	// TODO: [LATER] forking and unforking pipelines
	// TODO: [LATER] capture output of a running process (see: https://stackoverflow.com/q/19584825/98528)
	// TODO: [LATER] richer TUI:
	// - show # of read lines & kbytes
	// - show status (errorlevel) of process, or that it's still running (also with background colors)
	// - allow copying and pasting to/from command line
	// TODO: [LATER] allow connecting external editor (become server/engine via e.g. socket)
	// TODO: [LATER] become pluggable into http://luna-lang.org
	// TODO: [LATER][MAYBE] allow "plugins" ("combos" - commands with default options) e.g. for Lua `lua -e`+auto-quote, etc.
	// TODO: [LATER] make it more friendly to infrequent Linux users by providing "descriptive" commands like "search" etc.
	// TODO: [LATER] advertise on: HN, r/programming, r/golang, r/commandline, r/linux, up-for-grabs.net; data exploration? data science?
}

type Buf struct {
	bytes []byte

	mu   sync.Mutex // guards the following fields
	cond *sync.Cond
	// NOTE: n and eof can be written only by Collect
	n   int
	eof bool
}

func NewBuf() *Buf {
	const bufsize = 40 * 1024 * 1024 // 40 MB
	buf := &Buf{bytes: make([]byte, bufsize)}
	buf.cond = sync.NewCond(&buf.mu)
	return buf
}

func (b *Buf) Collect(r io.Reader, signal func()) {
	// TODO: allow stopping - take context?
	for {
		n, err := r.Read(b.bytes[b.n:])
		b.mu.Lock()
		b.n += n
		if err == io.EOF {
			b.eof = true
		}
		b.cond.Broadcast()
		b.mu.Unlock()
		go signal()
		if err == io.EOF {
			return
		} else if err != nil {
			// TODO: better handling of errors
			panic(err)
		}
		if b.n == len(b.bytes) {
			return
		}
	}
}

func (b *Buf) Draw(tui tcell.Screen, y0 int, view BufView) {
	b.mu.Lock()
	buf := b.bytes[:b.n]
	b.mu.Unlock()

	// PgDn/PgUp etc. support
	for ; view.Y > 0; view.Y-- {
		newline := bytes.IndexByte(buf, '\n')
		if newline != -1 {
			buf = buf[newline+1:]
		}
	}

	w, h := tui.Size()
	putch := func(x, y int, ch rune) {
		if x <= view.X && view.X != 0 {
			x, ch = 0, '«'
		} else {
			x -= view.X
		}
		if x