Skip to content

Commit 8193a24

Browse files
committed
dangling-whitespace: rule for trailing spaces
Signed-off-by: Vincent Batts <[email protected]>
1 parent 1a447a0 commit 8193a24

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

git/commits.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,19 @@ var FieldNames = map[string]string{
5757
"%G?": "verification_flag",
5858
}
5959

60+
// Show returns the diff of a commit.
61+
//
62+
// NOTE: This could be expensive for very large commits.
63+
func Show(commit string) ([]byte, error) {
64+
cmd := exec.Command("git", "show", commit)
65+
cmd.Stderr = os.Stderr
66+
out, err := cmd.Output()
67+
if err != nil {
68+
return nil, err
69+
}
70+
return out, nil
71+
}
72+
6073
// CommitEntry represents a single commit's information from `git`.
6174
// See also FieldNames
6275
type CommitEntry map[string]string

main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"os"
88
"strings"
99

10+
_ "github.com/vbatts/git-validation/rules/danglingwhitespace"
1011
_ "github.com/vbatts/git-validation/rules/dco"
1112
_ "github.com/vbatts/git-validation/rules/shortsubject"
1213
"github.com/vbatts/git-validation/validate"

rules/danglingwhitespace/rule.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package danglingwhitespace
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
7+
"github.com/vbatts/git-validation/git"
8+
"github.com/vbatts/git-validation/validate"
9+
)
10+
11+
var (
12+
// DanglingWhitespace is the rule for checking the presence of dangling
13+
// whitespaces on line endings.
14+
DanglingWhitespace = validate.Rule{
15+
Name: "dangling-whitespace",
16+
Description: "checking the presence of dangling whitespaces on line endings",
17+
Run: ValidateDanglingWhitespace,
18+
}
19+
)
20+
21+
func init() {
22+
validate.RegisterRule(DanglingWhitespace)
23+
}
24+
25+
func ValidateDanglingWhitespace(c git.CommitEntry) (vr validate.Result) {
26+
diff, err := git.Show(c["commit"])
27+
if err != nil {
28+
return validate.Result{Pass: false, Msg: err.Error(), CommitEntry: c}
29+
}
30+
31+
vr.CommitEntry = c
32+
vr.Pass = true
33+
for _, line := range bytes.Split(diff, newLine) {
34+
if !bytes.HasPrefix(line, diffAddLine) || bytes.Equal(line, diffAddLine) {
35+
continue
36+
}
37+
if len(bytes.TrimSpace(line)) != len(line) {
38+
vr.Pass = false
39+
vr.Msg = fmt.Sprintf("line %q has trailiing spaces", string(line))
40+
}
41+
}
42+
vr.Msg = "all added diff lines do not have trailing spaces"
43+
return
44+
}
45+
46+
var (
47+
newLine = []byte("\n")
48+
diffAddLine = []byte("+ ")
49+
)

0 commit comments

Comments
 (0)