fileindir.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. }, watchMetaForAction(act))
  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. }, watchMetaForAction(act))
  27. }(action, dirname)
  28. }
  29. }
  30. }
  31. func watchMetaForAction(action *config.Action) filehelper.WatchMeta {
  32. return filehelper.WatchMeta{
  33. ActionID: action.ID,
  34. ActionTitle: action.Title,
  35. ConfigFile: action.SourceFile,
  36. }
  37. }
  38. func scheduleExec(action *config.Action, cfg *config.Config, ex *executor.Executor, path string) {
  39. args := map[string]string{
  40. "filepath": path,
  41. "filename": filepath.Base(path),
  42. "filedir": filepath.Dir(path),
  43. "fileext": filepath.Ext(path),
  44. }
  45. if stat, err := os.Stat(path); err == nil {
  46. args["filesizebytes"] = fmt.Sprintf("%v", stat.Size())
  47. args["filemode"] = fmt.Sprintf("%#o", stat.Mode())
  48. args["filemtime"] = fmt.Sprintf("%v", stat.ModTime())
  49. args["fileisdir"] = fmt.Sprintf("%v", stat.IsDir())
  50. }
  51. fmt.Printf("%+v", args)
  52. req := &executor.ExecutionRequest{
  53. Binding: ex.FindBindingWithNoEntity(action),
  54. Cfg: cfg,
  55. Tags: []string{},
  56. Arguments: args,
  57. AuthenticatedUser: auth.UserFromSystem(cfg, "fileindir"),
  58. }
  59. ex.ExecRequest(req)
  60. }