Compare commits

...

287 Commits

Author SHA1 Message Date
Andrey Nering
7722aba403 v2.3.0 2019-01-02 13:44:27 -02:00
Andrey Nering
4817d8c67f Move documentation tasks to its own Taskfile 2019-01-02 13:42:06 -02:00
Andrey Nering
9a062d90d1 Merge pull request #159 from go-task/global-environment-variables-#138
Add ability to globally set environment variables
2019-01-02 13:29:14 -02:00
Andrey Nering
959eb45373 Docs: Fix some typos 2019-01-02 13:25:58 -02:00
Andrey Nering
a42f2af9eb Documentation and changelog for global environment variables 2019-01-02 13:21:21 -02:00
Andrey Nering
4ddad68212 Merge global environment variables when merging tasks 2019-01-02 13:20:12 -02:00
Andrey Nering
aac6c5a1c7 Add hability to globally set environment variables
Closes #138
2019-01-02 12:06:12 -02:00
Andrey Nering
5572e31fd4 Merge pull request #157 from frederikhors/patch-2
Misprint
2018-12-27 10:49:24 -02:00
frederikhors
233b8bf81a Misprint 2018-12-27 01:11:36 +01:00
Andrey Nering
2ae3810f80 Merge pull request #156 from frederikhors/patch-1
Misprint
2018-12-26 10:38:20 -02:00
frederikhors
736165876c Misprint 2018-12-26 12:04:00 +01:00
Andrey Nering
61b3fca9a3 Merge pull request #154 from go-task/upgrade-mvdan-sh
Upgrade mvdan/sh
2018-12-24 15:30:45 -02:00
Andrey Nering
469863b7b3 go mod vendor 2018-12-24 15:26:33 -02:00
Andrey Nering
5238bc55fd Upgrade mvdan.cc/sh
Fixes #153
2018-12-24 15:25:19 -02:00
Andrey Nering
57a01aa6ff Fix failing test
There was some breaking changes described at
https://github.com/mvdan/sh/issues/335#issuecomment-447605295
2018-12-24 15:19:53 -02:00
Andrey Nering
9361dbc39e Merge branch 'master' into upgrade-mvdan-sh 2018-12-24 15:08:29 -02:00
Andrey Nering
11d257cb26 Changelog: Mention Scoop 2018-12-24 15:03:30 -02:00
Andrey Nering
a928ab75e3 Docs: Give more visibility to sponsors and contributors 2018-12-24 15:00:14 -02:00
Andrey Nering
55a240c82e Improve documentation on Scoop
Updates #152
2018-12-24 14:42:49 -02:00
Andrey Nering
f8aedf438b Merge pull request #152 from lambdalisue/docs-scoop
Add Scoop
2018-12-24 14:32:53 -02:00
Andrey Nering
9f1bb9a42e Add CHANGELOG.md
This was generated in a semi-automated way using the existing GitHub releases,
fetch thought the GitHub API.
2018-12-15 16:14:39 -02:00
Andrey Nering
0ed7274610 go mod vendor 2018-12-15 15:44:17 -02:00
Andrey Nering
df032b09a7 Upgrade mvdan/sh 2018-12-15 15:43:40 -02:00
Andrey Nering
7dba742e4c v2.2.1 2018-12-09 15:58:59 -02:00
Andrey Nering
83dbe78965 Documentation: Mention that including Taskfiles is still experimental 2018-12-09 15:57:13 -02:00
Andrey Nering
95b75c5330 Fix issue on running dependencies or tasks on included Taskfiles
Fixes #151
2018-12-09 15:54:58 -02:00
lambdalisue
780bd08490 Add Scoop
Task is now available on Scoop for Windows users.
https://github.com/lukesampson/scoop-extras/pull/1485
2018-12-06 22:21:03 +09:00
Andrey Nering
a9b1f38a7c Fix nil errors when merging Taskfiles
Closes #150
2018-12-02 14:17:32 -02:00
Andrey Nering
4ed4ad9852 .gitignore: Ignore the .task directory 2018-12-02 14:04:35 -02:00
Andrey Nering
81f172315c Merge pull request #143 from go-task/switch-to-go-modules
Switch to Go modules
2018-11-10 20:15:16 -02:00
Andrey Nering
54666221a4 Update install documentation after switch to Go Modules 2018-11-10 20:10:44 -02:00
Andrey Nering
5327d702f8 go mod vendor 2018-11-04 21:37:53 -02:00
Andrey Nering
a701ea3007 go mod tidy 2018-11-04 21:36:55 -02:00
Andrey Nering
f0fb7d9661 go.mod: Pin some versions 2018-11-04 21:31:29 -02:00
Andrey Nering
3cbc89769d Re-write import paths to v2 2018-11-04 21:23:35 -02:00
Andrey Nering
cb95200be3 go mod vendor 2018-10-27 17:02:24 -03:00
Andrey Nering
a52f6c0acf Switch to Go modules
Let's keep the vendor directory for a while to not break Task for
users that install it using `go get`.

Closes #119
2018-10-27 17:01:14 -03:00
Andrey Nering
77f9e3dd41 Update link on the Taskfile generated by 2018-10-27 15:30:48 -03:00
Andrey Nering
259d3e2df1 Fix more internal documentation links when viewing on GitHub
Applies fixes done on #142 on more links
2018-10-27 15:25:39 -03:00
Andrey Nering
6eee5421b0 Merge pull request #142 from aseembajaj/patch-1
Fix broken URL to installation doc
2018-10-27 15:19:56 -03:00
Aseem Bajaj
8004e9c943 Fix broken URL to installation doc
The links to installation doc were broken, perhaps it was a typo or maybe installation document was relocated from "installation" directory to "installation.md". In either case, making this change fixes the problem.
2018-10-26 16:06:33 -07:00
Andrey Nering
2ab8511f45 v2.2.0 2018-10-25 20:19:28 -03:00
Andrey Nering
7514ff53c9 Documentation: SeedAndDew script tag 2018-10-21 09:55:14 -03:00
Andrey Nering
309cfb1499 Docs: Google Search Console Verification Tag 2018-10-13 18:42:07 -03:00
Andrey Nering
a567f7ed20 Merge pull request #134 from go-task/feature/include
Support including Taskfiles
2018-10-13 18:31:19 -03:00
Andrey Nering
5720936247 Fix CI 2018-10-13 18:29:23 -03:00
Andrey Nering
5d9de14ca3 Increment the current Taskfile version to 2.2 2018-10-13 18:25:40 -03:00
Andrey Nering
f519f56078 Add documentation for including other Taskfiles 2018-10-13 18:14:42 -03:00
Andrey Nering
5eb1a1f7f5 Fixes to Taskfile including:
- Disallow recursive Taskfile including (i.e. included Taskfile including other Taskfiles)
- Write test for included a file instead of a directory
2018-10-13 17:52:09 -03:00
Andrey Nering
5a28560177 Write first test for including a Taskfile 2018-10-13 16:56:51 -03:00
Andrey Nering
db280adf55 Merge branch 'master' into feature/include 2018-10-13 16:40:32 -03:00
Andrey Nering
b77fcd6c8a Documentation improvements 2018-10-07 18:34:03 -03:00
Andrey Nering
b5b2649283 Fix broken --status flag
Fixes #139
2018-10-06 17:55:23 -03:00
Andrey Nering
318f9b216d Fix typo 2018-09-24 21:52:14 -03:00
Andrey Nering
61247a0b2a Cosmetic changes 2018-09-24 21:42:33 -03:00
Andrey Nering
849a418273 Create CNAME 2018-09-24 21:21:23 -03:00
Andrey Nering
2e63a62e08 Delete CNAME 2018-09-24 21:20:58 -03:00
Andrey Nering
6ccf1f2a3c Documentation: GA 2018-09-23 15:31:00 -03:00
Andrey Nering
e298256b82 Use HTTP for now
GitHub Pages can take up to 1 hour to enable HTTPS on the site
2018-09-23 15:16:53 -03:00
Andrey Nering
787e5b2e29 Create CNAME 2018-09-23 15:08:03 -03:00
Andrey Nering
4aa1e8b093 Documentation improvements 2018-09-23 15:06:43 -03:00
Andrey Nering
9ee224c36b Documentation site using docsify 2018-09-22 18:44:24 -03:00
Andrey Nering
08263c0597 Fix wrong error message beingg print when the file has a syntax error
Fixes #137
2018-09-22 17:29:18 -03:00
Andrey Nering
347fe87229 v2.1.1 2018-09-16 22:17:36 -03:00
Andrey Nering
b65a0a3a8d Fix signal handling when --watch flag is given
Closes #132
2018-09-16 21:59:00 -03:00
Andrey Nering
9a5a1e2253 Start support to including Taskfiles 2018-09-09 22:29:29 -03:00
Andrey Nering
687b4ec837 Fix error when using checksum method and no file exists for a source glob
Closes #131
2018-09-01 11:23:38 -03:00
Andrey Nering
8bdf5c554d Fixes after updating mvdan.cc/sh 2018-09-01 11:02:23 -03:00
Andrey Nering
f4a18e531f Update dependencies 2018-09-01 11:00:49 -03:00
Andrey Nering
df951a0c7c Fix suggestion to use task --init not being shown anymore 2018-08-19 16:23:32 -03:00
Andrey Nering
a6cac2691b Delete unused errors 2018-08-19 16:15:19 -03:00
Andrey Nering
a9f5179066 README: Fix title case 2018-08-19 16:12:53 -03:00
Andrey Nering
687e2699cf Improvements on documentation 2018-08-19 15:47:21 -03:00
Andrey Nering
491da0ceb9 "ignore_error" is only available on version >= 2.1 2018-08-19 15:46:07 -03:00
Andrey Nering
1bac40bc58 README: Update alternatives 2018-08-18 17:50:40 -03:00
Andrey Nering
fb9061480d Merge branch 'Eun-master' 2018-08-05 13:02:22 -03:00
Andrey Nering
a04cf100b4 Improve README a bit 2018-08-05 13:01:30 -03:00
Andrey Nering
76253bf516 Reduce code duplication on test 2018-08-05 12:56:55 -03:00
Andrey Nering
feaf70922d Allow ignore_error at task level 2018-08-05 12:53:42 -03:00
Andrey Nering
c70343a5bc Handle ignore_error one level up on the code 2018-08-05 12:40:11 -03:00
Andrey Nering
550c116aea Merge branch 'master' into master 2018-08-05 11:32:07 -03:00
Andrey Nering
a5f31a4280 Dry run small code style changes 2018-08-05 11:28:02 -03:00
Andrey Nering
27fc4c4ca8 Merge pull request #126 from bebbs/125-dry-run
Implemented dry run mode
2018-08-05 11:21:52 -03:00
Tobias Salzmann
90a5f17f58 Merge branch 'master' into master 2018-08-01 10:47:25 +02:00
Tobias Salzmann
108cb91d95 IgnoreError
* Document ignore_error
* ignore_error only for commands
2018-08-01 10:44:53 +02:00
Josh Bebbington
00a0755ff3 Added test for executor.DryRun 2018-07-31 23:17:21 +01:00
Josh Bebbington
3f7e8c88eb Changed --dry-run flag to --dry 2018-07-29 22:03:22 +01:00
Josh Bebbington
1c7ca94d49 Implemented dry run mode
Added a --dry-run flag that compiles and steps through each task, but does not execute them. The commands that would have been run are printed. See #125.
2018-07-29 00:39:25 +01:00
Andrey Nering
31273cd6ff Update README 2018-07-22 18:15:11 -03:00
Andrey Nering
14e39dd745 Update dependencies 2018-07-22 18:05:13 -03:00
Andrey Nering
cc6f7b6088 Manually implement merging of Taskfiles and remove dependency on github.com/imdario/mergo
I was carreful enough to check the behavior keeps the same
2018-07-22 17:54:44 -03:00
Andrey Nering
da1b0c9558 Error if Taskfile_{{GOOS}}.yml version doesn't match Taskfile.yml version
This change is not backward incompatible because merging was already not
working if versions 1 and 2 coexist in Taskfile.yml and Taskfile_{{GOOS}}.yml
2018-07-22 17:36:30 -03:00
Andrey Nering
9f294b4d10 Refactor and move logic of reading Taskfiles to its own package
Idea to making things easier to start implementing #98
2018-07-22 16:10:20 -03:00
Andrey Nering
13f60bae41 Merge pull request #124 from go-task/shell-expand
Move path expanding logic to shell.Expand
2018-07-22 15:16:21 -03:00
Andrey Nering
67105b332f Move path expanding logic to shell.Expand 2018-07-15 15:49:00 -03:00
Andrey Nering
18961e3d07 README improvements 2018-07-15 15:47:38 -03:00
Andrey Nering
fe31f5050d Taskfile.yml improvements 2018-07-15 15:42:46 -03:00
Andrey Nering
ab8549adea Update dependencies 2018-07-15 14:38:39 -03:00
Tobias Salzmann
05600601ff add ignoreError option 2018-07-10 10:44:58 +02:00
Andrey Nering
c541356289 Fix typo 2018-06-24 11:05:54 -03:00
Andrey Nering
467c4360ca v2.0.3 2018-06-24 10:52:19 -03:00
Andrey Nering
3b152a38b0 .goreleaser.yml: Use CGO_ENABLED=0 2018-06-24 10:51:04 -03:00
Andrey Nering
f4d3855528 Update deps 2018-06-24 10:40:44 -03:00
Andrey Nering
09eab770a7 Skip empty commands
Fixes #120
2018-06-24 10:29:46 -03:00
Andrey Nering
102f8ab74e Expand environment variables on "dir", "sources" and "generates"
So a path like this works: $GOPATH/src/github.com/go-task/task

Allowing of "~" was also implemented. See #74 and baac067a1a

Fixes #116
2018-06-16 14:30:40 -03:00
Andrey Nering
a830dba5da Taskfile: Disable CGO 2018-06-16 14:24:50 -03:00
Andrey Nering
3f13a50ca3 Merge pull request #115 from AlekSi/patch-1
Use latest patch releases of Go
2018-05-31 18:24:06 -03:00
Alexey Palazhchenko
7c456f2ab9 Use latest patch releases of Go 2018-05-31 15:43:52 +00:00
Andrey Nering
bae95cd6f6 Travis: Remove Go 1.8 2018-04-28 15:44:35 -03:00
Andrey Nering
bbd6e443b0 YAML: Don't use strict unmarshaling anymore
Fixes #112
2018-04-28 15:39:54 -03:00
Andrey Nering
db0d847e03 Fix compilation after updating mvdan/sh 2018-04-28 15:36:01 -03:00
Andrey Nering
0afb453fed Update dependencies 2018-04-28 15:35:33 -03:00
Andrey Nering
dbc79b4311 Merge pull request #109 from go-task/feature/parallel-task-output-#104
Add "output" option to Taskfile to control how stuff are printed to stdout/stderr
2018-04-28 15:18:05 -03:00
Andrey Nering
ac6008c33c Merge pull request #111 from sawadashota/add-zsh-completion
Add zsh completion
2018-04-28 15:07:06 -03:00
Shota Sawada
e540e752f2 Add zsh completion 2018-04-27 17:50:56 +09:00
Andrey Nering
cdbe821eb8 Write documentation for output types 2018-04-22 22:13:31 -03:00
Andrey Nering
6be994f1ca Write test for ouput types 2018-04-22 21:40:03 -03:00
Andrey Nering
a407b0a8eb First step implementing "prefixed" output option
Ref #104
2018-04-22 15:41:53 -03:00
Andrey Nering
051ff35878 Add "output" option to Taskfile to control how stuff are printed to stdout/stderr
First step for #104
2018-04-15 14:37:44 -03:00
Andrey Nering
8b3c34c308 Add "output" options to the Taskfile
Also, fix handling of Taskfile by making the version an instance of
`semver.Constraints` instead of `semver.Version`. This makes the version
works as described on TASKFILE_VERSIONS.md document, i.e. version "2" will
include "2.x" features but version "2.0" not.
2018-04-15 11:11:07 -03:00
Andrey Nering
2cb2668803 Fix Travis CI 2018-04-07 15:36:37 -03:00
Andrey Nering
4dccdb95b9 README: Add image links 2018-04-07 15:15:35 -03:00
Andrey Nering
96db9a9410 Using godownloader to generate a install script
Closes #78
2018-04-07 15:07:43 -03:00
Andrey Nering
0cd34bbebc Move variables from Taskvars to Taskfile 2018-04-07 14:42:24 -03:00
Andrey Nering
15f50c0e58 Update README.md and CONTRIBUTING.md 2018-04-07 14:33:10 -03:00
Andrey Nering
7fca9732e7 Merge pull request #105 from michael-k/patch-1
Fix some typos in readme
2018-03-18 21:35:35 -03:00
Michael
0ea8c3ed28 Fix some typos in readme 2018-03-16 06:32:14 +00:00
Andrey Nering
0af9600e92 Update the release process once again:
- Release both Homebrew and Snapcraft packages manually for now;
- Fix some artifacts file names to keep them consistent.
2018-03-11 15:58:32 -03:00
Andrey Nering
328e3725e5 Merge pull request #102 from go-task/develop
v2.0.1
2018-03-11 15:37:18 -03:00
Andrey Nering
2183e1e9f5 Improve release process and testing automatic release on new tag using Travis 2018-03-11 15:31:27 -03:00
Andrey Nering
120d0be84c Fixes panic on task --list
Fixes #99
2018-03-11 14:39:40 -03:00
Andrey Nering
5649f75a8d Merge pull request #97 from seblw/patch-1
Editorial changes in TASKFILE_VERSIONS.md
2018-03-08 08:07:31 -03:00
Sebastian Lawniczak
a209f7d6be Editorial changes in TASKFILE_VERSIONS.md 2018-03-08 10:18:27 +01:00
Andrey Nering
d48a2f3ccf Documentation changes for v2.0.0 release 2018-03-07 22:54:37 -03:00
Andrey Nering
c1ae36866e Remove warning for version 2 2018-03-04 16:27:16 -03:00
Andrey Nering
4f368923a5 Upgrade own Taskfile to version 2 2018-03-04 16:20:26 -03:00
Andrey Nering
7c02097d93 Improve --init flag
- Update generated Taskfile to version 2
- Don't loop anymore on extensions since we only support YAML
- Use 644 for file permission
2018-03-04 16:19:52 -03:00
Andrey Nering
51998f706f Allow customizable number of expansions
Updates #66
2018-03-04 15:50:03 -03:00
Andrey Nering
1a3df08aca Allow global variables in the Taskfile
Closes #66
2018-03-04 15:39:14 -03:00
Andrey Nering
975f262ac0 Fix "test-release" task
Goreleaser changed some flags
2018-03-04 11:06:19 -03:00
Andrey Nering
1cb4a3b8d5 Fix CI
Goreleaser now requires Go 1.10, but we still support Go 1.8
2018-03-04 10:57:46 -03:00
Andrey Nering
35f4b2f686 Travis: Test Go 1.10 2018-03-03 19:28:13 -03:00
Andrey Nering
407ec91ca7 Update dependencies 2018-03-03 19:28:08 -03:00
Andrey Nering
12c0d18932 Move setting of default version to "taskfile" package 2018-03-03 18:56:15 -03:00
Andrey Nering
2d4ca37226 Use semver for Taskfile versions 2018-03-03 18:54:42 -03:00
Andrey Nering
afe6744e97 Merge pull request #93 from go-task/v2_refactor
Re-organization and refactoring targeting v2
2018-02-18 10:14:00 -03:00
Andrey Nering
19d4b8b7f7 Add warning about Taskfile version 2 until v2.0.0 release 2018-02-18 10:04:17 -03:00
Andrey Nering
3556942516 Improve nested variables support
Closes #76 #89 #77 #83
2018-02-18 09:50:39 -03:00
Andrey Nering
87a200e42c Extract some functionality to its own packages
Like variable and template handling, and logging
2018-02-17 16:12:41 -02:00
Andrey Nering
152fc0ad38 Move all structs related to Taskfile to its own package 2018-02-17 14:22:18 -02:00
Andrey Nering
3212ae4713 Update dependencies 2018-02-11 22:02:22 -02:00
Andrey Nering
040cef1479 Fix usage of "dep"
Now, "dep prune" should not be run, and instead pruning options should be set on Gopkg.toml
2018-02-11 22:00:40 -02:00
Andrey Nering
f5f70d7a75 README: Document Homebrew as an installation method 2018-01-27 14:44:20 -02:00
Andrey Nering
42509cf2f5 Update dependencies
Fixes #86
2018-01-21 09:39:15 -02:00
atar-axis
6f74c2d823 Added "passing variables to dependencies" (#85) 2018-01-11 10:10:12 -02:00
Andrey Nering
e23a6dc9f1 Update dependencies 2018-01-03 15:12:40 -02:00
Andrey Nering
134c6b79c4 Add Taskfile struct and start implementing new format
Updates #54, #66 and #77
2017-12-29 18:46:15 -02:00
Andrey Nering
00ff1447ee Update README.md
Includes removing unmaintained alternatives
2017-12-26 21:53:57 -02:00
Andrey Nering
78f6cb08d8 Add --status flag to check is a task is up-to-date
Closes #81
2017-12-26 21:43:52 -02:00
Andrey Nering
dfd890c8a6 Revert "simplify getVariables() and improve nested variables support"
This reverts commit 9619c7f54d.
2017-11-19 18:46:46 -02:00
Andrey Nering
7457b3668b Revert "Revert "list: print message with there's no task with description""
This reverts commit e065dcb816.

Reintroducing this. Reverted unintentionally.
2017-11-19 18:45:41 -02:00
Andrey Nering
71e7cd5808 listening for SIGINT and SIGTERM
closes #75
2017-11-19 18:33:57 -02:00
Andrey Nering
57e42af238 update deps 2017-11-19 18:26:37 -02:00
Andrey Nering
e065dcb816 Revert "list: print message with there's no task with description"
This reverts commit 2508bed363.

I still want to do this, but since it break some existing Taskfiles,
let's give a little more thought on this first.
2017-11-19 18:12:16 -02:00
Andrey Nering
9619c7f54d simplify getVariables() and improve nested variables support
/cc @smyrman
2017-11-17 00:54:26 -02:00
Andrey Nering
2508bed363 list: print message with there's no task with description 2017-11-16 23:35:53 -02:00
Andrey Nering
c469632ee0 update deps 2017-11-02 10:41:46 -02:00
Andrey Nering
44a52359dc checksum: save them in a subdir .task/checksum
future-proof since the .task directory can be used to save other state
in the future
2017-11-02 10:37:02 -02:00
Andrey Nering
2022551b26 checksum: also sum the name of the files, so it changes after renaming 2017-11-02 10:31:34 -02:00
Andrey Nering
baac067a1a expand home dir ("~" symbol) on paths
fixes #74
2017-11-02 10:25:50 -02:00
Andrey Nering
f4216dd67f list tasks: ensure at least one space after colon 2017-11-02 09:45:00 -02:00
Andrey Nering
60186bdcd5 readme: document Snap as an installation method 2017-10-30 21:12:20 -02:00
Andrey Nering
2c2eb1684b readme: fix markdown 2017-10-15 18:03:04 -02:00
Andrey Nering
33b167215d move some packages to the "internal" directory
- this makes it impossible to import these packages outside Task
- as a side effect, it makes the root directory cleaner
2017-10-15 17:58:21 -02:00
Andrey Nering
c53db134c6 move examples to its own repo 2017-10-15 17:55:26 -02:00
Andrey Nering
0513a21e25 update dependencies
also make sure the module that enables /dev/null path of the sh
interpreter is enabled
2017-10-15 17:41:15 -02:00
Andrey Nering
2fc32414f5 project stuff
- move some files to .github/ folder
- add an issue template
- add two more alternatives
2017-10-01 15:46:47 -03:00
Andrey Nering
309bc4ee4c checksum: add tests for filename 2017-10-01 15:06:12 -03:00
Andrey Nering
7977e6fb16 watch: also walk on tasks called on on "cmds" 2017-09-30 15:19:58 -03:00
Andrey Nering
abb19dfbf8 print logs to stderr instead of stdout
also, don't print up-to-date status when the --silent flag was given

closes #68
2017-09-30 14:56:35 -03:00
Andrey Nering
14676dc3f8 checksum: normalize filename 2017-09-30 14:40:11 -03:00
Andrey Nering
c16f8a4d46 checksum: skip directories 2017-09-19 14:03:24 -03:00
Andrey Nering
48bf09da21 remove deprecated set keyword 2017-09-17 11:24:30 -03:00
Andrey Nering
c295a1998a add checksum based status check, alternative to timestamp based 2017-09-17 11:06:47 -03:00
Andrey Nering
95f7b9443f v1.4.3 2017-09-07 14:40:54 -03:00
Andrey Nering
0160f5dd30 update deps
fixes #67 fixed upstream on mvdan/sh#159
2017-09-07 14:02:52 -03:00
Andrey Nering
f3097845b4 allow assigning variables to tasks at run time via CLI
using a similar syntax than setting env variables to command in bash,
but used right after the task:

```bash
task print MESSAGE=Hello!
```

closes #33
2017-09-07 13:57:06 -03:00
Andrey Nering
5e72de4ba2 Revert "execext: use sync.Pool to instantiate parser and runner"
This reverts commit 451b965fb0.
2017-09-07 10:40:21 -03:00
Sindre Røkenes Myren
7a64530e83 Added suport for multiline variables from sh
Instead of giving an error on multiline results from sh, the results are
now stored as is, except that the last newline is stripped away to make
the output of most commands easy to use in shell commands.

Two helper functions have been added to help deal with multi-line
results. In addition, previous PascalCase template function names have
been renamed to camelCase for consistency with the sprig lib.
2017-09-04 10:14:09 +02:00
Andrey Nering
36f3be9979 travis: test Go 1.8 and 1.9 2017-09-02 11:42:33 -03:00
Andrey Nering
451b965fb0 execext: use sync.Pool to instantiate parser and runner
A benchmark was added. The performance improvement is considerable:

BenchmarkNoPool-4   	   30000	     43405 ns/op
BenchmarkPool-4     	   20000	     71219 ns/op
2017-09-02 11:32:24 -03:00
Andrey Nering
2b2852aad7 update deps and moving from github.com/mvdan/sh to mvdan.cc/sh 2017-09-02 11:19:00 -03:00
Sindre Røkenes Myren
72bfd94329 Fixes env: remove square braces and evaluate shell (#62)
Fixes bug #61, and makes `env` work more similar to `vars` by allowing
dynamic shell values to be evaluated as part of `CompiledTask`.
2017-08-16 08:04:58 -03:00
Andrey Nering
300376b0b1 update README 2017-08-05 14:52:32 -03:00
Andrey Nering
e67792177d execext: fix sh 2017-08-05 14:20:44 -03:00
Andrey Nering
0f24fd593e update dependencies
- add watch
- remove fsnotify
- update others
2017-08-05 14:13:35 -03:00
Andrey Nering
23ec6c721d Merge branch 'watch' 2017-08-05 14:06:46 -03:00
Andrey Nering
26761e5445 watch: isContextError is as a var func 2017-08-05 14:04:34 -03:00
Andrey Nering
e78e4e6a2e watch: ignore usually big dirs
Two items by now:
- ".git"
- "node_modules"
2017-08-05 13:35:10 -03:00
Andrey Nering
e765b7a9c4 do not check for maximum call if is watch 2017-08-05 13:26:30 -03:00
Andrey Nering
c210e34ce3 watch: switch to watcher as waych lib and few fixes
watcher whould be more consistent across differente OSes
2017-08-05 11:50:39 -03:00
Jack Mordaunt
ddd063f29e Cancel and restart long running process on file change by using context.WithCancel(..)
Closes #59
2017-08-04 12:48:15 -03:00
Andrey Nering
a2c96e9cdd re-generate vendor/ folder
maybe a bug on dep? these two files were not copied
2017-07-30 21:09:05 -03:00
Andrey Nering
f2416d68b8 fix travis again
something was wrong with .gitignore rules
2017-07-30 21:00:50 -03:00
Andrey Nering
1eccb61d44 fix travis
somehow the dev.go file was ignored by Git
2017-07-30 20:53:54 -03:00
Andrey Nering
cf2b189fbd v1.4.2 2017-07-30 20:42:15 -03:00
Andrey Nering
394b69676a rename func to handleShVar 2017-07-30 20:36:35 -03:00
Andrey Nering
9704dc5734 reuse of minTime and maxTime funcs 2017-07-30 20:00:35 -03:00
Andrey Nering
f54dde4f78 func isUpToDate should be bound to Task struct 2017-07-30 19:45:59 -03:00
Andrey Nering
70ef9fbcfe rename func: ReplaceVariables -> CompiledTask 2017-07-30 19:34:28 -03:00
Andrey Nering
bb1aff84cf custom stdout for InitTaskfile func 2017-07-30 19:29:49 -03:00
Andrey Nering
dc1ec77da5 own Taskfile: non-verbose test 2017-07-30 19:26:18 -03:00
Andrey Nering
7077b20a54 flag to set directory of execution 2017-07-30 19:24:53 -03:00
Andrey Nering
09e84c2583 always echo command if is verbose mode 2017-07-30 19:21:06 -03:00
Andrey Nering
e3ac6f9e01 fix sh field name 2017-07-30 19:12:26 -03:00
Andrey Nering
f91bbe9397 update deps 2017-07-30 19:11:34 -03:00
Sindre Røkenes Myren
31faf05c3a Reintroduce template evaluation in variables
With a recent commit, template evaluation for variables in tasks got
broken. This reindroudces temmplate evaluation in taks, and resolves
a series of issues that where previouisly present on master, such as:

- Taskvars did not get evaluated as templates.
- Taskvars would, in contrast to the documentation, _override_ task
  variables for the taks called directly via `Executor.Run(args
  ...string)`. This caused different behaviour in the "default" task
  v.s. other tasks.

This commit ensures:
 - Priority order for variables is now according to the documentation,
   also for the "default" task.
 - Variables gets resolved in a particular order to ensure logical
   access to varaibles on template compile time, and that template
   compilation finds place _before_ resolution of dynamic variables.

This change also allows the following to work:

    task:
      vars:
        A: "52"
        B: "{{.A}}"

However, the following will always replace C with the uncompiled
`{{.A}}`:

    task:
      vars:
        A: "52"
        C: "{{.B}}"
        B: "{{.A}}"

Several tests have also been added to prevent this feature from breaking
again. This should hopefully finally resolve issue #40.
2017-07-22 00:50:23 +02:00
Andrey Nering
55672410cd own Taskfile: small improvement of lint task 2017-07-19 20:24:40 -03:00
Andrey Nering
8a66857fb9 Merge branch 'silent' 2017-07-19 20:20:49 -03:00
Andrey Nering
d0b37df615 add silent mode to disable echoing of commands 2017-07-19 20:20:24 -03:00
Andrey Nering
dc6cb68327 rename file.go to status.go, and move related code there 2017-07-16 16:15:29 -03:00
Andrey Nering
72250b32d3 replace variables in a task once, instead of mixing these calls with unrelated code
this is the first big step of #45

now t.ReplaceVariable will return a copy of the task, but with variables
replaced

now we don't need to replace variables everywhere in the code, and will
make other refactorings easier
2017-07-16 16:09:55 -03:00
Andrey Nering
726130be09 v1.4.1 2017-07-15 15:52:33 -03:00
Andrey Nering
968a29d869 deduplicate conversion from dep and cmd to call 2017-07-15 15:46:53 -03:00
Andrey Nering
ce27e973be hotpath for a blank variable template 2017-07-15 15:38:57 -03:00
Andrey Nering
2607866c49 readme: document new syntax for synamic variables 2017-07-15 15:37:24 -03:00
Andrey Nering
e8e914b11c use YAML for dynamix variable instead of $ prefix
$ prefix still works but is now deprecated

before:

    VAR: $echo var

after:

    VAR:
      sh: echo bar

closes #46
2017-07-15 15:28:59 -03:00
Andrey Nering
d22b3b0d88 readme: document the task_checksum.txt file on releases
closes #44
2017-07-15 14:52:31 -03:00
Andrey Nering
5ece1d74f6 fix Taskvars.yml vars not available while interpolating vars prop
closes #40
2017-07-15 14:40:58 -03:00
Andrey Nering
ac7ab42d94 Create CODE_OF_CONDUCT.md 2017-07-15 14:31:53 -03:00
Andrey Nering
38a3f538f5 add CONTRIBUTING.md 2017-07-15 14:27:45 -03:00
Andrey Nering
998935ea55 add --list (or -l) flag to print existing tasks
If an inexixtent task is given, the help also prints as before

Also fixing README documentation

Closes #51
2017-07-15 14:10:46 -03:00
Andrey Nering
e781ac2512 own Taskfile: add task "todo" to print TODOs in code 2017-07-15 13:58:03 -03:00
Andrey Nering
ef2695974d os specific Taskvars file
Now it's possible to have Taskfile_windows.yml or Taskvars_linux.yml
(and others).

Asked in a comment in #46
2017-07-15 13:52:02 -03:00
Andrey Nering
b552cc2b12 yaml: use UnmarshalStrict instead on Unmarshal
https://github.com/go-yaml/yaml/pull/262
2017-07-15 13:36:22 -03:00
Andrey Nering
4ae9c2445d update deps 2017-07-15 13:34:42 -03:00
Sindre Røkenes Myren
769e25f080 Consider task up-to-date on equal timestamps
Fixes issue #48 by considering a task up-to-date if the newest
file from sources and the oldest file from generates has
exactly the same time-stamp.
2017-07-12 18:18:26 +02:00
Sindre Røkenes Myren
86a23849e0 Allow absolute path in generates section
Fixes issue #47 by allowing absolute paths in a task's generates and
sources sections. Tests are added for the generates section only at this
time.
2017-07-12 18:14:34 +02:00
Andrey Nering
a586fef414 Merge pull request #43 from smyrman/issue-42
Bugfix: allow templating when calling deps
2017-07-09 20:02:39 -03:00
Sindre Myren
a548c63a92 Bugfix: allow templating when calling deps
Fixes issue #42 by allowing for template evaluatation on task override
variables when the task is launched as dependency.
2017-07-09 23:48:36 +02:00
Andrey Nering
5268df6bfd only get variable map twice and implement vars template
ref #40
2017-07-08 16:00:17 -03:00
Andrey Nering
82e1c0f810 refactor: functions reorder (higher level first) 2017-07-08 15:13:27 -03:00
Andrey Nering
81b0ffb7f4 rename: readTaskvarsFile() -> readTaskvars() 2017-07-08 15:10:01 -03:00
Andrey Nering
0da130ee2c refactor: simplify some controls 2017-07-08 15:08:44 -03:00
Andrey Nering
6e880c9027 refactor: don't need to run template on Executor.Dir 2017-07-08 15:01:45 -03:00
Andrey Nering
082fa321cb rename 2 files
- read_taskfile.go -> taskfile.go
- variable_handling.go -> variables.go
2017-07-08 14:58:43 -03:00
Andrey Nering
ff1c49f111 refactor: better usage of bytes.Buffer type 2017-07-08 14:57:12 -03:00
Andrey Nering
50f592c540 refactor getVariables() 2017-07-08 14:48:37 -03:00
Andrey Nering
7a7f66dfdc refactor: join task and vars parameters in a single Call struct 2017-07-08 14:34:17 -03:00
Andrey Nering
a1140aa62f Merge branch 'cyclic-dep' 2017-07-08 13:36:45 -03:00
Andrey Nering
2dd3564da1 changed cyclic dep detection
since interpolation can be used, detection should be a execution time,
and not before

now, to prevent infinite execution, there's a miximum of 100 calls per
task

closes #37
2017-07-08 13:33:55 -03:00
Andrey Nering
fb4b0a187e Merge branch 'issue-37-cyclic-dep' 2017-07-08 10:26:18 -03:00
Andrey Nering
ac48ee066e fix panic for invalid task in cyclic dep detection
resolves partly #37
2017-07-08 10:25:15 -03:00
Andrey Nering
06031efc09 cyclic: refactor to return error instead 2017-07-08 10:13:56 -03:00
Andrey Nering
9bea80b862 Merge pull request #41 from zbindenren/master
better error output for dynamic variables in Taskvars.yml
2017-07-07 07:01:21 -03:00
Rene Zbinden
92ecb1c7ec better error output for dynamic variables in Taskvars.yml 2017-07-07 08:33:56 +02:00
Andrey Nering
645f77b849 Merge pull request #39 from smyrman/issue-38
Allow template evaluation when calling a task with vars
2017-07-06 21:30:47 -03:00
Sindre Røkenes Myren
2f9381065d Allow template evaluation in parameters
When passing variables to a sub-task, allow template evaluation
within the passed-on variables.
2017-07-07 00:47:56 +02:00
Sindre Røkenes Myren
774ef61c2f Update usage text slightly 2017-07-06 18:40:01 +02:00
Andrey Nering
dd2c66d2e1 v1.4.0 2017-07-05 21:32:30 -03:00
Andrey Nering
0deb2d78fb improve README documentation 2017-07-05 21:31:41 -03:00
Andrey Nering
fdd7e7f2a8 add own Taskfile.yml file 2017-07-05 21:06:12 -03:00
Andrey Nering
ad1a440576 cache dymanic variables 2017-07-05 21:03:59 -03:00
Andrey Nering
222b5cb587 add verbose mode (-v flag) 2017-07-05 20:56:31 -03:00
Andrey Nering
a1d1f73fe7 update dependencies 2017-07-05 20:46:05 -03:00
Andrey Nering
e7f9ace559 rename goreleaser.yml to .goreleaser.yml 2017-07-05 20:39:19 -03:00
Andrey Nering
cb72c404f5 Merge pull request #32 from go-task/parameters
Add task parameters
2017-07-05 20:34:42 -03:00
Andrey Nering
01b9bf5289 update README documentation about calling another task 2017-07-05 20:30:58 -03:00
Andrey Nering
a52a66ec1c test usage of param with $ prefix 2017-07-05 20:12:40 -03:00
Andrey Nering
313d7089da fix lint 2017-07-05 20:10:45 -03:00
Andrey Nering
06d80e92eb rename Cmd.Params to Cmd.Vars 2017-07-05 20:07:27 -03:00
Andrey Nering
e1fc3aa4fb remove support for TOML and JSON
ref #34
2017-07-05 19:56:52 -03:00
Andrey Nering
b8fe8d465e refactor: onyl read Taskvars file once 2017-07-03 21:16:10 -03:00
Andrey Nering
196d3cb13d add custom Cmd and Dep types 2017-07-03 21:04:38 -03:00
Andrey Nering
a3bfa13670 Merge pull request #35 from smyrman/print-on-set
Print on set
2017-07-03 19:53:03 -03:00
Sindre Røkenes Myren
2ace0defd0 Print command, also when "set:" is specified
Always prints the command, even when the
set-keyword is used within the task.
2017-07-03 15:05:19 +02:00
Sindre Røkenes Myren
023a902f61 Improve task command help text 2017-07-03 15:05:19 +02:00
Andrey Nering
789a4c03df Merge branch 'stdout-redir' 2017-07-01 15:33:44 -03:00
Andrey Nering
ecfd8e8a62 change all tests to call functions instead of binary directly
I had to temporarely hack github.com/mvdan/sh to fix dir handling
2017-07-01 15:32:13 -03:00
Andrey Nering
9ba44f3e6e allow custom Stdin, Stdout and Stderr while running as a lib 2017-07-01 15:05:51 -03:00
Andrey Nering
03fd5c84ec improvements on README 2017-06-28 21:20:52 -03:00
Andrey Nering
81e0f170ef accept setting dir of execution and improve tests
One test is not yet migrated. First we should have specific
Stdin, Stdout and Stderr for executor.
2017-06-24 20:09:05 -03:00
Andrey Nering
7e06ba1728 update deps 2017-06-24 16:00:10 -03:00
Andrey Nering
f8a5825083 readme: improve releases paragraph 2017-06-19 20:55:21 -03:00
Andrey Nering
a14f7f215c setup fpm to release .deb and .rpm packages
closes #15
2017-06-19 20:48:39 -03:00
Andrey Nering
8393e8c52f have a consistent release name format
closes #30
2017-06-19 20:31:03 -03:00
Andrey Nering
81d221667b update deps 2017-06-16 14:59:12 -03:00
569 changed files with 90159 additions and 26598 deletions

View File

@@ -9,6 +9,6 @@ trim_trailing_whitespace = true
indent_style = tab
indent_size = 8
[*.{md,yml,yaml,json,toml}]
[*.{md,yml,yaml,json,toml,htm,html}]
indent_style = space
indent_size = 2

46
.github/CODE_OF_CONDUCT.md vendored Normal file
View File

@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at andrey.nering@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

6
.github/CONTRIBUTING.md vendored Normal file
View File

@@ -0,0 +1,6 @@
* Bug reports and feature requests are welcome in [the issues][issues]
* Pull Requests are welcome. For more complex changes and features it's
recommended to open an issue with the feature request first
* Documentation contributions are as important as code contributions
[issues]: https://github.com/go-task/task/issues

6
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,6 @@
<!--
If relevant, include the following information:
- Task version
- OS
- Example Taskfile showing the issue
-->

9
.gitignore vendored
View File

@@ -14,12 +14,7 @@
.glide/
./task
.task
dist/
vendor/**
!vendor/**/*.go
!vendor/**/LICENSE
!vendor/**/COPYING
!vendor/**/README
!vendor/**/README.md
vendor/**/*_test.go
.DS_Store

44
.goreleaser.yml Normal file
View File

@@ -0,0 +1,44 @@
build:
binary: task
main: cmd/task/task.go
goos:
- windows
- darwin
- linux
goarch:
- 386
- amd64
ignore:
- goos: darwin
goarch: 386
env:
- CGO_ENABLED=0
archive:
name_template: "{{.Binary}}_{{.Os}}_{{.Arch}}"
format_overrides:
- goos: windows
format: zip
release:
draft: true
snapshot:
name_template: "{{.Tag}}"
checksum:
name_template: "task_checksums.txt"
nfpm:
vendor: Task
homepage: https://github.com/go-task/task
maintainer: Andrey Nering <andrey.nering@gmail.com>
description: Simple task runner written in Go
license: MIT
conflicts:
- taskwarrior
formats:
- deb
- rpm
name_template: "{{.ProjectName}}_{{.Os}}_{{.Arch}}"

View File

@@ -1,9 +1,22 @@
language: go
go:
- 1.7
- 1.8
- 1.10.x
- 1.11.x
addons:
apt:
packages:
- rpm
script:
- go install github.com/go-task/task/cmd/task
- task dl-deps
- task lint
- task test
- task ci
deploy:
- provider: script
skip_cleanup: true
script: curl -sL http://git.io/goreleaser | bash
on:
tags: true
condition: $TRAVIS_OS_NAME = linux

151
CHANGELOG.md Normal file
View File

@@ -0,0 +1,151 @@
# Changelog
## v2.3.0 - 2019-01-02
- On Windows, Task can now be installed using [Scoop](https://scoop.sh/)
([#152](https://github.com/go-task/task/pull/152));
- Fixed issue with file/directory globing
([#153](https://github.com/go-task/task/issues/153));
- Added ability to globally set environment variables
(
[#138](https://github.com/go-task/task/pull/138),
[#159](https://github.com/go-task/task/pull/159)
).
## v2.2.1 - 2018-12-09
- This repository now uses Go Modules (#143). We'll still keep the `vendor` directory in sync for some time, though;
- Fixing a bug when the Taskfile has no tasks but includes another Taskfile (#150);
- Fix a bug when calling another task or a dependency in an included Taskfile (#151).
## v2.2.0 - 2018-10-25
- Added support for [including other Taskfiles](https://taskfile.org/#/usage?id=including-other-taskfiles) (#98)
- This should be considered experimental. For now, only including local files is supported, but support for including remote Taskfiles is being discussed. If you have any feedback, please comment on #98.
- Task now have a dedicated documentation site: https://taskfile.org
- Thanks to [Docsify](https://docsify.js.org/) for making this pretty easy. To check the source code, just take a look at the [docs](https://github.com/go-task/task/tree/master/docs) directory of this repository. Contributions to the documentation is really appreciated.
## v2.1.1 - 2018-09-17
- Fix suggestion to use `task --init` not being shown anymore (when a `Taskfile.yml` is not found)
- Fix error when using checksum method and no file exists for a source glob (#131)
- Fix signal handling when the `--watch` flag is given (#132)
## v2.1.0 - 2018-08-19
- Add a `ignore_error` option to task and command (#123)
- Add a dry run mode (`--dry` flag) (#126)
## v2.0.3 - 2018-06-24
- Expand environment variables on "dir", "sources" and "generates" (#116)
- Fix YAML merging syntax (#112)
- Add ZSH completion (#111)
- Implement new `output` option. Please check out the [documentation](https://github.com/go-task/task#output-syntax)
## v2.0.2 - 2018-05-01
- Fix merging of YAML anchors (#112)
## v2.0.1 - 2018-03-11
- Fixes panic on `task --list`
## v2.0.0 - 2018-03-08
Version 2.0.0 is here, with a new Taskfile format.
Please, make sure to read the [Taskfile versions](https://github.com/go-task/task/blob/master/TASKFILE_VERSIONS.md) document, since it describes in depth what changed for this version.
* New Taskfile version 2 (https://github.com/go-task/task/issues/77)
* Possibility to have global variables in the `Taskfile.yml` instead of `Taskvars.yml` (https://github.com/go-task/task/issues/66)
* Small improvements and fixes
## v1.4.4 - 2017-11-19
- Handle SIGINT and SIGTERM (#75);
- List: print message with there's no task with description;
- Expand home dir ("~" symbol) on paths (#74);
- Add Snap as an installation method;
- Move examples to its own repo;
- Watch: also walk on tasks called on on "cmds", and not only on "deps";
- Print logs to stderr instead of stdout (#68);
- Remove deprecated `set` keyword;
- Add checksum based status check, alternative to timestamp based.
## v1.4.3 - 2017-09-07
- Allow assigning variables to tasks at run time via CLI (#33)
- Added suport for multiline variables from sh (#64)
- Fixes env: remove square braces and evaluate shell (#62)
- Watch: change watch library and few fixes and improvements
- When use watching, cancel and restart long running process on file change (#59 and #60)
## v1.4.2 - 2017-07-30
- Flag to set directory of execution
- Always echo command if is verbose mode
- Add silent mode to disable echoing of commands
- Fixes and improvements of variables (#56)
## v1.4.1 - 2017-07-15
- Allow use of YAML for dynamic variables instead of $ prefix
- `VAR: {sh: echo Hello}` instead of `VAR: $echo Hello`
- Add `--list` (or `-l`) flag to print existing tasks
- OS specific Taskvars file (e.g. `Taskvars_windows.yml`, `Taskvars_linux.yml`, etc)
- Consider task up-to-date on equal timestamps (#49)
- Allow absolute path in generates section (#48)
- Bugfix: allow templating when calling deps (#42)
- Fix panic for invalid task in cyclic dep detection
- Better error output for dynamic variables in Taskvars.yml (#41)
- Allow template evaluation in parameters
## v1.4.0 - 2017-07-06
- Cache dynamic variables
- Add verbose mode (`-v` flag)
- Support to task parameters (overriding vars) (#31) (#32)
- Print command, also when "set:" is specified (#35)
- Improve task command help text (#35)
## v1.3.1 - 2017-06-14
- Fix glob not working on commands (#28)
- Add ExeExt template function
- Add `--init` flag to create a new Taskfile
- Add status option to prevent task from running (#27)
- Allow interpolation on `generates` and `sources` attributes (#26)
## v1.3.0 - 2017-04-24
- Migrate from os/exec.Cmd to a native Go sh/bash interpreter
- This is a potentially breaking change if you use Windows.
- Now, `cmd` is not used anymore on Windows. Always use Bash-like syntax for your commands, even on Windows.
- Add "ToSlash" and "FromSlash" to template functions
- Use functions defined on github.com/Masterminds/sprig
- Do not redirect stdin while running variables commands
- Using `context` and `errgroup` packages (this will make other tasks to be cancelled, if one returned an error)
## v1.2.0 - 2017-04-02
- More tests and Travis integration
- Watch a task (experimental)
- Possibility to call another task
- Fix "=" not being reconized in variables/environment variables
- Tasks can now have a description, and help will print them (#10)
- Task dependencies now run concurrently
- Support for a default task (#16)
## v1.1.0 - 2017-03-08
- Support for YAML, TOML and JSON (#1)
- Support running command in another directory (#4)
- `--force` or `-f` flag to force execution of task even when it's up-to-date
- Detection of cyclic dependencies (#5)
- Support for variables (#6, #9, #14)
- Operation System specific commands and variables (#13)
## v1.0.0 - 2017-02-28
- Add LICENSE file

105
Gopkg.lock generated
View File

@@ -1,105 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
branch = "master"
name = "github.com/BurntSushi/toml"
packages = ["."]
revision = "b26d9c308763d68093482582cea63d69be07a0f0"
[[projects]]
branch = "master"
name = "github.com/Masterminds/semver"
packages = ["."]
revision = "abff1900528dbdaf6f3f5aa92c398be1eaf2a9f7"
[[projects]]
branch = "master"
name = "github.com/Masterminds/sprig"
packages = ["."]
revision = "e039e20e500c2c025d9145be375e27cf42a94174"
[[projects]]
branch = "master"
name = "github.com/aokoli/goutils"
packages = ["."]
revision = "3391d3790d23d03408670993e957e8f408993c34"
[[projects]]
branch = "master"
name = "github.com/fsnotify/fsnotify"
packages = ["."]
revision = "4da3e2cfbabc9f751898f250b49f2439785783a1"
[[projects]]
branch = "master"
name = "github.com/huandu/xstrings"
packages = ["."]
revision = "3959339b333561bf62a38b424fd41517c2c90f40"
[[projects]]
branch = "master"
name = "github.com/imdario/mergo"
packages = ["."]
revision = "d806ba8c21777d504a2090a2ca4913c750dd3a33"
[[projects]]
branch = "master"
name = "github.com/mattn/go-zglob"
packages = [".","fastwalk"]
revision = "95345c4e1c0ebc9d16a3284177f09360f4d20fab"
[[projects]]
branch = "master"
name = "github.com/mvdan/sh"
packages = ["interp","syntax"]
revision = "c79708369f1c3cde582a511d52173966c25edefd"
[[projects]]
branch = "master"
name = "github.com/satori/go.uuid"
packages = ["."]
revision = "5bf94b69c6b68ee1b541973bb8e1144db23a194b"
[[projects]]
branch = "master"
name = "github.com/spf13/pflag"
packages = ["."]
revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66"
[[projects]]
branch = "master"
name = "golang.org/x/crypto"
packages = ["pbkdf2","scrypt"]
revision = "e1a4589e7d3ea14a3352255d04b6f1a418845e5e"
[[projects]]
branch = "master"
name = "golang.org/x/net"
packages = ["context"]
revision = "e4fa1c5465ad6111f206fc92186b8c83d64adbe1"
[[projects]]
branch = "master"
name = "golang.org/x/sync"
packages = ["errgroup"]
revision = "f52d1811a62927559de87708c8913c1650ce4f26"
[[projects]]
branch = "master"
name = "golang.org/x/sys"
packages = ["unix"]
revision = "b90f89a1e7a9c1f6b918820b3daa7f08488c8594"
[[projects]]
branch = "v2"
name = "gopkg.in/yaml.v2"
packages = ["."]
revision = "cd8b52f8269e0feb286dfeef29f8fe4d5b397e0b"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "2f626389e1dc4d5ac2e6b83c6b9a50cab0dd3187bbc4e03694810df03a08b3fc"
solver-name = "gps-cdcl"
solver-version = 1

View File

@@ -1,103 +0,0 @@
## Gopkg.toml example (these lines may be deleted)
## "metadata" defines metadata about the project that could be used by other independent
## systems. The metadata defined here will be ignored by dep.
# [metadata]
# key1 = "value that convey data to other systems"
# system1-data = "value that is used by a system"
# system2-data = "value that is used by another system"
## "required" lists a set of packages (not projects) that must be included in
## Gopkg.lock. This list is merged with the set of packages imported by the current
## project. Use it when your project needs a package it doesn't explicitly import -
## including "main" packages.
# required = ["github.com/user/thing/cmd/thing"]
## "ignored" lists a set of packages (not projects) that are ignored when
## dep statically analyzes source code. Ignored packages can be in this project,
## or in a dependency.
# ignored = ["github.com/user/project/badpkg"]
## Constraints are rules for how directly imported projects
## may be incorporated into the depgraph. They are respected by
## dep whether coming from the Gopkg.toml of the current project or a dependency.
# [[constraint]]
## Required: the root import path of the project being constrained.
# name = "github.com/user/project"
#
## Recommended: the version constraint to enforce for the project.
## Only one of "branch", "version" or "revision" can be specified.
# version = "1.0.0"
# branch = "master"
# revision = "abc123"
#
## Optional: an alternate location (URL or import path) for the project's source.
# source = "https://github.com/myfork/package.git"
#
## "metadata" defines metadata about the dependency or override that could be used
## by other independent systems. The metadata defined here will be ignored by dep.
# [metadata]
# key1 = "value that convey data to other systems"
# system1-data = "value that is used by a system"
# system2-data = "value that is used by another system"
## Overrides have the same structure as [[constraint]], but supersede all
## [[constraint]] declarations from all projects. Only [[override]] from
## the current project's are applied.
##
## Overrides are a sledgehammer. Use them only as a last resort.
# [[override]]
## Required: the root import path of the project being constrained.
# name = "github.com/user/project"
#
## Optional: specifying a version constraint override will cause all other
## constraints on this project to be ignored; only the overridden constraint
## need be satisfied.
## Again, only one of "branch", "version" or "revision" can be specified.
# version = "1.0.0"
# branch = "master"
# revision = "abc123"
#
## Optional: specifying an alternate source location as an override will
## enforce that the alternate location is used for that project, regardless of
## what source location any dependent projects specify.
# source = "https://github.com/myfork/package.git"
[[constraint]]
branch = "master"
name = "github.com/BurntSushi/toml"
[[constraint]]
branch = "master"
name = "github.com/Masterminds/sprig"
[[constraint]]
branch = "master"
name = "github.com/fsnotify/fsnotify"
[[constraint]]
branch = "master"
name = "github.com/imdario/mergo"
[[constraint]]
branch = "master"
name = "github.com/mattn/go-zglob"
[[constraint]]
branch = "master"
name = "github.com/mvdan/sh"
[[constraint]]
branch = "master"
name = "github.com/spf13/pflag"
[[constraint]]
branch = "master"
name = "golang.org/x/sync"
[[constraint]]
branch = "v2"
name = "gopkg.in/yaml.v2"

385
README.md
View File

@@ -1,385 +1,22 @@
[![License](https://img.shields.io/github/license/go-task/task.svg)](https://github.com/go-task/task/blob/master/LICENSE)
[![Join the chat at https://gitter.im/go-task/task](https://img.shields.io/gitter/room/go-task/task.svg)](https://gitter.im/go-task/task?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Join Slack room](https://img.shields.io/badge/%23task%20on-gophers%20slack-blue.svg)](https://gophers.slack.com/messages/task)
[![Release Download Count](https://img.shields.io/github/downloads/go-task/task/total.svg)](http://www.somsubhra.com/github-release-stats/?username=go-task&repository=task)
[![Build Status](https://travis-ci.org/go-task/task.svg?branch=master)](https://travis-ci.org/go-task/task)
# Task - Simple task runner / "Make" alternative
# Task
Task is a simple tool that allows you to easily run development and build
tasks. Task is written in Golang, but can be used to develop any language.
It aims to be simpler and easier to use then [GNU Make][make].
Task is a task runner / build tool that aims to be simpler and easier to use
than, for example, [GNU Make](https://www.gnu.org/software/make/).
## Installation
See [taskfile.org](https://taskfile.org) for documentation.
If you have a [Golang][golang] environment setup, you can simply run:
---
```bash
go get -u -v github.com/go-task/task/cmd/task
```
## Sponsors
Or you can download from the [releases][releases] page and add to your `PATH`.
[![Sponsors](https://opencollective.com/task/sponsors.svg?width=890)](https://opencollective.com/task)
## Usage
## Backers
Create a file called `Taskfile.yml` in the root of the project.
(`Taskfile.toml` and `Taskfile.json` are also supported, but YAML is used in
the documentation). The `cmds` attribute should contains the commands of a
task:
[![Backers](https://opencollective.com/task/backers.svg?width=890)](https://opencollective.com/task)
```yml
build:
cmds:
- go build -v -i main.go
## Contributors
assets:
cmds:
- gulp
```
Running the tasks is as simple as running:
```bash
task assets build
```
Task uses [github.com/mvdan/sh](https://github.com/mvdan/sh), a native Go sh
interpreter. So you can write sh/bash commands and it will work even on
Windows, where `sh` or `bash` is usually not available. Just remember any
executable called must be available by the OS or in PATH.
If you ommit a task name, "default" will be assumed.
### Environment
You can specify environment variables that are added when running a command:
```yml
build:
cmds:
- echo $hallo
env:
hallo: welt
```
### OS specific task support
If you add a `Taskfile_{{GOOS}}` you can override or amend your taskfile based
on the operating system.
Example:
Taskfile.yml:
```yml
build:
cmds:
- echo "default"
```
Taskfile_linux.yml:
```yml
build:
cmds:
- echo "linux"
```
Will print out `linux` and not default
### Running task in another dir
By default, tasks will be executed in the directory where the Taskfile is
located. But you can easily make the task run in another folder informing
`dir`:
```yml
js:
dir: www/public/js
cmds:
- gulp
```
### Task dependencies
You may have tasks that depends on others. Just pointing them on `deps` will
make them run automatically before running the parent task:
```yml
build:
deps: [assets]
cmds:
- go build -v -i main.go
assets:
cmds:
- gulp
```
In the above example, `assets` will always run right before `build` if you run
`task build`.
A task can have only dependencies and no commands to group tasks together:
```yml
assets:
deps: [js, css]
js:
cmds:
- npm run buildjs
css:
cmds:
- npm run buildcss
```
Each task can only be run once. If it is included from another dependend task causing
a cyclomatic dependency, execution will be stopped.
```yml
task1:
deps: [task2]
task2:
deps: [task1]
```
Will stop at the moment the dependencies of `task2` are executed.
### Calling a task from another task
When a task has many dependencies, they are executed concurrently. This will
often result in a faster build pipeline. But in some situations you may need
to call other tasks serially. For this just prefix a command with `^`:
```yml
a-task:
cmds:
- ^another-task
- ^even-another-task
- echo "Both done"
another-task:
cmds:
- ...
even-another-task:
cmds:
- ...
```
### Prevent task from running when not necessary
If a task generates something, you can inform Task the source and generated
files, so Task will prevent to run them if not necessary.
```yml
build:
deps: [js, css]
cmds:
- go build -v -i main.go
js:
cmds:
- npm run buildjs
sources:
- js/src/**/*.js
generates:
- public/bundle.js
css:
cmds:
- npm run buildcss
sources:
- css/src/*.css
generates:
- public/bundle.css
```
`sources` and `generates` should be file patterns. When both are given, Task
will compare the modification date/time of the files to determine if it's
necessary to run the task. If not, it will just print
`Task "js" is up to date`.
Alternatively, you can inform a sequence of tests as `status`. If no error
is returned (exit status 0), the task is considered up-to-date:
```yml
generate-files:
cmds:
- mkdir directory
- touch directory/file1.txt
- touch directory/file2.txt
# test existence of files
status:
- test -d directory
- test -f directory/file1.txt
- test -f directory/file2.txt
```
You can use `--force` or `-f` if you want to force a task to run even when
up-to-date.
### Variables
```yml
build:
deps: [setvar]
cmds:
- echo "{{.PREFIX}} {{.THEVAR}}"
vars:
PREFIX: "Path:"
setvar:
cmds:
- echo "{{.PATH}}"
set: THEVAR
```
The above sample saves the path into a new variable which is then again echoed.
You can use environment variables, task level variables and a file called
`Taskvars.yml` (or `Taskvars.toml` or `Taskvars.json`) as source of variables.
They are evaluated in the following order:
Task local variables are overwritten by variables found in `Taskvars` file.
Variables found in `Taskvars` file are overwritten with variables from the
environment. The output of the last command is stored in the environment. So
you can do something like this:
```yml
build:
deps: [setvar]
cmds:
- echo "{{.PREFIX}} '{{.THEVAR}}'"
vars:
PREFIX: "Result: "
setvar:
cmds:
- echo -n "a"
- echo -n "{{.THEVAR}}b"
- echo -n "{{.THEVAR}}c"
set: THEVAR
```
The result of a run of build would be:
```
a
ab
abc
Result: 'abc'
```
#### Dynamic variables
If you prefix a variable with `$`, then the variable is considered a dynamic
variable. The value after the $-symbol will be treated as a command and the
output assigned.
```yml
build:
cmds:
- go build -ldflags="-X main.Version={{.LAST_GIT_COMMIT}}" main.go
vars:
LAST_GIT_COMMIT: $git log -n 1 --format=%h
```
### Go's template engine
Task parse commands as [Go's template engine][gotemplate] before executing
them. Variables are acessible through dot syntax (`.VARNAME`).
All functions by the Go's [sprig lib](http://masterminds.github.io/sprig/)
are available. The following example gets the current date in a given format:
```go
print-date:
cmds:
- echo {{now | date "2006-01-02"}}
```
Task also adds the following functions:
- `OS`: Returns operating system. Possible values are "windows", "linux",
"darwin" (macOS) and "freebsd".
- `ARCH`: return the architecture Task was compiled to: "386", "amd64", "arm"
or "s390x".
- `ToSlash`: Does nothing on Unix, but on Windows converts a string from `\`
path format to `/`.
- `FromSlash`: Oposite of `ToSlash`. Does nothing on Unix, but on Windows
converts a string from `\` path format to `/`.
- `ExeExt`: Returns the right executable extension for the current OS
(`".exe"` for Windows, `""` for others).
Example:
```yml
printos:
cmds:
- echo '{{OS}} {{ARCH}}'
- "echo '{{if eq OS \"windows\"}}windows-command{{else}}unix-command{{end}}'"
# This will be path/to/file on Unix but path\to\file on Windows
- "{{FromSlash \"path/to/file\"}}"
```
### Help
Running `task help` lists all tasks with a description. The following taskfile:
```yml
build:
desc: Build the go binary.
cmds:
- go build -v -i main.go
test:
desc: Run all the go tests.
cmds:
- go test -race ./...
js:
cmds:
- npm run buildjs
css:
cmds:
- npm run buildcss
```
would print the following output:
```bash
build Build the go binary.
test Run all the go tests.
```
## Watch tasks (experimental)
If you give a `--watch` or `-w` argument, task will watch for files changes
and run the task again. This requires the `sources` attribute to be given,
so task know which files to watch.
## Alternative task runners
- YAML based:
- [tj/robo][robo]
- [dogtools/dog][dog]
- [goeuro/myke][myke]
- Go based:
- [go-godo][godo]
- [markbates/grift][grift]
[make]: https://www.gnu.org/software/make/
[releases]: https://github.com/go-task/task/releases
[golang]: https://golang.org/
[gotemplate]: https://golang.org/pkg/text/template/
[robo]: https://github.com/tj/robo
[dog]: https://github.com/dogtools/dog
[myke]: https://github.com/goeuro/myke
[godo]: https://github.com/go-godo/godo
[grift]: https://github.com/markbates/grift
[sh]: https://github.com/mvdan/sh
[![Contributors](https://opencollective.com/task/contributors.svg?width=890)](https://github.com/go-task/task/graphs/contributors)

View File

@@ -1,49 +1,88 @@
# compiles current source code and make "task" executable available on
# $GOPATH/bin/task{.exe}
install:
desc: Installs Task
cmds:
- go install -v -ldflags="-w -s -X main.version={{.GIT_COMMIT}}" ./cmd/task
vars:
GIT_COMMIT: $git log -n 1 --format=%h
version: '2'
dl-deps:
desc: Downloads cli dependencies
cmds:
- go get -u github.com/golang/lint/golint
- go get -u github.com/goreleaser/goreleaser
- go get -u github.com/golang/dep/cmd/dep
includes:
docs: ./docs
update-deps:
cmds:
- dep ensure
- dep prune
vars:
GIT_COMMIT:
sh: git log -n 1 --format=%h
clean:
desc: Cleans temp files and folders
cmds:
- rm -rf dist/
GO_PACKAGES:
sh: go list ./...
lint:
desc: Runs golint
cmds:
- golint .
- golint ./execext
- golint ./cmd/task
tasks:
default:
cmds:
- task: test
test:
desc: Runs test suite
deps: [install]
cmds:
- go test -v
install:
desc: Installs Task
cmds:
- go install -v -ldflags="-w -s -X main.version={{.GIT_COMMIT}}" ./cmd/task
env:
CGO_ENABLED: '0'
# https://github.com/goreleaser/goreleaser
release:
desc: Release Task
cmds:
- goreleaser
dl-deps:
desc: Downloads cli dependencies
cmds:
- task: go-get
vars: {REPO: golang.org/x/lint/golint}
- task: go-get
vars: {REPO: github.com/goreleaser/goreleaser}
- task: go-get
vars: {REPO: github.com/goreleaser/godownloader}
test-release:
desc: Tests release process without publishing
cmds:
- goreleaser --skip-validate --skip-publish
vendor:
desc: Sync vendor/ directory according to go.mod file
cmds:
- go mod vendor
update-deps:
desc: Updates dependencies
cmds:
- dep ensure
- dep ensure -update
clean:
desc: Cleans temp files and folders
cmds:
- rm -rf dist/
lint:
desc: Runs golint
cmds:
- golint {{catLines .GO_PACKAGES}}
silent: true
test:
desc: Runs test suite
deps: [install]
cmds:
- go test {{catLines .GO_PACKAGES}}
test-release:
desc: Tests release process without publishing
cmds:
- goreleaser --snapshot --rm-dist
generate-install-script:
desc: Generate install script using https://github.com/goreleaser/godownloader
cmds:
- godownloader --repo go-task/task -o install-task.sh
- cp ./install-task.sh ./docs/install.sh
ci:
cmds:
- task: go-get
vars: {REPO: golang.org/x/lint/golint}
- task: lint
- task: test
go-get:
cmds:
- go get -u {{.REPO}}
packages:
cmds:
- echo '{{.GO_PACKAGES}}'
silent: true

View File

@@ -1,10 +1,14 @@
package main
import (
"fmt"
"context"
"log"
"os"
"os/signal"
"syscall"
"github.com/go-task/task"
"github.com/go-task/task/v2"
"github.com/go-task/task/v2/internal/args"
"github.com/spf13/pflag"
)
@@ -13,14 +17,14 @@ var (
version = "master"
)
func main() {
log.SetFlags(0)
const usage = `Usage: task [-ilfwvsd] [--init] [--list] [--force] [--watch] [--verbose] [--silent] [--dir] [--dry] [task...]
pflag.Usage = func() {
fmt.Println(`task [target1 target2 ...]: Runs commands under targets like make.
Runs the specified task(s). Falls back to the "default" task if no task name
was specified, or lists all tasks if an unknown task name was specified.
Example: 'task hello' with the following 'Taskfile.yml' file will generate an
'output.txt' file with the content "hello".
Example: 'task hello' with the following 'Taskfile.yml' file will generate
an 'output.txt' file.
'''
hello:
cmds:
@@ -29,21 +33,42 @@ hello:
generates:
- output.txt
'''
`)
Options:
`
func main() {
log.SetFlags(0)
log.SetOutput(os.Stderr)
pflag.Usage = func() {
log.Print(usage)
pflag.PrintDefaults()
}
var (
versionFlag bool
init bool
list bool
status bool
force bool
watch bool
verbose bool
silent bool
dry bool
dir string
)
pflag.BoolVar(&versionFlag, "version", false, "show Task version")
pflag.BoolVarP(&init, "init", "i", false, "creates a new Taskfile.yml in the current folder")
pflag.BoolVarP(&list, "list", "l", false, "lists tasks with description of current Taskfile")
pflag.BoolVar(&status, "status", false, "exits with non-zero exit code if any of the given tasks is not up-to-date")
pflag.BoolVarP(&force, "force", "f", false, "forces execution even when the task is up-to-date")
pflag.BoolVarP(&watch, "watch", "w", false, "enables watch of the given task")
pflag.BoolVarP(&verbose, "verbose", "v", false, "enables verbose mode")
pflag.BoolVarP(&silent, "silent", "s", false, "disables echoing")
pflag.BoolVar(&dry, "dry", false, "compiles and prints tasks in the order that they would be run, without executing them")
pflag.StringVarP(&dir, "dir", "d", "", "sets directory of execution")
pflag.Parse()
if versionFlag {
@@ -52,27 +77,75 @@ hello:
}
if init {
if err := task.InitTaskfile(); err != nil {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if err := task.InitTaskfile(os.Stdout, wd); err != nil {
log.Fatal(err)
}
return
}
e := task.Executor{
Force: force,
Watch: watch,
ctx := context.Background()
if !watch {
ctx = getSignalContext()
}
if err := e.ReadTaskfile(); err != nil {
e := task.Executor{
Force: force,
Watch: watch,
Verbose: verbose,
Silent: silent,
Dir: dir,
Dry: dry,
Context: ctx,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
}
if err := e.Setup(); err != nil {
log.Fatal(err)
}
args := pflag.Args()
if len(args) == 0 {
log.Println("task: No argument given, trying default task")
args = []string{"default"}
if list {
e.PrintTasksHelp()
return
}
if err := e.Run(args...); err != nil {
arguments := pflag.Args()
if len(arguments) == 0 {
log.Println("task: No argument given, trying default task")
arguments = []string{"default"}
}
calls, err := args.Parse(arguments...)
if err != nil {
log.Fatal(err)
}
if status {
if err = e.Status(calls...); err != nil {
log.Fatal(err)
}
return
}
if err := e.Run(calls...); err != nil {
log.Fatal(err)
}
}
func getSignalContext() context.Context {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
sig := <-ch
log.Printf("task: signal received: %s", sig)
cancel()
}()
return ctx
}

25
completion/zsh/_task Normal file
View File

@@ -0,0 +1,25 @@
#compdef task
# Listing commands from Taskfile.yml
function __list() {
local -a scripts
if [ -f Taskfile.yml ]; then
scripts=($(task -l | sed '1d' | sed 's/://' | awk '{ print $2 }'))
_describe 'script' scripts
fi
}
_arguments \
'(-d --dir)'{-d,--dir}': :_files' \
'(--dry)'--dry \
'(-f --force)'{-f,--force} \
'(-i --init)'{-i,--init} \
'(-l --list)'{-l,--list} \
'(-s --silent)'{-s,--silent} \
'(--status)'--status \
'(-v --verbose)'{-v,--verbose} \
'(--version)'--version \
'(-w --watch)'{-w,--watch} \
'(- *)'{-h,--help} \
'*: :__list' \

View File

@@ -1,29 +0,0 @@
package task
// HasCyclicDep checks if a task tree has any cyclic dependency
func (e *Executor) HasCyclicDep() bool {
visits := make(map[string]struct{}, len(e.Tasks))
var checkCyclicDep func(string, *Task) bool
checkCyclicDep = func(name string, t *Task) bool {
if _, ok := visits[name]; ok {
return false
}
visits[name] = struct{}{}
defer delete(visits, name)
for _, d := range t.Deps {
if !checkCyclicDep(d, e.Tasks[d]) {
return false
}
}
return true
}
for k, v := range e.Tasks {
if !checkCyclicDep(k, v) {
return true
}
}
return false
}

View File

@@ -1,40 +0,0 @@
package task_test
import (
"testing"
"github.com/go-task/task"
)
func TestCyclicDepCheck(t *testing.T) {
isCyclic := &task.Executor{
Tasks: task.Tasks{
"task-a": &task.Task{
Deps: []string{"task-b"},
},
"task-b": &task.Task{
Deps: []string{"task-a"},
},
},
}
if !isCyclic.HasCyclicDep() {
t.Error("Task should be cyclic")
}
isNotCyclic := &task.Executor{
Tasks: task.Tasks{
"task-a": &task.Task{
Deps: []string{"task-c"},
},
"task-b": &task.Task{
Deps: []string{"task-c"},
},
"task-c": &task.Task{},
},
}
if isNotCyclic.HasCyclicDep() {
t.Error("Task should not be cyclic")
}
}

0
docs/.nojekyll Normal file
View File

1
docs/CNAME Normal file
View File

@@ -0,0 +1 @@
taskfile.org

59
docs/README.md Normal file
View File

@@ -0,0 +1,59 @@
# Task
Task is a task runner / build tool that aims to be simpler and easier to use
than, for example, [GNU Make][make].
Since it's written in [Go][go], Task is just a single binary and has no other
dependencies, which means you don't need to mess with any complicated install
setups just to use a build tool.
Once [installed](installation.md), you just need to describe your build tasks
using a simple [YAML][yaml] schema in a file called `Taskfile.yml`:
```yaml
version: '2'
tasks:
hello:
cmds:
- echo 'Hello World from Task!'
silent: true
```
And call it by running `task hello` from you terminal.
The above example is just the start, you can take a look at the [usage](usage.md)
guide to check the full schema documentation and Task features.
## Features
- [Easy installation](installation.md): just download a single binary, add to
$PATH and you're done! Or you can also install using [Homebrew][homebrew],
[Snapcraft][snapcraft], or [Scoop][scoop] if you want;
- Available on CIs: by adding [this simple command](installation.md#install-script)
to install on your CI script and you're done to use Task as part of your CI pipeline;
- Truly cross-platform: while most build tools only work well on Linux or macOS,
Task also supports Windows thanks to [this awesome shell interpreter for Go][sh];
- Great for code generation: you can easily [prevent a task from running](usage.md#prevent-unnecessary-work)
if a given set of files haven't changed since last run (based either on its
timestamp or content).
## Sponsors
[![Sponsors](https://opencollective.com/task/sponsors.svg?width=890)](https://opencollective.com/task)
## Backers
[![Backers](https://opencollective.com/task/backers.svg?width=890)](https://opencollective.com/task)
## Contributors
[![Contributors](https://opencollective.com/task/contributors.svg?width=890)](https://github.com/go-task/task/graphs/contributors)
[make]: https://www.gnu.org/software/make/
[go]: https://golang.org/
[yaml]: http://yaml.org/
[homebrew]: https://brew.sh/
[snapcraft]: https://snapcraft.io/
[scoop]: https://scoop.sh/
[sh]: https://mvdan.cc/sh

12
docs/Taskfile.yml Normal file
View File

@@ -0,0 +1,12 @@
version: '2'
tasks:
install:
desc: Installs docsify to work the on the documentation site
cmds:
- npm install docsify-cli -g
serve:
desc: Serves the documentation site locally
cmds:
- docsify serve docs

7
docs/_sidebar.md Normal file
View File

@@ -0,0 +1,7 @@
- [Installation](installation.md)
- [Usage](usage.md)
- [Taskfile Versions](taskfile_versions.md)
- [Examples](examples.md)
- [Releasing Task](releasing_task.md)
- [Alternative Task Runners](alternative_task_runners.md)
- [![Github](https://icongram.jgog.in/simple/github.svg?color=808080&size=16)Github](https://github.com/go-task/task)

View File

@@ -0,0 +1,17 @@
# Alternative task runners
## YAML based
- [rliebz/tusk][tusk]
## Go based
- [magefile/mage][mage]
## Make similar
- [casey/just][just]
[tusk]: https://github.com/rliebz/tusk
[mage]: https://github.com/magefile/mage
[just]: https://github.com/casey/just

7
docs/examples.md Normal file
View File

@@ -0,0 +1,7 @@
# Examples
The [go-task/examples][examples] intends to be a collection of Taskfiles for
various use cases.
(It still lacks many examples, though. Contributions are welcome).
[examples]: https://github.com/go-task/examples

BIN
docs/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

49
docs/index.html Normal file
View File

@@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="description" content="A task runner / simpler Make alternative written in Go">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//unpkg.com/docsify-themeable/dist/css/theme-simple.css">
<meta name="google-site-verification" content="VGAYkbdmuaciIDGkBe-eAg9yfZg0C6ostgonbGxxOa0" />
<script>
var SeedAndDewConfig = {};
(function() {
SeedAndDewConfig['adClass'] = "snd-ad";
/* * * DON'T EDIT BELOW THIS LINE * * */
SeedAndDewConfig['projectId'] = '16e0aed0-b265-48c9-9eae-0aad56147553';
SeedAndDewConfig['loadStartTime'] = performance.now();
SeedAndDewConfig['apiVersion'] = '2018-05-28'
SeedAndDewConfig['sessionId'] = Math.random().toString(36).substring(2, 15);
var snd = document.createElement('script');
snd.type = 'text/javascript';
snd.async = true;
snd.src = 'https://www.seedanddew.com/static/embed.min.js';
(document.getElementsByTagName('head')[0] ||
document.getElementsByTagName('body')[0]).appendChild(snd);
})();
</script>
</head>
<body>
<div id="app"></div>
<script>
window.$docsify = {
name: 'Task',
repo: 'go-task/task',
ga: 'UA-126286662-1',
themeColor: '#83d0f2',
loadSidebar: true,
auto2top: true,
maxLevel: 3,
subMaxLevel: 3
}
</script>
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
<script src="//unpkg.com/docsify/lib/plugins/ga.min.js"></script>
<script src="//unpkg.com/docsify-themeable"></script>
<script src="//unpkg.com/prismjs/components/prism-bash.min.js"></script>
<script src="//unpkg.com/prismjs/components/prism-yaml.min.js"></script>
</body>
</html>

390
docs/install.sh Executable file
View File

@@ -0,0 +1,390 @@
#!/bin/sh
set -e
# Code generated by godownloader on 2018-04-07T17:47:38Z. DO NOT EDIT.
#
usage() {
this=$1
cat <<EOF
$this: download go binaries for go-task/task
Usage: $this [-b] bindir [-d] [tag]
-b sets bindir or installation directory, Defaults to ./bin
-d turns on debug logging
[tag] is a tag from
https://github.com/go-task/task/releases
If tag is missing, then the latest will be used.
Generated by godownloader
https://github.com/goreleaser/godownloader
EOF
exit 2
}
parse_args() {
#BINDIR is ./bin unless set be ENV
# over-ridden by flag below
BINDIR=${BINDIR:-./bin}
while getopts "b:dh?" arg; do
case "$arg" in
b) BINDIR="$OPTARG" ;;
d) log_set_priority 10 ;;
h | \?) usage "$0" ;;
esac
done
shift $((OPTIND - 1))
TAG=$1
}
# this function wraps all the destructive operations
# if a curl|bash cuts off the end of the script due to
# network, either nothing will happen or will syntax error
# out preventing half-done work
execute() {
tmpdir=$(mktmpdir)
log_debug "downloading files into ${tmpdir}"
http_download "${tmpdir}/${TARBALL}" "${TARBALL_URL}"
http_download "${tmpdir}/${CHECKSUM}" "${CHECKSUM_URL}"
hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUM}"
srcdir="${tmpdir}"
(cd "${tmpdir}" && untar "${TARBALL}")
install -d "${BINDIR}"
for binexe in "task" ; do
if [ "$OS" = "windows" ]; then
binexe="${binexe}.exe"
fi
install "${srcdir}/${binexe}" "${BINDIR}/"
log_info "installed ${BINDIR}/${binexe}"
done
}
is_supported_platform() {
platform=$1
found=1
case "$platform" in
windows/386) found=0 ;;
windows/amd64) found=0 ;;
darwin/386) found=0 ;;
darwin/amd64) found=0 ;;
linux/386) found=0 ;;
linux/amd64) found=0 ;;
esac
case "$platform" in
darwin/386) found=1 ;;
esac
return $found
}
check_platform() {
if is_supported_platform "$PLATFORM"; then
# optional logging goes here
true
else
log_crit "platform $PLATFORM is not supported. Make sure this script is up-to-date and file request at https://github.com/${PREFIX}/issues/new"
exit 1
fi
}
tag_to_version() {
if [ -z "${TAG}" ]; then
log_info "checking GitHub for latest tag"
else
log_info "checking GitHub for tag '${TAG}'"
fi
REALTAG=$(github_release "$OWNER/$REPO" "${TAG}") && true
if test -z "$REALTAG"; then
log_crit "unable to find '${TAG}' - use 'latest' or see https://github.com/${PREFIX}/releases for details"
exit 1
fi
# if version starts with 'v', remove it
TAG="$REALTAG"
VERSION=${TAG#v}
}
adjust_format() {
# change format (tar.gz or zip) based on ARCH
case ${ARCH} in
windows) FORMAT=zip ;;
esac
true
}
adjust_os() {
# adjust archive name based on OS
true
}
adjust_arch() {
# adjust archive name based on ARCH
true
}
cat /dev/null <<EOF
------------------------------------------------------------------------
https://github.com/client9/shlib - portable posix shell functions
Public domain - http://unlicense.org
https://github.com/client9/shlib/blob/master/LICENSE.md
but credit (and pull requests) appreciated.
------------------------------------------------------------------------
EOF
is_command() {
command -v "$1" >/dev/null
}
echoerr() {
echo "$@" 1>&2
}
log_prefix() {
echo "$0"
}
_logp=6
log_set_priority() {
_logp="$1"
}
log_priority() {
if test -z "$1"; then
echo "$_logp"
return
fi
[ "$1" -le "$_logp" ]
}
log_tag() {
case $1 in
0) echo "emerg" ;;
1) echo "alert" ;;
2) echo "crit" ;;
3) echo "err" ;;
4) echo "warning" ;;
5) echo "notice" ;;
6) echo "info" ;;
7) echo "debug" ;;
*) echo "$1" ;;
esac
}
log_debug() {
log_priority 7 || return 0
echoerr "$(log_prefix)" "$(log_tag 7)" "$@"
}
log_info() {
log_priority 6 || return 0
echoerr "$(log_prefix)" "$(log_tag 6)" "$@"
}
log_err() {
log_priority 3 || return 0
echoerr "$(log_prefix)" "$(log_tag 3)" "$@"
}
log_crit() {
log_priority 2 || return 0
echoerr "$(log_prefix)" "$(log_tag 2)" "$@"
}
uname_os() {
os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
msys_nt) os="windows" ;;
esac
echo "$os"
}
uname_arch() {
arch=$(uname -m)
case $arch in
x86_64) arch="amd64" ;;
x86) arch="386" ;;
i686) arch="386" ;;
i386) arch="386" ;;
aarch64) arch="arm64" ;;
armv5*) arch="arm5" ;;
armv6*) arch="arm6" ;;
armv7*) arch="arm7" ;;
esac
echo ${arch}
}
uname_os_check() {
os=$(uname_os)
case "$os" in
darwin) return 0 ;;
dragonfly) return 0 ;;
freebsd) return 0 ;;
linux) return 0 ;;
android) return 0 ;;
nacl) return 0 ;;
netbsd) return 0 ;;
openbsd) return 0 ;;
plan9) return 0 ;;
solaris) return 0 ;;
windows) return 0 ;;
esac
log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib"
return 1
}
uname_arch_check() {
arch=$(uname_arch)
case "$arch" in
386) return 0 ;;
amd64) return 0 ;;
arm64) return 0 ;;
armv5) return 0 ;;
armv6) return 0 ;;
armv7) return 0 ;;
ppc64) return 0 ;;
ppc64le) return 0 ;;
mips) return 0 ;;
mipsle) return 0 ;;
mips64) return 0 ;;
mips64le) return 0 ;;
s390x) return 0 ;;
amd64p32) return 0 ;;
esac
log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib"
return 1
}
untar() {
tarball=$1
case "${tarball}" in
*.tar.gz | *.tgz) tar -xzf "${tarball}" ;;
*.tar) tar -xf "${tarball}" ;;
*.zip) unzip "${tarball}" ;;
*)
log_err "untar unknown archive format for ${tarball}"
return 1
;;
esac
}
mktmpdir() {
test -z "$TMPDIR" && TMPDIR="$(mktemp -d)"
mkdir -p "${TMPDIR}"
echo "${TMPDIR}"
}
http_download_curl() {
local_file=$1
source_url=$2
header=$3
if [ -z "$header" ]; then
code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url")
else
code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url")
fi
if [ "$code" != "200" ]; then
log_debug "http_download_curl received HTTP status $code"
return 1
fi
return 0
}
http_download_wget() {
local_file=$1
source_url=$2
header=$3
if [ -z "$header" ]; then
wget -q -O "$local_file" "$source_url"
else
wget -q --header "$header" -O "$local_file" "$source_url"
fi
}
http_download() {
log_debug "http_download $2"
if is_command curl; then
http_download_curl "$@"
return
elif is_command wget; then
http_download_wget "$@"
return
fi
log_crit "http_download unable to find wget or curl"
return 1
}
http_copy() {
tmp=$(mktemp)
http_download "${tmp}" "$1" "$2" || return 1
body=$(cat "$tmp")
rm -f "${tmp}"
echo "$body"
}
github_release() {
owner_repo=$1
version=$2
test -z "$version" && version="latest"
giturl="https://github.com/${owner_repo}/releases/${version}"
json=$(http_copy "$giturl" "Accept:application/json")
test -z "$json" && return 1
version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//')
test -z "$version" && return 1
echo "$version"
}
hash_sha256() {
TARGET=${1:-/dev/stdin}
if is_command gsha256sum; then
hash=$(gsha256sum "$TARGET") || return 1
echo "$hash" | cut -d ' ' -f 1
elif is_command sha256sum; then
hash=$(sha256sum "$TARGET") || return 1
echo "$hash" | cut -d ' ' -f 1
elif is_command shasum; then
hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1
echo "$hash" | cut -d ' ' -f 1
elif is_command openssl; then
hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1
echo "$hash" | cut -d ' ' -f a
else
log_crit "hash_sha256 unable to find command to compute sha-256 hash"
return 1
fi
}
hash_sha256_verify() {
TARGET=$1
checksums=$2
if [ -z "$checksums" ]; then
log_err "hash_sha256_verify checksum file not specified in arg2"
return 1
fi
BASENAME=${TARGET##*/}
want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1)
if [ -z "$want" ]; then
log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'"
return 1
fi
got=$(hash_sha256 "$TARGET")
if [ "$want" != "$got" ]; then
log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got"
return 1
fi
}
cat /dev/null <<EOF
------------------------------------------------------------------------
End of functions from https://github.com/client9/shlib
------------------------------------------------------------------------
EOF
PROJECT_NAME="task"
OWNER=go-task
REPO="task"
BINARY=task
FORMAT=tar.gz
OS=$(uname_os)
ARCH=$(uname_arch)
PREFIX="$OWNER/$REPO"
# use in logging routines
log_prefix() {
echo "$PREFIX"
}
PLATFORM="${OS}/${ARCH}"
GITHUB_DOWNLOAD=https://github.com/${OWNER}/${REPO}/releases/download
uname_os_check "$OS"
uname_arch_check "$ARCH"
parse_args "$@"
check_platform
tag_to_version
adjust_format
adjust_os
adjust_arch
log_info "found version: ${VERSION} for ${TAG}/${OS}/${ARCH}"
NAME=${BINARY}_${OS}_${ARCH}
TARBALL=${NAME}.${FORMAT}
TARBALL_URL=${GITHUB_DOWNLOAD}/${TAG}/${TARBALL}
CHECKSUM=task_checksums.txt
CHECKSUM_URL=${GITHUB_DOWNLOAD}/${TAG}/${CHECKSUM}
execute

90
docs/installation.md Normal file
View File

@@ -0,0 +1,90 @@
# Installation
## Binary
Or you can download the binary from the [releases][releases] page and add to
your $PATH. DEB and RPM packages are also available.
The `task_checksums.txt` file contains the sha256 checksum for each file.
## Homebrew
If you're on macOS and have [Homebrew][homebrew] installed, getting Task is
as simple as running:
```bash
brew install go-task/tap/go-task
```
## Snap
Task is available for [Snapcraft][snapcraft], but keep in mind that your
Linux distribution should allow classic confinement for Snaps to Task work
right:
```bash
sudo snap install task
```
## Scoop
If you're on Windows and have [Scoop][scoop] installed, use `extras` bucket
to install Task like:
```cmd
scoop bucket add extras
scoop install task
```
This installation method is community owned. After a new release of Task, it
may take some time until it's available on Scoop.
## Go
Task now uses [Go Modules](https://github.com/golang/go/wiki/Modules), which
means you may have trouble compiling it on older Go versions.
For CI environments we recommend using the [Install Script](#install-script)
instead, which is faster and more stable, since it'll just download the latest
released binary, instead of compiling the edge (master branch) version.
Installing in your `$GOPATH`:
```bash
go get -u -v github.com/go-task/task/cmd/task
```
Installing in another directory:
```bash
git clone https://github.com/go-task/task
cd task
# compiling binary to $GOPATH/bin
go install -v
# compiling it to another location
# use -o ./task.exe on Windows
go build -v -o ./task ./cmd/task
```
Both methods requires having the [Go][go] environment properly setup locally.
## Install script
We also have a [install script][installscript], which is very useful on
scenarios like CIs. Many thanks to [godownloader][godownloader] for allowing
easily generating this script.
```bash
curl -s https://taskfile.org/install.sh | sh
```
> This method will download the binary on the local `./bin` directory by default.
[go]: https://golang.org/
[snapcraft]: https://snapcraft.io/
[homebrew]: https://brew.sh/
[installscript]: https://github.com/go-task/task/blob/master/install-task.sh
[releases]: https://github.com/go-task/task/releases
[godownloader]: https://github.com/goreleaser/godownloader
[scoop]: https://scoop.sh/

39
docs/releasing_task.md Normal file
View File

@@ -0,0 +1,39 @@
# Releasing Task
The release process of Task is done with the help of
[GoReleaser][goreleaser]. You can test the release process locally by calling
the `test-release` task of the Taskfile.
The Travis CI should release automatically when a new
Git tag is pushed to master, either for the artifact uploading (raw executables
and DEB and RPM packages)
# Homebrew
To release a new version on the [Homebrew tap][homebrewtap] edit the
[Formula/go-task.rb][gotaskrb] file, updating with the new version, download
URL and sha256.
# Snapcraft
The exception is the publishing of a new version of the
[snap package][snappackage]. This current require two steps after publishing
the binaries:
* Updating the current version on [snapcraft.yaml][snapcraftyaml];
* Moving both `i386` and `amd64` new artifacts to the stable channel on
the [Snapscraft dashboard][snapcraftdashboard]
# Scoop
Scoop is a community owned installation method. Scoop owners usually take care
of updating versions there by editing
[this file](https://github.com/lukesampson/scoop-extras/blob/master/task.json).
If you think its Task version is outdated, open an issue to let us know.
[goreleaser]: https://goreleaser.com/#continuous_integration
[homebrewtap]: https://github.com/go-task/homebrew-tap
[gotaskrb]: https://github.com/go-task/homebrew-tap/blob/master/Formula/go-task.rb
[snappackage]: https://github.com/go-task/snap
[snapcraftyaml]: https://github.com/go-task/snap/blob/master/snap/snapcraft.yaml#L2
[snapcraftdashboard]: https://dashboard.snapcraft.io/

148
docs/taskfile_versions.md Normal file
View File

@@ -0,0 +1,148 @@
# Taskfile Versions
The Taskfile syntax and features changed with time. This document explains what
changed on each version and how to upgrade your Taskfile.
## What the Taskfile version mean
The Taskfile version follows the Task version. E.g. the change to Taskfile
version `2` means that Task `v2.0.0` should be release to support it.
The `version:` key on Taskfile accepts a semver string, so either `2`, `2.0` or
`2.0.0` is accepted. You you choose to use `2.0` Task will not enable future
`2.1` features, but if you choose to use `2`, than any `2.x.x` features will be
available, but not `3.0.0+`.
## Version 1
In the first version of the `Taskfile`, the `version:` key was not available,
because the tasks was in the root of the YAML document. Like this:
```yaml
echo:
cmds:
- echo "Hello, World!"
```
The variable priority order was also different:
1. Call variables
2. Environment
3. Task variables
4. `Taskvars.yml` variables
## Version 2.0
At version 2, we introduced the `version:` key, to allow us to envolve Task
with new features without breaking existing Taskfiles. The new syntax is as
follows:
```yaml
version: '2'
tasks:
echo:
cmds:
- echo "Hello, World!"
```
Version 2 allows you to write global variables directly in the Taskfile,
if you don't want to create a `Taskvars.yml`:
```yaml
version: '2'
vars:
GREETING: Hello, World!
tasks:
greet:
cmds:
- echo "{{.GREETING}}"
```
The variable priority order changed to the following:
1. Task variables
2. Call variables
3. Taskfile variables
4. Taskvars file variables
5. Environment variables
A new global option was added to configure the number of variables expansions
(which default to 2):
```yaml
version: '2'
expansions: 3
vars:
FOO: foo
BAR: bar
BAZ: baz
FOOBAR: "{{.FOO}}{{.BAR}}"
FOOBARBAZ: "{{.FOOBAR}}{{.BAZ}}"
tasks:
default:
cmds:
- echo "{{.FOOBARBAZ}}"
```
## Version 2.1
Version 2.1 includes a global `output` option, to allow having more control
over how commands output are printed to the console
(see [documentation][output] for more info):
```yaml
version: '2'
output: prefixed
tasks:
server:
cmds:
- go run main.go
prefix: server
```
From this version it's not also possible to ignore errors of a command or task
(check documentation [here][ignore_errors]):
```yaml
version: '2'
tasks:
example-1:
cmds:
- cmd: exit 1
ignore_error: true
- echo "This will be print"
example-2:
cmds:
- exit 1
- echo "This will be print"
ignore_error: true
```
## Version 2.2
Version 2.2 comes with a global `includes` options to include other
Taskfiles:
```yaml
version: '2'
includes:
docs: ./documentation # will look for ./documentation/Taskfile.yml
docker: ./DockerTasks.yml
```
Please check the [documentation][includes]
[output]: usage.md#output-syntax
[ignore_errors]: usage.md#ignore-errors
[includes]: usage.md#including-other-taskfiles

714
docs/usage.md Normal file
View File

@@ -0,0 +1,714 @@
# Usage
## Getting started
Create a file called `Taskfile.yml` in the root of your project.
The `cmds` attribute should contain the commands of a task.
The example below allows compiling a Go app and uses [Minify][minify] to concat
and minify multiple CSS files into a single one.
```yaml
version: '2'
tasks:
build:
cmds:
- go build -v -i main.go
assets:
cmds:
- minify -o public/style.css src/css
```
Running the tasks is as simple as running:
```bash
task assets build
```
Task uses [github.com/mvdan/sh](https://github.com/mvdan/sh), a native Go sh
interpreter. So you can write sh/bash commands and it will work even on
Windows, where `sh` or `bash` are usually not available. Just remember any
executable called must be available by the OS or in PATH.
If you omit a task name, "default" will be assumed.
## Environment
You can use `env` to set custom environment variables for a specific task:
```yaml
version: '2'
tasks:
greet:
cmds:
- echo $GREETING
env:
GREETING: Hey, there!
```
Additionally, you can set globally environment variables, that'll be available
to all tasks:
```yaml
version: '2'
env:
GREETING: Hey, there!
tasks:
greet:
cmds:
- echo $GREETING
```
> NOTE: `env` supports expansion and and retrieving output from a shell command
> just like variables, as you can see on the [Variables](#variables) section.
## Operating System specific tasks
If you add a `Taskfile_{{GOOS}}.yml` you can override or amend your Taskfile
based on the operating system.
Example:
Taskfile.yml:
```yaml
version: '2'
tasks:
build:
cmds:
- echo "default"
```
Taskfile_linux.yml:
```yaml
version: '2'
tasks:
build:
cmds:
- echo "linux"
```
Will print out `linux` and not `default`.
Keep in mind that the version of the files should match. Also, when redefining
a task the whole task is replaced, properties of the task are not merged.
It's also possible to have an OS specific `Taskvars.yml` file, like
`Taskvars_windows.yml`, `Taskvars_linux.yml`, or `Taskvars_darwin.yml`. See the
[variables section](#variables) below.
## Including other Taskfiles
> This feature is still experimental and may have bugs.
If you want to share tasks between different projects (Taskfiles), you can use
the importing mechanism to include other Taskfiles using the `includes` keyword:
```yaml
version: '2'
includes:
docs: ./documentation # will look for ./documentation/Taskfile.yml
docker: ./DockerTasks.yml
```
The tasks described in the given Taskfiles will be available with the informed
namespace. So, you'd call `task docs:serve` to run the `serve` task from
`documentation/Taskfile.yml` or `task docker:build` to run the `build` task
from the `DockerTasks.yml` file.
> The included Taskfiles must be using the same schema version the main
> Taskfile uses.
> Also, for now included Taskfiles can't include other Taskfiles.
> This was a deliberate decision to keep use and implementation simple.
> If you disagree, open an GitHub issue and explain your use case. =)
## Task directory
By default, tasks will be executed in the directory where the Taskfile is
located. But you can easily make the task run in another folder informing
`dir`:
```yaml
version: '2'
tasks:
serve:
dir: public/www
cmds:
# run http server
- caddy
```
## Task dependencies
You may have tasks that depend on others. Just pointing them on `deps` will
make them run automatically before running the parent task:
```yaml
version: '2'
tasks:
build:
deps: [assets]
cmds:
- go build -v -i main.go
assets:
cmds:
- minify -o public/style.css src/css
```
In the above example, `assets` will always run right before `build` if you run
`task build`.
A task can have only dependencies and no commands to group tasks together:
```yaml
version: '2'
tasks:
assets:
deps: [js, css]
js:
cmds:
- minify -o public/script.js src/js
css:
cmds:
- minify -o public/style.css src/css
```
If there is more than one dependency, they always run in parallel for better
performance.
If you want to pass information to dependencies, you can do that the same
manner as you would to [call another task](#calling-another-task):
```yaml
version: '2'
tasks:
default:
deps:
- task: echo_sth
vars: {TEXT: "before 1"}
- task: echo_sth
vars: {TEXT: "before 2"}
cmds:
- echo "after"
echo_sth:
cmds:
- echo {{.TEXT}}
```
## Calling another task
When a task has many dependencies, they are executed concurrently. This will
often result in a faster build pipeline. But in some situations you may need
to call other tasks serially. In this case, just use the following syntax:
```yaml
version: '2'
tasks:
main-task:
cmds:
- task: task-to-be-called
- task: another-task
- echo "Both done"
task-to-be-called:
cmds:
- echo "Task to be called"
another-task:
cmds:
- echo "Another task"
```
Overriding variables in the called task is as simple as informing `vars`
attribute:
```yaml
version: '2'
tasks:
main-task:
cmds:
- task: write-file
vars: {FILE: "hello.txt", CONTENT: "Hello!"}
- task: write-file
vars: {FILE: "world.txt", CONTENT: "World!"}
write-file:
cmds:
- echo "{{.CONTENT}}" > {{.FILE}}
```
The above syntax is also supported in `deps`.
## Prevent unnecessary work
If a task generates something, you can inform Task the source and generated
files, so Task will prevent to run them if not necessary.
```yaml
version: '2'
tasks:
build:
deps: [js, css]
cmds:
- go build -v -i main.go
js:
cmds:
- minify -o public/script.js src/js
sources:
- src/js/**/*.js
generates:
- public/script.js
css:
cmds:
- minify -o public/style.css src/css
sources:
- src/css/**/*.css
generates:
- public/style.css
```
`sources` and `generates` can be files or file patterns. When both are given,
Task will compare the modification date/time of the files to determine if it's
necessary to run the task. If not, it will just print a message like
`Task "js" is up to date`.
If you prefer this check to be made by the content of the files, instead of
its timestamp, just set the `method` property to `checksum`.
You will probably want to ignore the `.task` folder in your `.gitignore` file
(It's there that Task stores the last checksum).
```yaml
version: '2'
tasks:
build:
cmds:
- go build .
sources:
- ./*.go
generates:
- app{{exeExt}}
method: checksum
```
> TIP: method `none` skips any validation and always run the task.
Alternatively, you can inform a sequence of tests as `status`. If no error
is returned (exit status 0), the task is considered up-to-date:
```yaml
version: '2'
tasks:
generate-files:
cmds:
- mkdir directory
- touch directory/file1.txt
- touch directory/file2.txt
# test existence of files
status:
- test -d directory
- test -f directory/file1.txt
- test -f directory/file2.txt
```
You can use `--force` or `-f` if you want to force a task to run even when
up-to-date.
Also, `task --status [tasks]...` will exit with a non-zero exit code if any of
the tasks are not up-to-date.
## Variables
When doing interpolation of variables, Task will look for the below.
They are listed below in order of importance (e.g. most important first):
- Variables declared locally in the task
- Variables given while calling a task from another.
(See [Calling another task](#calling-another-task) above)
- Variables declared in the `vars:` option in the `Taskfile`
- Variables available in the `Taskvars.yml` file
- Environment variables
Example of sending parameters with environment variables:
```bash
$ TASK_VARIABLE=a-value task do-something
```
Since some shells don't support above syntax to set environment variables
(Windows) tasks also accepts a similar style when not in the beginning of
the command. Variables given in this form are only visible to the task called
right before.
```bash
$ task write-file FILE=file.txt "CONTENT=Hello, World!" print "MESSAGE=All done!"
```
Example of locally declared vars:
```yaml
version: '2'
tasks:
print-var:
cmds:
echo "{{.VAR}}"
vars:
VAR: Hello!
```
Example of global vars in a `Taskfile.yml`:
```yaml
version: '2'
vars:
GREETING: Hello from Taskfile!
tasks:
greet:
cmds:
- echo "{{.GREETING}}"
```
Example of `Taskvars.yml` file:
```yaml
PROJECT_NAME: My Project
DEV_MODE: production
GIT_COMMIT: {sh: git log -n 1 --format=%h}
```
### Variables expansion
Variables are expanded 2 times by default. You can change that by setting the
`expansions:` option. Change that will be necessary if you compose many
variables together:
```yaml
version: '2'
expansions: 3
vars:
FOO: foo
BAR: bar
BAZ: baz
FOOBAR: "{{.FOO}}{{.BAR}}"
FOOBARBAZ: "{{.FOOBAR}}{{.BAZ}}"
tasks:
default:
cmds:
- echo "{{.FOOBARBAZ}}"
```
### Dynamic variables
The below syntax (`sh:` prop in a variable) is considered a dynamic variable.
The value will be treated as a command and the output assigned. If there is one
or more trailing newlines, the last newline will be trimmed.
```yaml
version: '2'
tasks:
build:
cmds:
- go build -ldflags="-X main.Version={{.GIT_COMMIT}}" main.go
vars:
GIT_COMMIT:
sh: git log -n 1 --format=%h
```
This works for all types of variables.
## Go's template engine
Task parse commands as [Go's template engine][gotemplate] before executing
them. Variables are accessible through dot syntax (`.VARNAME`).
All functions by the Go's [sprig lib](http://masterminds.github.io/sprig/)
are available. The following example gets the current date in a given format:
```yaml
version: '2'
tasks:
print-date:
cmds:
- echo {{now | date "2006-01-02"}}
```
Task also adds the following functions:
- `OS`: Returns operating system. Possible values are "windows", "linux",
"darwin" (macOS) and "freebsd".
- `ARCH`: return the architecture Task was compiled to: "386", "amd64", "arm"
or "s390x".
- `splitLines`: Splits Unix (\n) and Windows (\r\n) styled newlines.
- `catLines`: Replaces Unix (\n) and Windows (\r\n) styled newlines with a space.
- `toSlash`: Does nothing on Unix, but on Windows converts a string from `\`
path format to `/`.
- `fromSlash`: Opposite of `toSlash`. Does nothing on Unix, but on Windows
converts a string from `\` path format to `/`.
- `exeExt`: Returns the right executable extension for the current OS
(`".exe"` for Windows, `""` for others).
Example:
```yaml
version: '2'
tasks:
print-os:
cmds:
- echo '{{OS}} {{ARCH}}'
- echo '{{if eq OS "windows"}}windows-command{{else}}unix-command{{end}}'
# This will be path/to/file on Unix but path\to\file on Windows
- echo '{{fromSlash "path/to/file"}}'
enumerated-file:
vars:
CONTENT: |
foo
bar
cmds:
- |
cat << EOF > output.txt
{{range $i, $line := .CONTENT | splitLines -}}
{{printf "%3d" $i}}: {{$line}}
{{end}}EOF
```
## Help
Running `task --list` (or `task -l`) lists all tasks with a description.
The following Taskfile:
```yaml
version: '2'
tasks:
build:
desc: Build the go binary.
cmds:
- go build -v -i main.go
test:
desc: Run all the go tests.
cmds:
- go test -race ./...
js:
cmds:
- minify -o public/script.js src/js
css:
cmds:
- minify -o public/style.css src/css
```
would print the following output:
```bash
* build: Build the go binary.
* test: Run all the go tests.
```
## Silent mode
Silent mode disables echoing of commands before Task runs it.
For the following Taskfile:
```yaml
version: '2'
tasks:
echo:
cmds:
- echo "Print something"
```
Normally this will be print:
```sh
echo "Print something"
Print something
```
With silent mode on, the below will be print instead:
```sh
Print something
```
There's three ways to enable silent mode:
* At command level:
```yaml
version: '2'
tasks:
echo:
cmds:
- cmd: echo "Print something"
silent: true
```
* At task level:
```yaml
version: '2'
tasks:
echo:
cmds:
- echo "Print something"
silent: true
```
* Or globally with `--silent` or `-s` flag
If you want to suppress STDOUT instead, just redirect a command to `/dev/null`:
```yaml
version: '2'
tasks:
echo:
cmds:
- echo "This will print nothing" > /dev/null
```
## Dry run mode
Dry run mode (`--dry`) compiles and steps through each task, printing the commands
that would be run without executing them. This is useful for debugging your Taskfiles.
## Ignore errors
You have the option to ignore errors during command execution.
Given the following Taskfile:
```yaml
version: '2'
tasks:
echo:
cmds:
- exit 1
- echo "Hello World"
```
Task will abort the execution after running `exit 1` because the status code `1` stands for `EXIT_FAILURE`.
However it is possible to continue with execution using `ignore_error`:
```yaml
version: '2'
tasks:
echo:
cmds:
- cmd: exit 1
ignore_error: true
- echo "Hello World"
```
`ignore_error` can also be set for a task, which mean errors will be supressed
for all commands. But keep in mind this option won't propagate to other tasks
called either by `deps` or `cmds`!
## Output syntax
By default, Task just redirect the STDOUT and STDERR of the running commands
to the shell in real time. This is good for having live feedback for log
printed by commands, but the output can become messy if you have multiple
commands running at the same time and printing lots of stuff.
To make this more customizable, there are currently three different output
options you can choose:
- `interleaved` (default)
- `group`
- `prefixed`
To choose another one, just set it to root in the Taskfile:
```yaml
version: '2'
output: 'group'
tasks:
# ...
```
The `group` output will print the entire output of a command once, after it
finishes, so you won't have live feedback for commands that take a long time
to run.
The `prefix` output will prefix every line printed by a command with
`[task-name] ` as the prefix, but you can customize the prefix for a command
with the `prefix:` attribute:
```yaml
version: '2'
output: prefixed
tasks:
default:
deps:
- task: print
vars: {TEXT: foo}
- task: print
vars: {TEXT: bar}
- task: print
vars: {TEXT: baz}
print:
cmds:
- echo "{{.TEXT}}"
prefix: "print-{{.TEXT}}"
silent: true
```
```bash
$ task default
[print-foo] foo
[print-bar] bar
[print-baz] baz
```
## Watch tasks
If you give a `--watch` or `-w` argument, task will watch for file changes
and run the task again. This requires the `sources` attribute to be given,
so task know which files to watch.
[gotemplate]: https://golang.org/pkg/text/template/
[minify]: https://github.com/tdewolff/minify/tree/master/cmd/minify

View File

@@ -6,20 +6,10 @@ import (
)
var (
// ErrCyclicDependencyDetected is returned when a cyclic dependency was found in the Taskfile
ErrCyclicDependencyDetected = errors.New("task: cyclic dependency detected")
// ErrTaskfileAlreadyExists is returned on creating a Taskfile if one already exists
ErrTaskfileAlreadyExists = errors.New("task: A Taskfile already exists")
)
type taskFileNotFound struct {
taskFile string
}
func (err taskFileNotFound) Error() string {
return fmt.Sprintf(`task: No task file found (is it named "%s"?). Use "task --init" to create a new one`, err.taskFile)
}
type taskNotFoundError struct {
taskName string
}
@@ -37,18 +27,17 @@ func (err *taskRunError) Error() string {
return fmt.Sprintf(`task: Failed to run task "%s": %v`, err.taskName, err.err)
}
type cyclicDepError struct {
taskName string
// MaximumTaskCallExceededError is returned when a task is called too
// many times. In this case you probably have a cyclic dependendy or
// infinite loop
type MaximumTaskCallExceededError struct {
task string
}
func (err *cyclicDepError) Error() string {
return fmt.Sprintf(`task: Cyclic dependency of task "%s" detected`, err.taskName)
}
type cantWatchNoSourcesError struct {
taskName string
}
func (err *cantWatchNoSourcesError) Error() string {
return fmt.Sprintf(`task: Can't watch task "%s" because it has no specified sources`, err.taskName)
func (e *MaximumTaskCallExceededError) Error() string {
return fmt.Sprintf(
`task: maximum task call exceeded (%d) for task "%s": probably an cyclic dep or infinite loop`,
MaximumTaskCall,
e.task,
)
}

View File

@@ -1,11 +0,0 @@
{
"hello": {
"cmds": [
"echo \"I am going to write a file named 'output.txt' now.\"",
"echo \"hello\" > output.txt"
],
"generates": [
"output.txt"
]
}
}

View File

@@ -1,6 +0,0 @@
[hello]
cmds = [
"echo \"I am going to write a file named 'output.txt' now.\"",
"echo \"hello\" > output.txt"
]
generates = ["output.txt"]

View File

@@ -1,6 +0,0 @@
hello:
cmds:
- echo "I am going to write a file named 'output.txt' now."
- echo "hello" > output.txt
generates:
- output.txt

View File

@@ -1,53 +0,0 @@
package execext
import (
"context"
"errors"
"io"
"strings"
"github.com/mvdan/sh/interp"
"github.com/mvdan/sh/syntax"
)
// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
Context context.Context
Command string
Dir string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
var (
// ErrNilOptions is returned when a nil options is given
ErrNilOptions = errors.New("execext: nil options given")
)
// RunCommand runs a shell command
func RunCommand(opts *RunCommandOptions) error {
if opts == nil {
return ErrNilOptions
}
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
if err != nil {
return err
}
r := interp.Runner{
Context: opts.Context,
File: p,
Dir: opts.Dir,
Env: opts.Env,
Stdin: opts.Stdin,
Stdout: opts.Stdout,
Stderr: opts.Stderr,
}
if err = r.Run(); err != nil {
return err
}
return nil
}

82
file.go
View File

@@ -1,82 +0,0 @@
package task
import (
"os"
"time"
"github.com/mattn/go-zglob"
)
func minTime(a, b time.Time) time.Time {
if !a.IsZero() && a.Before(b) {
return a
}
return b
}
func maxTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
func getPatternsMinTime(patterns []string) (m time.Time, err error) {
for _, p := range patterns {
mp, err := getPatternMinTime(p)
if err != nil {
return time.Time{}, err
}
m = minTime(m, mp)
}
return
}
func getPatternsMaxTime(patterns []string) (m time.Time, err error) {
for _, p := range patterns {
mp, err := getPatternMaxTime(p)
if err != nil {
return time.Time{}, err
}
m = maxTime(m, mp)
}
return
}
func getPatternMinTime(pattern string) (minTime time.Time, err error) {
files, err := zglob.Glob(pattern)
if err != nil {
return time.Time{}, err
}
for _, f := range files {
info, err := os.Stat(f)
if err != nil {
return time.Time{}, err
}
modTime := info.ModTime()
if minTime.IsZero() || modTime.Before(minTime) {
minTime = modTime
}
}
return
}
func getPatternMaxTime(pattern string) (maxTime time.Time, err error) {
files, err := zglob.Glob(pattern)
if err != nil {
return time.Time{}, err
}
for _, f := range files {
info, err := os.Stat(f)
if err != nil {
return time.Time{}, err
}
modTime := info.ModTime()
if modTime.After(maxTime) {
maxTime = modTime
}
}
return
}

24
go.mod Normal file
View File

@@ -0,0 +1,24 @@
module github.com/go-task/task/v2
require (
github.com/Masterminds/semver v1.4.2
github.com/Masterminds/sprig v2.16.0+incompatible
github.com/aokoli/goutils v1.0.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/google/uuid v1.0.0 // indirect
github.com/huandu/xstrings v1.1.0 // indirect
github.com/imdario/mergo v0.3.6 // indirect
github.com/kr/pretty v0.1.0 // indirect
github.com/mattn/go-zglob v0.0.0-20180803001819-2ea3427bfa53
github.com/mitchellh/go-homedir v1.0.0
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/radovskyb/watcher v1.0.2
github.com/spf13/pflag v1.0.3
github.com/stretchr/testify v1.2.2
golang.org/x/crypto v0.0.0-20180830192347-182538f80094 // indirect
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d // indirect
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f
golang.org/x/sys v0.0.0-20180831094639-fa5fdf94c789 // indirect
gopkg.in/yaml.v2 v2.2.1
mvdan.cc/sh v2.6.3-0.20181216173157-8aeb0734cd0f+incompatible
)

45
go.sum Normal file
View File

@@ -0,0 +1,45 @@
github.com/Masterminds/semver v1.4.2 h1:WBLTQ37jOCzSLtXNdoo8bNM8876KhNqOKvrlGITgsTc=
github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/Masterminds/sprig v2.16.0+incompatible h1:QZbMUPxRQ50EKAq3LFMnxddMu88/EUUG3qmxwtDmPsY=
github.com/Masterminds/sprig v2.16.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o=
github.com/aokoli/goutils v1.0.1 h1:7fpzNGoJ3VA8qcrm++XEE1QUe0mIwNeLa02Nwq7RDkg=
github.com/aokoli/goutils v1.0.1/go.mod h1:SijmP0QR8LtwsmDs8Yii5Z/S4trXFGFC2oO5g9DP+DQ=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.0.0 h1:b4Gk+7WdP/d3HZH8EJsZpvV7EtDOgaZLtnaNGIu1adA=
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/huandu/xstrings v1.1.0 h1:9oZY6Z/H3A1gytJxzuicbmV5QoR8M1TAPcn9WTg7vqg=
github.com/huandu/xstrings v1.1.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4=
github.com/imdario/mergo v0.3.6 h1:xTNEAn+kxVO7dTZGu0CegyqKZmoWFI0rF8UxjlB2d28=
github.com/imdario/mergo v0.3.6/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mattn/go-zglob v0.0.0-20180803001819-2ea3427bfa53 h1:tGfIHhDghvEnneeRhODvGYOt305TPwingKt6p90F4MU=
github.com/mattn/go-zglob v0.0.0-20180803001819-2ea3427bfa53/go.mod h1:9fxibJccNxU2cnpIKLRRFA7zX7qhkJIQWBb449FYHOo=
github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/radovskyb/watcher v1.0.2 h1:9L5TsZUbo1nKhQEQPtICVc+x9UZQ6VPdBepLHyGw/bQ=
github.com/radovskyb/watcher v1.0.2/go.mod h1:78okwvY5wPdzcb1UYnip1pvrZNIVEIh/Cm+ZuvsUYIg=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
golang.org/x/crypto v0.0.0-20180830192347-182538f80094 h1:rVTAlhYa4+lCfNxmAIEOGQRoD23UqP72M3+rSWVGDTg=
golang.org/x/crypto v0.0.0-20180830192347-182538f80094/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d h1:g9qWBGx4puODJTMVyoPrpoxPFgVGd+z1DZwjfRu4d0I=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180831094639-fa5fdf94c789 h1:T8D7l6WB3tLu+VpKvw06ieD/OhBi1XpJmG1U/FtttZg=
golang.org/x/sys v0.0.0-20180831094639-fa5fdf94c789/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
mvdan.cc/sh v2.6.3-0.20181216173157-8aeb0734cd0f+incompatible h1:jf0jjqiqwKXdH3JBKY+K3tFXGtUQZr/pFIO+cn0tQCc=
mvdan.cc/sh v2.6.3-0.20181216173157-8aeb0734cd0f+incompatible/go.mod h1:IeeQbZq+x2SUGBensq/jge5lLQbS3XT2ktyp3wrt4x8=

View File

@@ -1,23 +0,0 @@
build:
binary: task
main: cmd/task/task.go
goos:
- windows
- darwin
- linux
goarch:
- 386
- amd64
ignore:
- goos: darwin
goarch: 386
archive:
format_overrides:
- goos: windows
format: zip
replacements:
amd64: x64
386: x86
darwin: macOS

22
help.go
View File

@@ -2,32 +2,36 @@ package task
import (
"fmt"
"os"
"sort"
"text/tabwriter"
"github.com/go-task/task/v2/internal/taskfile"
)
func (e *Executor) printExistingTasksHelp() {
// PrintTasksHelp prints help os tasks that have a description
func (e *Executor) PrintTasksHelp() {
tasks := e.tasksWithDesc()
if len(tasks) == 0 {
e.Logger.Outf("task: No tasks with description available")
return
}
fmt.Println("Available tasks for this project:")
e.Logger.Outf("task: Available tasks for this project:")
// Format in tab-separated columns with a tab stop of 8.
w := tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
w := tabwriter.NewWriter(e.Stdout, 0, 8, 0, '\t', 0)
for _, task := range tasks {
fmt.Fprintln(w, fmt.Sprintf("- %s:\t%s", task, e.Tasks[task].Desc))
fmt.Fprintf(w, "* %s: \t%s\n", task.Task, task.Desc)
}
w.Flush()
}
func (e *Executor) tasksWithDesc() (tasks []string) {
for name, task := range e.Tasks {
func (e *Executor) tasksWithDesc() (tasks []*taskfile.Task) {
tasks = make([]*taskfile.Task, 0, len(e.Taskfile.Tasks))
for _, task := range e.Taskfile.Tasks {
if task.Desc != "" {
tasks = append(tasks, name)
tasks = append(tasks, task)
}
}
sort.Strings(tasks)
sort.Slice(tasks, func(i, j int) bool { return tasks[i].Task < tasks[j].Task })
return
}

33
init.go
View File

@@ -1,29 +1,38 @@
package task
import (
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
)
const defaultTaskfile = `# github.com/go-task/task
const defaultTaskfile = `# https://taskfile.org
default:
cmds:
- echo "Hello, World!"
version: '2'
vars:
GREETING: Hello, World!
tasks:
default:
cmds:
- echo "{{.GREETING}}"
silent: true
`
// InitTaskfile Taskfile creates a new Taskfile
func InitTaskfile() error {
for _, f := range []string{"Taskfile.yml", "Taskfile.toml", "Taskfile.json"} {
if _, err := os.Stat(f); err == nil {
return ErrTaskfileAlreadyExists
}
func InitTaskfile(w io.Writer, dir string) error {
f := filepath.Join(dir, "Taskfile.yml")
if _, err := os.Stat(f); err == nil {
return ErrTaskfileAlreadyExists
}
if err := ioutil.WriteFile("Taskfile.yml", []byte(defaultTaskfile), 0666); err != nil {
if err := ioutil.WriteFile(f, []byte(defaultTaskfile), 0644); err != nil {
return err
}
log.Printf("Taskfile.yml created in the current directory")
fmt.Fprintf(w, "Taskfile.yml created in the current directory\n")
return nil
}

390
install-task.sh Executable file
View File

@@ -0,0 +1,390 @@
#!/bin/sh
set -e
# Code generated by godownloader on 2018-04-07T17:47:38Z. DO NOT EDIT.
#
usage() {
this=$1
cat <<EOF
$this: download go binaries for go-task/task
Usage: $this [-b] bindir [-d] [tag]
-b sets bindir or installation directory, Defaults to ./bin
-d turns on debug logging
[tag] is a tag from
https://github.com/go-task/task/releases
If tag is missing, then the latest will be used.
Generated by godownloader
https://github.com/goreleaser/godownloader
EOF
exit 2
}
parse_args() {
#BINDIR is ./bin unless set be ENV
# over-ridden by flag below
BINDIR=${BINDIR:-./bin}
while getopts "b:dh?" arg; do
case "$arg" in
b) BINDIR="$OPTARG" ;;
d) log_set_priority 10 ;;
h | \?) usage "$0" ;;
esac
done
shift $((OPTIND - 1))
TAG=$1
}
# this function wraps all the destructive operations
# if a curl|bash cuts off the end of the script due to
# network, either nothing will happen or will syntax error
# out preventing half-done work
execute() {
tmpdir=$(mktmpdir)
log_debug "downloading files into ${tmpdir}"
http_download "${tmpdir}/${TARBALL}" "${TARBALL_URL}"
http_download "${tmpdir}/${CHECKSUM}" "${CHECKSUM_URL}"
hash_sha256_verify "${tmpdir}/${TARBALL}" "${tmpdir}/${CHECKSUM}"
srcdir="${tmpdir}"
(cd "${tmpdir}" && untar "${TARBALL}")
install -d "${BINDIR}"
for binexe in "task" ; do
if [ "$OS" = "windows" ]; then
binexe="${binexe}.exe"
fi
install "${srcdir}/${binexe}" "${BINDIR}/"
log_info "installed ${BINDIR}/${binexe}"
done
}
is_supported_platform() {
platform=$1
found=1
case "$platform" in
windows/386) found=0 ;;
windows/amd64) found=0 ;;
darwin/386) found=0 ;;
darwin/amd64) found=0 ;;
linux/386) found=0 ;;
linux/amd64) found=0 ;;
esac
case "$platform" in
darwin/386) found=1 ;;
esac
return $found
}
check_platform() {
if is_supported_platform "$PLATFORM"; then
# optional logging goes here
true
else
log_crit "platform $PLATFORM is not supported. Make sure this script is up-to-date and file request at https://github.com/${PREFIX}/issues/new"
exit 1
fi
}
tag_to_version() {
if [ -z "${TAG}" ]; then
log_info "checking GitHub for latest tag"
else
log_info "checking GitHub for tag '${TAG}'"
fi
REALTAG=$(github_release "$OWNER/$REPO" "${TAG}") && true
if test -z "$REALTAG"; then
log_crit "unable to find '${TAG}' - use 'latest' or see https://github.com/${PREFIX}/releases for details"
exit 1
fi
# if version starts with 'v', remove it
TAG="$REALTAG"
VERSION=${TAG#v}
}
adjust_format() {
# change format (tar.gz or zip) based on ARCH
case ${ARCH} in
windows) FORMAT=zip ;;
esac
true
}
adjust_os() {
# adjust archive name based on OS
true
}
adjust_arch() {
# adjust archive name based on ARCH
true
}
cat /dev/null <<EOF
------------------------------------------------------------------------
https://github.com/client9/shlib - portable posix shell functions
Public domain - http://unlicense.org
https://github.com/client9/shlib/blob/master/LICENSE.md
but credit (and pull requests) appreciated.
------------------------------------------------------------------------
EOF
is_command() {
command -v "$1" >/dev/null
}
echoerr() {
echo "$@" 1>&2
}
log_prefix() {
echo "$0"
}
_logp=6
log_set_priority() {
_logp="$1"
}
log_priority() {
if test -z "$1"; then
echo "$_logp"
return
fi
[ "$1" -le "$_logp" ]
}
log_tag() {
case $1 in
0) echo "emerg" ;;
1) echo "alert" ;;
2) echo "crit" ;;
3) echo "err" ;;
4) echo "warning" ;;
5) echo "notice" ;;
6) echo "info" ;;
7) echo "debug" ;;
*) echo "$1" ;;
esac
}
log_debug() {
log_priority 7 || return 0
echoerr "$(log_prefix)" "$(log_tag 7)" "$@"
}
log_info() {
log_priority 6 || return 0
echoerr "$(log_prefix)" "$(log_tag 6)" "$@"
}
log_err() {
log_priority 3 || return 0
echoerr "$(log_prefix)" "$(log_tag 3)" "$@"
}
log_crit() {
log_priority 2 || return 0
echoerr "$(log_prefix)" "$(log_tag 2)" "$@"
}
uname_os() {
os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in
msys_nt) os="windows" ;;
esac
echo "$os"
}
uname_arch() {
arch=$(uname -m)
case $arch in
x86_64) arch="amd64" ;;
x86) arch="386" ;;
i686) arch="386" ;;
i386) arch="386" ;;
aarch64) arch="arm64" ;;
armv5*) arch="arm5" ;;
armv6*) arch="arm6" ;;
armv7*) arch="arm7" ;;
esac
echo ${arch}
}
uname_os_check() {
os=$(uname_os)
case "$os" in
darwin) return 0 ;;
dragonfly) return 0 ;;
freebsd) return 0 ;;
linux) return 0 ;;
android) return 0 ;;
nacl) return 0 ;;
netbsd) return 0 ;;
openbsd) return 0 ;;
plan9) return 0 ;;
solaris) return 0 ;;
windows) return 0 ;;
esac
log_crit "uname_os_check '$(uname -s)' got converted to '$os' which is not a GOOS value. Please file bug at https://github.com/client9/shlib"
return 1
}
uname_arch_check() {
arch=$(uname_arch)
case "$arch" in
386) return 0 ;;
amd64) return 0 ;;
arm64) return 0 ;;
armv5) return 0 ;;
armv6) return 0 ;;
armv7) return 0 ;;
ppc64) return 0 ;;
ppc64le) return 0 ;;
mips) return 0 ;;
mipsle) return 0 ;;
mips64) return 0 ;;
mips64le) return 0 ;;
s390x) return 0 ;;
amd64p32) return 0 ;;
esac
log_crit "uname_arch_check '$(uname -m)' got converted to '$arch' which is not a GOARCH value. Please file bug report at https://github.com/client9/shlib"
return 1
}
untar() {
tarball=$1
case "${tarball}" in
*.tar.gz | *.tgz) tar -xzf "${tarball}" ;;
*.tar) tar -xf "${tarball}" ;;
*.zip) unzip "${tarball}" ;;
*)
log_err "untar unknown archive format for ${tarball}"
return 1
;;
esac
}
mktmpdir() {
test -z "$TMPDIR" && TMPDIR="$(mktemp -d)"
mkdir -p "${TMPDIR}"
echo "${TMPDIR}"
}
http_download_curl() {
local_file=$1
source_url=$2
header=$3
if [ -z "$header" ]; then
code=$(curl -w '%{http_code}' -sL -o "$local_file" "$source_url")
else
code=$(curl -w '%{http_code}' -sL -H "$header" -o "$local_file" "$source_url")
fi
if [ "$code" != "200" ]; then
log_debug "http_download_curl received HTTP status $code"
return 1
fi
return 0
}
http_download_wget() {
local_file=$1
source_url=$2
header=$3
if [ -z "$header" ]; then
wget -q -O "$local_file" "$source_url"
else
wget -q --header "$header" -O "$local_file" "$source_url"
fi
}
http_download() {
log_debug "http_download $2"
if is_command curl; then
http_download_curl "$@"
return
elif is_command wget; then
http_download_wget "$@"
return
fi
log_crit "http_download unable to find wget or curl"
return 1
}
http_copy() {
tmp=$(mktemp)
http_download "${tmp}" "$1" "$2" || return 1
body=$(cat "$tmp")
rm -f "${tmp}"
echo "$body"
}
github_release() {
owner_repo=$1
version=$2
test -z "$version" && version="latest"
giturl="https://github.com/${owner_repo}/releases/${version}"
json=$(http_copy "$giturl" "Accept:application/json")
test -z "$json" && return 1
version=$(echo "$json" | tr -s '\n' ' ' | sed 's/.*"tag_name":"//' | sed 's/".*//')
test -z "$version" && return 1
echo "$version"
}
hash_sha256() {
TARGET=${1:-/dev/stdin}
if is_command gsha256sum; then
hash=$(gsha256sum "$TARGET") || return 1
echo "$hash" | cut -d ' ' -f 1
elif is_command sha256sum; then
hash=$(sha256sum "$TARGET") || return 1
echo "$hash" | cut -d ' ' -f 1
elif is_command shasum; then
hash=$(shasum -a 256 "$TARGET" 2>/dev/null) || return 1
echo "$hash" | cut -d ' ' -f 1
elif is_command openssl; then
hash=$(openssl -dst openssl dgst -sha256 "$TARGET") || return 1
echo "$hash" | cut -d ' ' -f a
else
log_crit "hash_sha256 unable to find command to compute sha-256 hash"
return 1
fi
}
hash_sha256_verify() {
TARGET=$1
checksums=$2
if [ -z "$checksums" ]; then
log_err "hash_sha256_verify checksum file not specified in arg2"
return 1
fi
BASENAME=${TARGET##*/}
want=$(grep "${BASENAME}" "${checksums}" 2>/dev/null | tr '\t' ' ' | cut -d ' ' -f 1)
if [ -z "$want" ]; then
log_err "hash_sha256_verify unable to find checksum for '${TARGET}' in '${checksums}'"
return 1
fi
got=$(hash_sha256 "$TARGET")
if [ "$want" != "$got" ]; then
log_err "hash_sha256_verify checksum for '$TARGET' did not verify ${want} vs $got"
return 1
fi
}
cat /dev/null <<EOF
------------------------------------------------------------------------
End of functions from https://github.com/client9/shlib
------------------------------------------------------------------------
EOF
PROJECT_NAME="task"
OWNER=go-task
REPO="task"
BINARY=task
FORMAT=tar.gz
OS=$(uname_os)
ARCH=$(uname_arch)
PREFIX="$OWNER/$REPO"
# use in logging routines
log_prefix() {
echo "$PREFIX"
}
PLATFORM="${OS}/${ARCH}"
GITHUB_DOWNLOAD=https://github.com/${OWNER}/${REPO}/releases/download
uname_os_check "$OS"
uname_arch_check "$ARCH"
parse_args "$@"
check_platform
tag_to_version
adjust_format
adjust_os
adjust_arch
log_info "found version: ${VERSION} for ${TAG}/${OS}/${ARCH}"
NAME=${BINARY}_${OS}_${ARCH}
TARBALL=${NAME}.${FORMAT}
TARBALL_URL=${GITHUB_DOWNLOAD}/${TAG}/${TARBALL}
CHECKSUM=task_checksums.txt
CHECKSUM_URL=${GITHUB_DOWNLOAD}/${TAG}/${CHECKSUM}
execute

36
internal/args/args.go Normal file
View File

@@ -0,0 +1,36 @@
package args
import (
"errors"
"strings"
"github.com/go-task/task/v2/internal/taskfile"
)
var (
// ErrVariableWithoutTask is returned when variables are given before any task
ErrVariableWithoutTask = errors.New("task: variable given before any task")
)
// Parse parses command line argument: tasks and vars of each task
func Parse(args ...string) ([]taskfile.Call, error) {
var calls []taskfile.Call
for _, arg := range args {
if !strings.Contains(arg, "=") {
calls = append(calls, taskfile.Call{Task: arg})
continue
}
if len(calls) < 1 {
return nil, ErrVariableWithoutTask
}
if calls[len(calls)-1].Vars == nil {
calls[len(calls)-1].Vars = make(taskfile.Vars)
}
pair := strings.SplitN(arg, "=", 2)
calls[len(calls)-1].Vars[pair[0]] = taskfile.Var{Static: pair[1]}
}
return calls, nil
}

View File

@@ -0,0 +1,70 @@
package args_test
import (
"fmt"
"testing"
"github.com/go-task/task/v2/internal/args"
"github.com/go-task/task/v2/internal/taskfile"
"github.com/stretchr/testify/assert"
)
func TestArgs(t *testing.T) {
tests := []struct {
Args []string
Expected []taskfile.Call
Err error
}{
{
Args: []string{"task-a", "task-b", "task-c"},
Expected: []taskfile.Call{
{Task: "task-a"},
{Task: "task-b"},
{Task: "task-c"},
},
},
{
Args: []string{"task-a", "FOO=bar", "task-b", "task-c", "BAR=baz", "BAZ=foo"},
Expected: []taskfile.Call{
{
Task: "task-a",
Vars: taskfile.Vars{
"FOO": taskfile.Var{Static: "bar"},
},
},
{Task: "task-b"},
{
Task: "task-c",
Vars: taskfile.Vars{
"BAR": taskfile.Var{Static: "baz"},
"BAZ": taskfile.Var{Static: "foo"},
},
},
},
},
{
Args: []string{"task-a", "CONTENT=with some spaces"},
Expected: []taskfile.Call{
{
Task: "task-a",
Vars: taskfile.Vars{
"CONTENT": taskfile.Var{Static: "with some spaces"},
},
},
},
},
{
Args: []string{"FOO=bar", "task-a"},
Err: args.ErrVariableWithoutTask,
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("TestArgs%d", i+1), func(t *testing.T) {
calls, err := args.Parse(test.Args...)
assert.Equal(t, test.Err, err)
assert.Equal(t, test.Expected, calls)
})
}
}

View File

@@ -0,0 +1,12 @@
package compiler
import (
"github.com/go-task/task/v2/internal/taskfile"
)
// Compiler handles compilation of a task before its execution.
// E.g. variable merger, template processing, etc.
type Compiler interface {
GetVariables(t *taskfile.Task, call taskfile.Call) (taskfile.Vars, error)
HandleDynamicVar(v taskfile.Var) (string, error)
}

24
internal/compiler/env.go Normal file
View File

@@ -0,0 +1,24 @@
package compiler
import (
"os"
"strings"
"github.com/go-task/task/v2/internal/taskfile"
)
// GetEnviron the all return all environment variables encapsulated on a
// taskfile.Vars
func GetEnviron() taskfile.Vars {
var (
env = os.Environ()
m = make(taskfile.Vars, len(env))
)
for _, e := range env {
keyVal := strings.SplitN(e, "=", 2)
key, val := keyVal[0], keyVal[1]
m[key] = taskfile.Var{Static: val}
}
return m
}

View File

@@ -0,0 +1,137 @@
package v1
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"github.com/go-task/task/v2/internal/compiler"
"github.com/go-task/task/v2/internal/execext"
"github.com/go-task/task/v2/internal/logger"
"github.com/go-task/task/v2/internal/taskfile"
"github.com/go-task/task/v2/internal/templater"
)
var _ compiler.Compiler = &CompilerV1{}
type CompilerV1 struct {
Dir string
Vars taskfile.Vars
Logger *logger.Logger
dynamicCache map[string]string
muDynamicCache sync.Mutex
}
// GetVariables returns fully resolved variables following the priority order:
// 1. Call variables (should already have been resolved)
// 2. Environment (should not need to be resolved)
// 3. Task variables, resolved with access to:
// - call, taskvars and environment variables
// 4. Taskvars variables, resolved with access to:
// - environment variables
func (c *CompilerV1) GetVariables(t *taskfile.Task, call taskfile.Call) (taskfile.Vars, error) {
merge := func(dest taskfile.Vars, srcs ...taskfile.Vars) {
for _, src := range srcs {
for k, v := range src {
dest[k] = v
}
}
}
varsKeys := func(srcs ...taskfile.Vars) []string {
m := make(map[string]struct{})
for _, src := range srcs {
for k := range src {
m[k] = struct{}{}
}
}
lst := make([]string, 0, len(m))
for k := range m {
lst = append(lst, k)
}
return lst
}
replaceVars := func(dest taskfile.Vars, keys []string) error {
r := templater.Templater{Vars: dest}
for _, k := range keys {
v := dest[k]
dest[k] = taskfile.Var{
Static: r.Replace(v.Static),
Sh: r.Replace(v.Sh),
}
}
return r.Err()
}
resolveShell := func(dest taskfile.Vars, keys []string) error {
for _, k := range keys {
v := dest[k]
static, err := c.HandleDynamicVar(v)
if err != nil {
return err
}
dest[k] = taskfile.Var{Static: static}
}
return nil
}
update := func(dest taskfile.Vars, srcs ...taskfile.Vars) error {
merge(dest, srcs...)
// updatedKeys ensures template evaluation is run only once.
updatedKeys := varsKeys(srcs...)
if err := replaceVars(dest, updatedKeys); err != nil {
return err
}
return resolveShell(dest, updatedKeys)
}
// Resolve taskvars variables to "result" with environment override variables.
override := compiler.GetEnviron()
result := make(taskfile.Vars, len(c.Vars)+len(t.Vars)+len(override))
if err := update(result, c.Vars, override); err != nil {
return nil, err
}
// Resolve task variables to "result" with environment and call override variables.
merge(override, call.Vars)
if err := update(result, t.Vars, override); err != nil {
return nil, err
}
return result, nil
}
func (c *CompilerV1) HandleDynamicVar(v taskfile.Var) (string, error) {
if v.Static != "" || v.Sh == "" {
return v.Static, nil
}
c.muDynamicCache.Lock()
defer c.muDynamicCache.Unlock()
if c.dynamicCache == nil {
c.dynamicCache = make(map[string]string, 30)
}
if result, ok := c.dynamicCache[v.Sh]; ok {
return result, nil
}
var stdout bytes.Buffer
opts := &execext.RunCommandOptions{
Command: v.Sh,
Dir: c.Dir,
Stdout: &stdout,
Stderr: c.Logger.Stderr,
}
if err := execext.RunCommand(context.Background(), opts); err != nil {
return "", fmt.Errorf(`task: Command "%s" in taskvars file failed: %s`, opts.Command, err)
}
// Trim a single trailing newline from the result to make most command
// output easier to use in shell commands.
result := strings.TrimSuffix(stdout.String(), "\n")
c.dynamicCache[v.Sh] = result
c.Logger.VerboseErrf(`task: dynamic variable: '%s' result: '%s'`, v.Sh, result)
return result, nil
}

View File

@@ -0,0 +1,109 @@
package v2
import (
"bytes"
"context"
"fmt"
"strings"
"sync"
"github.com/go-task/task/v2/internal/compiler"
"github.com/go-task/task/v2/internal/execext"
"github.com/go-task/task/v2/internal/logger"
"github.com/go-task/task/v2/internal/taskfile"
"github.com/go-task/task/v2/internal/templater"
)
var _ compiler.Compiler = &CompilerV2{}
type CompilerV2 struct {
Dir string
Taskvars taskfile.Vars
TaskfileVars taskfile.Vars
Expansions int
Logger *logger.Logger
dynamicCache map[string]string
muDynamicCache sync.Mutex
}
// GetVariables returns fully resolved variables following the priority order:
// 1. Task variables
// 2. Call variables
// 3. Taskfile variables
// 4. Taskvars file variables
// 5. Environment variables
func (c *CompilerV2) GetVariables(t *taskfile.Task, call taskfile.Call) (taskfile.Vars, error) {
vr := varResolver{c: c, vars: compiler.GetEnviron()}
for _, vars := range []taskfile.Vars{c.Taskvars, c.TaskfileVars, call.Vars, t.Vars} {
for i := 0; i < c.Expansions; i++ {
vr.merge(vars)
}
}
return vr.vars, vr.err
}
type varResolver struct {
c *CompilerV2
vars taskfile.Vars
err error
}
func (vr *varResolver) merge(vars taskfile.Vars) {
if vr.err != nil {
return
}
tr := templater.Templater{Vars: vr.vars}
for k, v := range vars {
v = taskfile.Var{
Static: tr.Replace(v.Static),
Sh: tr.Replace(v.Sh),
}
static, err := vr.c.HandleDynamicVar(v)
if err != nil {
vr.err = err
return
}
vr.vars[k] = taskfile.Var{Static: static}
}
vr.err = tr.Err()
}
func (c *CompilerV2) HandleDynamicVar(v taskfile.Var) (string, error) {
if v.Static != "" || v.Sh == "" {
return v.Static, nil
}
c.muDynamicCache.Lock()
defer c.muDynamicCache.Unlock()
if c.dynamicCache == nil {
c.dynamicCache = make(map[string]string, 30)
}
if result, ok := c.dynamicCache[v.Sh]; ok {
return result, nil
}
var stdout bytes.Buffer
opts := &execext.RunCommandOptions{
Command: v.Sh,
Dir: c.Dir,
Stdout: &stdout,
Stderr: c.Logger.Stderr,
}
if err := execext.RunCommand(context.Background(), opts); err != nil {
return "", fmt.Errorf(`task: Command "%s" in taskvars file failed: %s`, opts.Command, err)
}
// Trim a single trailing newline from the result to make most command
// output easier to use in shell commands.
result := strings.TrimSuffix(stdout.String(), "\n")
c.dynamicCache[v.Sh] = result
c.Logger.VerboseErrf(`task: dynamic variable: '%s' result: '%s'`, v.Sh, result)
return result, nil
}

83
internal/execext/exec.go Normal file
View File

@@ -0,0 +1,83 @@
package execext
import (
"context"
"errors"
"io"
"os"
"strings"
"mvdan.cc/sh/expand"
"mvdan.cc/sh/interp"
"mvdan.cc/sh/shell"
"mvdan.cc/sh/syntax"
)
// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
Command string
Dir string
Env []string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
var (
// ErrNilOptions is returned when a nil options is given
ErrNilOptions = errors.New("execext: nil options given")
)
// RunCommand runs a shell command
func RunCommand(ctx context.Context, opts *RunCommandOptions) error {
if opts == nil {
return ErrNilOptions
}
p, err := syntax.NewParser().Parse(strings.NewReader(opts.Command), "")
if err != nil {
return err
}
environ := opts.Env
if len(environ) == 0 {
environ = os.Environ()
}
r, err := interp.New(
interp.Dir(opts.Dir),
interp.Env(expand.ListEnviron(environ...)),
interp.Module(interp.DefaultExec),
interp.Module(interp.OpenDevImpls(interp.DefaultOpen)),
interp.StdIO(opts.Stdin, opts.Stdout, opts.Stderr),
)
if err != nil {
return err
}
return r.Run(ctx, p)
}
// IsExitError returns true the given error is an exis status error
func IsExitError(err error) bool {
switch err.(type) {
case interp.ExitStatus, interp.ShellExitStatus:
return true
default:
return false
}
}
// Expand is a helper to mvdan.cc/shell.Fields that returns the first field
// if available.
func Expand(s string) (string, error) {
fields, err := shell.Fields(s, nil)
if err != nil {
return "", err
}
if len(fields) > 0 {
return fields[0], nil
}
return "", nil
}

38
internal/logger/logger.go Normal file
View File

@@ -0,0 +1,38 @@
package logger
import (
"fmt"
"io"
)
type Logger struct {
Stdout io.Writer
Stderr io.Writer
Verbose bool
}
func (l *Logger) Outf(s string, args ...interface{}) {
if len(args) == 0 {
s, args = "%s", []interface{}{s}
}
fmt.Fprintf(l.Stdout, s+"\n", args...)
}
func (l *Logger) VerboseOutf(s string, args ...interface{}) {
if l.Verbose {
l.Outf(s, args...)
}
}
func (l *Logger) Errf(s string, args ...interface{}) {
if len(args) == 0 {
s, args = "%s", []interface{}{s}
}
fmt.Fprintf(l.Stderr, s+"\n", args...)
}
func (l *Logger) VerboseErrf(s string, args ...interface{}) {
if l.Verbose {
l.Errf(s, args...)
}
}

26
internal/output/group.go Normal file
View File

@@ -0,0 +1,26 @@
package output
import (
"bytes"
"io"
)
type Group struct{}
func (Group) WrapWriter(w io.Writer, _ string) io.WriteCloser {
return &groupWriter{writer: w}
}
type groupWriter struct {
writer io.Writer
buff bytes.Buffer
}
func (gw *groupWriter) Write(p []byte) (int, error) {
return gw.buff.Write(p)
}
func (gw *groupWriter) Close() error {
_, err := io.Copy(gw.writer, &gw.buff)
return err
}

View File

@@ -0,0 +1,23 @@
package output
import (
"io"
)
type Interleaved struct{}
func (Interleaved) WrapWriter(w io.Writer, _ string) io.WriteCloser {
return nopWriterCloser{w: w}
}
type nopWriterCloser struct {
w io.Writer
}
func (wc nopWriterCloser) Write(p []byte) (int, error) {
return wc.w.Write(p)
}
func (wc nopWriterCloser) Close() error {
return nil
}

View File

@@ -0,0 +1,9 @@
package output
import (
"io"
)
type Output interface {
WrapWriter(w io.Writer, prefix string) io.WriteCloser
}

View File

@@ -0,0 +1,62 @@
package output_test
import (
"bytes"
"fmt"
"testing"
"github.com/go-task/task/v2/internal/output"
"github.com/stretchr/testify/assert"
)
func TestInterleaved(t *testing.T) {
var b bytes.Buffer
var o output.Output = output.Interleaved{}
var w = o.WrapWriter(&b, "")
fmt.Fprintln(w, "foo\nbar")
assert.Equal(t, "foo\nbar\n", b.String())
fmt.Fprintln(w, "baz")
assert.Equal(t, "foo\nbar\nbaz\n", b.String())
}
func TestGroup(t *testing.T) {
var b bytes.Buffer
var o output.Output = output.Group{}
var w = o.WrapWriter(&b, "")
fmt.Fprintln(w, "foo\nbar")
assert.Equal(t, "", b.String())
fmt.Fprintln(w, "baz")
assert.Equal(t, "", b.String())
assert.NoError(t, w.Close())
assert.Equal(t, "foo\nbar\nbaz\n", b.String())
}
func TestPrefixed(t *testing.T) {
var b bytes.Buffer
var o output.Output = output.Prefixed{}
var w = o.WrapWriter(&b, "prefix")
t.Run("simple use cases", func(t *testing.T) {
b.Reset()
fmt.Fprintln(w, "foo\nbar")
assert.Equal(t, "[prefix] foo\n[prefix] bar\n", b.String())
fmt.Fprintln(w, "baz")
assert.Equal(t, "[prefix] foo\n[prefix] bar\n[prefix] baz\n", b.String())
})
t.Run("multiple writes for a single line", func(t *testing.T) {
b.Reset()
for _, char := range []string{"T", "e", "s", "t", "!"} {
fmt.Fprint(w, char)
assert.Equal(t, "", b.String())
}
assert.NoError(t, w.Close())
assert.Equal(t, "[prefix] Test!\n", b.String())
})
}

View File

@@ -0,0 +1,65 @@
package output
import (
"bytes"
"fmt"
"io"
"strings"
)
type Prefixed struct{}
func (Prefixed) WrapWriter(w io.Writer, prefix string) io.WriteCloser {
return &prefixWriter{writer: w, prefix: prefix}
}
type prefixWriter struct {
writer io.Writer
prefix string
buff bytes.Buffer
}
func (pw *prefixWriter) Write(p []byte) (int, error) {
n, err := pw.buff.Write(p)
if err != nil {
return n, err
}
return n, pw.writeOutputLines(false)
}
func (pw *prefixWriter) Close() error {
return pw.writeOutputLines(true)
}
func (pw *prefixWriter) writeOutputLines(force bool) error {
for {
line, err := pw.buff.ReadString('\n')
if err == nil {
if err = pw.writeLine(line); err != nil {
return err
}
} else if err == io.EOF {
// if this line was not a complete line, re-add to the buffer
if !force && !strings.HasSuffix(line, "\n") {
_, err = pw.buff.WriteString(line)
return err
}
return pw.writeLine(line)
} else {
return err
}
}
}
func (pw *prefixWriter) writeLine(line string) error {
if line == "" {
return nil
}
if !strings.HasSuffix(line, "\n") {
line += "\n"
}
_, err := fmt.Fprintf(pw.writer, "[%s] %s", pw.prefix, line)
return err
}

View File

@@ -0,0 +1,87 @@
package status
import (
"crypto/md5"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
)
// Checksum validades if a task is up to date by calculating its source
// files checksum
type Checksum struct {
Dir string
Task string
Sources []string
}
// IsUpToDate implements the Checker interface
func (c *Checksum) IsUpToDate() (bool, error) {
checksumFile := c.checksumFilePath()
data, _ := ioutil.ReadFile(checksumFile)
oldMd5 := strings.TrimSpace(string(data))
sources, err := glob(c.Dir, c.Sources)
if err != nil {
return false, err
}
newMd5, err := c.checksum(sources...)
if err != nil {
return false, nil
}
_ = os.MkdirAll(filepath.Join(c.Dir, ".task", "checksum"), 0755)
if err = ioutil.WriteFile(checksumFile, []byte(newMd5+"\n"), 0644); err != nil {
return false, err
}
return oldMd5 == newMd5, nil
}
func (c *Checksum) checksum(files ...string) (string, error) {
h := md5.New()
for _, f := range files {
f, err := os.Open(f)
if err != nil {
return "", err
}
info, err := f.Stat()
if err != nil {
return "", err
}
if info.IsDir() {
continue
}
// also sum the filename, so checksum changes for renaming a file
if _, err = io.Copy(h, strings.NewReader(info.Name())); err != nil {
return "", err
}
if _, err = io.Copy(h, f); err != nil {
return "", err
}
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
// OnError implements the Checker interface
func (c *Checksum) OnError() error {
return os.Remove(c.checksumFilePath())
}
func (c *Checksum) checksumFilePath() string {
return filepath.Join(c.Dir, ".task", "checksum", c.normalizeFilename(c.Task))
}
var checksumFilenameRegexp = regexp.MustCompile("[^A-z0-9]")
// replaces invalid caracters on filenames with "-"
func (*Checksum) normalizeFilename(f string) string {
return checksumFilenameRegexp.ReplaceAllString(f, "-")
}

View File

@@ -0,0 +1,21 @@
package status
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNormalizeFilename(t *testing.T) {
tests := []struct {
In, Out string
}{
{"foobarbaz", "foobarbaz"},
{"foo/bar/baz", "foo-bar-baz"},
{"foo@bar/baz", "foo-bar-baz"},
{"foo1bar2baz3", "foo1bar2baz3"},
}
for _, test := range tests {
assert.Equal(t, test.Out, (&Checksum{}).normalizeFilename(test.In))
}
}

29
internal/status/glob.go Normal file
View File

@@ -0,0 +1,29 @@
package status
import (
"path/filepath"
"sort"
"github.com/go-task/task/v2/internal/execext"
"github.com/mattn/go-zglob"
)
func glob(dir string, globs []string) (files []string, err error) {
for _, g := range globs {
if !filepath.IsAbs(g) {
g = filepath.Join(dir, g)
}
g, err = execext.Expand(g)
if err != nil {
return nil, err
}
f, err := zglob.Glob(g)
if err != nil {
continue
}
files = append(files, f...)
}
sort.Strings(files)
return
}

14
internal/status/none.go Normal file
View File

@@ -0,0 +1,14 @@
package status
// None is a no-op Checker
type None struct{}
// IsUpToDate implements the Checker interface
func (None) IsUpToDate() (bool, error) {
return false, nil
}
// OnError implements the Checker interface
func (None) OnError() error {
return nil
}

13
internal/status/status.go Normal file
View File

@@ -0,0 +1,13 @@
package status
var (
_ Checker = &Timestamp{}
_ Checker = &Checksum{}
_ Checker = None{}
)
// Checker is an interface that checks if the status is up-to-date
type Checker interface {
IsUpToDate() (bool, error)
OnError() error
}

View File

@@ -0,0 +1,85 @@
package status
import (
"os"
"time"
)
// Timestamp checks if any source change compared with the generated files,
// using file modifications timestamps.
type Timestamp struct {
Dir string
Sources []string
Generates []string
}
// IsUpToDate implements the Checker interface
func (t *Timestamp) IsUpToDate() (bool, error) {
if len(t.Sources) == 0 || len(t.Generates) == 0 {
return false, nil
}
sources, err := glob(t.Dir, t.Sources)
if err != nil {
return false, nil
}
generates, err := glob(t.Dir, t.Generates)
if err != nil {
return false, nil
}
sourcesMaxTime, err := getMaxTime(sources...)
if err != nil || sourcesMaxTime.IsZero() {
return false, nil
}
generatesMinTime, err := getMinTime(generates...)
if err != nil || generatesMinTime.IsZero() {
return false, nil
}
return !generatesMinTime.Before(sourcesMaxTime), nil
}
func getMinTime(files ...string) (time.Time, error) {
var t time.Time
for _, f := range files {
info, err := os.Stat(f)
if err != nil {
return time.Time{}, err
}
t = minTime(t, info.ModTime())
}
return t, nil
}
func getMaxTime(files ...string) (time.Time, error) {
var t time.Time
for _, f := range files {
info, err := os.Stat(f)
if err != nil {
return time.Time{}, err
}
t = maxTime(t, info.ModTime())
}
return t, nil
}
func minTime(a, b time.Time) time.Time {
if !a.IsZero() && a.Before(b) {
return a
}
return b
}
func maxTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}
// OnError implements the Checker interface
func (*Timestamp) OnError() error {
return nil
}

View File

@@ -0,0 +1,7 @@
package taskfile
// Call is the parameters to a task call
type Call struct {
Task string
Vars Vars
}

81
internal/taskfile/cmd.go Normal file
View File

@@ -0,0 +1,81 @@
package taskfile
import (
"errors"
"strings"
)
// Cmd is a task command
type Cmd struct {
Cmd string
Silent bool
Task string
Vars Vars
IgnoreError bool
}
// Dep is a task dependency
type Dep struct {
Task string
Vars Vars
}
var (
// ErrCantUnmarshalCmd is returned for invalid command YAML
ErrCantUnmarshalCmd = errors.New("task: can't unmarshal cmd value")
// ErrCantUnmarshalDep is returned for invalid dependency YAML
ErrCantUnmarshalDep = errors.New("task: can't unmarshal dep value")
)
// UnmarshalYAML implements yaml.Unmarshaler interface
func (c *Cmd) UnmarshalYAML(unmarshal func(interface{}) error) error {
var cmd string
if err := unmarshal(&cmd); err == nil {
if strings.HasPrefix(cmd, "^") {
c.Task = strings.TrimPrefix(cmd, "^")
} else {
c.Cmd = cmd
}
return nil
}
var cmdStruct struct {
Cmd string
Silent bool
IgnoreError bool `yaml:"ignore_error"`
}
if err := unmarshal(&cmdStruct); err == nil && cmdStruct.Cmd != "" {
c.Cmd = cmdStruct.Cmd
c.Silent = cmdStruct.Silent
c.IgnoreError = cmdStruct.IgnoreError
return nil
}
var taskCall struct {
Task string
Vars Vars
}
if err := unmarshal(&taskCall); err == nil {
c.Task = taskCall.Task
c.Vars = taskCall.Vars
return nil
}
return ErrCantUnmarshalCmd
}
// UnmarshalYAML implements yaml.Unmarshaler interface
func (d *Dep) UnmarshalYAML(unmarshal func(interface{}) error) error {
var task string
if err := unmarshal(&task); err == nil {
d.Task = task
return nil
}
var taskCall struct {
Task string
Vars Vars
}
if err := unmarshal(&taskCall); err == nil {
d.Task = taskCall.Task
d.Vars = taskCall.Vars
return nil
}
return ErrCantUnmarshalDep
}

View File

@@ -0,0 +1,70 @@
package taskfile
import (
"fmt"
"strings"
)
// NamespaceSeparator contains the character that separates namescapes
const NamespaceSeparator = ":"
// Merge merges the second Taskfile into the first
func Merge(t1, t2 *Taskfile, namespaces ...string) error {
if t1.Version != t2.Version {
return fmt.Errorf(`Taskfiles versions should match. First is "%s" but second is "%s"`, t1.Version, t2.Version)
}
if t2.Expansions != 0 && t2.Expansions != 2 {
t1.Expansions = t2.Expansions
}
if t2.Output != "" {
t1.Output = t2.Output
}
if t1.Includes == nil {
t1.Includes = make(map[string]string)
}
for k, v := range t2.Includes {
t1.Includes[k] = v
}
if t1.Vars == nil {
t1.Vars = make(Vars)
}
for k, v := range t2.Vars {
t1.Vars[k] = v
}
if t1.Env == nil {
t1.Env = make(Vars)
}
for k, v := range t2.Vars {
t1.Env[k] = v
}
if t1.Tasks == nil {
t1.Tasks = make(Tasks)
}
for k, v := range t2.Tasks {
// FIXME(@andreynering): Refactor this block, otherwise we can
// have serious side-effects in the future, since we're editing
// the original references instead of deep copying them.
t1.Tasks[taskNameWithNamespace(k, namespaces...)] = v
for _, dep := range v.Deps {
dep.Task = taskNameWithNamespace(dep.Task, namespaces...)
}
for _, cmd := range v.Cmds {
if cmd.Task != "" {
cmd.Task = taskNameWithNamespace(cmd.Task, namespaces...)
}
}
}
return nil
}
func taskNameWithNamespace(taskName string, namespaces ...string) string {
return strings.Join(append(namespaces, taskName), NamespaceSeparator)
}

View File

@@ -0,0 +1,75 @@
package read
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/go-task/task/v2/internal/taskfile"
"gopkg.in/yaml.v2"
)
// ErrIncludedTaskfilesCantHaveIncludes is returned when a included Taskfile contains includes
var ErrIncludedTaskfilesCantHaveIncludes = errors.New("task: Included Taskfiles can't have includes. Please, move the include to the main Taskfile")
// Taskfile reads a Taskfile for a given directory
func Taskfile(dir string) (*taskfile.Taskfile, error) {
path := filepath.Join(dir, "Taskfile.yml")
if _, err := os.Stat(path); err != nil {
return nil, fmt.Errorf(`No Taskfile.yml found. Use "task --init" to create a new one`)
}
t, err := readTaskfile(path)
if err != nil {
return nil, err
}
for namespace, path := range t.Includes {
path = filepath.Join(dir, path)
info, err := os.Stat(path)
if err != nil {
return nil, err
}
if info.IsDir() {
path = filepath.Join(path, "Taskfile.yml")
}
includedTaskfile, err := readTaskfile(path)
if err != nil {
return nil, err
}
if len(includedTaskfile.Includes) > 0 {
return nil, ErrIncludedTaskfilesCantHaveIncludes
}
if err = taskfile.Merge(t, includedTaskfile, namespace); err != nil {
return nil, err
}
}
path = filepath.Join(dir, fmt.Sprintf("Taskfile_%s.yml", runtime.GOOS))
if _, err = os.Stat(path); err == nil {
osTaskfile, err := readTaskfile(path)
if err != nil {
return nil, err
}
if err = taskfile.Merge(t, osTaskfile); err != nil {
return nil, err
}
}
for name, task := range t.Tasks {
task.Task = name
}
return t, nil
}
func readTaskfile(file string) (*taskfile.Taskfile, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
var t taskfile.Taskfile
return &t, yaml.NewDecoder(f).Decode(&t)
}

View File

@@ -0,0 +1,52 @@
package read
import (
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/go-task/task/v2/internal/taskfile"
"gopkg.in/yaml.v2"
)
// Taskvars reads a Taskvars for a given directory
func Taskvars(dir string) (taskfile.Vars, error) {
vars := make(taskfile.Vars)
path := filepath.Join(dir, "Taskvars.yml")
if _, err := os.Stat(path); err == nil {
vars, err = readTaskvars(path)
if err != nil {
return nil, err
}
}
path = filepath.Join(dir, fmt.Sprintf("Taskvars_%s.yml", runtime.GOOS))
if _, err := os.Stat(path); err == nil {
osVars, err := readTaskvars(path)
if err != nil {
return nil, err
}
if vars == nil {
vars = osVars
} else {
for k, v := range osVars {
vars[k] = v
}
}
}
return vars, nil
}
func readTaskvars(file string) (taskfile.Vars, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
var vars taskfile.Vars
return vars, yaml.NewDecoder(f).Decode(&vars)
}

22
internal/taskfile/task.go Normal file
View File

@@ -0,0 +1,22 @@
package taskfile
// Tasks representas a group of tasks
type Tasks map[string]*Task
// Task represents a task
type Task struct {
Task string
Cmds []*Cmd
Deps []*Dep
Desc string
Sources []string
Generates []string
Status []string
Dir string
Vars Vars
Env Vars
Silent bool
Method string
Prefix string
IgnoreError bool `yaml:"ignore_error"`
}

View File

@@ -0,0 +1,44 @@
package taskfile
// Taskfile represents a Taskfile.yml
type Taskfile struct {
Version string
Expansions int
Output string
Includes map[string]string
Vars Vars
Env Vars
Tasks Tasks
}
// UnmarshalYAML implements yaml.Unmarshaler interface
func (tf *Taskfile) UnmarshalYAML(unmarshal func(interface{}) error) error {
if err := unmarshal(&tf.Tasks); err == nil {
tf.Version = "1"
return nil
}
var taskfile struct {
Version string
Expansions int
Output string
Includes map[string]string
Vars Vars
Env Vars
Tasks Tasks
}
if err := unmarshal(&taskfile); err != nil {
return err
}
tf.Version = taskfile.Version
tf.Expansions = taskfile.Expansions
tf.Output = taskfile.Output
tf.Includes = taskfile.Includes
tf.Vars = taskfile.Vars
tf.Env = taskfile.Env
tf.Tasks = taskfile.Tasks
if tf.Expansions <= 0 {
tf.Expansions = 2
}
return nil
}

View File

@@ -0,0 +1,60 @@
package taskfile_test
import (
"testing"
"github.com/go-task/task/v2/internal/taskfile"
"github.com/stretchr/testify/assert"
"gopkg.in/yaml.v2"
)
func TestCmdParse(t *testing.T) {
const (
yamlCmd = `echo "a string command"`
yamlDep = `"task-name"`
yamlTaskCall = `
task: another-task
vars:
PARAM1: VALUE1
PARAM2: VALUE2
`
)
tests := []struct {
content string
v interface{}
expected interface{}
}{
{
yamlCmd,
&taskfile.Cmd{},
&taskfile.Cmd{Cmd: `echo "a string command"`},
},
{
yamlTaskCall,
&taskfile.Cmd{},
&taskfile.Cmd{Task: "another-task", Vars: taskfile.Vars{
"PARAM1": taskfile.Var{Static: "VALUE1"},
"PARAM2": taskfile.Var{Static: "VALUE2"},
}},
},
{
yamlDep,
&taskfile.Dep{},
&taskfile.Dep{Task: "task-name"},
},
{
yamlTaskCall,
&taskfile.Dep{},
&taskfile.Dep{Task: "another-task", Vars: taskfile.Vars{
"PARAM1": taskfile.Var{Static: "VALUE1"},
"PARAM2": taskfile.Var{Static: "VALUE2"},
}},
},
}
for _, test := range tests {
err := yaml.Unmarshal([]byte(test.content), test.v)
assert.NoError(t, err)
assert.Equal(t, test.expected, test.v)
}
}

58
internal/taskfile/var.go Normal file
View File

@@ -0,0 +1,58 @@
package taskfile
import (
"errors"
"strings"
)
var (
// ErrCantUnmarshalVar is returned for invalid var YAML.
ErrCantUnmarshalVar = errors.New("task: can't unmarshal var value")
)
// Vars is a string[string] variables map.
type Vars map[string]Var
// ToStringMap converts Vars to a string map containing only the static
// variables
func (vs Vars) ToStringMap() (m map[string]string) {
m = make(map[string]string, len(vs))
for k, v := range vs {
if v.Sh != "" {
// Dynamic variable is not yet resolved; trigger
// <no value> to be used in templates.
continue
}
m[k] = v.Static
}
return
}
// Var represents either a static or dynamic variable.
type Var struct {
Static string
Sh string
}
// UnmarshalYAML implements yaml.Unmarshaler interface.
func (v *Var) UnmarshalYAML(unmarshal func(interface{}) error) error {
var str string
if err := unmarshal(&str); err == nil {
if strings.HasPrefix(str, "$") {
v.Sh = strings.TrimPrefix(str, "$")
} else {
v.Static = str
}
return nil
}
var sh struct {
Sh string
}
if err := unmarshal(&sh); err == nil {
v.Sh = sh.Sh
return nil
}
return ErrCantUnmarshalVar
}

View File

@@ -0,0 +1,46 @@
package version
import (
"github.com/Masterminds/semver"
)
var (
v1 = mustVersion("1")
v2 = mustVersion("2")
v21 = mustVersion("2.1")
v22 = mustVersion("2.2")
v23 = mustVersion("2.3")
)
// IsV1 returns if is a given Taskfile version is version 1
func IsV1(v *semver.Constraints) bool {
return v.Check(v1)
}
// IsV2 returns if is a given Taskfile version is at least version 2
func IsV2(v *semver.Constraints) bool {
return v.Check(v2)
}
// IsV21 returns if is a given Taskfile version is at least version 2.1
func IsV21(v *semver.Constraints) bool {
return v.Check(v21)
}
// IsV22 returns if is a given Taskfile version is at least version 2.2
func IsV22(v *semver.Constraints) bool {
return v.Check(v22)
}
// IsV23 returns if is a given Taskfile version is at least version 2.3
func IsV23(v *semver.Constraints) bool {
return v.Check(v23)
}
func mustVersion(s string) *semver.Version {
v, err := semver.NewVersion(s)
if err != nil {
panic(err)
}
return v
}

View File

@@ -0,0 +1,52 @@
package templater
import (
"path/filepath"
"runtime"
"strings"
"text/template"
"github.com/Masterminds/sprig"
)
var (
templateFuncs template.FuncMap
)
func init() {
taskFuncs := template.FuncMap{
"OS": func() string { return runtime.GOOS },
"ARCH": func() string { return runtime.GOARCH },
"catLines": func(s string) string {
s = strings.Replace(s, "\r\n", " ", -1)
return strings.Replace(s, "\n", " ", -1)
},
"splitLines": func(s string) []string {
s = strings.Replace(s, "\r\n", "\n", -1)
return strings.Split(s, "\n")
},
"fromSlash": func(path string) string {
return filepath.FromSlash(path)
},
"toSlash": func(path string) string {
return filepath.ToSlash(path)
},
"exeExt": func() string {
if runtime.GOOS == "windows" {
return ".exe"
}
return ""
},
// IsSH is deprecated.
"IsSH": func() bool { return true },
}
// Deprecated aliases for renamed functions.
taskFuncs["FromSlash"] = taskFuncs["fromSlash"]
taskFuncs["ToSlash"] = taskFuncs["toSlash"]
taskFuncs["ExeExt"] = taskFuncs["exeExt"]
templateFuncs = sprig.TxtFuncMap()
for k, v := range taskFuncs {
templateFuncs[k] = v
}
}

View File

@@ -0,0 +1,73 @@
package templater
import (
"bytes"
"text/template"
"github.com/go-task/task/v2/internal/taskfile"
)
// Templater is a help struct that allow us to call "replaceX" funcs multiple
// times, without having to check for error each time. The first error that
// happen will be assigned to r.err, and consecutive calls to funcs will just
// return the zero value.
type Templater struct {
Vars taskfile.Vars
strMap map[string]string
err error
}
func (r *Templater) Replace(str string) string {
if r.err != nil || str == "" {
return ""
}
templ, err := template.New("").Funcs(templateFuncs).Parse(str)
if err != nil {
r.err = err
return ""
}
if r.strMap == nil {
r.strMap = r.Vars.ToStringMap()
}
var b bytes.Buffer
if err = templ.Execute(&b, r.strMap); err != nil {
r.err = err
return ""
}
return b.String()
}
func (r *Templater) ReplaceSlice(strs []string) []string {
if r.err != nil || len(strs) == 0 {
return nil
}
new := make([]string, len(strs))
for i, str := range strs {
new[i] = r.Replace(str)
}
return new
}
func (r *Templater) ReplaceVars(vars taskfile.Vars) taskfile.Vars {
if r.err != nil || len(vars) == 0 {
return nil
}
new := make(taskfile.Vars, len(vars))
for k, v := range vars {
new[k] = taskfile.Var{
Static: r.Replace(v.Static),
Sh: r.Replace(v.Sh),
}
}
return new
}
func (r *Templater) Err() error {
return r.err
}

View File

@@ -1,48 +0,0 @@
package task
import (
"encoding/json"
"fmt"
"io/ioutil"
"runtime"
"github.com/BurntSushi/toml"
"github.com/imdario/mergo"
"gopkg.in/yaml.v2"
)
// ReadTaskfile parses Taskfile from the disk
func (e *Executor) ReadTaskfile() error {
var err error
e.Tasks, err = e.readTaskfileData(TaskFilePath)
if err != nil {
return err
}
osTasks, err := e.readTaskfileData(fmt.Sprintf("%s_%s", TaskFilePath, runtime.GOOS))
if err != nil {
switch err.(type) {
case taskFileNotFound:
return nil
default:
return err
}
}
if err := mergo.MapWithOverwrite(&e.Tasks, osTasks); err != nil {
return err
}
return nil
}
func (e *Executor) readTaskfileData(path string) (tasks map[string]*Task, err error) {
if b, err := ioutil.ReadFile(path + ".yml"); err == nil {
return tasks, yaml.Unmarshal(b, &tasks)
}
if b, err := ioutil.ReadFile(path + ".json"); err == nil {
return tasks, json.Unmarshal(b, &tasks)
}
if b, err := ioutil.ReadFile(path + ".toml"); err == nil {
return tasks, toml.Unmarshal(b, &tasks)
}
return nil, taskFileNotFound{path}
}

84
status.go Normal file
View File

@@ -0,0 +1,84 @@
package task
import (
"context"
"fmt"
"github.com/go-task/task/v2/internal/execext"
"github.com/go-task/task/v2/internal/status"
"github.com/go-task/task/v2/internal/taskfile"
)
// Status returns an error if any the of given tasks is not up-to-date
func (e *Executor) Status(calls ...taskfile.Call) error {
for _, call := range calls {
t, err := e.CompiledTask(call)
if err != nil {
return err
}
isUpToDate, err := isTaskUpToDate(e.Context, t)
if err != nil {
return err
}
if !isUpToDate {
return fmt.Errorf(`task: Task "%s" is not up-to-date`, t.Task)
}
}
return nil
}
func isTaskUpToDate(ctx context.Context, t *taskfile.Task) (bool, error) {
if len(t.Status) > 0 {
return isTaskUpToDateStatus(ctx, t)
}
checker, err := getStatusChecker(t)
if err != nil {
return false, err
}
return checker.IsUpToDate()
}
func statusOnError(t *taskfile.Task) error {
checker, err := getStatusChecker(t)
if err != nil {
return err
}
return checker.OnError()
}
func getStatusChecker(t *taskfile.Task) (status.Checker, error) {
switch t.Method {
case "", "timestamp":
return &status.Timestamp{
Dir: t.Dir,
Sources: t.Sources,
Generates: t.Generates,
}, nil
case "checksum":
return &status.Checksum{
Dir: t.Dir,
Task: t.Task,
Sources: t.Sources,
}, nil
case "none":
return status.None{}, nil
default:
return nil, fmt.Errorf(`task: invalid method "%s"`, t.Method)
}
}
func isTaskUpToDateStatus(ctx context.Context, t *taskfile.Task) (bool, error) {
for _, s := range t.Status {
err := execext.RunCommand(ctx, &execext.RunCommandOptions{
Command: s,
Dir: t.Dir,
Env: getEnviron(t),
})
if err != nil {
return false, nil
}
}
return true, nil
}

375
task.go
View File

@@ -1,253 +1,276 @@
package task
import (
"bytes"
"context"
"fmt"
"log"
"io"
"os"
"strings"
"sync/atomic"
"github.com/go-task/task/execext"
"github.com/go-task/task/v2/internal/compiler"
compilerv1 "github.com/go-task/task/v2/internal/compiler/v1"
compilerv2 "github.com/go-task/task/v2/internal/compiler/v2"
"github.com/go-task/task/v2/internal/execext"
"github.com/go-task/task/v2/internal/logger"
"github.com/go-task/task/v2/internal/output"
"github.com/go-task/task/v2/internal/taskfile"
"github.com/go-task/task/v2/internal/taskfile/read"
"github.com/go-task/task/v2/internal/taskfile/version"
"github.com/Masterminds/semver"
"golang.org/x/sync/errgroup"
)
const (
// TaskFilePath is the default Taskfile
TaskFilePath = "Taskfile"
// MaximumTaskCall is the max number of times a task can be called.
// This exists to prevent infinite loops on cyclic dependencies
MaximumTaskCall = 100
)
// Executor executes a Taskfile
type Executor struct {
Tasks Tasks
Force bool
Watch bool
Taskfile *taskfile.Taskfile
Dir string
Force bool
Watch bool
Verbose bool
Silent bool
Dry bool
watchingFiles map[string]struct{}
}
Context context.Context
// Tasks representas a group of tasks
type Tasks map[string]*Task
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// Task represents a task
type Task struct {
Cmds []string
Deps []string
Desc string
Sources []string
Generates []string
Status []string
Dir string
Vars map[string]string
Set string
Env map[string]string
Logger *logger.Logger
Compiler compiler.Compiler
Output output.Output
taskvars taskfile.Vars
taskCallCount map[string]*int32
}
// Run runs Task
func (e *Executor) Run(args ...string) error {
if e.HasCyclicDep() {
return ErrCyclicDependencyDetected
}
func (e *Executor) Run(calls ...taskfile.Call) error {
// check if given tasks exist
for _, a := range args {
if _, ok := e.Tasks[a]; !ok {
for _, c := range calls {
if _, ok := e.Taskfile.Tasks[c.Task]; !ok {
// FIXME: move to the main package
e.printExistingTasksHelp()
return &taskNotFoundError{taskName: a}
e.PrintTasksHelp()
return &taskNotFoundError{taskName: c.Task}
}
}
if e.Watch {
if err := e.watchTasks(args...); err != nil {
return err
}
return nil
return e.watchTasks(calls...)
}
for _, a := range args {
if err := e.RunTask(context.Background(), a); err != nil {
for _, c := range calls {
if err := e.RunTask(e.Context, c); err != nil {
return err
}
}
return nil
}
// Setup setups Executor's internal state
func (e *Executor) Setup() error {
var err error
e.Taskfile, err = read.Taskfile(e.Dir)
if err != nil {
return err
}
e.taskvars, err = read.Taskvars(e.Dir)
if err != nil {
return err
}
v, err := semver.NewConstraint(e.Taskfile.Version)
if err != nil {
return fmt.Errorf(`task: could not parse taskfile version "%s": %v`, e.Taskfile.Version, err)
}
if e.Context == nil {
e.Context = context.Background()
}
if e.Stdin == nil {
e.Stdin = os.Stdin
}
if e.Stdout == nil {
e.Stdout = os.Stdout
}
if e.Stderr == nil {
e.Stderr = os.Stderr
}
e.Logger = &logger.Logger{
Stdout: e.Stdout,
Stderr: e.Stderr,
Verbose: e.Verbose,
}
switch {
case version.IsV1(v):
e.Compiler = &compilerv1.CompilerV1{
Dir: e.Dir,
Vars: e.taskvars,
Logger: e.Logger,
}
case version.IsV2(v), version.IsV21(v), version.IsV22(v):
e.Compiler = &compilerv2.CompilerV2{
Dir: e.Dir,
Taskvars: e.taskvars,
TaskfileVars: e.Taskfile.Vars,
Expansions: e.Taskfile.Expansions,
Logger: e.Logger,
}
case version.IsV23(v):
return fmt.Errorf(`task: Taskfile versions greater than v2.3 not implemented in the version of Task`)
}
if !version.IsV21(v) && e.Taskfile.Output != "" {
return fmt.Errorf(`task: Taskfile option "output" is only available starting on Taskfile version v2.1`)
}
if !version.IsV22(v) && len(e.Taskfile.Includes) > 0 {
return fmt.Errorf(`task: Including Taskfiles is only available starting on Taskfile version v2.2`)
}
switch e.Taskfile.Output {
case "", "interleaved":
e.Output = output.Interleaved{}
case "group":
e.Output = output.Group{}
case "prefixed":
e.Output = output.Prefixed{}
default:
return fmt.Errorf(`task: output option "%s" not recognized`, e.Taskfile.Output)
}
if !version.IsV21(v) {
err := fmt.Errorf(`task: Taskfile option "ignore_error" is only available starting on Taskfile version v2.1`)
for _, task := range e.Taskfile.Tasks {
if task.IgnoreError {
return err
}
for _, cmd := range task.Cmds {
if cmd.IgnoreError {
return err
}
}
}
}
e.taskCallCount = make(map[string]*int32, len(e.Taskfile.Tasks))
for k := range e.Taskfile.Tasks {
e.taskCallCount[k] = new(int32)
}
return nil
}
// RunTask runs a task by its name
func (e *Executor) RunTask(ctx context.Context, name string) error {
t, ok := e.Tasks[name]
if !ok {
return &taskNotFoundError{name}
func (e *Executor) RunTask(ctx context.Context, call taskfile.Call) error {
t, err := e.CompiledTask(call)
if err != nil {
return err
}
if !e.Watch && atomic.AddInt32(e.taskCallCount[call.Task], 1) >= MaximumTaskCall {
return &MaximumTaskCallExceededError{task: call.Task}
}
if err := e.runDeps(ctx, name); err != nil {
if err := e.runDeps(ctx, t); err != nil {
return err
}
if !e.Force {
upToDate, err := t.isUpToDate(ctx)
upToDate, err := isTaskUpToDate(ctx, t)
if err != nil {
return err
}
if upToDate {
log.Printf(`task: Task "%s" is up to date`, name)
if !e.Silent {
e.Logger.Errf(`task: Task "%s" is up to date`, t.Task)
}
return nil
}
}
for i := range t.Cmds {
if err := e.runCommand(ctx, name, i); err != nil {
return &taskRunError{name, err}
if err := e.runCommand(ctx, t, call, i); err != nil {
if err2 := statusOnError(t); err2 != nil {
e.Logger.VerboseErrf("task: error cleaning status on error: %v", err2)
}
if execext.IsExitError(err) && t.IgnoreError {
e.Logger.VerboseErrf("task: task error ignored: %v", err)
continue
}
return &taskRunError{t.Task, err}
}
}
return nil
}
func (e *Executor) runDeps(ctx context.Context, task string) error {
func (e *Executor) runDeps(ctx context.Context, t *taskfile.Task) error {
g, ctx := errgroup.WithContext(ctx)
t := e.Tasks[task]
for _, d := range t.Deps {
dep := d
d := d
g.Go(func() error {
dep, err := t.ReplaceVariables(dep)
if err != nil {
return err
}
return e.RunTask(ctx, taskfile.Call{Task: d.Task, Vars: d.Vars})
})
}
if err = e.RunTask(ctx, dep); err != nil {
return err
}
return g.Wait()
}
func (e *Executor) runCommand(ctx context.Context, t *taskfile.Task, call taskfile.Call, i int) error {
cmd := t.Cmds[i]
switch {
case cmd.Task != "":
return e.RunTask(ctx, taskfile.Call{Task: cmd.Task, Vars: cmd.Vars})
case cmd.Cmd != "":
if e.Verbose || (!cmd.Silent && !t.Silent && !e.Silent) {
e.Logger.Errf(cmd.Cmd)
}
if e.Dry {
return nil
})
}
}
if err := g.Wait(); err != nil {
return err
}
return nil
}
stdOut := e.Output.WrapWriter(e.Stdout, t.Prefix)
stdErr := e.Output.WrapWriter(e.Stderr, t.Prefix)
defer stdOut.Close()
defer stdErr.Close()
func (t *Task) isUpToDate(ctx context.Context) (bool, error) {
if len(t.Status) > 0 {
return t.isUpToDateStatus(ctx)
}
return t.isUpToDateTimestamp(ctx)
}
func (t *Task) isUpToDateStatus(ctx context.Context) (bool, error) {
environ, err := t.getEnviron()
if err != nil {
return false, err
}
for _, s := range t.Status {
err = execext.RunCommand(&execext.RunCommandOptions{
Context: ctx,
Command: s,
err := execext.RunCommand(ctx, &execext.RunCommandOptions{
Command: cmd.Cmd,
Dir: t.Dir,
Env: environ,
Env: getEnviron(t),
Stdin: e.Stdin,
Stdout: stdOut,
Stderr: stdErr,
})
if err != nil {
return false, nil
if execext.IsExitError(err) && cmd.IgnoreError {
e.Logger.VerboseErrf("task: command error ignored: %v", err)
return nil
}
}
return true, nil
}
func (t *Task) isUpToDateTimestamp(ctx context.Context) (bool, error) {
if len(t.Sources) == 0 || len(t.Generates) == 0 {
return false, nil
}
sources, err := t.ReplaceSliceVariables(t.Sources)
if err != nil {
return false, err
}
generates, err := t.ReplaceSliceVariables(t.Generates)
if err != nil {
return false, err
}
sourcesMaxTime, err := getPatternsMaxTime(sources)
if err != nil || sourcesMaxTime.IsZero() {
return false, nil
}
generatesMinTime, err := getPatternsMinTime(generates)
if err != nil || generatesMinTime.IsZero() {
return false, nil
}
return generatesMinTime.After(sourcesMaxTime), nil
}
func (e *Executor) runCommand(ctx context.Context, task string, i int) error {
t := e.Tasks[task]
c, err := t.ReplaceVariables(t.Cmds[i])
if err != nil {
return err
default:
return nil
}
}
if strings.HasPrefix(c, "^") {
c = strings.TrimPrefix(c, "^")
if err = e.RunTask(ctx, c); err != nil {
return err
}
func getEnviron(t *taskfile.Task) []string {
if t.Env == nil {
return nil
}
dir, err := t.ReplaceVariables(t.Dir)
if err != nil {
return err
environ := os.Environ()
for k, v := range t.Env.ToStringMap() {
environ = append(environ, fmt.Sprintf("%s=%s", k, v))
}
envs, err := t.getEnviron()
if err != nil {
return err
}
opts := &execext.RunCommandOptions{
Context: ctx,
Command: c,
Dir: dir,
Env: envs,
Stdin: os.Stdin,
Stderr: os.Stderr,
}
if t.Set == "" {
log.Println(c)
opts.Stdout = os.Stdout
if err = execext.RunCommand(opts); err != nil {
return err
}
} else {
buff := bytes.NewBuffer(nil)
opts.Stdout = buff
if err = execext.RunCommand(opts); err != nil {
return err
}
os.Setenv(t.Set, strings.TrimSpace(buff.String()))
}
return nil
}
func (t *Task) getEnviron() ([]string, error) {
if t.Env == nil {
return nil, nil
}
envs := os.Environ()
for k, v := range t.Env {
env, err := t.ReplaceVariables(fmt.Sprintf("%s=%s", k, v))
if err != nil {
return nil, err
}
envs = append(envs, env)
}
return envs, nil
return environ
}

View File

@@ -2,14 +2,206 @@ package task_test
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/go-task/task/v2"
"github.com/go-task/task/v2/internal/taskfile"
"github.com/mitchellh/go-homedir"
"github.com/stretchr/testify/assert"
)
// fileContentTest provides a basic reusable test-case for running a Taskfile
// and inspect generated files.
type fileContentTest struct {
Dir string
Target string
TrimSpace bool
Files map[string]string
}
func (fct fileContentTest) name(file string) string {
return fmt.Sprintf("target=%q,file=%q", fct.Target, file)
}
func (fct fileContentTest) Run(t *testing.T) {
for f := range fct.Files {
_ = os.Remove(filepath.Join(fct.Dir, f))
}
e := &task.Executor{
Dir: fct.Dir,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
}
assert.NoError(t, e.Setup(), "e.Setup()")
assert.NoError(t, e.Run(taskfile.Call{Task: fct.Target}), "e.Run(target)")
for name, expectContent := range fct.Files {
t.Run(fct.name(name), func(t *testing.T) {
b, err := ioutil.ReadFile(filepath.Join(fct.Dir, name))
assert.NoError(t, err, "Error reading file")
s := string(b)
if fct.TrimSpace {
s = strings.TrimSpace(s)
}
assert.Equal(t, expectContent, s, "unexpected file content")
})
}
}
func TestEnv(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/env",
Target: "default",
TrimSpace: false,
Files: map[string]string{
"local.txt": "GOOS='linux' GOARCH='amd64' CGO_ENABLED='0'\n",
"global.txt": "FOO='foo' BAR='overriden' BAZ='baz'\n",
},
}
tt.Run(t)
}
func TestVarsV1(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/vars/v1",
Target: "default",
TrimSpace: true,
Files: map[string]string{
// hello task:
"foo.txt": "foo",
"bar.txt": "bar",
"baz.txt": "baz",
"tmpl_foo.txt": "foo",
"tmpl_bar.txt": "<no value>",
"tmpl_foo2.txt": "foo2",
"tmpl_bar2.txt": "bar2",
"shtmpl_foo.txt": "foo",
"shtmpl_foo2.txt": "foo2",
"nestedtmpl_foo.txt": "{{.FOO}}",
"nestedtmpl_foo2.txt": "foo2",
"foo2.txt": "foo2",
"bar2.txt": "bar2",
"baz2.txt": "baz2",
"tmpl2_foo.txt": "<no value>",
"tmpl2_foo2.txt": "foo2",
"tmpl2_bar.txt": "<no value>",
"tmpl2_bar2.txt": "<no value>",
"shtmpl2_foo.txt": "<no value>",
"shtmpl2_foo2.txt": "foo2",
"nestedtmpl2_foo2.txt": "{{.FOO2}}",
"override.txt": "bar",
},
}
tt.Run(t)
// Ensure identical results when running hello task directly.
tt.Target = "hello"
tt.Run(t)
}
func TestVarsV2(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/vars/v2",
Target: "default",
TrimSpace: true,
Files: map[string]string{
"foo.txt": "foo",
"bar.txt": "bar",
"baz.txt": "baz",
"tmpl_foo.txt": "foo",
"tmpl_bar.txt": "bar",
"tmpl_foo2.txt": "foo2",
"tmpl_bar2.txt": "bar2",
"shtmpl_foo.txt": "foo",
"shtmpl_foo2.txt": "foo2",
"nestedtmpl_foo.txt": "<no value>",
"nestedtmpl_foo2.txt": "foo2",
"foo2.txt": "foo2",
"bar2.txt": "bar2",
"baz2.txt": "baz2",
"tmpl2_foo.txt": "<no value>",
"tmpl2_foo2.txt": "foo2",
"tmpl2_bar.txt": "<no value>",
"tmpl2_bar2.txt": "bar2",
"shtmpl2_foo.txt": "<no value>",
"shtmpl2_foo2.txt": "foo2",
"nestedtmpl2_foo2.txt": "<no value>",
"override.txt": "bar",
"nested.txt": "Taskvars-TaskfileVars-TaskVars",
},
}
tt.Run(t)
// Ensure identical results when running hello task directly.
tt.Target = "hello"
tt.Run(t)
}
func TestMultilineVars(t *testing.T) {
for _, dir := range []string{"testdata/vars/v1/multiline", "testdata/vars/v2/multiline"} {
tt := fileContentTest{
Dir: dir,
Target: "default",
TrimSpace: false,
Files: map[string]string{
// Note:
// - task does not strip a trailing newline from var entries
// - task strips one trailing newline from shell output
// - the cat command adds a trailing newline
"echo_foobar.txt": "foo\nbar\n",
"echo_n_foobar.txt": "foo\nbar\n",
"echo_n_multiline.txt": "\n\nfoo\n bar\nfoobar\n\nbaz\n\n",
"var_multiline.txt": "\n\nfoo\n bar\nfoobar\n\nbaz\n\n\n",
"var_catlines.txt": " foo bar foobar baz \n",
"var_enumfile.txt": "0:\n1:\n2:foo\n3: bar\n4:foobar\n5:\n6:baz\n7:\n8:\n",
},
}
tt.Run(t)
}
}
func TestVarsInvalidTmpl(t *testing.T) {
const (
dir = "testdata/vars/v1"
target = "invalid-var-tmpl"
expectError = "template: :1: unexpected EOF"
)
e := &task.Executor{
Dir: dir,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
}
assert.NoError(t, e.Setup(), "e.Setup()")
assert.EqualError(t, e.Run(taskfile.Call{Task: target}), expectError, "e.Run(target)")
}
func TestParams(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/params",
Target: "default",
TrimSpace: false,
Files: map[string]string{
"hello.txt": "Hello\n",
"world.txt": "World\n",
"exclamation.txt": "!\n",
"dep1.txt": "Dependence1\n",
"dep2.txt": "Dependence2\n",
"spanish.txt": "¡Holla mundo!\n",
"spanish-dep.txt": "¡Holla dependencia!\n",
"portuguese.txt": "Olá, mundo!\n",
"portuguese2.txt": "Olá, mundo!\n",
"german.txt": "Welt!\n",
},
}
tt.Run(t)
}
func TestDeps(t *testing.T) {
const dir = "testdata/deps"
@@ -32,12 +224,13 @@ func TestDeps(t *testing.T) {
_ = os.Remove(filepath.Join(dir, f))
}
c := exec.Command("task")
c.Dir = dir
if err := c.Run(); err != nil {
t.Error(err)
return
e := &task.Executor{
Dir: dir,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
}
assert.NoError(t, e.Setup())
assert.NoError(t, e.Run(taskfile.Call{Task: "default"}))
for _, f := range files {
f = filepath.Join(dir, f)
@@ -47,73 +240,6 @@ func TestDeps(t *testing.T) {
}
}
func TestVars(t *testing.T) {
const dir = "testdata/vars"
files := []struct {
file string
content string
}{
{"foo.txt", "foo"},
{"bar.txt", "bar"},
{"foo2.txt", "foo2"},
{"bar2.txt", "bar2"},
{"equal.txt", "foo=bar"},
}
for _, f := range files {
_ = os.Remove(filepath.Join(dir, f.file))
}
c := exec.Command("task")
c.Dir = dir
if err := c.Run(); err != nil {
t.Error(err)
return
}
for _, f := range files {
d, err := ioutil.ReadFile(filepath.Join(dir, f.file))
if err != nil {
t.Errorf("Error reading %s: %v", f.file, err)
}
s := string(d)
s = strings.TrimSpace(s)
if s != f.content {
t.Errorf("File content should be %s but is %s", f.content, s)
}
}
}
func TestTaskCall(t *testing.T) {
const dir = "testdata/task_call"
files := []string{
"foo.txt",
"bar.txt",
}
for _, f := range files {
_ = os.Remove(filepath.Join(dir, f))
}
c := exec.Command("task")
c.Dir = dir
if err := c.Run(); err != nil {
t.Error(err)
return
}
for _, f := range files {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
t.Error(err)
}
}
}
func TestStatus(t *testing.T) {
const dir = "testdata/status"
var file = filepath.Join(dir, "foo.txt")
@@ -123,28 +249,118 @@ func TestStatus(t *testing.T) {
if _, err := os.Stat(file); err == nil {
t.Errorf("File should not exists: %v", err)
}
c := exec.Command("task", "gen-foo")
c.Dir = dir
if err := c.Run(); err != nil {
t.Error(err)
var buff bytes.Buffer
e := &task.Executor{
Dir: dir,
Stdout: &buff,
Stderr: &buff,
Silent: true,
}
assert.NoError(t, e.Setup())
assert.NoError(t, e.Run(taskfile.Call{Task: "gen-foo"}))
if _, err := os.Stat(file); err != nil {
t.Errorf("File should exists: %v", err)
}
buff := bytes.NewBuffer(nil)
c = exec.Command("task", "gen-foo")
c.Dir = dir
c.Stderr = buff
c.Stdout = buff
if err := c.Run(); err != nil {
t.Error(err)
}
e.Silent = false
assert.NoError(t, e.Run(taskfile.Call{Task: "gen-foo"}))
if buff.String() != `task: Task "gen-foo" is up to date`+"\n" {
t.Errorf("Wrong output message: %s", buff.String())
}
}
func TestGenerates(t *testing.T) {
var srcTask = "sub/src.txt"
var relTask = "rel.txt"
var absTask = "abs.txt"
// This test does not work with a relative dir.
dir, err := filepath.Abs("testdata/generates")
assert.NoError(t, err)
var srcFile = filepath.Join(dir, srcTask)
for _, task := range []string{srcTask, relTask, absTask} {
path := filepath.Join(dir, task)
_ = os.Remove(path)
if _, err := os.Stat(path); err == nil {
t.Errorf("File should not exists: %v", err)
}
}
buff := bytes.NewBuffer(nil)
e := &task.Executor{
Dir: dir,
Stdout: buff,
Stderr: buff,
}
assert.NoError(t, e.Setup())
for _, theTask := range []string{relTask, absTask} {
var destFile = filepath.Join(dir, theTask)
var upToDate = fmt.Sprintf("task: Task \"%s\" is up to date\n", srcTask) +
fmt.Sprintf("task: Task \"%s\" is up to date\n", theTask)
// Run task for the first time.
assert.NoError(t, e.Run(taskfile.Call{Task: theTask}))
if _, err := os.Stat(srcFile); err != nil {
t.Errorf("File should exists: %v", err)
}
if _, err := os.Stat(destFile); err != nil {
t.Errorf("File should exists: %v", err)
}
// Ensure task was not incorrectly found to be up-to-date on first run.
if buff.String() == upToDate {
t.Errorf("Wrong output message: %s", buff.String())
}
buff.Reset()
// Re-run task to ensure it's now found to be up-to-date.
assert.NoError(t, e.Run(taskfile.Call{Task: theTask}))
if buff.String() != upToDate {
t.Errorf("Wrong output message: %s", buff.String())
}
buff.Reset()
}
}
func TestStatusChecksum(t *testing.T) {
const dir = "testdata/checksum"
files := []string{
"generated.txt",
".task/checksum/build",
}
for _, f := range files {
_ = os.Remove(filepath.Join(dir, f))
_, err := os.Stat(filepath.Join(dir, f))
assert.Error(t, err)
}
var buff bytes.Buffer
e := task.Executor{
Dir: dir,
Stdout: &buff,
Stderr: &buff,
}
assert.NoError(t, e.Setup())
assert.NoError(t, e.Run(taskfile.Call{Task: "build"}))
for _, f := range files {
_, err := os.Stat(filepath.Join(dir, f))
assert.NoError(t, err)
}
buff.Reset()
assert.NoError(t, e.Run(taskfile.Call{Task: "build"}))
assert.Equal(t, `task: Task "build" is up to date`+"\n", buff.String())
}
func TestInit(t *testing.T) {
const dir = "testdata/init"
var file = filepath.Join(dir, "Taskfile.yml")
@@ -154,12 +370,144 @@ func TestInit(t *testing.T) {
t.Errorf("Taskfile.yml should not exists")
}
c := exec.Command("task", "--init")
c.Dir = dir
if err := c.Run(); err != nil {
if err := task.InitTaskfile(ioutil.Discard, dir); err != nil {
t.Error(err)
}
if _, err := os.Stat(file); err != nil {
t.Errorf("Taskfile.yml should exists")
}
}
func TestCyclicDep(t *testing.T) {
const dir = "testdata/cyclic"
e := task.Executor{
Dir: dir,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
}
assert.NoError(t, e.Setup())
assert.IsType(t, &task.MaximumTaskCallExceededError{}, e.Run(taskfile.Call{Task: "task-1"}))
}
func TestTaskVersion(t *testing.T) {
tests := []struct {
Dir string
Version string
}{
{"testdata/version/v1", "1"},
{"testdata/version/v2", "2"},
}
for _, test := range tests {
t.Run(test.Dir, func(t *testing.T) {
e := task.Executor{
Dir: test.Dir,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
}
assert.NoError(t, e.Setup())
assert.Equal(t, test.Version, e.Taskfile.Version)
assert.Equal(t, 2, len(e.Taskfile.Tasks))
})
}
}
func TestTaskIgnoreErrors(t *testing.T) {
const dir = "testdata/ignore_errors"
e := task.Executor{
Dir: dir,
Stdout: ioutil.Discard,
Stderr: ioutil.Discard,
}
assert.NoError(t, e.Setup())
assert.NoError(t, e.Run(taskfile.Call{Task: "task-should-pass"}))
assert.Error(t, e.Run(taskfile.Call{Task: "task-should-fail"}))
assert.NoError(t, e.Run(taskfile.Call{Task: "cmd-should-pass"}))
assert.Error(t, e.Run(taskfile.Call{Task: "cmd-should-fail"}))
}
func TestExpand(t *testing.T) {
const dir = "testdata/expand"
home, err := homedir.Dir()
if err != nil {
t.Errorf("Couldn't get $HOME: %v", err)
}
var buff bytes.Buffer
e := task.Executor{
Dir: dir,
Stdout: &buff,
Stderr: &buff,
}
assert.NoError(t, e.Setup())
assert.NoError(t, e.Run(taskfile.Call{Task: "pwd"}))
assert.Equal(t, home, strings.TrimSpace(buff.String()))
}
func TestDry(t *testing.T) {
const dir = "testdata/dry"
file := filepath.Join(dir, "file.txt")
_ = os.Remove(file)
var buff bytes.Buffer
e := task.Executor{
Dir: dir,
Stdout: &buff,
Stderr: &buff,
Dry: true,
}
assert.NoError(t, e.Setup())
assert.NoError(t, e.Run(taskfile.Call{Task: "build"}))
assert.Equal(t, "touch file.txt", strings.TrimSpace(buff.String()))
if _, err := os.Stat(file); err == nil {
t.Errorf("File should not exist %s", file)
}
}
func TestIncludes(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/includes",
Target: "default",
TrimSpace: true,
Files: map[string]string{
"main.txt": "main",
"included_directory.txt": "included_directory",
"included_taskfile.txt": "included_taskfile",
},
}
tt.Run(t)
}
func TestIncludesEmptyMain(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/includes_empty",
Target: "included:default",
TrimSpace: true,
Files: map[string]string{
"file.txt": "default",
},
}
tt.Run(t)
}
func TestIncludesDependencies(t *testing.T) {
tt := fileContentTest{
Dir: "testdata/includes_deps",
Target: "default",
TrimSpace: true,
Files: map[string]string{
"default.txt": "default",
"called_dep.txt": "called_dep",
"called_task.txt": "called_task",
},
}
tt.Run(t)
}

2
testdata/checksum/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
.task/
generated.txt

9
testdata/checksum/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,9 @@
build:
cmds:
- cp ./source.txt ./generated.txt
sources:
- ./**/glob-with-inexistent-file.txt
- ./source.txt
generates:
- ./generated.txt
method: checksum

1
testdata/checksum/source.txt vendored Normal file
View File

@@ -0,0 +1 @@
Hello, World!

7
testdata/cyclic/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,7 @@
task-1:
deps:
- task: task-2
task-2:
deps:
- task: task-1

6
testdata/dry/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,6 @@
version: '2'
tasks:
build:
cmds:
- touch file.txt

33
testdata/env/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,33 @@
version: '2'
vars:
BAZ:
sh: echo baz
env:
FOO: foo
BAR: bar
BAZ: "{{.BAZ}}"
tasks:
default:
cmds:
- task: local
- task: global
local:
vars:
AMD64: amd64
env:
GOOS: linux
GOARCH: "{{.AMD64}}"
CGO_ENABLED:
sh: echo '0'
cmds:
- echo "GOOS='$GOOS' GOARCH='$GOARCH' CGO_ENABLED='$CGO_ENABLED'" > local.txt
global:
env:
BAR: overriden
cmds:
- echo "FOO='$FOO' BAR='$BAR' BAZ='$BAZ'" > global.txt

8
testdata/expand/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,8 @@
version: '2'
tasks:
pwd:
cmds:
- pwd
dir: '~'
silent: true

31
testdata/generates/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
abs.txt:
desc: generates dest file based on absolute paths
deps:
- sub/src.txt
dir: sub
cmds:
- cat src.txt > '{{.BUILD_DIR}}/abs.txt'
sources:
- src.txt
generates:
- "{{.BUILD_DIR}}/abs.txt"
rel.txt:
desc: generates dest file based on relative paths
deps:
- sub/src.txt
dir: sub
cmds:
- cat src.txt > '../rel.txt'
sources:
- src.txt
generates:
- "../rel.txt"
sub/src.txt:
desc: generate source file
cmds:
- mkdir -p sub
- echo "hello world" > sub/src.txt
status:
- test -f sub/src.txt

1
testdata/generates/Taskvars.yml vendored Normal file
View File

@@ -0,0 +1 @@
BUILD_DIR: $pwd

20
testdata/ignore_errors/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
version: '2'
tasks:
task-should-pass:
cmds:
- exit 1
ignore_error: true
task-should-fail:
cmds:
- exit 1
cmd-should-pass:
cmds:
- cmd: exit 1
ignore_error: true
cmd-should-fail:
cmds:
- cmd: exit 1

1
testdata/includes/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.txt

16
testdata/includes/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
version: '2'
includes:
included: ./included
included_taskfile: ./Taskfile2.yml
tasks:
default:
cmds:
- task: gen
- task: included:gen
- task: included_taskfile:gen
gen:
cmds:
- echo main > main.txt

6
testdata/includes/Taskfile2.yml vendored Normal file
View File

@@ -0,0 +1,6 @@
version: '2'
tasks:
gen:
cmds:
- echo included_taskfile > included_taskfile.txt

View File

@@ -0,0 +1,6 @@
version: '2'
tasks:
gen:
cmds:
- echo included_directory > included_directory.txt

1
testdata/includes_deps/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.txt

9
testdata/includes_deps/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,9 @@
version: '2'
includes:
included: Taskfile2.yml
tasks:
default:
cmds:
- task: included:default

16
testdata/includes_deps/Taskfile2.yml vendored Normal file
View File

@@ -0,0 +1,16 @@
version: '2'
tasks:
default:
deps: [called_dep]
cmds:
- echo "default" > default.txt
- task: called_task
called_dep:
cmds:
- echo "called_dep" > called_dep.txt
called_task:
cmds:
- echo "called_task" > called_task.txt

1
testdata/includes_empty/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
file.txt

4
testdata/includes_empty/Taskfile.yml vendored Normal file
View File

@@ -0,0 +1,4 @@
version: '2'
includes:
included: Taskfile2.yml

10
testdata/includes_empty/Taskfile2.yml vendored Normal file
View File

@@ -0,0 +1,10 @@
version: '2'
vars:
FILE: file.txt
CONTENT: default
tasks:
default:
cmds:
- echo "{{.CONTENT}}" > {{.FILE}}

1
testdata/params/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.txt

Some files were not shown because too many files have changed in this diff Show More