From 7b5450d0e55ee47b370589ccfd84875e22afd5fc Mon Sep 17 00:00:00 2001 From: Csaba Henk Date: Tue, 10 Apr 2018 13:55:06 +0200 Subject: [PATCH] Abstracts away statement printing --- main.go | 31 +++++++++++++++---------------- statements.go | 13 +++++++++++++ 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/main.go b/main.go index da728d7..75f0641 100644 --- a/main.go +++ b/main.go @@ -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 { diff --git a/statements.go b/statements.go index 088d5ee..a2791dd 100644 --- a/statements.go +++ b/statements.go @@ -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 {