fs.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package decoder
  2. import (
  3. "errors"
  4. "io/fs"
  5. "os"
  6. "path/filepath"
  7. )
  8. var (
  9. ErrNotDir = errors.New("not a directory")
  10. )
  11. type FSPluginDecoder struct {
  12. PluginDecoder
  13. // root directory of the plugin
  14. root string
  15. fs fs.FS
  16. }
  17. func NewFSPluginDecoder(root string) (*FSPluginDecoder, error) {
  18. decoder := &FSPluginDecoder{
  19. root: root,
  20. }
  21. err := decoder.Open()
  22. if err != nil {
  23. return nil, err
  24. }
  25. return decoder, nil
  26. }
  27. func (d *FSPluginDecoder) Open() error {
  28. d.fs = os.DirFS(d.root)
  29. // try to stat the root directory
  30. s, err := os.Stat(d.root)
  31. if err != nil {
  32. return err
  33. }
  34. if !s.IsDir() {
  35. return ErrNotDir
  36. }
  37. return nil
  38. }
  39. func (d *FSPluginDecoder) Walk(fn func(filename string, dir string) error) error {
  40. return filepath.Walk(d.root, func(path string, info fs.FileInfo, err error) error {
  41. if err != nil {
  42. return err
  43. }
  44. return fn(info.Name(), filepath.Dir(path))
  45. })
  46. }
  47. func (d *FSPluginDecoder) Close() error {
  48. return nil
  49. }
  50. func (d *FSPluginDecoder) ReadFile(filename string) ([]byte, error) {
  51. return os.ReadFile(filepath.Join(d.root, filename))
  52. }
  53. func (d *FSPluginDecoder) Signature() (string, error) {
  54. return "", nil
  55. }
  56. func (d *FSPluginDecoder) CreateTime() (int64, error) {
  57. return 0, nil
  58. }