]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/go: in list, don't print blank lines for no output
authorRob Pike <r@golang.org>
Fri, 24 Feb 2012 21:00:55 +0000 (08:00 +1100)
committerRob Pike <r@golang.org>
Fri, 24 Feb 2012 21:00:55 +0000 (08:00 +1100)
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

index 30baaa7b2f6260f11a9773d4e9b4a0b0669716c3..45b0a614ebc967135c65544dc2d652c60d796f09 100644 (file)
@@ -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
+}