marker

package module
v0.0.0-...-ec8d542 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 28, 2022 License: MIT Imports: 8 Imported by: 4

README

Marker is the easiest way to match and mark strings for colorful terminal outputs.

marker

Marker is built for easily match and mark strings for colorful terminal outputs. You can match your strings with built-in matchers or easily implement a custom matcher for your usecase. Marker uses fatih/color for colorizing terminal output.

Installation

go get github.com/cyucelen/marker

Basic Usage

Marker has very simple and extensible way to get your strings colorful and brilliant!

Example
aristotleQuote := "The more you know, the more you realize you don't know."
emphasized := marker.Mark(aristotleQuote, marker.MatchAll("know"), color.New(color.FgRed))
fmt.Println(emphasized)

Table of Contents


Mark Your Log Stream

You may want to instrument a logger such that any output coming from it is colorized in the expected manner. marker contains functionality which can be easily integrated with Golang's log or any interface that supports io.Writer.

stdoutMarker := marker.NewStdoutMarker()
markRules := []marker.MarkRule{
  {marker.MatchBracketSurrounded(), color.New(color.FgBlue)},
  {marker.MatchAll("marker"), color.New(color.FgRed)},
}

stdoutMarker.AddRules(markRules)
logger := log.New(stdoutMarker, "", 0)

logger.Println("[INFO] marker is working as expected")
Custom io.Writer out for log interface

marker also allows you to specify the io.Writer that you want to send output to. This is useful if the logger is writing to somewhere other than stdout like a file.

f, _ := os.Create("/tmp/awesome.log")
w := bufio.NewWriter(f)

writeMarker := marker.NewWriteMarker(w)

markRules := []marker.MarkRule{
  {marker.MatchBracketSurrounded(), blueFg},
  {marker.MatchAll("marker"), magentaFg},
}

writeMarker.AddRules(markRules)

logger := log.New(writeMarker, "", 0)
logger.Println("[INFO] colorful logs even in files, marker to mark them all!")

w.Flush()
f.Close()

output := catFile("/tmp/awesome.log") // $ cat /tmp/awesome.log
fmt.Print(output)

Matchers

MatchAll
aristotleQuote := "The more you know, the more you realize you don't know."
emphasized := marker.Mark(aristotleQuote, marker.MatchAll("know"), color.New(color.FgRed))
fmt.Println(emphasized)
MatchN
boringLog := "[INFO] Nobody wants to read pale [INFO] tags."
brilliantLog := marker.Mark(boringLog, marker.MatchN("[INFO]", 1), color.New(color.FgBlue))
fmt.Println(brilliantLog)
MatchRegexp
rhyme := "I scream, you all scream, we all scream for ice cream."
r, _ := regexp.Compile("([a-z]?cream)")
careAboutCream := marker.Mark(rhyme, marker.MatchRegexp(r), color.New(color.FgYellow))
fmt.Println(careAboutCream)
MatchSurrounded
sentence := "I pull out things surrounded by abcWHOA COLORSdef"
markedSurrounded := marker.Mark(sentence, marker.MatchSurrounded("abc", "def"), color.New(color.FgMagenta))
fmt.Println(markedSurrounded)
MatchBracketSurrounded
sentence = "[INFO] This is what log lines look like"
markedSurrounded = marker.Mark(sentence, marker.MatchBracketSurrounded(), color.New(color.FgRed))
fmt.Println(markedSurrounded)
MatchParensSurrounded
sentence = "[ERROR] This is what (parens) lines look like"
markedSurrounded = marker.Mark(sentence, marker.MatchParensSurrounded(), color.New(color.FgBlue))
fmt.Println(markedSurrounded)
MatchTimestamp

MatchTimestamp can be used for matching the timestamps fits the layouts in Golang's time.

All possible formats can be found here.

  goodOldTimes := "2006-01-02T15:04:05Z07:00 [INFO] Loading King of Fighters '97 ROM"
  timestampMarked := marker.Mark(goodOldTimes, marker.MatchTimestamp(time.RFC3339), color.New(color.FgBlue))
  fmt.Println(timestampMarked)

Builder way

If you want to mark different patterns in the same string, marker builder is neater way to do this.

rhyme := "I scream, you all scream, we all scream for ice cream."
b := &marker.MarkBuilder{}
r, _ := regexp.Compile("([a-z]?cream)")

markedWithBuilder := b.SetString(rhyme).
  Mark(marker.MatchN("for ice", 1), color.New(color.FgRed)).
  Mark(marker.MatchAll("all"), color.New(color.FgMagenta)).
  Mark(marker.MatchRegexp(r), color.New(color.FgYellow)).
  Build()

fmt.Println(markedWithBuilder)

Writing your custom Matcher

As you see in above examples, Mark function takes an MatcherFunc to match the patterns in given string and colorize them. A Matcher is a simple closure that returns a MatcherFunc to be called by Mark function to get Match information to put colorized versions of patterns into template.

Lets write our own custom Matcher that matches first encounter of given pattern.

Example

  func MatchFirst(pattern string) marker.MatcherFunc {
    return func(str string) marker.Match {
      return marker.Match{
        // replace first matching pattern with %s
        Template: strings.Replace(str, pattern, "%s", 1),
        // patterns to be colorized by Mark, in order
        Patterns: []string{pattern},
      }
    }
  }

You can also check built-in matchers for inspiration.

Contribution

I would like to accept any contributions to make Marker better and feature rich. So feel free to contribute your features(i.e. more Matchers!), improvements and fixes.

Have fun!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ANSICRegexp       = regexp.MustCompile(fmt.Sprintf("%s %s %s %s %s", weekdaysAbv, monthsAbv, days, hhmmss, year))
	UnixDateRegexp    = regexp.MustCompile(fmt.Sprintf("%s %s %s %s %s %s", weekdaysAbv, monthsAbv, days, hhmmss, timezone, year))
	RubyDateRegexp    = regexp.MustCompile(fmt.Sprintf("%s %s %s %s %s %s", weekdaysAbv, monthsAbv, daysWithZero, hhmmss, numericZone, year))
	RFC822Regexp      = regexp.MustCompile(fmt.Sprintf("%s %s [0-9]{2} %s %s", daysWithZero, monthsAbv, hhmm, timezone))
	RFC822ZRegexp     = regexp.MustCompile(fmt.Sprintf("%s %s [0-9]{2} %s %s", daysWithZero, monthsAbv, hhmm, numericZone))
	RFC850Regexp      = regexp.MustCompile(fmt.Sprintf("%s, %s-%s-[0-9]{2} %s %s", weekdays, daysWithZero, monthsAbv, hhmmss, timezone))
	RFC1123Regexp     = regexp.MustCompile(fmt.Sprintf("%s, %s %s %s %s %s", weekdaysAbv, daysWithZero, monthsAbv, year, hhmmss, timezone))
	RFC1123ZRegexp    = regexp.MustCompile(fmt.Sprintf("%s, %s %s %s %s %s", weekdaysAbv, daysWithZero, monthsAbv, year, hhmmss, numericZone))
	RFC3339Regexp     = regexp.MustCompile(fmt.Sprintf("%s-%s-%sT%sZ%s", year, numericmonths, daysWithZero, hhmmss, hhmm))
	RFC3339NanoRegexp = regexp.MustCompile(fmt.Sprintf("%s-%s-%sT%s%sZ%s", year, numericmonths, daysWithZero, hhmmss, nano, hhmm))
	KitchenRegexp     = regexp.MustCompile("(([0-1]?[0-9]|2[0-3]):[0-5][0-9][P|A]M)")
	StampRegexp       = regexp.MustCompile(fmt.Sprintf("%s %s %s(\\s|$)", monthsAbv, days, hhmmss))
	StampMilliRegexp  = regexp.MustCompile(fmt.Sprintf("%s %s %s%s", monthsAbv, days, hhmmss, milli))
	StampMicroRegexp  = regexp.MustCompile(fmt.Sprintf("%s %s %s%s", monthsAbv, days, hhmmss, micro))
	StampNanoRegexp   = regexp.MustCompile(fmt.Sprintf("%s %s %s%s", monthsAbv, days, hhmmss, nano))
)
View Source
var EmailRegexp = regexp.MustCompile(`[a-z0-9!#$%&'*+/=?^_{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])`)

EmailRegexp is a Regular expression for RFC5322

Functions

func Mark

func Mark(str string, matcherFunc MatcherFunc, c *color.Color) string

Mark marks the patterns that returned from MatcherFunc with colors in given string

func MarkMany

func MarkMany(str string, c *color.Color, matcherFuncs ...MatcherFunc) string

MarkMany marks each set of patterns returns by a variable number of MatcherFunc with color in given string

Types

type MarkBuilder

type MarkBuilder struct {
	// contains filtered or unexported fields
}

MarkBuilder is a better and neater way to mark different patterns of the string

func (*MarkBuilder) Build

func (m *MarkBuilder) Build() string

Build returns the marked string

func (*MarkBuilder) Mark

func (m *MarkBuilder) Mark(matcherFunc MatcherFunc, c *color.Color) *MarkBuilder

Mark marks the string with the matcher function and color

func (*MarkBuilder) MarkMany

func (m *MarkBuilder) MarkMany(c *color.Color, matcherFuncs ...MatcherFunc) *MarkBuilder

MarkMany marks the string with a variable number of matcher functions and color

func (*MarkBuilder) SetString

func (m *MarkBuilder) SetString(str string) *MarkBuilder

SetString sets the first parameter as the string that is going to be marked

type MarkRule

type MarkRule struct {
	Matcher MatcherFunc
	Color   *color.Color
}

MarkRule contains marking information to be applied on log stream

type Match

type Match struct {
	Template string
	Patterns []string
}

Match contains information about found patterns by MatcherFunc

type MatcherFunc

type MatcherFunc func(string) Match

MatcherFunc returns a Match which contains information about found patterns

func MatchAll

func MatchAll(pattern string) MatcherFunc

MatchAll creates a MatcherFunc that matches all patterns in given string

func MatchBracketSurrounded

func MatchBracketSurrounded() MatcherFunc

MatchBracketSurrounded is a helper utility for easy matching of bracket surrounded text

func MatchDaysOfWeek

func MatchDaysOfWeek() MatcherFunc

MatchDaysOfWeek creates a MatcherFunc that matches days of the week in given string

func MatchEmail

func MatchEmail() MatcherFunc

MatchEmail creates a MatcherFunc that matches emails which meets the conditions of RFC5322 standard

func MatchMultiple

func MatchMultiple(patternsToMatch []string) MatcherFunc

MatchMultiple creates a MatcherFunc that matches all string patterns from given slice in given string

func MatchN

func MatchN(pattern string, n int) MatcherFunc

MatchN creates a MatcherFunc that matches first n patterns in given string

func MatchParensSurrounded

func MatchParensSurrounded() MatcherFunc

MatchParensSurrounded is a helper utility for easy matching text surrounded in parentheses

func MatchRegexp

func MatchRegexp(r *regexp.Regexp) MatcherFunc

MatchRegexp creates a MatcherFunc that matches given regexp in given string

func MatchSurrounded

func MatchSurrounded(opening string, closure string) MatcherFunc

MatchSurrounded creates a MatcherFunc that matches the patterns surrounded by given opening and closure strings

func MatchTimestamp

func MatchTimestamp(layout string) MatcherFunc

MatchTimestamp creates a MatcherFunc that matches given time layout pattern in given string

type WriteMarker

type WriteMarker struct {
	// contains filtered or unexported fields
}

WriteMarker contains specified rules for applying them on output

func NewStdoutMarker

func NewStdoutMarker() *WriteMarker

NewStdoutMarker creates a WriteMarker with default out as os.Stdout

func NewWriteMarker

func NewWriteMarker(writer io.Writer) *WriteMarker

NewWriteMarker creates a Marker that writes out to the given io.Writer

func (*WriteMarker) AddRule

func (s *WriteMarker) AddRule(rule MarkRule) *WriteMarker

AddRule appends a rule to WriteMarker and returns itself

func (*WriteMarker) AddRules

func (s *WriteMarker) AddRules(rules []MarkRule)

AddRules appends all rules from given slice to WriteMarker rules

func (WriteMarker) Write

func (s WriteMarker) Write(p []byte) (n int, err error)

Write marks the text with specified rules and writes the output to specifed out

type WriteMarkerOption

type WriteMarkerOption func(*WriteMarker)

WriteMarkerOption is functional option type for WriteMarker

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL