github.com/bingoohuang/pkger@v0.0.0-20210127185155-a71b9df4c4c7/parser/open.go (about)

     1  package parser
     2  
     3  import (
     4  	"encoding/json"
     5  	"go/token"
     6  	"os"
     7  	"path/filepath"
     8  )
     9  
    10  var _ Decl = OpenDecl{}
    11  
    12  type OpenDecl struct {
    13  	file  *File
    14  	pos   token.Position
    15  	value string
    16  }
    17  
    18  func (d OpenDecl) String() string {
    19  	b, _ := json.Marshal(d)
    20  	return string(b)
    21  }
    22  
    23  func (d OpenDecl) MarshalJSON() ([]byte, error) {
    24  	return json.Marshal(map[string]interface{}{
    25  		"type":  "pkger.Open",
    26  		"file":  d.file,
    27  		"pos":   d.pos,
    28  		"value": d.value,
    29  	})
    30  }
    31  
    32  func (d OpenDecl) File() (*File, error) {
    33  	if d.file == nil {
    34  		return nil, os.ErrNotExist
    35  	}
    36  	return d.file, nil
    37  }
    38  
    39  func (d OpenDecl) Position() (token.Position, error) {
    40  	return d.pos, nil
    41  }
    42  
    43  func (d OpenDecl) Value() (string, error) {
    44  	if d.value == "" {
    45  		return "", os.ErrNotExist
    46  	}
    47  	return d.value, nil
    48  }
    49  
    50  func (d OpenDecl) Files(virtual map[string]string) ([]*File, error) {
    51  	if _, ok := virtual[d.value]; ok {
    52  		return nil, nil
    53  	}
    54  
    55  	her := d.file.Here
    56  	pt := d.file.Path
    57  
    58  	fp := filepath.Join(her.Module.Dir, pt.Name)
    59  
    60  	osf, err := os.Stat(fp)
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  
    65  	if osf.IsDir() {
    66  		wd := WalkDecl{
    67  			file:  d.file,
    68  			pos:   d.pos,
    69  			value: d.value,
    70  		}
    71  		return wd.Files(virtual)
    72  	}
    73  
    74  	var files []*File
    75  	files = append(files, d.file)
    76  
    77  	return files, nil
    78  }