-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.go
67 lines (52 loc) · 1.3 KB
/
mod.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
// Copyright (C) 2018 Storj Labs, Inc.
// See LICENSE for copying information.
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/kylelemons/godebug/diff"
)
type IsTidy struct {
Common
}
func (cmd *IsTidy) Name() string { return "istidy" }
func (cmd *IsTidy) Parse(args []string) error {
set := flag.NewFlagSet(cmd.Name(), flag.ExitOnError)
return set.Parse(args)
}
func (cmd *IsTidy) Exec() {
repodir := cmd.RepoDir()
before, err := ioutil.ReadFile(filepath.Join(repodir, "go.mod"))
ErrFatal(err)
cmd.Tidy()
after, err := ioutil.ReadFile(filepath.Join(repodir, "go.mod"))
ErrFatal(err)
if string(before) != string(after) {
diff, removed := difflines(string(before), string(after))
fmt.Fprintln(os.Stderr, "go.mod is not tidy")
fmt.Fprintln(os.Stderr, diff)
if removed {
os.Exit(1)
}
}
}
func difflines(a, b string) (patch string, removed bool) {
alines, blines := strings.Split(a, "\n"), strings.Split(b, "\n")
chunks := diff.DiffChunks(alines, blines)
buf := new(bytes.Buffer)
for _, c := range chunks {
for _, line := range c.Added {
fmt.Fprintf(buf, "+%s\n", line)
}
for _, line := range c.Deleted {
fmt.Fprintf(buf, "-%s\n", line)
removed = true
}
}
return strings.TrimRight(buf.String(), "\n"), removed
}