-
Notifications
You must be signed in to change notification settings - Fork 1
/
write.go
66 lines (54 loc) · 1.52 KB
/
write.go
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
// Copyright 2020 murosan. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gollect
import (
"fmt"
"go/ast"
"go/format"
"io"
)
// Write writes filtered and formatted code to io.Writer.
func Write(w io.Writer, program *Program) error {
fset, dset := program.FileSet(), program.DeclSet()
iset, pset := program.ImportSet(), program.PackageSet()
// get head of main package's ast files
// treat this as base ast
mainPackage := pset["main"]
main := mainPackage.files[0]
filter := NewFilter(dset, mainPackage)
// delete unused codes and all imports from base ast
main.Decls = filter.Decls(main.Decls)
filter.PackageSelectorExpr(main)
// build new import decl and push it to head of decls
if ispec := iset.ToDecl(); len(ispec.Specs) != 0 {
main.Decls = append([]ast.Decl{ispec}, main.Decls...)
}
if err := format.Node(w, fset, main); err != nil {
return fmt.Errorf("format: %w", err)
}
for path, pkg := range pset {
for _, file := range pkg.files {
if file == main {
continue
}
filter := NewFilter(dset, pset[path])
decls := filter.Decls(file.Decls)
for _, d := range decls {
filter.PackageSelectorExpr(d)
}
if len(decls) != 0 {
if _, err := w.Write([]byte("\n")); err != nil {
return err
}
if err := format.Node(w, fset, decls); err != nil {
return fmt.Errorf("format: %w", err)
}
if _, err := w.Write([]byte("\n")); err != nil {
return err
}
}
}
}
return nil
}