Skip to content

Commit 0561d17

Browse files
authored
Merge pull request #1438 from eklatzer/ek/unused-imports-issue-1279
Add imports processing when formating source files to remove unused imports
2 parents 4e7be9c + 19d9999 commit 0561d17

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

boilingcore/output.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414

1515
"github.com/friendsofgo/errors"
1616
"github.com/volatiletech/sqlboiler/v4/importers"
17+
"golang.org/x/tools/imports"
1718
)
1819

1920
// Copied from the go source
@@ -269,9 +270,15 @@ func executeTemplate(buf *bytes.Buffer, t *template.Template, name string, data
269270
}
270271

271272
func formatBuffer(buf *bytes.Buffer) ([]byte, error) {
272-
output, err := format.Source(buf.Bytes())
273+
// format and process imports to remove unused ones
274+
src, err := imports.Process("", buf.Bytes(), nil /* options */)
273275
if err == nil {
274-
return output, nil
276+
var output []byte
277+
// format the output
278+
output, err = format.Source(src)
279+
if err == nil {
280+
return output, nil
281+
}
275282
}
276283

277284
matches := rgxSyntaxError.FindStringSubmatch(err.Error())

boilingcore/output_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,44 @@ func TestFormatBuffer(t *testing.T) {
7070
}
7171
}
7272

73+
func TestFormatBufferWithUnusedImports(t *testing.T) {
74+
t.Parallel()
75+
76+
src := `
77+
package main
78+
79+
import (
80+
"fmt"
81+
"os"
82+
"strings"
83+
)
84+
85+
func main() {
86+
fmt.Println("Hello, World!")
87+
}
88+
`
89+
90+
buf := &bytes.Buffer{}
91+
fmt.Fprint(buf, src)
92+
93+
got, err := formatBuffer(buf)
94+
if err != nil {
95+
t.Error(err)
96+
}
97+
98+
// expect strings import to be removed
99+
var importsToBeRemoved = []string{"os", "strings"}
100+
for _, imp := range importsToBeRemoved {
101+
if strings.Contains(string(got), imp) {
102+
t.Errorf("import %s should be removed", imp)
103+
}
104+
}
105+
106+
if !strings.Contains(string(got), "fmt") {
107+
t.Error("fmt import should be present")
108+
}
109+
}
110+
73111
func TestOutputFilenameParts(t *testing.T) {
74112
t.Parallel()
75113

testdata/psql_test_schema.sql

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -455,3 +455,8 @@ CREATE TABLE "User" (
455455

456456
PRIMARY KEY ("id")
457457
);
458+
459+
-- Create view that joins jets and pilots
460+
-- https://github.com/volatiletech/sqlboiler/issues/1279
461+
CREATE OR REPLACE VIEW jets_pilots AS SELECT jets.id AS jet_id, jets.name as name, pilots.name AS pilot_name FROM jets AS jets LEFT JOIN pilots AS pilots ON pilots.id=jets.pilot_id;
462+

0 commit comments

Comments
 (0)