-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
129 lines (115 loc) · 2.47 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"bufio"
"bytes"
"context"
"flag"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
)
var (
write = flag.Bool("w", false, "write result to (source) file instead of stdout")
localPrefix = flag.String("local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
)
func main() {
flag.Parse()
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer cancel()
failed := false
go func() {
for _, file := range flag.Args() {
if err := processFile(ctx, file); err != nil {
if e, ok := err.(*exec.ExitError); ok {
os.Exit(e.ExitCode())
}
fmt.Fprintf(os.Stderr, "FAIL: %s %s\n", file, err)
failed = true
}
}
cancel()
}()
<-ctx.Done()
if failed {
os.Exit(2)
}
}
func processFile(ctx context.Context, file string) error {
src, err := formatCode(ctx, nil, file)
if err != nil {
return err
}
s, err := ParseSourceFile(bytes.NewBuffer(src))
if err != nil {
return fmt.Errorf("parse source file: %s", err)
}
buf := bytes.NewBuffer(nil)
buf.Write(s.PackageClause)
for _, b := range s.ImportDecl {
if bytes.Equal(b, []byte("\n")) {
// ignore empty line
continue
}
if bytes.HasPrefix(b, []byte("\t//")) {
// ignore commented line
continue
}
buf.Write(b)
}
buf.Write(s.TopLevelDecl)
var args []string
if *localPrefix != "" {
args = append(args, "-local", *localPrefix)
}
dst, err := formatCode(ctx, buf, "", args...)
if err != nil {
return err
}
if *write {
if err := os.WriteFile(file, dst, 0600); err != nil {
return err
}
} else {
if _, err := io.Copy(os.Stdout, bytes.NewReader(dst)); err != nil {
return err
}
}
return nil
}
func formatCode(ctx context.Context, r io.Reader, file string, arg ...string) (formattedCode []byte, err error) {
cmd := exec.CommandContext(ctx, "goimports")
if len(arg) != 0 {
cmd.Args = append(cmd.Args, arg...)
}
if file != "" {
cmd.Args = append(cmd.Args, file)
}
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
if file != "" {
cmd.Stderr = os.Stderr
} else {
cmd.Stderr = &stderr
}
if r != nil {
cmd.Stdin = r
}
if err := cmd.Run(); err != nil {
if file != "" {
return nil, err
}
r := bufio.NewReader(&stderr)
for {
b, err2 := r.ReadBytes('\n')
if err2 == io.EOF {
return nil, err
}
os.Stderr.Write(bytes.Replace(b, []byte("<standard input>"), []byte(file), 1))
}
}
return stdout.Bytes(), nil
}