summaryrefslogtreecommitdiffstats
path: root/build/codeformat/formatimports.go
blob: c9fc2a27b4ab7a52c8828d8d28eb885f79c1a69f (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package codeformat

import (
	"bytes"
	"errors"
	"io"
	"os"
	"sort"
	"strings"
)

var importPackageGroupOrders = map[string]int{
	"":                     1, // internal
	"code.gitea.io/gitea/": 2,
}

var errInvalidCommentBetweenImports = errors.New("comments between imported packages are invalid, please move comments to the end of the package line")

var (
	importBlockBegin = []byte("\nimport (\n")
	importBlockEnd   = []byte("\n)")
)

type importLineParsed struct {
	group   string
	pkg     string
	content string
}

func parseImportLine(line string) (*importLineParsed, error) {
	il := &importLineParsed{content: line}
	p1 := strings.IndexRune(line, '"')
	if p1 == -1 {
		return nil, errors.New("invalid import line: " + line)
	}
	p1++
	p := strings.IndexRune(line[p1:], '"')
	if p == -1 {
		return nil, errors.New("invalid import line: " + line)
	}
	p2 := p1 + p
	il.pkg = line[p1:p2]

	pDot := strings.IndexRune(il.pkg, '.')
	pSlash := strings.IndexRune(il.pkg, '/')
	if pDot != -1 && pDot < pSlash {
		il.group = "domain-package"
	}
	for groupName := range importPackageGroupOrders {
		if groupName == "" {
			continue // skip internal
		}
		if strings.HasPrefix(il.pkg, groupName) {
			il.group = groupName
		}
	}
	return il, nil
}

type (
	importLineGroup    []*importLineParsed
	importLineGroupMap map[string]importLineGroup
)

func formatGoImports(contentBytes []byte) ([]byte, error) {
	p1 := bytes.Index(contentBytes, importBlockBegin)
	if p1 == -1 {
		return nil, nil
	}
	p1 += len(importBlockBegin)
	p := bytes.Index(contentBytes[p1:], importBlockEnd)
	if p == -1 {
		return nil, nil
	}
	p2 := p1 + p

	importGroups := importLineGroupMap{}
	r := bytes.NewBuffer(contentBytes[p1:p2])
	eof := false
	for !eof {
		line, err := r.ReadString('\n')
		eof = err == io.EOF
		if err != nil && !eof {
			return nil, err
		}
		line = strings.TrimSpace(line)
		if line != "" {
			if strings.HasPrefix(line, "//") || strings.HasPrefix(line, "/*") {
				return nil, errInvalidCommentBetweenImports
			}
			importLine, err := parseImportLine(line)
			if err != nil {
				return nil, err
			}
			importGroups[importLine.group] = append(importGroups[importLine.group], importLine)
		}
	}

	var groupNames []string
	for groupName, importLines := range importGroups {
		groupNames = append(groupNames, groupName)
		sort.Slice(importLines, func(i, j int) bool {
			return strings.Compare(importLines[i].pkg, importLines[j].pkg) < 0
		})
	}

	sort.Slice(groupNames, func(i, j int) bool {
		n1 := groupNames[i]
		n2 := groupNames[j]
		o1 := importPackageGroupOrders[n1]
		o2 := importPackageGroupOrders[n2]
		if o1 != 0 && o2 != 0 {
			return o1 < o2
		}
		if o1 == 0 && o2 == 0 {
			return strings.Compare(n1, n2) < 0
		}
		return o1 != 0
	})

	formattedBlock := bytes.Buffer{}
	for _, groupName := range groupNames {
		hasNormalImports := false
		hasDummyImports := false
		// non-dummy import comes first
		for _, importLine := range importGroups[groupName] {
			if strings.HasPrefix(importLine.content, "_") {
				hasDummyImports = true
			} else {
				formattedBlock.WriteString("\t" + importLine.content + "\n")
				hasNormalImports = true
			}
		}
		// dummy (_ "pkg") comes later
		if hasDummyImports {
			if hasNormalImports {
				formattedBlock.WriteString("\n")
			}
			for _, importLine := range importGroups[groupName] {
				if strings.HasPrefix(importLine.content, "_") {
					formattedBlock.WriteString("\t" + importLine.content + "\n")
				}
			}
		}
		formattedBlock.WriteString("\n")
	}
	formattedBlockBytes := bytes.TrimRight(formattedBlock.Bytes(), "\n")

	var formattedBytes []byte
	formattedBytes = append(formattedBytes, contentBytes[:p1]...)
	formattedBytes = append(formattedBytes, formattedBlockBytes...)
	formattedBytes = append(formattedBytes, contentBytes[p2:]...)
	return formattedBytes, nil
}

// FormatGoImports format the imports by our rules (see unit tests)
func FormatGoImports(file string, doWriteFile bool) error {
	f, err := os.Open(file)
	if err != nil {
		return err
	}
	var contentBytes []byte
	{
		defer f.Close()
		contentBytes, err = io.ReadAll(f)
		if err != nil {
			return err
		}
	}
	formattedBytes, err := formatGoImports(contentBytes)
	if err != nil {
		return err
	}
	if formattedBytes == nil {
		return nil
	}
	if bytes.Equal(contentBytes, formattedBytes) {
		return nil
	}

	if doWriteFile {
		f, err = os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, 0o644)
		if err != nil {
			return err
		}
		defer f.Close()
		_, err = f.Write(formattedBytes)
		return err
	}

	return err
}