~yerinalexey/rex

ref: 1ea118709ba9d4a13f7d82ccbc1ed9ce80953200 rex/main.go -rw-r--r-- 5.4 KiB
1ea11870Alexey Yerin Bump version to 2.0.1 5 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
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
// 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"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
	"time"

	"regexp"

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

const (
	VERSION = "2.0.1"
)

type Options struct {
	// Show help message
	help bool

	// Show version number
	version bool

	// Default value for regex input
	input string

	// Print matched lines on exit
	printOnExit bool
}

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

// splitLines splits lines by line feeds, removing \r
func splitLines(lines string) []string {
	newLines := []string{}

	for _, line := range strings.Split(lines, "\n") {
		// Here we strip \r that might come from files with CRLF,
		// which causes issues with matching $
		line = strings.TrimSuffix(line, "\r")

		newLines = append(newLines, line)
	}

	return newLines
}

// 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) {
	var timer *time.Timer

	for {
		expr := <-in

		if timer != nil {
			timer.Stop()
		}

		timer = time.AfterFunc(time.Millisecond, func() {
			rg, err := regexp.Compile(expr)
			if err != nil {
				// TODO: Notify about the error
				return
			}

			row, column := out.GetScrollOffset()

			out.Clear()

			lines := splitLines(tests)
			for _, line := range lines {
				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.ScrollTo(row, column)
		})
	}
}

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

	return data
}

func readFile(fname string) (string, error) {
	// TODO: This will block before file loads, should be in a separate
	// goroutine
	raw, err := ioutil.ReadFile(fname)

	return string(raw), err
}

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

		pflag.PrintDefaults()
	}

	opts := Options{}

	// TODO: More flags
	pflag.StringVarP(&opts.input, "input", "i", ".", "Default value for the input field")
	pflag.BoolVarP(&opts.printOnExit, "print", "p", false, "Print matching lines exit")
	pflag.BoolVarP(&opts.version, "version", "V", false, "Show version number")
	pflag.BoolVarP(&opts.help, "help", "h", false, "Show this message")
	pflag.Parse()

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

	if opts.version {
		fmt.Printf("rex %s\n", VERSION)
		return
	}

	file := pflag.Arg(0)

	var data string

	// Determine type of input
	if file == "" {
		data = readStdin()
	} else {
		var err error
		data, err = readFile(file)

		if err != nil {
			fatalf("Failed to read %s: %v\n", file, err)
		}
	}

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

	exprChan := make(chan string)

	app := tview.NewApplication()

	regexInput := tview.NewInputField().
		SetLabel("Regex: ").
		SetFieldBackgroundColor(tview.Styles.PrimitiveBackgroundColor).
		SetText(opts.input).
		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
	exprChan <- opts.input

	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()

			if opts.printOnExit {
				rg, err := regexp.Compile(regexInput.GetText())
				if err != nil {
					break
				}

				lines := splitLines(data)
				for _, line := range lines {
					matches := rg.MatchString(line)

					if matches {
						fmt.Println(line)
					}
				}
			}
		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)
	}
}