github.com/bingoohuang/pkger@v0.0.0-20210127185155-a71b9df4c4c7/parser/include.go (about) 1 package parser 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "go/token" 7 "os" 8 "path/filepath" 9 10 "github.com/bingoohuang/pkger/here" 11 ) 12 13 var _ Decl = IncludeDecl{} 14 15 type IncludeDecl struct { 16 file *File 17 pos token.Position 18 value string 19 typ string 20 } 21 22 func NewInclude(her here.Info, inc string) ([]IncludeDecl, error) { 23 pt, err := her.Parse(inc) 24 if err != nil { 25 return nil, err 26 } 27 28 if pt.Pkg != her.ImportPath { 29 her, err = here.Package(pt.Pkg) 30 if err != nil { 31 return nil, err 32 } 33 } 34 35 abs := filepath.Join(her.Module.Dir, pt.Name) 36 37 f := &File{ 38 Abs: abs, 39 Path: pt, 40 Here: her, 41 } 42 43 return []IncludeDecl{ 44 {value: inc, file: f, typ: "pkger.Include"}, 45 {value: inc, file: f, typ: "pkger.Read"}, 46 {value: inc, file: f, typ: "pkger.ReadStr"}, 47 {value: inc, file: f, typ: "pkger.MustRead"}, 48 {value: inc, file: f, typ: "pkger.MustReadStr"}, 49 }, nil 50 } 51 52 func (d IncludeDecl) String() string { 53 return fmt.Sprintf("%s(%q)", d.typ, d.value) 54 } 55 56 func (d IncludeDecl) MarshalJSON() ([]byte, error) { 57 return json.Marshal(map[string]interface{}{ 58 "type": d.typ, 59 "file": d.file, 60 "pos": d.pos, 61 "value": d.value, 62 }) 63 } 64 65 func (d IncludeDecl) File() (*File, error) { 66 if d.file == nil { 67 return nil, os.ErrNotExist 68 } 69 return d.file, nil 70 } 71 72 func (d IncludeDecl) Position() (token.Position, error) { 73 return d.pos, nil 74 } 75 76 func (d IncludeDecl) Value() (string, error) { 77 if d.value == "" { 78 return "", os.ErrNotExist 79 } 80 return d.value, nil 81 } 82 83 func (d IncludeDecl) Files(virtual map[string]string) ([]*File, error) { 84 od := OpenDecl{ 85 file: d.file, 86 pos: d.pos, 87 value: d.value, 88 } 89 90 return od.Files(virtual) 91 }