github.com/stackb/rules_proto@v0.0.0-20240221195024-5428336c51f1/cmd/examplegen/linewriter.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/ioutil" 7 "log" 8 "strings" 9 "text/template" 10 ) 11 12 type LineWriter struct { 13 lines []string 14 } 15 16 func (w *LineWriter) w(s string, args ...interface{}) { 17 w.lines = append(w.lines, fmt.Sprintf(s, args...)) 18 } 19 20 func (w *LineWriter) t(t *template.Template, data interface{}) { 21 var buf bytes.Buffer 22 err := t.Execute(&buf, data) 23 if err != nil { 24 log.Fatalf("%v", err) 25 } 26 w.lines = append(w.lines, buf.String()) 27 } 28 29 func (w *LineWriter) tpl(filename string, data interface{}) { 30 tpl, err := template.ParseFiles(filename) 31 if err != nil { 32 log.Fatalf("Failed to parse %s: %v", filename, err) 33 } 34 w.t(tpl, data) 35 } 36 37 func (w *LineWriter) ln() { 38 w.lines = append(w.lines, "") 39 } 40 41 func (w *LineWriter) MustWrite(filepath string) { 42 err := ioutil.WriteFile(filepath, []byte(strings.Join(w.lines, "\n")), 0666) 43 if err != nil { 44 log.Fatalf("FAIL %s: %v", filepath, err) 45 } 46 log.Printf("Wrote %s", filepath) 47 } 48 49 func (w *LineWriter) Write(filepath string) error { 50 if err := ioutil.WriteFile(filepath, []byte(strings.Join(w.lines, "\n")), 0666); err != nil { 51 return fmt.Errorf("could not write %s: %w", filepath, err) 52 } 53 log.Printf("Wrote %s", filepath) 54 return nil 55 } 56 57 func mustTemplate(tpl string) *template.Template { 58 return template.Must(template.New("").Option("missingkey=error").Parse(tpl)) 59 }