pkger/parser/walk.go

103 lines
1.6 KiB
Go
Raw Normal View History

2019-10-21 17:27:04 +03:00
package parser
import (
2019-10-22 21:50:48 +03:00
"encoding/json"
2019-10-21 17:27:04 +03:00
"go/token"
"os"
"path/filepath"
"strings"
"github.com/markbates/pkger/here"
)
var _ Decl = WalkDecl{}
type WalkDecl struct {
file *File
pos token.Position
2019-10-21 17:27:04 +03:00
value string
}
2019-10-23 20:19:39 +03:00
func (d WalkDecl) String() string {
b, _ := json.Marshal(d)
return string(b)
}
2019-10-22 21:50:48 +03:00
func (d WalkDecl) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{
"type": "pkger.Walk",
"file": d.file,
"pos": d.pos,
"value": d.value,
})
}
2019-10-21 17:27:04 +03:00
func (d WalkDecl) File() (*File, error) {
if d.file == nil {
return nil, os.ErrNotExist
}
return d.file, nil
}
func (d WalkDecl) Position() (token.Position, error) {
2019-10-21 17:27:04 +03:00
return d.pos, nil
}
func (d WalkDecl) Value() (string, error) {
if d.value == "" {
return "", os.ErrNotExist
}
return d.value, nil
}
2019-10-23 20:19:39 +03:00
func (d WalkDecl) Files(virtual map[string]string) ([]*File, error) {
var files []*File
her, err := here.Dir(filepath.Dir(d.pos.Filename))
2019-10-21 17:27:04 +03:00
if err != nil {
return nil, err
}
pt, err := her.Parse(d.value)
2019-10-21 17:27:04 +03:00
if err != nil {
return nil, err
}
root := filepath.Join(her.Dir, pt.Name)
2019-10-21 17:27:04 +03:00
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
her, err = here.Dir(path)
if err != nil {
return err
2019-10-23 20:19:39 +03:00
}
}
2019-10-21 17:27:04 +03:00
pt, err := her.Parse(path)
2019-10-21 17:27:04 +03:00
if err != nil {
return err
}
n := strings.TrimPrefix(path, her.Dir)
if _, ok := virtual[n]; ok {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
2019-10-21 17:27:04 +03:00
files = append(files, &File{
Abs: path,
Path: pt,
Here: her,
2019-10-21 17:27:04 +03:00
})
return nil
})
return files, err
}