first commit

This commit is contained in:
2020-10-25 10:00:59 +03:00
commit 0bd6f67397
80 changed files with 4741 additions and 0 deletions

5
output/formatter/ansi.go Normal file
View File

@@ -0,0 +1,5 @@
package formatter
func Ansi() *Formatter {
return New()
}

View File

@@ -0,0 +1,79 @@
package formatter
import (
"bytes"
"context"
"regexp"
"gitoa.ru/go-4devs/console/output/style"
)
//nolint: gochecknoglobals
var re = regexp.MustCompile(`<(([a-z][^<>]+)|/([a-z][^<>]+)?)>`)
func WithStyle(styles func(string) (style.Style, error)) func(*Formatter) {
return func(f *Formatter) {
f.styles = styles
}
}
func New(opts ...func(*Formatter)) *Formatter {
f := &Formatter{
styles: style.Find,
}
for _, opt := range opts {
opt(f)
}
return f
}
type Formatter struct {
styles func(string) (style.Style, error)
}
func (a *Formatter) Format(ctx context.Context, msg string) string {
var (
out bytes.Buffer
cur int
)
for _, idx := range re.FindAllStringIndex(msg, -1) {
tag := msg[idx[0]+1 : idx[1]-1]
if cur < idx[0] {
out.WriteString(msg[cur:idx[0]])
}
var (
st style.Style
err error
)
switch {
case tag[0:1] == "/":
st, err = a.styles(tag[1:])
if err == nil {
out.WriteString(st.Set(style.ActionUnset))
}
default:
st, err = a.styles(tag)
if err == nil {
out.WriteString(st.Set(style.ActionSet))
}
}
if err != nil {
cur = idx[0]
} else {
cur = idx[1]
}
}
if len(msg) > cur {
out.WriteString(msg[cur:])
}
return out.String()
}

View File

@@ -0,0 +1,26 @@
package formatter_test
import (
"context"
"testing"
"gitoa.ru/go-4devs/console/output/formatter"
)
func TestFormatter(t *testing.T) {
ctx := context.Background()
formatter := formatter.New()
cases := map[string]string{
"<info>info message</info>": "\x1b[32minfo message\x1b[39m",
"<info><command></info>": "\x1b[32m<command>\x1b[39m",
"<html>...</html>": "<html>...</html>",
}
for msg, ex := range cases {
got := formatter.Format(ctx, msg)
if ex != got {
t.Errorf("ivalid expected:%#v, got: %#v", ex, got)
}
}
}

14
output/formatter/none.go Normal file
View File

@@ -0,0 +1,14 @@
package formatter
import "gitoa.ru/go-4devs/console/output/style"
func None() *Formatter {
return New(
WithStyle(func(name string) (style.Style, error) {
if _, err := style.Find(name); err != nil {
return style.Empty(), err
}
return style.Empty(), nil
}))
}

View File

@@ -0,0 +1,27 @@
package formatter_test
import (
"context"
"testing"
"gitoa.ru/go-4devs/console/output/formatter"
)
func TestNone(t *testing.T) {
ctx := context.Background()
none := formatter.None()
cases := map[string]string{
"<info>message info</info>": "message info",
"<error>message error</error>": "message error",
"<comment><scheme></comment>": "<scheme>",
"<body>body</body>": "<body>body</body>",
}
for msg, ex := range cases {
got := none.Format(ctx, msg)
if ex != got {
t.Errorf("expect:%#v, got:%#v", ex, got)
}
}
}