Commit e6e60cda authored by Anthony Martin's avatar Anthony Martin Committed by Russ Cox

cmd/go: suppress extraneous newlines in list

Before:
$ go list -f '{{range .Deps}}{{println $.Name .}}{{end}}' math time
math runtime
math unsafe

time errors
time runtime
time sync
time sync/atomic
time syscall
time unsafe

$

After:
$ go list -f '{{range .Deps}}{{println $.Name .}}{{end}}' math time
math runtime
math unsafe
time errors
time runtime
time sync
time sync/atomic
time syscall
time unsafe
$

R=minux.ma, rsc
CC=golang-dev
https://golang.org/cl/7130052
parent a1231839
...@@ -99,7 +99,7 @@ var listJson = cmdList.Flag.Bool("json", false, "") ...@@ -99,7 +99,7 @@ var listJson = cmdList.Flag.Bool("json", false, "")
var nl = []byte{'\n'} var nl = []byte{'\n'}
func runList(cmd *Command, args []string) { func runList(cmd *Command, args []string) {
out := newCountingWriter(os.Stdout) out := newTrackingWriter(os.Stdout)
defer out.w.Flush() defer out.w.Flush()
var do func(*Package) var do func(*Package)
...@@ -119,13 +119,12 @@ func runList(cmd *Command, args []string) { ...@@ -119,13 +119,12 @@ func runList(cmd *Command, args []string) {
fatalf("%s", err) fatalf("%s", err)
} }
do = func(p *Package) { do = func(p *Package) {
out.Reset()
if err := tmpl.Execute(out, p); err != nil { if err := tmpl.Execute(out, p); err != nil {
out.Flush() out.Flush()
fatalf("%s", err) fatalf("%s", err)
} }
if out.Count() > 0 { if out.NeedNL() {
out.w.WriteRune('\n') out.Write([]byte{'\n'})
} }
} }
} }
...@@ -140,32 +139,33 @@ func runList(cmd *Command, args []string) { ...@@ -140,32 +139,33 @@ func runList(cmd *Command, args []string) {
} }
} }
// CountingWriter counts its data, so we can avoid appending a newline // TrackingWriter tracks the last byte written on every write so
// if there was no actual output. // we can avoid printing a newline if one was already written or
type CountingWriter struct { // if there is no output at all.
w *bufio.Writer type TrackingWriter struct {
count int64 w *bufio.Writer
last byte
} }
func newCountingWriter(w io.Writer) *CountingWriter { func newTrackingWriter(w io.Writer) *TrackingWriter {
return &CountingWriter{ return &TrackingWriter{
w: bufio.NewWriter(w), w: bufio.NewWriter(w),
last: '\n',
} }
} }
func (cw *CountingWriter) Write(p []byte) (n int, err error) { func (t *TrackingWriter) Write(p []byte) (n int, err error) {
cw.count += int64(len(p)) n, err = t.w.Write(p)
return cw.w.Write(p) if n > 0 {
} t.last = p[n-1]
}
func (cw *CountingWriter) Flush() { return
cw.w.Flush()
} }
func (cw *CountingWriter) Reset() { func (t *TrackingWriter) Flush() {
cw.count = 0 t.w.Flush()
} }
func (cw *CountingWriter) Count() int64 { func (t *TrackingWriter) NeedNL() bool {
return cw.count return t.last != '\n'
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment