/
new.go
40 lines (37 loc) · 834 Bytes
/
new.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
package gofile
import (
"go/parser"
"go/token"
"os"
"github.com/dorenproctor/pkgfmt/cmd/pkg/impt"
"github.com/dorenproctor/pkgfmt/cmd/pkg/pkgpart"
)
func New(filePath string) (GoFile, error) {
gf := GoFile{
FilePath: filePath,
Fns: []pkgpart.PkgPart{},
Vars: []pkgpart.PkgPart{},
Imports: []impt.Impt{},
}
// get body
fileBytes, err := os.ReadFile(filePath)
if err != nil {
return gf, err
}
gf.Body = string(fileBytes)
// get ast
fset := token.NewFileSet()
gf.Ast, err = parser.ParseFile(fset, filePath, nil, parser.ParseComments)
if err != nil {
return gf, err
}
// get package name
if gf.Ast.Name != nil {
gf.PackageName = gf.Ast.Name.Name
}
// load all imports used in file
gf.Imports = impt.LoadImports(gf.Ast)
// load TypeSpecs, Fns, and Vars
gf.loadFromAst()
return gf, nil
}