Skip to content

Commit

Permalink
Merge pull request #23 from catatsuy/feature_use_color_text
Browse files Browse the repository at this point in the history
Add color option to CLI flags for output styling
  • Loading branch information
catatsuy authored Mar 31, 2024
2 parents 8740fca + 12d56ac commit b60f559
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
22 changes: 17 additions & 5 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type CLI struct {
filters rawStrings
excludes rawStrings
help bool
color bool
}

func NewCLI(outStream, errStream io.Writer, inputStream io.Reader) *CLI {
Expand Down Expand Up @@ -144,6 +145,7 @@ func (c *CLI) parseFlags(args []string) (*flag.FlagSet, error) {
flags.StringVar(&c.replaceExpr, "replace", "", `Replacement expression, e.g., "@search@replace@"`)
flags.Var(&c.filters, "filter", `filter expression`)
flags.Var(&c.excludes, "exclude", `exclude expression`)
flags.BoolVar(&c.color, "color", false, `Colorize output`)
flags.BoolVar(&c.help, "help", false, `Show help`)

flags.Usage = func() {
Expand Down Expand Up @@ -214,8 +216,14 @@ func (c *CLI) filterProcess(filters []*regexp.Regexp, excludes []*regexp.Regexp)

for scanner.Scan() {
line := scanner.Text()
if (len(filters) == 0 || matchesFilters(line, filters)) && !matchesFilters(line, excludes) {
fmt.Fprintln(c.outStream, line)
hit, hitRe := matchesFilters(line, filters)
if len(filters) == 0 || hit {
if excludeHit, _ := matchesFilters(line, excludes); !excludeHit {
if hitRe != nil && (c.color || term.IsTerminal(int(os.Stdout.Fd()))) {
line = colorText(line, hitRe)
}
fmt.Fprintln(c.outStream, line)
}
}
}

Expand All @@ -238,11 +246,15 @@ func compileRegexps(rawPatterns []string) ([]*regexp.Regexp, error) {
return regexps, nil
}

func matchesFilters(line string, regexps []*regexp.Regexp) bool {
func matchesFilters(line string, regexps []*regexp.Regexp) (bool, *regexp.Regexp) {
for _, re := range regexps {
if re.MatchString(line) {
return true
return true, re
}
}
return false
return false, nil
}

func colorText(line string, re *regexp.Regexp) string {
return re.ReplaceAllString(line, "\x1b[1m\x1b[91m$0\x1b[0m")
}
5 changes: 5 additions & 0 deletions cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ func TestRun_successProcess(t *testing.T) {
args: []string{"purl", "-replace", "@search@replacement@", "testdata/test.txt"},
expected: "replacementa replacementb\n",
},
"color text": {
args: []string{"purl", "-filter", "search", "-color"},
input: "searchb searchc",
expected: "\x1b[1m\x1b[91msearch\x1b[0mb \x1b[1m\x1b[91msearch\x1b[0mc\n",
},
}

for name, test := range tests {
Expand Down

0 comments on commit b60f559

Please sign in to comment.