From 1086dd7cfb70e382d6bb3242d26e7f673fffb808 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Sat, 25 Feb 2012 08:00:55 +1100 Subject: [PATCH] cmd/go: in list, don't print blank lines for no output Otherwise go list -f "{{if .Stale}}{{.ImportPath}}{{end}}" all and similar commands can print pages of empty lines. R=golang-dev, rsc CC=golang-dev https://golang.org/cl/5696058 --- src/cmd/go/list.go | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/src/cmd/go/list.go b/src/cmd/go/list.go index 30baaa7b2f6..45b0a614ebc 100644 --- a/src/cmd/go/list.go +++ b/src/cmd/go/list.go @@ -7,6 +7,7 @@ package main import ( "bufio" "encoding/json" + "io" "os" "text/template" ) @@ -82,8 +83,8 @@ var listJson = cmdList.Flag.Bool("json", false, "") var nl = []byte{'\n'} func runList(cmd *Command, args []string) { - out := bufio.NewWriter(os.Stdout) - defer out.Flush() + out := newCountingWriter(os.Stdout) + defer out.w.Flush() var do func(*Package) if *listJson { @@ -97,15 +98,19 @@ func runList(cmd *Command, args []string) { out.Write(nl) } } else { - tmpl, err := template.New("main").Parse(*listFmt + "\n") + tmpl, err := template.New("main").Parse(*listFmt) if err != nil { fatalf("%s", err) } do = func(p *Package) { + out.Reset() if err := tmpl.Execute(out, p); err != nil { out.Flush() fatalf("%s", err) } + if out.Count() > 0 { + out.w.WriteRune('\n') + } } } @@ -118,3 +123,33 @@ func runList(cmd *Command, args []string) { do(pkg) } } + +// CountingWriter counts its data, so we can avoid appending a newline +// if there was no actual output. +type CountingWriter struct { + w *bufio.Writer + count int64 +} + +func newCountingWriter(w io.Writer) *CountingWriter { + return &CountingWriter{ + w: bufio.NewWriter(w), + } +} + +func (cw *CountingWriter) Write(p []byte) (n int, err error) { + cw.count += int64(len(p)) + return cw.w.Write(p) +} + +func (cw *CountingWriter) Flush() { + cw.w.Flush() +} + +func (cw *CountingWriter) Reset() { + cw.count = 0 +} + +func (cw *CountingWriter) Count() int64 { + return cw.count +}