reader.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package taskfile
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "sync"
  7. "time"
  8. "github.com/dominikbraun/graph"
  9. "golang.org/x/sync/errgroup"
  10. "gopkg.in/yaml.v3"
  11. "github.com/go-task/task/v3/errors"
  12. "github.com/go-task/task/v3/internal/compiler"
  13. "github.com/go-task/task/v3/internal/filepathext"
  14. "github.com/go-task/task/v3/internal/logger"
  15. "github.com/go-task/task/v3/internal/templater"
  16. "github.com/go-task/task/v3/taskfile/ast"
  17. )
  18. const (
  19. taskfileUntrustedPrompt = `The task you are attempting to run depends on the remote Taskfile at %q.
  20. --- Make sure you trust the source of this Taskfile before continuing ---
  21. Continue?`
  22. taskfileChangedPrompt = `The Taskfile at %q has changed since you last used it!
  23. --- Make sure you trust the source of this Taskfile before continuing ---
  24. Continue?`
  25. )
  26. // A Reader will recursively read Taskfiles from a given source using a directed
  27. // acyclic graph (DAG).
  28. type Reader struct {
  29. graph *ast.TaskfileGraph
  30. node Node
  31. insecure bool
  32. download bool
  33. offline bool
  34. timeout time.Duration
  35. tempDir string
  36. logger *logger.Logger
  37. promptMutex sync.Mutex
  38. }
  39. func NewReader(
  40. node Node,
  41. insecure bool,
  42. download bool,
  43. offline bool,
  44. timeout time.Duration,
  45. tempDir string,
  46. logger *logger.Logger,
  47. ) *Reader {
  48. return &Reader{
  49. graph: ast.NewTaskfileGraph(),
  50. node: node,
  51. insecure: insecure,
  52. download: download,
  53. offline: offline,
  54. timeout: timeout,
  55. tempDir: tempDir,
  56. logger: logger,
  57. promptMutex: sync.Mutex{},
  58. }
  59. }
  60. func (r *Reader) Read() (*ast.TaskfileGraph, error) {
  61. // Recursively loop through each Taskfile, adding vertices/edges to the graph
  62. if err := r.include(r.node); err != nil {
  63. return nil, err
  64. }
  65. return r.graph, nil
  66. }
  67. func (r *Reader) include(node Node) error {
  68. // Create a new vertex for the Taskfile
  69. vertex := &ast.TaskfileVertex{
  70. URI: node.Location(),
  71. Taskfile: nil,
  72. }
  73. // Add the included Taskfile to the DAG
  74. // If the vertex already exists, we return early since its Taskfile has
  75. // already been read and its children explored
  76. if err := r.graph.AddVertex(vertex); err == graph.ErrVertexAlreadyExists {
  77. return nil
  78. } else if err != nil {
  79. return err
  80. }
  81. // Read and parse the Taskfile from the file and add it to the vertex
  82. var err error
  83. vertex.Taskfile, err = r.readNode(node)
  84. if err != nil {
  85. return err
  86. }
  87. // Create an error group to wait for all included Taskfiles to be read
  88. var g errgroup.Group
  89. // Loop over each included taskfile
  90. _ = vertex.Taskfile.Includes.Range(func(namespace string, include *ast.Include) error {
  91. vars := compiler.GetEnviron()
  92. vars.Merge(vertex.Taskfile.Vars, nil)
  93. // Start a goroutine to process each included Taskfile
  94. g.Go(func() error {
  95. cache := &templater.Cache{Vars: vars}
  96. include = &ast.Include{
  97. Namespace: include.Namespace,
  98. Taskfile: templater.Replace(include.Taskfile, cache),
  99. Dir: templater.Replace(include.Dir, cache),
  100. Optional: include.Optional,
  101. Internal: include.Internal,
  102. Flatten: include.Flatten,
  103. Aliases: include.Aliases,
  104. AdvancedImport: include.AdvancedImport,
  105. Vars: include.Vars,
  106. }
  107. if err := cache.Err(); err != nil {
  108. return err
  109. }
  110. entrypoint, err := node.ResolveEntrypoint(include.Taskfile)
  111. if err != nil {
  112. return err
  113. }
  114. include.Dir, err = node.ResolveDir(include.Dir)
  115. if err != nil {
  116. return err
  117. }
  118. includeNode, err := NewNode(r.logger, entrypoint, include.Dir, r.insecure, r.timeout,
  119. WithParent(node),
  120. )
  121. if err != nil {
  122. if include.Optional {
  123. return nil
  124. }
  125. return err
  126. }
  127. // Recurse into the included Taskfile
  128. if err := r.include(includeNode); err != nil {
  129. return err
  130. }
  131. // Create an edge between the Taskfiles
  132. r.graph.Lock()
  133. defer r.graph.Unlock()
  134. edge, err := r.graph.Edge(node.Location(), includeNode.Location())
  135. if err == graph.ErrEdgeNotFound {
  136. // If the edge doesn't exist, create it
  137. err = r.graph.AddEdge(
  138. node.Location(),
  139. includeNode.Location(),
  140. graph.EdgeData([]*ast.Include{include}),
  141. graph.EdgeWeight(1),
  142. )
  143. } else {
  144. // If the edge already exists
  145. edgeData := append(edge.Properties.Data.([]*ast.Include), include)
  146. err = r.graph.UpdateEdge(
  147. node.Location(),
  148. includeNode.Location(),
  149. graph.EdgeData(edgeData),
  150. graph.EdgeWeight(len(edgeData)),
  151. )
  152. }
  153. if errors.Is(err, graph.ErrEdgeCreatesCycle) {
  154. return errors.TaskfileCycleError{
  155. Source: node.Location(),
  156. Destination: includeNode.Location(),
  157. }
  158. }
  159. return err
  160. })
  161. return nil
  162. })
  163. // Wait for all the go routines to finish
  164. return g.Wait()
  165. }
  166. func (r *Reader) readNode(node Node) (*ast.Taskfile, error) {
  167. b, err := r.loadNodeContent(node)
  168. if err != nil {
  169. return nil, err
  170. }
  171. var tf ast.Taskfile
  172. if err := yaml.Unmarshal(b, &tf); err != nil {
  173. // Decode the taskfile and add the file info the any errors
  174. taskfileInvalidErr := &errors.TaskfileDecodeError{}
  175. if errors.As(err, &taskfileInvalidErr) {
  176. return nil, taskfileInvalidErr.WithFileInfo(node.Location(), b, 2)
  177. }
  178. return nil, &errors.TaskfileInvalidError{URI: filepathext.TryAbsToRel(node.Location()), Err: err}
  179. }
  180. // Check that the Taskfile is set and has a schema version
  181. if tf.Version == nil {
  182. return nil, &errors.TaskfileVersionCheckError{URI: node.Location()}
  183. }
  184. // Set the taskfile/task's locations
  185. tf.Location = node.Location()
  186. for _, task := range tf.Tasks.Values() {
  187. // If the task is not defined, create a new one
  188. if task == nil {
  189. task = &ast.Task{}
  190. }
  191. // Set the location of the taskfile for each task
  192. if task.Location.Taskfile == "" {
  193. task.Location.Taskfile = tf.Location
  194. }
  195. }
  196. return &tf, nil
  197. }
  198. func (r *Reader) loadNodeContent(node Node) ([]byte, error) {
  199. if !node.Remote() {
  200. ctx, cf := context.WithTimeout(context.Background(), r.timeout)
  201. defer cf()
  202. return node.Read(ctx)
  203. }
  204. cache, err := NewCache(r.tempDir)
  205. if err != nil {
  206. return nil, err
  207. }
  208. if r.offline {
  209. // In offline mode try to use cached copy
  210. cached, err := cache.read(node)
  211. if errors.Is(err, os.ErrNotExist) {
  212. return nil, &errors.TaskfileCacheNotFoundError{URI: node.Location()}
  213. } else if err != nil {
  214. return nil, err
  215. }
  216. r.logger.VerboseOutf(logger.Magenta, "task: [%s] Fetched cached copy\n", node.Location())
  217. return cached, nil
  218. }
  219. ctx, cf := context.WithTimeout(context.Background(), r.timeout)
  220. defer cf()
  221. b, err := node.Read(ctx)
  222. if errors.Is(err, &errors.TaskfileNetworkTimeoutError{}) {
  223. // If we timed out then we likely have a network issue
  224. // If a download was requested, then we can't use a cached copy
  225. if r.download {
  226. return nil, &errors.TaskfileNetworkTimeoutError{URI: node.Location(), Timeout: r.timeout}
  227. }
  228. // Search for any cached copies
  229. cached, err := cache.read(node)
  230. if errors.Is(err, os.ErrNotExist) {
  231. return nil, &errors.TaskfileNetworkTimeoutError{URI: node.Location(), Timeout: r.timeout, CheckedCache: true}
  232. } else if err != nil {
  233. return nil, err
  234. }
  235. r.logger.VerboseOutf(logger.Magenta, "task: [%s] Network timeout. Fetched cached copy\n", node.Location())
  236. return cached, nil
  237. } else if err != nil {
  238. return nil, err
  239. }
  240. r.logger.VerboseOutf(logger.Magenta, "task: [%s] Fetched remote copy\n", node.Location())
  241. // Get the checksums
  242. checksum := checksum(b)
  243. cachedChecksum := cache.readChecksum(node)
  244. var prompt string
  245. if cachedChecksum == "" {
  246. // If the checksum doesn't exist, prompt the user to continue
  247. prompt = fmt.Sprintf(taskfileUntrustedPrompt, node.Location())
  248. } else if checksum != cachedChecksum {
  249. // If there is a cached hash, but it doesn't match the expected hash, prompt the user to continue
  250. prompt = fmt.Sprintf(taskfileChangedPrompt, node.Location())
  251. }
  252. if prompt != "" {
  253. if err := func() error {
  254. r.promptMutex.Lock()
  255. defer r.promptMutex.Unlock()
  256. return r.logger.Prompt(logger.Yellow, prompt, "n", "y", "yes")
  257. }(); err != nil {
  258. return nil, &errors.TaskfileNotTrustedError{URI: node.Location()}
  259. }
  260. // Store the checksum
  261. if err := cache.writeChecksum(node, checksum); err != nil {
  262. return nil, err
  263. }
  264. // Cache the file
  265. r.logger.VerboseOutf(logger.Magenta, "task: [%s] Caching downloaded file\n", node.Location())
  266. if err = cache.write(node, b); err != nil {
  267. return nil, err
  268. }
  269. }
  270. return b, nil
  271. }