This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
main.go
111 lines (93 loc) · 2.03 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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
_ "golang.org/x/tools/go/gcimporter"
"rsc.io/grind/deadcode"
"rsc.io/grind/gotoinline"
"rsc.io/grind/grinder"
"rsc.io/grind/vardecl"
)
var diff = flag.Bool("diff", false, "print diffs")
var verbose = flag.Bool("v", false, "verbose")
func usage() {
fmt.Fprintf(os.Stderr, "usage: grind [-diff] [-v] packagepath... (or file...)\n")
os.Exit(2)
}
var ctxt = grinder.Context{
Logf: log.Printf,
}
func main() {
flag.Usage = usage
flag.Parse()
if flag.NArg() == 0 {
usage()
}
ctxt.Grinders = []grinder.Func{
deadcode.Grind,
gotoinline.Grind,
vardecl.Grind,
DeleteUnusedLabels,
}
defer func() {
if ctxt.Errors {
os.Exit(1)
}
}()
if strings.HasSuffix(flag.Arg(0), ".go") {
grind(ctxt.GrindFiles(flag.Args()...))
return
}
for _, path := range flag.Args() {
grind(ctxt.GrindPackage(path))
}
}
func grind(pkg *grinder.Package) {
for _, name := range pkg.Filenames {
if !pkg.Modified(name) {
continue
}
if *diff {
diffText, err := runDiff([]byte(pkg.OrigSrc(name)), []byte(pkg.Src(name)))
if err != nil {
ctxt.Errorf("%v", err)
}
os.Stdout.Write(diffText)
continue
}
if err := ioutil.WriteFile(name, []byte(pkg.Src(name)), 0666); err != nil {
ctxt.Errorf("%v", err)
}
}
}
func runDiff(b1, b2 []byte) (data []byte, err error) {
f1, err := ioutil.TempFile("", "grind-")
if err != nil {
return nil, err
}
defer os.Remove(f1.Name())
defer f1.Close()
f2, err := ioutil.TempFile("", "grind-")
if err != nil {
return nil, err
}
defer os.Remove(f2.Name())
defer f2.Close()
f1.Write(b1)
f2.Write(b2)
data, err = exec.Command("git", "diff", f1.Name(), f2.Name()).CombinedOutput()
if len(data) > 0 {
// diff exits with a non-zero status when the files don't match.
// Ignore that failure as long as we get output.
err = nil
}
return
}