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

     1  package parser
     2  
     3  import (
     4  	"encoding/json"
     5  	"go/token"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	"github.com/bingoohuang/pkger/here"
    11  )
    12  
    13  var _ Decl = WalkDecl{}
    14  
    15  type WalkDecl struct {
    16  	file  *File
    17  	pos   token.Position
    18  	value string
    19  }
    20  
    21  func (d WalkDecl) String() string {
    22  	b, _ := json.Marshal(d)
    23  	return string(b)
    24  }
    25  
    26  func (d WalkDecl) MarshalJSON() ([]byte, error) {
    27  	return json.Marshal(map[string]interface{}{
    28  		"type":  "pkger.Walk",
    29  		"file":  d.file,
    30  		"pos":   d.pos,
    31  		"value": d.value,
    32  	})
    33  }
    34  
    35  func (d WalkDecl) File() (*File, error) {
    36  	if d.file == nil {
    37  		return nil, os.ErrNotExist
    38  	}
    39  	return d.file, nil
    40  }
    41  
    42  func (d WalkDecl) Position() (token.Position, error) {
    43  	return d.pos, nil
    44  }
    45  
    46  func (d WalkDecl) Value() (string, error) {
    47  	if d.value == "" {
    48  		return "", os.ErrNotExist
    49  	}
    50  	return d.value, nil
    51  }
    52  
    53  func (d WalkDecl) Files(virtual map[string]string) ([]*File, error) {
    54  	var files []*File
    55  
    56  	her := d.file.Here
    57  	pt := d.file.Path
    58  
    59  	root := filepath.Join(her.Module.Dir, pt.Name)
    60  
    61  	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
    62  		if err != nil {
    63  			return err
    64  		}
    65  
    66  		if info.IsDir() {
    67  			her, err = here.Dir(path)
    68  			if err != nil {
    69  				return err
    70  			}
    71  		}
    72  
    73  		n := strings.TrimPrefix(path, her.Module.Dir)
    74  
    75  		pt, err := her.Parse(n)
    76  		if err != nil {
    77  			return err
    78  		}
    79  
    80  		if _, ok := virtual[n]; ok {
    81  			if info.IsDir() {
    82  				return filepath.SkipDir
    83  			}
    84  			return nil
    85  		}
    86  
    87  		files = append(files, &File{
    88  			Abs:  path,
    89  			Path: pt,
    90  			Here: her,
    91  		})
    92  		return nil
    93  	})
    94  
    95  	return files, err
    96  }