~yerinalexey/rex

ref: 347d0080b5ba0e2470a9dbc20a3e3f588fb281de rex/main.go -rw-r--r-- 4.2 KiB
347d0080Garrit Franke Add support for STDIN 6 months ago
                                                                                
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
// rex - command line playground for regular expressions
// Copyright (C) 2021-present Alexey Yerin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"strings"

	"regexp"

	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
)

type Options struct {
	// Show help message
	help bool
}

func fatalf(format string, v ...interface{}) {
	fmt.Fprintf(os.Stderr, format, v...)
	os.Exit(1)
}

// regexWorker matches data from `in` to each line in `tests` and writes
// colored result to `out`
func regexWorker(in chan string, tests string, out *tview.TextView) {
	// TODO: Debounce input
	//
	// App might mess up if you type too fast
	for {
		expr := <-in

		rg, err := regexp.Compile(expr)
		if err != nil {
			// TODO: Notify about the error
			continue
		}

		out.Clear()

		// TODO: crlf?
		for _, line := range strings.Split(tests, "\n") {
			matches := rg.MatchString(line)

			color := "red"
			if matches {
				color = "green"
			}

			// tview.Escape prevents messing up text if line includes
			// [squarebrackets]
			fmt.Fprintf(out, "[%s]%s[white]\n", color, tview.Escape(line))
		}

		out.ScrollToBeginning()
	}
}

func fromStdin() string {
	var data string
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		data += scanner.Text()
		data += "\n"
	}

	return data
}

func fromFile(fname string) string {
	// TODO: This will block before file loads, should be in a separate
	// goroutine
	var data string

	if raw, err := ioutil.ReadFile(fname); err == nil {
		data = string(raw)
	} else {
		fatalf("Failed to read %s: %v\n", fname, err)
	}

	return data
}

func main() {
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: rex [flags] <file>")
		fmt.Fprintln(os.Stderr)
		fmt.Fprintln(os.Stderr, "Flags:")

		flag.PrintDefaults()
	}

	opts := Options{}

	// TODO: More flags
	flag.BoolVar(&opts.help, "help", false, "Show this message")
	flag.Parse()

	if opts.help {
		flag.Usage()
		return
	}

	file := flag.Arg(0)

	var data string

	// Determine type of input
	if file == "" {
		data = fromStdin()
	} else {
		data = fromFile(file)
	}

	if data == "" {
		flag.Usage()
		return
	}

	exprChan := make(chan string)

	app := tview.NewApplication()

	regexInput := tview.NewInputField().
		SetLabel("Regex: ").
		SetFieldBackgroundColor(tview.Styles.PrimitiveBackgroundColor).
		SetText(".").
		SetChangedFunc(func(text string) {
			exprChan <- text
		})

	matchesView := tview.NewTextView().
		SetRegions(true).
		SetDynamicColors(true).
		SetChangedFunc(func() {
			app.Draw()
		})

	go regexWorker(exprChan, data, matchesView)

	// Load initial expression
	// TODO: Do this in better way (maybe command line flag?)
	exprChan <- "."

	grid := tview.NewGrid().
		SetBorders(true).
		SetRows(1, 0).
		SetColumns(0).
		AddItem(regexInput, 0, 0, 1, 1, 0, 0, true).
		AddItem(matchesView, 1, 0, 1, 1, 0, 0, true)

	// Focusable elements
	elements := []tview.Primitive{regexInput, matchesView}

	app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		var move int

		switch ev := event.Key(); ev {
		case tcell.KeyEscape:
			app.Stop()

			fmt.Println(regexInput.GetText())
		case tcell.KeyTab:
			move = 1
		case tcell.KeyBacktab:
			move = -1
		default:
			return event
		}

		for i, el := range elements {
			if el.HasFocus() {
				newIndex := i + move

				// Move to the beginning if ran past the end and vise versa
				switch {
				case newIndex < 0:
					newIndex = len(elements)
				case newIndex == len(elements):
					newIndex = 0
				}

				app.SetFocus(elements[newIndex])

				return nil
			}
		}

		return event
	})

	if err := app.SetRoot(grid, true).Run(); err != nil {
		fatalf("%v\n", err)
	}
}