Skip to content

Commit

Permalink
Implementation of multiple matching expressions per line. Needs refac…
Browse files Browse the repository at this point in the history
…tor.
  • Loading branch information
Renan de Souza committed Apr 16, 2021
1 parent eeb926e commit 04d3b5e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
52 changes: 46 additions & 6 deletions logh.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,32 @@ func Highlight(in io.Reader, out io.Writer, matches ...string) {
// See if matches with any regexes
matched := false

// lineColors = make([]int, len(line))
// for i := range lineColors {
// lineColors[i] = -1
// }
// TODO refactor this new implementation
lineColors := make([]int, len(line))
for i := range lineColors {
lineColors[i] = -1
}

for i, rg := range regexes {
indexes := rg.FindAllStringIndex(line, -1)

for _, match := range indexes {
start, end := match[0], match[1]
fmt.Fprintf(out, "%s%s%s\n", line[:start], colors[i].Sprint(line[start:end]), line[end:])
for j := start; j < end; j++ {
lineColors[j] = i
}

matched = true
break
}

// for _, match := range indexes {
// start, end := match[0], match[1]
// fmt.Fprintf(out, "%s%s%s\n", line[:start], colors[i].Sprint(line[start:end]), line[end:])

// matched = true
// break
// }

// TODO: Add config to highlight the whole line?
// if rg.MatchString(line) {
// // Matches! Highlight and output
Expand All @@ -74,6 +85,35 @@ func Highlight(in io.Reader, out io.Writer, matches ...string) {
// }
}

if matched {
lastColorIdx := -1
newLine := ""
buff := ""
for i, ch := range line {
if lineColors[i] != lastColorIdx {
if lastColorIdx != -1 {
lastColor := colors[lastColorIdx]
newLine += lastColor.Sprint(buff)
} else {
newLine += buff
}
buff = ""

lastColorIdx = lineColors[i]
}
buff += string(ch)
}
if buff != "" {
if lastColorIdx != -1 {
lastColor := colors[lastColorIdx]
newLine += lastColor.Sprint(buff)
} else {
newLine += buff
}
}
fmt.Fprintf(out, "%s\n", newLine)
}

// No matches, print with default color
if !matched {
fmt.Fprintf(out, "%s\n", scanner.Text())
Expand Down
2 changes: 1 addition & 1 deletion logh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func TestLogHighlight(t *testing.T) {
want := "col1 col" + color.RedString("2") + " " + color.GreenString("col3") + "\n"

got := &bytes.Buffer{}
logh.Highlight(input, got, "2", "line3")
logh.Highlight(input, got, "2", "col3")
assertStringEqual(t, got.String(), want)
})
}
Expand Down

0 comments on commit 04d3b5e

Please sign in to comment.