reader.go 8.2 KB

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