pkger/parser/file.go

57 lines
893 B
Go
Raw Normal View History

2019-08-01 19:03:12 +03:00
package parser
import (
2019-10-21 17:27:04 +03:00
"encoding/json"
2019-08-01 19:03:12 +03:00
"go/ast"
"go/parser"
"go/token"
"io"
"io/ioutil"
2019-10-21 17:27:04 +03:00
"github.com/markbates/pkger/here"
2019-08-01 19:03:12 +03:00
)
2019-10-21 17:27:04 +03:00
type File struct {
Abs string // full path on disk to file
Path here.Path
Here here.Info
}
func (f File) String() string {
b, _ := json.MarshalIndent(f, "", " ")
return string(b)
}
2019-08-01 19:06:50 +03:00
type parsedFile struct {
2019-08-01 19:03:12 +03:00
File string
FileSet *token.FileSet
Ast *ast.File
}
2019-08-01 19:06:50 +03:00
// parseFileMode ...
func parseFileMode(f string, mode parser.Mode) (parsedFile, error) {
pf := parsedFile{
2019-08-01 19:03:12 +03:00
File: f,
FileSet: token.NewFileSet(),
}
b, err := ioutil.ReadFile(f)
if err != nil {
return pf, err
}
src := string(b)
pff, err := parser.ParseFile(pf.FileSet, f, src, mode)
2019-10-16 17:20:02 +03:00
if err != nil && err != io.EOF {
2019-08-01 19:03:12 +03:00
return pf, err
}
pf.Ast = pff
return pf, nil
}
2019-08-01 19:06:50 +03:00
// parseFile ...
func parseFile(f string) (parsedFile, error) {
return parseFileMode(f, 0)
2019-08-01 19:03:12 +03:00
}