golang.org/x/tools@v0.21.1-0.20240520172518-788d39e776b1/internal/apidiff/report.go (about) 1 // Copyright 2019 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package apidiff 6 7 import ( 8 "bytes" 9 "fmt" 10 "io" 11 ) 12 13 // Report describes the changes detected by Changes. 14 type Report struct { 15 Changes []Change 16 } 17 18 // A Change describes a single API change. 19 type Change struct { 20 Message string 21 Compatible bool 22 } 23 24 func (r Report) messages(compatible bool) []string { 25 var msgs []string 26 for _, c := range r.Changes { 27 if c.Compatible == compatible { 28 msgs = append(msgs, c.Message) 29 } 30 } 31 return msgs 32 } 33 34 func (r Report) String() string { 35 var buf bytes.Buffer 36 if err := r.Text(&buf); err != nil { 37 return fmt.Sprintf("!!%v", err) 38 } 39 return buf.String() 40 } 41 42 func (r Report) Text(w io.Writer) error { 43 if err := r.TextIncompatible(w, true); err != nil { 44 return err 45 } 46 return r.TextCompatible(w) 47 } 48 49 func (r Report) TextIncompatible(w io.Writer, withHeader bool) error { 50 if withHeader { 51 return r.writeMessages(w, "Incompatible changes:", r.messages(false)) 52 } 53 return r.writeMessages(w, "", r.messages(false)) 54 } 55 56 func (r Report) TextCompatible(w io.Writer) error { 57 return r.writeMessages(w, "Compatible changes:", r.messages(true)) 58 } 59 60 func (r Report) writeMessages(w io.Writer, header string, msgs []string) error { 61 if len(msgs) == 0 { 62 return nil 63 } 64 if header != "" { 65 if _, err := fmt.Fprintf(w, "%s\n", header); err != nil { 66 return err 67 } 68 } 69 for _, m := range msgs { 70 if _, err := fmt.Fprintf(w, "- %s\n", m); err != nil { 71 return err 72 } 73 } 74 return nil 75 }