fs.go 1.7 KB

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