watch_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //go:build watch
  2. // +build watch
  3. package task_test
  4. import (
  5. "bytes"
  6. "context"
  7. "fmt"
  8. "os"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. "github.com/go-task/task/v3"
  15. "github.com/go-task/task/v3/internal/filepathext"
  16. "github.com/go-task/task/v3/taskfile/ast"
  17. )
  18. func TestFileWatcherInterval(t *testing.T) {
  19. const dir = "testdata/watcher_interval"
  20. expectedOutput := strings.TrimSpace(`
  21. task: Started watching for tasks: default
  22. task: [default] echo "Hello, World!"
  23. Hello, World!
  24. task: [default] echo "Hello, World!"
  25. Hello, World!
  26. `)
  27. var buff bytes.Buffer
  28. e := &task.Executor{
  29. Dir: dir,
  30. Stdout: &buff,
  31. Stderr: &buff,
  32. Watch: true,
  33. }
  34. require.NoError(t, e.Setup())
  35. buff.Reset()
  36. err := os.MkdirAll(filepathext.SmartJoin(dir, "src"), 0755)
  37. require.NoError(t, err)
  38. err = os.WriteFile(filepathext.SmartJoin(dir, "src/a"), []byte("test"), 0644)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. ctx := context.Background()
  43. ctx, cancel := context.WithCancel(ctx)
  44. go func(ctx context.Context) {
  45. for {
  46. select {
  47. case <-ctx.Done():
  48. return
  49. default:
  50. err := e.Run(ctx, &ast.Call{Task: "default"})
  51. if err != nil {
  52. return
  53. }
  54. }
  55. }
  56. }(ctx)
  57. time.Sleep(10 * time.Millisecond)
  58. err = os.WriteFile(filepathext.SmartJoin(dir, "src/a"), []byte("test updated"), 0644)
  59. if err != nil {
  60. t.Fatal(err)
  61. }
  62. time.Sleep(700 * time.Millisecond)
  63. cancel()
  64. assert.Equal(t, expectedOutput, strings.TrimSpace(buff.String()))
  65. buff.Reset()
  66. err = os.RemoveAll(filepathext.SmartJoin(dir, ".task"))
  67. require.NoError(t, err)
  68. err = os.RemoveAll(filepathext.SmartJoin(dir, "src"))
  69. require.NoError(t, err)
  70. }
  71. func TestShouldIgnoreFile(t *testing.T) {
  72. tt := []struct {
  73. path string
  74. expect bool
  75. }{
  76. {"/.git/hooks", true},
  77. {"/.github/workflows/build.yaml", false},
  78. }
  79. for k, ct := range tt {
  80. ct := ct
  81. t.Run(fmt.Sprintf("ignore - %d", k), func(t *testing.T) {
  82. t.Parallel()
  83. require.Equal(t, task.ShouldIgnoreFile(ct.path), ct.expect)
  84. })
  85. }
  86. }