fileindir.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package onfileindir
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "github.com/OliveTin/OliveTin/internal/auth"
  7. "github.com/OliveTin/OliveTin/internal/config"
  8. "github.com/OliveTin/OliveTin/internal/executor"
  9. "github.com/OliveTin/OliveTin/internal/filehelper"
  10. )
  11. func WatchFilesInDirectory(cfg *config.Config, ex *executor.Executor) {
  12. for _, action := range cfg.Actions {
  13. for _, dirname := range action.ExecOnFileCreatedInDir {
  14. go func(act *config.Action, dir string) {
  15. filehelper.WatchDirectoryCreate(dir, func(filename string) {
  16. scheduleExec(act, cfg, ex, filename)
  17. })
  18. }(action, dirname)
  19. }
  20. for _, dirname := range action.ExecOnFileChangedInDir {
  21. // Pass values into anonymous function because of this issue
  22. // https://github.com/OliveTin/OliveTin/issues/503
  23. go func(act *config.Action, dir string) {
  24. filehelper.WatchDirectoryWrite(dir, func(filename string) {
  25. scheduleExec(act, cfg, ex, filename)
  26. })
  27. }(action, dirname)
  28. }
  29. }
  30. }
  31. func scheduleExec(action *config.Action, cfg *config.Config, ex *executor.Executor, path string) {
  32. args := map[string]string{
  33. "filepath": path,
  34. "filename": filepath.Base(path),
  35. "filedir": filepath.Dir(path),
  36. "fileext": filepath.Ext(path),
  37. }
  38. if stat, err := os.Stat(path); err == nil {
  39. args["filesizebytes"] = fmt.Sprintf("%v", stat.Size())
  40. args["filemode"] = fmt.Sprintf("%#o", stat.Mode())
  41. args["filemtime"] = fmt.Sprintf("%v", stat.ModTime())
  42. args["fileisdir"] = fmt.Sprintf("%v", stat.IsDir())
  43. }
  44. fmt.Printf("%+v", args)
  45. req := &executor.ExecutionRequest{
  46. Binding: ex.FindBindingWithNoEntity(action),
  47. Cfg: cfg,
  48. Tags: []string{},
  49. Arguments: args,
  50. AuthenticatedUser: auth.UserFromSystem(cfg, "fileindir"),
  51. }
  52. ex.ExecRequest(req)
  53. }