aboutsummaryrefslogtreecommitdiff
path: root/formatter.go
blob: 7b05b703b539241acc9e16382776952c3ecca849 (plain) (blame)
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
package main

import (
	"go/format"
	"go/parser"
	"go/token"
)

type CommentMode int

const (
	CommentsFollow CommentMode = iota
	CommentsPrecede
	CommentsStandalone
)

type Formatter struct {
	CommentMode CommentMode
}

type lineInformation struct {
	statementType string
	isTopLevel    bool
	isScoped      bool
	isStartLine   bool
}

func (f *Formatter) Format(source []byte) ([]byte, error) {
	formattedSource, err := format.Source(source)

	if err != nil {
		return nil, err
	}

	tokenFileSet := token.NewFileSet()
	parsedFile, err := parser.ParseFile(tokenFileSet, "", formattedSource, parser.ParseComments)

	if err != nil {
		return nil, err
	}

	lineInformationMap := f.buildLineInfo(tokenFileSet, parsedFile)

	return f.rewrite(formattedSource, lineInformationMap), nil
}