fs.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package decoder
  2. import (
  3. "errors"
  4. "io/fs"
  5. "os"
  6. "path"
  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 fs.WalkDir(d.fs, ".", func(root_path string, d fs.DirEntry, err error) error {
  41. if err != nil {
  42. return err
  43. }
  44. if d.IsDir() {
  45. return nil
  46. }
  47. return fn(root_path, d.Name())
  48. })
  49. }
  50. func (d *FSPluginDecoder) Close() error {
  51. return nil
  52. }
  53. func (d *FSPluginDecoder) ReadFile(filename string) ([]byte, error) {
  54. return os.ReadFile(path.Join(d.root, filename))
  55. }
  56. func (d *FSPluginDecoder) Signature() (string, error) {
  57. return "", nil
  58. }
  59. func (d *FSPluginDecoder) CreateTime() (int64, error) {
  60. return 0, nil
  61. }