1
2
3
4
5 package sgutil
6
7 import (
8 "bufio"
9 "bytes"
10 "fmt"
11 "go/format"
12 "os"
13 "path/filepath"
14 )
15
16 func CreatePath(newFile string) (*os.File, error) {
17 dir := filepath.Dir(newFile)
18 err := os.MkdirAll(dir, 0755)
19 if err != nil {
20 return nil, fmt.Errorf("failed to create directory %s: %w", dir, err)
21 }
22 f, err := os.Create(newFile)
23 if err != nil {
24 return nil, fmt.Errorf("failed to create file %s: %w", newFile, err)
25 }
26 return f, nil
27 }
28
29
30
31
32
33 func FormatWriteAndClose(source *bytes.Buffer, newFile string) {
34 b, err := format.Source(source.Bytes())
35 if err != nil {
36 fmt.Fprintf(os.Stderr, "%v\n", err)
37 fmt.Fprintf(os.Stderr, "%s\n", NumberLines(source.Bytes()))
38 fmt.Fprintf(os.Stderr, "%v\n", err)
39 panic(err)
40 } else {
41 WriteAndClose(b, newFile)
42 }
43 }
44
45
46
47 func WriteAndClose(b []byte, newFile string) {
48 ofile, err := CreatePath(newFile)
49 if err != nil {
50 panic(err)
51 }
52 ofile.Write(b)
53 ofile.Close()
54 }
55
56
57
58 func NumberLines(data []byte) string {
59 var buf bytes.Buffer
60 r := bytes.NewReader(data)
61 s := bufio.NewScanner(r)
62 for i := 1; s.Scan(); i++ {
63 fmt.Fprintf(&buf, "%d: %s\n", i, s.Text())
64 }
65 return buf.String()
66 }
67
View as plain text