terminal: Helpers for doing fmt-ish operations on the streams

It's pretty common to want to apply the various fmt.Fprint... functions
to our two output streams, and so to make that much less noisy at the
callsite here we have a small number of very thin wrappers around the
underlying fmt package functionality.

Although we're aiming to not have too much abstraction in this "terminal"
package, this seems justified in that it is only a very thin wrapper
around functionality that most Go programmers are already familiar with,
and so the risk of this causing any surprises is low and the improvement
to readability of callers seems worth it.
This commit is contained in:
Martin Atkins 2021-02-12 09:58:25 -08:00
parent 6f26203ae4
commit f91a3b87c1
2 changed files with 69 additions and 0 deletions

View File

@ -15,6 +15,7 @@
package terminal
import (
"fmt"
"os"
)
@ -72,3 +73,33 @@ func Init() (*Streams, error) {
Stdin: stdin,
}, nil
}
// Print is a helper for conveniently calling fmt.Fprint on the Stdout stream.
func (s *Streams) Print(a ...interface{}) (n int, err error) {
return fmt.Fprint(s.Stdout.File, a...)
}
// Printf is a helper for conveniently calling fmt.Fprintf on the Stdout stream.
func (s *Streams) Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(s.Stdout.File, format, a...)
}
// Println is a helper for conveniently calling fmt.Fprintln on the Stdout stream.
func (s *Streams) Println(a ...interface{}) (n int, err error) {
return fmt.Fprintln(s.Stdout.File, a...)
}
// Eprint is a helper for conveniently calling fmt.Fprint on the Stderr stream.
func (s *Streams) Eprint(a ...interface{}) (n int, err error) {
return fmt.Fprint(s.Stderr.File, a...)
}
// Eprintf is a helper for conveniently calling fmt.Fprintf on the Stderr stream.
func (s *Streams) Eprintf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(s.Stderr.File, format, a...)
}
// Eprintln is a helper for conveniently calling fmt.Fprintln on the Stderr stream.
func (s *Streams) Eprintln(a ...interface{}) (n int, err error) {
return fmt.Fprintln(s.Stderr.File, a...)
}

View File

@ -0,0 +1,38 @@
package terminal
import (
"testing"
"github.com/google/go-cmp/cmp"
)
func TestStreamsFmtHelpers(t *testing.T) {
streams, close := StreamsForTesting(t)
streams.Print("stdout print ", 5, "\n")
streams.Eprint("stderr print ", 6, "\n")
streams.Println("stdout println", 7)
streams.Eprintln("stderr println", 8)
streams.Printf("stdout printf %d\n", 9)
streams.Eprintf("stderr printf %d\n", 10)
outp := close(t)
gotOut := outp.Stdout()
wantOut := `stdout print 5
stdout println 7
stdout printf 9
`
if diff := cmp.Diff(wantOut, gotOut); diff != "" {
t.Errorf("wrong stdout\n%s", diff)
}
gotErr := outp.Stderr()
wantErr := `stderr print 6
stderr println 8
stderr printf 10
`
if diff := cmp.Diff(wantErr, gotErr); diff != "" {
t.Errorf("wrong stderr\n%s", diff)
}
}