Abstracts away statement printing

This commit is contained in:
Csaba Henk 2018-04-10 13:55:06 +02:00
parent df86d25381
commit 7b5450d0e5
2 changed files with 28 additions and 16 deletions

31
main.go
View file

@ -183,14 +183,15 @@ func gron(r io.Reader, w io.Writer, opts int) (int, error) {
sort.Sort(ss)
}
var conv statementconv
if opts&optMonochrome > 0 {
for _, s := range ss {
fmt.Fprintln(w, s.String())
}
conv = statementToString
} else {
for _, s := range ss {
fmt.Fprintln(w, s.colorString())
}
conv = statementToColorString
}
for _, s := range ss {
fmt.Fprintln(w, conv(s))
}
return exitOK, nil
@ -219,12 +220,16 @@ func gronStream(r io.Reader, w io.Writer, opts int) (int, error) {
{"[]", typEmptyArray},
{";", typSemi},
}
var conv func(s statement) string
if opts&optMonochrome > 0 {
fmt.Fprintln(w, top.String())
conv = statementToString
} else {
fmt.Fprintln(w, top.colorString())
conv = statementToColorString
}
fmt.Fprintln(w, conv(top))
// Read the input line by line
sc := bufio.NewScanner(r)
buf := make([]byte, 0, 64*1024)
@ -246,14 +251,8 @@ func gronStream(r io.Reader, w io.Writer, opts int) (int, error) {
sort.Sort(ss)
}
if opts&optMonochrome > 0 {
for _, s := range ss {
fmt.Fprintln(w, s.String())
}
} else {
for _, s := range ss {
fmt.Fprintln(w, s.colorString())
}
for _, s := range ss {
fmt.Fprintln(w, conv(s))
}
}
if err := sc.Err(); err != nil {

View file

@ -40,6 +40,19 @@ func (s statement) colorString() string {
return strings.Join(out, "")
}
// a statementconv converts a statement to string
type statementconv func(s statement) string
// statementconv variant of statement.String
func statementToString(s statement) string {
return s.String()
}
// statementconv variant of statement.colorString
func statementToColorString(s statement) string {
return s.colorString()
}
// withBare returns a copy of a statement with a new bare
// word token appended to it
func (s statement) withBare(k string) statement {