196 lines
5.3 KiB
Go
196 lines
5.3 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"github.com/fatih/color"
|
|
)
|
|
|
|
var (
|
|
// regex with sub groups
|
|
input = flag.String("i", `^(.|\n)*?$`, "input pattern")
|
|
|
|
// format string with {0} as placeholders
|
|
// {0} always matches the whole line
|
|
// {1} and onwards match their respective sub groups
|
|
//
|
|
// You can optionally specify a printf-syntax for formatting like this: {1:%s} or {1:%02d}
|
|
// printf-syntax is currently supported for: strings, floats, integers.
|
|
//
|
|
// Addtionally mutators can be provided
|
|
// to further manipulate the value using the given syntax: {1:%d:+1}
|
|
//
|
|
// The value mutated by can also be a back reference to another group
|
|
// using round brackets like this: {1:%d:+(2)}}
|
|
//
|
|
// Multiple mutators can be used at once: {1:%d:+2*3-(2)}
|
|
// Be aware that they will be applied strictly from left to right!
|
|
//
|
|
// The following number mutators (integers and floats) are allowed:
|
|
// + - * / ^ %
|
|
output = flag.String("o", "{0}", "output pattern")
|
|
|
|
// don't ignore lines which do not match against input.
|
|
// they will be copied without any changes
|
|
keepUnmatched = flag.Bool("k", false, "keep unmatched lines")
|
|
|
|
// if the amount of lines in stdin are not divisible by lineParseAmount,
|
|
// the last lines will be ignored completely.
|
|
// it may be useful to have a boolean flag for this behavior
|
|
lineParseAmount = flag.Int("n", 1, "amount of lines to feed into input pattern")
|
|
|
|
replacePattern = regexp.MustCompile(`\{(\d+)(?::(.*?))?(?::(.*?))?(?::(.*?))?\}`)
|
|
|
|
numMutationPattern = regexp.MustCompile(`([+\-*/])(\d+|\((\d+)\))`)
|
|
)
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
|
|
pattern, err := regexp.Compile(*input)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
matchesWholeLine := strings.HasPrefix(*input, "^") && strings.HasSuffix(*input, "$")
|
|
|
|
if matchesWholeLine {
|
|
escapedOutput := EscSeqReplacer.Replace(*output)
|
|
handleWholeLineRegex(pattern, escapedOutput)
|
|
} else {
|
|
handleInlineRegex(pattern)
|
|
}
|
|
}
|
|
|
|
// handleWholeLineRegex is using input pattern ot replace
|
|
// placeholders in output pattern with the given subgroups
|
|
func handleWholeLineRegex(pattern *regexp.Regexp, output string) {
|
|
for line := range readLines(os.Stdin) {
|
|
matches := pattern.FindStringSubmatch(line)
|
|
if len(matches) == 0 {
|
|
if *keepUnmatched {
|
|
fmt.Println(line)
|
|
}
|
|
continue
|
|
}
|
|
fmt.Println(replaceVars(output, matches...))
|
|
}
|
|
}
|
|
|
|
// handleInlineRegex is using input pattern
|
|
// and color-codes all matches within input
|
|
func handleInlineRegex(pattern *regexp.Regexp) {
|
|
c := color.New(color.FgRed, color.Bold)
|
|
for line := range readLines(os.Stdin) {
|
|
matches := pattern.FindAllStringIndex(line, -1)
|
|
|
|
if len(matches) == 0 {
|
|
if *keepUnmatched {
|
|
fmt.Println(line)
|
|
}
|
|
continue
|
|
}
|
|
|
|
runes := []rune(line)
|
|
b := new(strings.Builder)
|
|
nextMatch := 0
|
|
currentIndex := 0
|
|
for currentRune := 0; currentRune < len(runes); currentRune++ {
|
|
if nextMatch >= len(matches) || currentIndex < matches[nextMatch][0] {
|
|
// handle next rune
|
|
b.WriteRune(runes[currentRune])
|
|
currentIndex += utf8.RuneLen(runes[currentRune])
|
|
} else {
|
|
// handle next match
|
|
match := line[matches[nextMatch][0]:matches[nextMatch][1]]
|
|
b.WriteString(c.Sprint(match))
|
|
currentIndex += len(match)
|
|
currentRune += utf8.RuneCountInString(match) - 1
|
|
nextMatch++
|
|
}
|
|
}
|
|
|
|
fmt.Println(b.String())
|
|
}
|
|
}
|
|
|
|
func readLines(r io.Reader) <-chan string {
|
|
ch := make(chan string, 10)
|
|
|
|
go func(out chan<- string, source io.Reader) {
|
|
defer close(out)
|
|
|
|
r := bufio.NewReader(source)
|
|
|
|
for {
|
|
var line string
|
|
var err error
|
|
lines := make([]string, 0, *lineParseAmount)
|
|
for line, err = r.ReadString('\n'); ; line, err = r.ReadString('\n') {
|
|
if rn, size := utf8.DecodeLastRuneInString(line); rn == '\n' {
|
|
line = line[:len(line)-size]
|
|
}
|
|
|
|
lines = append(lines, line)
|
|
|
|
// stop reading as soon as lineParseAmount is reached or an error occured (most likely EOF)
|
|
if len(lines) == cap(lines) || err != nil {
|
|
break
|
|
}
|
|
}
|
|
|
|
linesCombined := strings.Join(lines, "\n")
|
|
|
|
// use data as line if reading was successfull or EOF has been reached
|
|
// in the latter case: only use data if something could be read until EOF
|
|
if err == nil || err == io.EOF && linesCombined != "" {
|
|
out <- linesCombined
|
|
}
|
|
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|
|
}(ch, r)
|
|
|
|
return ch
|
|
}
|
|
|
|
func replaceVars(format string, vars ...string) string {
|
|
replacements := replacePattern.FindAllStringSubmatch(format, -1)
|
|
|
|
for _, replacement := range replacements {
|
|
rplStr := replacement[0]
|
|
varIndex, _ := strconv.Atoi(replacement[1])
|
|
rplColor := makeColor(replacement[2])
|
|
rplFmt := replacement[3]
|
|
|
|
// default format if not specified by user
|
|
if rplFmt == "" {
|
|
rplFmt = "%s"
|
|
}
|
|
|
|
if strings.HasSuffix(rplFmt, "d") { // replace integers
|
|
value, _ := strconv.ParseInt(vars[varIndex], 10, 64)
|
|
mutate := numMut2func[int64](replacement[4])
|
|
format = strings.Replace(format, rplStr, rplColor.Sprintf(rplFmt, mutate(value, vars)), 1)
|
|
} else if strings.HasSuffix(rplFmt, "f") || strings.HasSuffix(rplFmt, "g") { // replace floats
|
|
value, _ := strconv.ParseFloat(vars[varIndex], 64)
|
|
mutate := numMut2func[float64](replacement[4])
|
|
format = strings.Replace(format, rplStr, rplColor.Sprintf(rplFmt, mutate(value, vars)), 1)
|
|
} else { // replace strings
|
|
format = strings.Replace(format, rplStr, rplColor.Sprintf(rplFmt, vars[varIndex]), 1)
|
|
}
|
|
}
|
|
|
|
return format
|
|
}
|