fileindir.go 1.7 KB

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