1
0

node.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package taskfile
  2. import (
  3. "context"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "time"
  8. "github.com/go-task/task/v3/errors"
  9. "github.com/go-task/task/v3/internal/experiments"
  10. "github.com/go-task/task/v3/internal/logger"
  11. )
  12. type Node interface {
  13. Read(ctx context.Context) ([]byte, error)
  14. Parent() Node
  15. Location() string
  16. Dir() string
  17. Remote() bool
  18. ResolveEntrypoint(entrypoint string) (string, error)
  19. ResolveDir(dir string) (string, error)
  20. FilenameAndLastDir() (string, string)
  21. }
  22. func NewRootNode(
  23. l *logger.Logger,
  24. entrypoint string,
  25. dir string,
  26. insecure bool,
  27. timeout time.Duration,
  28. ) (Node, error) {
  29. dir = getDefaultDir(entrypoint, dir)
  30. // If the entrypoint is "-", we read from stdin
  31. if entrypoint == "-" {
  32. return NewStdinNode(dir)
  33. }
  34. return NewNode(l, entrypoint, dir, insecure, timeout)
  35. }
  36. func NewNode(
  37. l *logger.Logger,
  38. entrypoint string,
  39. dir string,
  40. insecure bool,
  41. timeout time.Duration,
  42. opts ...NodeOption,
  43. ) (Node, error) {
  44. var node Node
  45. var err error
  46. switch getScheme(entrypoint) {
  47. case "http", "https":
  48. node, err = NewHTTPNode(l, entrypoint, dir, insecure, timeout, opts...)
  49. default:
  50. // If no other scheme matches, we assume it's a file
  51. node, err = NewFileNode(l, entrypoint, dir, opts...)
  52. }
  53. if node.Remote() && !experiments.RemoteTaskfiles.Enabled {
  54. return nil, errors.New("task: Remote taskfiles are not enabled. You can read more about this experiment and how to enable it at https://taskfile.dev/experiments/remote-taskfiles")
  55. }
  56. return node, err
  57. }
  58. func getScheme(uri string) string {
  59. if i := strings.Index(uri, "://"); i != -1 {
  60. return uri[:i]
  61. }
  62. return ""
  63. }
  64. func getDefaultDir(entrypoint, dir string) string {
  65. // If the entrypoint and dir are empty, we default the directory to the current working directory
  66. if dir == "" {
  67. if entrypoint == "" {
  68. wd, err := os.Getwd()
  69. if err != nil {
  70. return ""
  71. }
  72. dir = wd
  73. }
  74. return dir
  75. }
  76. // If the directory is set, ensure it is an absolute path
  77. var err error
  78. dir, err = filepath.Abs(dir)
  79. if err != nil {
  80. return ""
  81. }
  82. return dir
  83. }