Skip to content

Commit 22fdad2

Browse files
author
Denis Krivak
committed
Fix checking for not gofmt-ed files.
1 parent a45b0ae commit 22fdad2

File tree

3 files changed

+34
-7
lines changed

3 files changed

+34
-7
lines changed

getters.go

+18-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
package godot
22

33
import (
4-
"bytes"
54
"fmt"
65
"go/ast"
7-
"go/format"
86
"go/token"
7+
"io/ioutil"
98
"strings"
109
)
1110

@@ -20,12 +19,14 @@ func getComments(file *ast.File, fset *token.FileSet, scope Scope) ([]comment, e
2019
return nil, nil
2120
}
2221

23-
// Render AST representation to a string
24-
var buf bytes.Buffer
25-
if err := format.Node(&buf, fset, file); err != nil {
26-
return nil, fmt.Errorf("render file: %v", err)
22+
// Read original file. This is necessary for making a replacements for
23+
// inline comments. I couldn't find a better way to get original line
24+
// with code and comment without reading the file. Function `Format`
25+
// from "go/format" won't help here if the original file is not gofmt-ed.
26+
lines, err := readFile(file, fset)
27+
if err != nil {
28+
return nil, fmt.Errorf("read file: %v", err)
2729
}
28-
lines := strings.Split(buf.String(), "\n")
2930

3031
// Check consistency to avoid checking index in each function
3132
lastComment := file.Comments[len(file.Comments)-1]
@@ -188,6 +189,16 @@ func getText(comment *ast.CommentGroup) (s string) {
188189
return s[:len(s)-1] // trim last "\n"
189190
}
190191

192+
// readFile reads file and returns it's lines as strings.
193+
func readFile(file *ast.File, fset *token.FileSet) ([]string, error) {
194+
fname := fset.File(file.Package)
195+
f, err := ioutil.ReadFile(fname.Name())
196+
if err != nil {
197+
return nil, err
198+
}
199+
return strings.Split(string(f), "\n"), nil
200+
}
201+
191202
// setDecl sets `decl` flag to comments which are declaration comments.
192203
func setDecl(comments, decl []comment) {
193204
for _, d := range decl {

testdata/check/main.go

+8
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ import (
1616
"unsafe"
1717
)
1818

19+
// Not gofmt-ed code [PASS].
20+
const (
21+
one = 1
22+
23+
two = 2
24+
25+
)
26+
1927
//args: tagged comment without period [PASS]
2028

2129
// #tag hashtag comment without period [PASS]

testdata/get/main.go

+8
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,14 @@ package example
44
// Import comment [DECL].
55
import "fmt"
66

7+
// Not gofmt-ed code [DECL].
8+
const (
9+
one = 1
10+
11+
two = 2
12+
13+
)
14+
715
// Top level one-line comment [TOP].
816

917
// Top level

0 commit comments

Comments
 (0)