Skip to content

Commit d33cc0e

Browse files
committed
feat: add file-length-limit rule
1 parent 842b3e2 commit d33cc0e

10 files changed

+722
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,7 @@ List of all available rules. The rules ported from `golint` are left unchanged a
540540
| [`enforce-repeated-arg-type-style`](./RULES_DESCRIPTIONS.md#enforce-repeated-arg-type-style) | string (defaults to "any") | Enforces consistent style for repeated argument and/or return value types. | no | no |
541541
| [`max-control-nesting`](./RULES_DESCRIPTIONS.md#max-control-nesting) | int (defaults to 5) | Sets restriction for maximum nesting of control structures. | no | no |
542542
| [`comments-density`](./RULES_DESCRIPTIONS.md#comments-density) | int (defaults to 0) | Enforces a minimum comment / code relation | no | no |
543+
| [`file-length-limit`](./RULES_DESCRIPTIONS.md#file-length-limit) | map (optional)| Enforces a maximum number of lines per file | no | no |
543544

544545

545546
## Configurable rules

RULES_DESCRIPTIONS.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ List of all available rules.
3838
- [errorf](#errorf)
3939
- [exported](#exported)
4040
- [file-header](#file-header)
41+
- [file-length-limit](#file-length-limit)
4142
- [flag-parameter](#flag-parameter)
4243
- [function-length](#function-length)
4344
- [function-result-limit](#function-result-limit)
@@ -501,6 +502,23 @@ Example:
501502
arguments = ["This is the text that must appear at the top of source files."]
502503
```
503504

505+
## file-length-limit
506+
507+
_Description_: This rule enforces a maximum number of lines per file, in order to aid in maintainability and reduce complexity.
508+
509+
_Configuration_:
510+
511+
* `max` (int) a maximum number of lines in a file (default 500)
512+
* `skipComments` (bool) ignore lines containing just comments
513+
* `skipBlankLines` (bool) ignore lines made up purely of whitespace
514+
515+
Example:
516+
517+
```toml
518+
[rule.file-length-limit]
519+
arguments = [{max=100,skipComments=true,skipBlankLines=true}]
520+
```
521+
504522
## flag-parameter
505523

506524
_Description_: If a function controls the flow of another by passing it information on what to do, both functions are said to be [control-coupled](https://en.wikipedia.org/wiki/Coupling_(computer_programming)#Procedural_programming).

config/config.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ var allRules = append([]lint.Rule{
9696
&rule.EnforceSliceStyleRule{},
9797
&rule.MaxControlNestingRule{},
9898
&rule.CommentsDensityRule{},
99+
&rule.FileLengthLimitRule{},
99100
}, defaultRules...)
100101

101102
var allFormatters = []lint.Formatter{

rule/file-length-limit.go

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package rule
2+
3+
import (
4+
"bufio"
5+
"bytes"
6+
"fmt"
7+
"go/ast"
8+
"go/token"
9+
"strings"
10+
"sync"
11+
12+
"github.com/mgechev/revive/lint"
13+
)
14+
15+
const defaultFileLengthLimitMax = 500
16+
17+
// FileLengthLimitRule lints the number of lines in a file.
18+
type FileLengthLimitRule struct {
19+
max int
20+
skipComments bool
21+
skipBlankLines bool
22+
sync.Mutex
23+
}
24+
25+
// Apply applies the rule to given file.
26+
func (r *FileLengthLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
27+
r.configure(arguments)
28+
29+
all := 0
30+
blank := 0
31+
scanner := bufio.NewScanner(bytes.NewReader(file.Content()))
32+
for scanner.Scan() {
33+
all++
34+
if len(scanner.Bytes()) == 0 {
35+
blank++
36+
}
37+
}
38+
39+
if err := scanner.Err(); err != nil {
40+
panic(err.Error())
41+
}
42+
43+
lines := all
44+
if r.skipComments {
45+
lines -= countCommentLines(file.AST.Comments)
46+
}
47+
48+
if r.skipBlankLines {
49+
lines -= blank
50+
}
51+
52+
if lines <= r.max {
53+
return nil
54+
}
55+
56+
return []lint.Failure{
57+
{
58+
Category: "code-style",
59+
Confidence: 1,
60+
Position: lint.FailurePosition{
61+
Start: token.Position{
62+
Filename: file.Name,
63+
Line: all,
64+
},
65+
},
66+
Failure: fmt.Sprintf("file length is %d lines, which exceeds the limit of %d", lines, r.max),
67+
},
68+
}
69+
}
70+
71+
func (r *FileLengthLimitRule) configure(arguments lint.Arguments) {
72+
r.Lock()
73+
defer r.Unlock()
74+
75+
if len(arguments) == 0 {
76+
r.max = defaultFileLengthLimitMax
77+
return
78+
}
79+
80+
argKV, ok := arguments[0].(map[string]any)
81+
if !ok {
82+
panic(fmt.Sprintf(`invalid argument to the "file-length-limit" rule. Expecting a k,v map, got %T`, arguments[0]))
83+
}
84+
for k, v := range argKV {
85+
switch k {
86+
case "max":
87+
maxLines, ok := v.(int64)
88+
if !ok || maxLines < 1 {
89+
panic(fmt.Sprintf(`invalid configuration value for max lines in "file-length-limit" rule; need int64 but got %T`, arguments[0]))
90+
}
91+
r.max = int(maxLines)
92+
case "skipComments":
93+
skipComments, ok := v.(bool)
94+
if !ok {
95+
panic(fmt.Sprintf(`invalid configuration value for skip comments in "file-length-limit" rule; need bool but got %T`, arguments[1]))
96+
}
97+
r.skipComments = skipComments
98+
case "skipBlankLines":
99+
skipBlankLines, ok := v.(bool)
100+
if !ok {
101+
panic(fmt.Sprintf(`invalid configuration value for skip blank lines in "file-length-limit" rule; need bool but got %T`, arguments[2]))
102+
}
103+
r.skipBlankLines = skipBlankLines
104+
}
105+
}
106+
}
107+
108+
func (*FileLengthLimitRule) Name() string {
109+
return "file-length-limit"
110+
}
111+
112+
func countCommentLines(comments []*ast.CommentGroup) int {
113+
count := 0
114+
for _, cg := range comments {
115+
for _, comment := range cg.List {
116+
switch comment.Text[1] {
117+
case '/': // single-line comment
118+
count++
119+
case '*': // multi-line comment
120+
count += strings.Count(comment.Text, "\n") + 1
121+
}
122+
}
123+
}
124+
return count
125+
}

test/file-length-limit_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/mgechev/revive/lint"
7+
"github.com/mgechev/revive/rule"
8+
)
9+
10+
func TestFileLengthLimit(t *testing.T) {
11+
testRule(t, "file-length-limit-default", &rule.FileLengthLimitRule{}, &lint.RuleConfig{
12+
Arguments: []any{},
13+
})
14+
testRule(t, "file-length-limit-9", &rule.FileLengthLimitRule{}, &lint.RuleConfig{
15+
Arguments: []any{map[string]any{"max": int64(9)}},
16+
})
17+
testRule(t, "file-length-limit-7-skip-comments", &rule.FileLengthLimitRule{}, &lint.RuleConfig{
18+
Arguments: []any{map[string]any{"max": int64(7), "skipComments": true}},
19+
})
20+
testRule(t, "file-length-limit-6-skip-blank", &rule.FileLengthLimitRule{}, &lint.RuleConfig{
21+
Arguments: []any{map[string]any{"max": int64(6), "skipBlankLines": true}},
22+
})
23+
testRule(t, "file-length-limit-4-skip-comments-skip-blank", &rule.FileLengthLimitRule{}, &lint.RuleConfig{
24+
Arguments: []any{map[string]any{"max": int64(4), "skipComments": true, "skipBlankLines": true}},
25+
})
26+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package fixtures
2+
3+
import "fmt"
4+
5+
// Foo is a function.
6+
func Foo(a, b int) {
7+
fmt.Println("Hello, world!")
8+
}
9+
10+
// MATCH /file length is 5 lines, which exceeds the limit of 4/
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package fixtures
2+
3+
import "fmt"
4+
5+
// Foo is a function.
6+
func Foo(a, b int) {
7+
fmt.Println("Hello, world!")
8+
}
9+
10+
// MATCH /file length is 7 lines, which exceeds the limit of 6/
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package fixtures
2+
3+
import "fmt"
4+
5+
// Foo is a function.
6+
func Foo(a, b int) {
7+
// This
8+
/* is
9+
a
10+
*/
11+
// a comment.
12+
fmt.Println("Hello, world!")
13+
/*
14+
This is
15+
multiline
16+
comment.
17+
*/
18+
}
19+
20+
// MATCH /file length is 8 lines, which exceeds the limit of 7/

testdata/file-length-limit-9.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package fixtures
2+
3+
import "fmt"
4+
5+
// Foo is a function.
6+
func Foo(a, b int) {
7+
fmt.Println("Hello, world!")
8+
}
9+
10+
// MATCH /file length is 10 lines, which exceeds the limit of 9/

0 commit comments

Comments
 (0)