~yerinalexey/rex

347d0080b5ba0e2470a9dbc20a3e3f588fb281de — Garrit Franke 5 months ago 68ec365
Add support for STDIN

This adds the ability to read from stdin, as opposed to reading a file.
A simple example would be the following:

printf "foo\nbar\n" | rex

If text is piped from stdin *and* from a file, the file will be
prioritized:

printf "foo\nbar\n" | rex test.txt
2 files changed, 37 insertions(+), 10 deletions(-)

M README.md
M main.go
M README.md => README.md +2 -1
@@ 21,7 21,8 @@ $ rex [flags] FILE
```

Rex reads `FILE` where each line is a test match (multi-line regexes are
not supported). Lines should be separated by line feeds (`\n`).
not supported). If not specified, the input is read from STDIN. Lines
should be separated by line feeds (`\n`).

In the interface you are presented with a regex input field and a list
of test data highlighted accordingly to them matching a regex.

M main.go => main.go +35 -9
@@ 17,6 17,7 @@
package main

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


@@ 74,6 75,31 @@ func regexWorker(in chan string, tests string, out *tview.TextView) {
	}
}

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


@@ 95,19 121,19 @@ func main() {
	}

	file := flag.Arg(0)
	if file == "" {
		flag.Usage()
		return
	}

	// TODO: This will block before file loads, should be in a separate
	// goroutine
	var data string

	if raw, err := ioutil.ReadFile(file); err == nil {
		data = string(raw)
	// Determine type of input
	if file == "" {
		data = fromStdin()
	} else {
		fatalf("Failed to read %s: %v\n", file, err)
		data = fromFile(file)
	}

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

	exprChan := make(chan string)