Skip to content

Commit

Permalink
refactor styles
Browse files Browse the repository at this point in the history
  • Loading branch information
seletskiy committed Jun 24, 2016
1 parent e3f2fc8 commit 231caf7
Show file tree
Hide file tree
Showing 7 changed files with 249 additions and 227 deletions.
Binary file added demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
206 changes: 0 additions & 206 deletions format.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
package main

import (
"fmt"
"os"
"regexp"
"strings"
"text/template"

"golang.org/x/crypto/ssh/terminal"

"github.com/kovetskiy/lorg"
"github.com/seletskiy/hierr"
"github.com/seletskiy/tplutil"
)

type (
Expand All @@ -23,147 +15,6 @@ const (
outputFormatJSON
)

const (
formatEscape = "\x1b"

formatAttrForeground = "3"
formatAttrBackground = "4"
formatAttrDefault = "9"

formatAttrReset = "0"
formatAttrReverse = "7"
formatAttrNoReverse = "27"
formatAttrBold = "1"
formatAttrNoBold = "22"

formatAttrForeground256 = "38;5"
formatAttrBackground256 = "48;5"

formatResetBlock = "{reset}"
)

var (
formatCodeRegexp = regexp.MustCompile(formatEscape + `[^m]+`)
)

func getResetFormatSequence() string {
return getFormatSequence(formatAttrReset)
}

func getBackgroundFormatSequence(color int) string {
if color == 0 {
return getFormatSequence(
formatAttrBackground + formatAttrDefault,
)
}

return getFormatSequence(formatAttrBackground256, fmt.Sprint(color))
}

func getForegroundFormatSequence(color int) string {
if color == 0 {
return getFormatSequence(
formatAttrForeground + formatAttrDefault,
)
}

return getFormatSequence(formatAttrForeground256, fmt.Sprint(color))
}

func getBoldFormatSequence() string {
return getFormatSequence(formatAttrBold)
}

func getNoBoldFormatSequence() string {
return getFormatSequence(formatAttrNoBold)
}

func getReverseFormatSequence() string {
return getFormatSequence(formatAttrReverse)
}

func getNoReverseFormatSequence() string {
return getFormatSequence(formatAttrNoReverse)
}

func getFormatSequence(attr ...string) string {
if !isColorEnabled {
return ""
}

return fmt.Sprintf("%s[%sm", formatEscape, strings.Join(attr, `;`))
}

func getLogPlaceholder(placeholder string) string {
return fmt.Sprintf("${%s}", placeholder)
}

func getLogLevelFormatPlaceholder(
level string,
formatString string,
) (string, error) {
format, err := compileFormat(formatString)
if err != nil {
return "", hierr.Errorf(
err,
`can't compile specified format string: '%s'`,
formatString,
)
}

formatCode, err := tplutil.ExecuteToString(format, nil)
if err != nil {
return "", hierr.Errorf(
err,
`can't execute specified format string: '%s'`,
formatString,
)
}

return fmt.Sprintf(
"${color:%s:%s}",
level,
strings.Replace(formatCode, ":", "\\:", -1),
), nil
}

func executeLogColorPlaceholder(level lorg.Level, value string) string {
var (
parts = strings.SplitN(value, ":", 2)
targetLevel = parts[0]
format = ""
)

if len(parts) > 1 {
format = parts[1]
}

if targetLevel == strings.ToLower(level.String()) {
return format
}

return ""
}

func compileFormat(format string) (*template.Template, error) {
functions := map[string]interface{}{
"bg": getBackgroundFormatSequence,
"fg": getForegroundFormatSequence,
"bold": getBoldFormatSequence,
"nobold": getNoBoldFormatSequence,
"reverse": getReverseFormatSequence,
"noreverse": getNoReverseFormatSequence,
"reset": getResetFormatSequence,

"log": getLogPlaceholder,
"level": getLogLevelFormatPlaceholder,
}

return template.New("format").Delims("{", "}").Funcs(functions).Parse(
format,
)
}

func parseOutputFormat(
args map[string]interface{},
) (outputFormat, bool, bool) {
Expand All @@ -187,60 +38,3 @@ func parseOutputFormat(

return format, isOutputOnTTY, isColorEnabled
}

func trimFormatCodes(input string) string {
return formatCodeRegexp.ReplaceAllLiteralString(input, ``)
}

func parseStatusBarFormat(
args map[string]interface{},
) (*template.Template, error) {
var (
theme = args["--status-format"].(string)
)

statusFormat := getStatusBarTheme(theme) + formatResetBlock

format, err := compileFormat(statusFormat)
if err != nil {
return nil, hierr.Errorf(
err,
`can't compile status bar format template`,
)
}

tracef("using status bar format: '%s'", statusFormat)

return format, nil
}

func parseLogFormat(args map[string]interface{}) (*lorg.Format, error) {
var (
theme = args["--log-format"].(string)
)

logFormat := getLogTheme(theme) + formatResetBlock

format, err := compileFormat(logFormat)
if err != nil {
return nil, hierr.Errorf(
err,
`can't compile log format template`,
)
}

formatString, err := tplutil.ExecuteToString(format, nil)
if err != nil {
return nil, hierr.Errorf(
err,
`can't execute log format template`,
)
}

tracef("using log format: '%#s'", logFormat)

lorgFormat := lorg.NewFormat(formatString)
lorgFormat.SetPlaceholder("color", executeLogColorPlaceholder)

return lorgFormat, nil
}
14 changes: 5 additions & 9 deletions debug.go → log.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ import (
"github.com/seletskiy/hierr"
)

func setupLogger(format *lorg.Format) {
logger.SetFormat(format)
}

func setLoggerOutputFormat(format outputFormat, logger *lorg.Log) {
func setLoggerOutputFormat(logger *lorg.Log, format outputFormat) {
if format == outputFormatJSON {
logger.SetOutput(&jsonOutputWriter{
stream: `stderr`,
Expand All @@ -40,6 +36,10 @@ func setLoggerVerbosity(level verbosity, logger *lorg.Log) {
}
}

func setLoggerStyle(logger *lorg.Log, style *lorg.Format) {
logger.SetFormat(style)
}

func colorize(
attributes ...color.Attribute,
) string {
Expand All @@ -56,10 +56,6 @@ func colorize(
}

func tracef(format string, args ...interface{}) {
if verbose < verbosityTrace {
return
}

args = serializeErrors(args)

logger.Tracef(format, args...)
Expand Down
25 changes: 18 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,8 @@ Output format and colors options:
* level <level> <format> - insert in place specified
format if log level matches specified level.
[default: ` + themeDark + `]
--dark Set all available formats to predefined dark theme.
--light Set all available formats to predefined light theme.
--no-colors Do not use colors.
Timeout options:
Expand Down Expand Up @@ -266,16 +268,19 @@ func main() {

format, isOutputOnTTY, isColorEnabled = parseOutputFormat(args)

logFormat, err := parseLogFormat(args)
setLoggerOutputFormat(logger, format)

loggerStyle, err := getLoggerStyle(parseTheme("log", args))
if err != nil {
errorf("%s", err)
errorf("%s", hierr.Errorf(
err,
`can't use given logger style`,
))

exit(1)
}

setupLogger(logFormat)

setLoggerOutputFormat(format, logger)
setLoggerStyle(logger, loggerStyle)

poolSize, err := parseThreadPoolSize(args)
if err != nil {
Expand All @@ -287,9 +292,15 @@ func main() {

pool = newThreadPool(poolSize)

statusFormat, err := parseStatusBarFormat(args)
statusStyle, err := getStatusBarStyle(parseTheme("status", args))
if err != nil {
errorf("%s", hierr.Errorf(
err,
`can't use given status bar style`,
))
}

status = newStatusBar(statusFormat)
status = newStatusBar(statusStyle)

switch {
case args["--upload"].(bool):
Expand Down
3 changes: 2 additions & 1 deletion status_bar.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func (bar *statusBar) IncFailures() {
defer bar.Unlock()

bar.Failures++
bar.Total--
}

func (bar *statusBar) SetOutputLock(lock sync.Locker) {
Expand Down Expand Up @@ -114,7 +115,7 @@ func (bar *statusBar) Draw(writer io.Writer) {

fmt.Fprintf(buffer, "\r")

bar.last = trimFormatCodes(buffer.String())
bar.last = trimStyleCodes(buffer.String())

io.Copy(writer, buffer)
}
Loading

0 comments on commit 231caf7

Please sign in to comment.