my CMS/Blog engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

watch.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. /*
  3. * This is freesofware under 2-clause BSD license, See LICENSE file
  4. * (C)opyright 2018,2019 juju
  5. */
  6. import (
  7. "time"
  8. "github.com/radovskyb/watcher"
  9. )
  10. const (
  11. // Sometimes many events can be triggered in succession for the same file
  12. // (i.e. Create followed by Modify, etc.). No need to rush to generate
  13. // the HTML, just wait for it to calm down before processing.
  14. watchEventDelay = 1 * time.Second
  15. )
  16. var (
  17. fwatcher *watcher.Watcher
  18. tempo = make(chan time.Time, 100)
  19. generate = make(chan bool, 1)
  20. )
  21. // start watch and loop till the end of time
  22. func beginWatch(paths ...string) {
  23. fwatcher = watcher.New()
  24. fwatcher.SetMaxEvents(1)
  25. fwatcher.FilterOps(watcher.Rename, watcher.Move, watcher.Create, watcher.Remove, watcher.Write)
  26. fwatcher.IgnoreHiddenFiles(true)
  27. fwatcher.Ignore("examples")
  28. go fwHandler()
  29. // Start by rebuild - and launch - your program
  30. rebuild()
  31. // The root directory for source to watch
  32. for _, path := range paths {
  33. if err := fwatcher.AddRecursive(path); err != nil {
  34. ERROR(err.Error())
  35. }
  36. }
  37. // start watch source change, will loop
  38. DEBUG("Begin file watch")
  39. if err := fwatcher.Start(watchEventDelay); err != nil {
  40. FATAL(err.Error())
  41. }
  42. }
  43. // Handle watch events such as file change, error or exit
  44. func fwHandler() {
  45. for {
  46. select {
  47. case event := <-fwatcher.Event:
  48. DEBUG("Change :%v", event) // Print the event's info.
  49. go rebuild()
  50. case err := <-fwatcher.Error:
  51. WARN(err.Error())
  52. case <-fwatcher.Closed:
  53. return
  54. }
  55. }
  56. }
  57. func rebuild() {
  58. DEBUG("REBUILD...")
  59. generateSite()
  60. }