Skip to content

Commit

Permalink
Fix checking for not gofmt-ed files.
Browse files Browse the repository at this point in the history
  • Loading branch information
Denis Krivak committed Dec 2, 2020
1 parent a45b0ae commit 22fdad2
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 7 deletions.
25 changes: 18 additions & 7 deletions getters.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package godot

import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/token"
"io/ioutil"
"strings"
)

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

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

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

// readFile reads file and returns it's lines as strings.
func readFile(file *ast.File, fset *token.FileSet) ([]string, error) {
fname := fset.File(file.Package)
f, err := ioutil.ReadFile(fname.Name())
if err != nil {
return nil, err
}
return strings.Split(string(f), "\n"), nil
}

// setDecl sets `decl` flag to comments which are declaration comments.
func setDecl(comments, decl []comment) {
for _, d := range decl {
Expand Down
8 changes: 8 additions & 0 deletions testdata/check/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ import (
"unsafe"
)

// Not gofmt-ed code [PASS].
const (
one = 1

two = 2

)

//args: tagged comment without period [PASS]

// #tag hashtag comment without period [PASS]
Expand Down
8 changes: 8 additions & 0 deletions testdata/get/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ package example
// Import comment [DECL].
import "fmt"

// Not gofmt-ed code [DECL].
const (
one = 1

two = 2

)

// Top level one-line comment [TOP].

// Top level
Expand Down

0 comments on commit 22fdad2

Please sign in to comment.