refactoring

This commit is contained in:
Timon Ringwald
2022-05-22 22:39:08 +02:00
parent a0487aa1fa
commit 0f6a7ce9ec
2 changed files with 75 additions and 22 deletions

22
main.go
View File

@ -14,6 +14,10 @@ import (
"github.com/fatih/color"
)
const (
DefaultOutput = "{0}"
)
var (
// regex with sub groups
input = flag.String("i", `^(.|\n)*?$`, "input pattern")
@ -36,7 +40,7 @@ var (
//
// The following number mutators (integers and floats) are allowed:
// + - * / ^ %
output = flag.String("o", "{0}", "output pattern")
output = flag.String("o", DefaultOutput, "output pattern")
// don't ignore lines which do not match against input.
// they will be copied without any changes
@ -60,19 +64,19 @@ func main() {
panic(err)
}
matchesWholeLine := strings.HasPrefix(*input, "^") && strings.HasSuffix(*input, "$")
reformatting := strings.HasPrefix(*input, "^") && strings.HasSuffix(*input, "$") && *output != DefaultOutput
if matchesWholeLine {
if reformatting {
escapedOutput := EscSeqReplacer.Replace(*output)
handleWholeLineRegex(pattern, escapedOutput)
reformatLine(pattern, escapedOutput)
} else {
handleInlineRegex(pattern)
colorCodeMatches(pattern)
}
}
// handleWholeLineRegex is using input pattern ot replace
// reformatLine is using input pattern to replace
// placeholders in output pattern with the given subgroups
func handleWholeLineRegex(pattern *regexp.Regexp, output string) {
func reformatLine(pattern *regexp.Regexp, output string) {
for line := range readLines(os.Stdin) {
matches := pattern.FindStringSubmatch(line)
if len(matches) == 0 {
@ -85,9 +89,9 @@ func handleWholeLineRegex(pattern *regexp.Regexp, output string) {
}
}
// handleInlineRegex is using input pattern
// colorCodeMatches is using input pattern
// and color-codes all matches within input
func handleInlineRegex(pattern *regexp.Regexp) {
func colorCodeMatches(pattern *regexp.Regexp) {
c := color.New(color.FgRed, color.Bold)
for line := range readLines(os.Stdin) {
matches := pattern.FindAllStringIndex(line, -1)