Pular para o conteúdo principal

Referência da API

Linha de comando

O comando "task" tem a seguinte sintaxe:

task [--flags] [tasks...] [-- CLI_ARGS...]
dica

If -- is given, all remaining arguments will be assigned to a special CLI_ARGS variable

AbreviaçãoModificadorTipoPredefiniçãoDescrição
-c--colorbooltrueSaída colorida. Habilitado por padrão. Defina o modificador como false ou use NO_COLOR=1 para desativar.
-C--concurrencyint0Limitar número de tarefas a serem executadas simultaneamente. Zero significa ilimitado.
-d--dirstringPasta atualDefine a pasta de execução.
-n--dryboolfalseCompila e imprime as tarefas na ordem em que elas seriam executadas, sem executá-las.
-x--exit-codeboolfalseFaz com que o código de saída do comando sendo executado seja repassado pelo Task.
-f--forceboolfalseForça a execução mesmo quando a tarefa está atualizada.
-g--globalboolfalseExecuta o Taskfile global, de $HOME/Taskfile.{yml,yaml}.
-h--helpboolfalseMostra a ajuda do Task.
-i--initboolfalseCria um novo Taskfile.yml na pasta atual.
-I--intervalstring5sDefine um intervalo de tempo diferente ao usar --watch, o padrão sendo 5 segundos. Este valor deve ser um Go Duration válido.
-l--listboolfalseLista as tarefas com descrição do Taskfile atual.
-a--list-allboolfalseLista todas as tarefas, com ou sem descrição.
--sortstringdefaultMuda order das terafas quando listadas.
default - Ordem alfabética com as tarefas fo Taskfile raíz listadas por primeiro
alphanumeric - Alfabética
none - Sem ordenação (mantém a mesma ordem de declaração no Taskfile)
--jsonboolfalseImprime a saída em JSON.
-o--outputstringO padrão é o que está definido no Taskfile, ou então intervealed.Configura o estilo de saída: [interleaved/group/prefixed].
--output-group-beginstringFormato de mensagem a imprimir antes da saída agrupada de uma tarefa.
--output-group-endstringFormato de mensagem a imprimir depois da saída agrupada de uma tarefa.
--output-group-error-onlyboolfalseOculta saída dos comandos que terminarem sem erro.
-p--parallelboolfalseExecuta as tarefas fornecidas na linha de comando em paralelo.
-s--silentboolfalseDesabilita impressão.
-y--yesboolfalseAssuma "sim" como resposta a todos os prompts.
--statusboolfalseSai com código de saída diferente de zero se alguma das tarefas especificadas não estiver atualizada.
--summaryboolfalseMostrar resumo sobre uma tarefa.
-t--taskfilestringTaskfile.yml ou Taskfile.yaml
-v--verboseboolfalseHabilita modo verboso.
--versionboolfalseMostrar versão do Task.
-w--watchboolfalseHabilita o monitoramento de tarefas.

Códigos de saída

O Task às vezes fecha com códigos de saída específicos. Estes códigos são divididos em três grupos com os seguintes intervalos:

  • General errors (0-99)
  • Taskfile errors (100-199)
  • Task errors (200-299)

Uma lista completa dos códigos de saída e suas descrições podem ser encontradas abaixo:

CódigoDescrição
0Sucesso
1Um erro desconhecido ocorreu
100Nenhum Arquivo foi encontrado
101Um arquivo Taskfile já existe ao tentar inicializar um
102O arquivo Taskfile é inválido ou não pode ser analisado
103A remote Taskfile could not be downlaoded
104A remote Taskfile was not trusted by the user
105A remote Taskfile was could not be fetched securely
106No cache was found for a remote Taskfile in offline mode
107No schema version was defined in the Taskfile
200A tarefa especificada não pôde ser encontrada
201Ocorreu um erro ao executar um comando dentro de uma tarefa
202O usuário tentou invocar uma tarefa que é interna
203Há várias tarefas com o mesmo nome ou apelido
204Uma tarefa foi chamada muitas vezes
205A tarefa foi cancelada pelo usuário
206A task was not executed due to missing required variables

Esses códigos também podem ser encontrados no repositório em errors/errors.go.

info

Quando o Task é executado com o modificador -x/--exit-code, o código de saída de todos os comandos falhados será passado para o usuário.

Saída em JSON

Quando estiver usando o modificador --json em combinação com o modificador --list ou --list-all, a saída será um objeto JSON com a seguinte estrutura:

{
"tasks": [
{
"name": "",
"desc": "",
"summary": "",
"up_to_date": false,
"location": {
"line": 54,
"column": 3,
"taskfile": "/path/to/Taskfile.yml"
}
}
// ...
],
"location": "/path/to/Taskfile.yml"
}

Variáveis Especiais

Há algumas variáveis especiais que são acessíveis via template:

VariávelDescrição
CLI_ARGSContém todos os argumentos extras passados depois de -- quando invocando o Task via linha de comando.
TASKO nome da tarefa atual.
ROOT_DIRO caminho absoluto para o Taskfile raíz.
TASKFILE_DIRO caminho absoluto para o Taskfile incluído.
USER_WORKING_DIRO caminho absoluto a partir do qual o comando task foi invocado.
CHECKSUMO "checksum" dos arquivos listados em sources. Apenas disponível dentro do atributo status e se o método estiver configurado como checksum.
TIMESTAMPThe date object of the greatest timestamp of the files listed in sources. Apenas disponível dentro do atributo status e se o método estiver configurado como timestamp.
TASK_VERSIONA versão atual do Task.
ITEMThe value of the current iteration when using the for property. Can be changed to a different variable name using as:.

ENV

Some environment variables can be overridden to adjust Task behavior.

ENVPadrãoDescrição
TASK_TEMP_DIR.taskCaminho da pasta temporária. Pode ser um caminho relativo ao projeto como tmp/task ou um caminho absoluto como /tmp/.task ou ~/.task.
TASK_COLOR_RESET0Cor utilizada para branco.
TASK_COLOR_BLUE34Cor utilizada para azul.
TASK_COLOR_GREEN32Cor utilizada para verde.
TASK_COLOR_CYAN36Cor utilizada para ciano.
TASK_COLOR_YELLOW33Cor utilizada para amarelo.
TASK_COLOR_MAGENTA35Cor utilizada para magenta.
TASK_COLOR_RED31Cor utilizada para vermelho.
FORCE_COLORForçar saída colorida no terminal.

Esquema do Taskfile

AtributoTipoPadrãoDescrição
versionstringVersão do Taskfile. A versão mais atual é a 3.
outputstringinterleavedMode de saída. Opções disponíveis: interleaved, group e prefixed.
methodstringchecksumO método padrão deste Taskfile. Can be overridden in a task by task basis. Opções disponíveis: checksum (conteúdo dos arquivos), timestamp (data/hora de modificação) e none (nenhum).
includesmap[string]IncludeTaskfiles adicionais a serem incluídos.
varsmap[string]VariableUm conjunto de variáveis globais.
envmap[string]VariableUm conjunto de variáveis de ambiente globais.
tasksmap[string]TaskUm conjunto de tarefas.
silentboolfalseOpção padrão para silent para este Taskfile. If false, can be overridden with true in a task by task basis.
dotenv[]stringUma lista de arquivos .env para serem incluídos.
runstringalwaysOpção padrão para run para este Taskfile. Opções disponíveis: always (sempre), once (uma vez) e when_changed (quando mudou).
intervalstring5sConfigura um intervalo de tempo diferente para --watch, sendo que o padrão é de 5 segundos. Essa string deve ser um Go Duration válido.
set[]stringConfigura opções para o builtin set.
shopt[]stringConfigura opções para o builtin shopt.

Include

AtributoTipoPadrãoDescrição
taskfilestringThe path for the Taskfile or directory to be included. If a directory, Task will look for files named Taskfile.yml or Taskfile.yaml inside that directory. If a relative path, resolved relative to the directory containing the including Taskfile.
dirstringThe parent Taskfile directoryThe working directory of the included tasks when run.
optionalboolfalseIf true, no errors will be thrown if the specified file does not exist.
internalboolfalseStops any task in the included Taskfile from being callable on the command line. These commands will also be omitted from the output when used with --list.
aliases[]stringAlternative names for the namespace of the included Taskfile.
varsmap[string]VariableA set of variables to apply to the included Taskfile.
info

Informing only a string like below is equivalent to setting that value to the taskfile attribute.

includes:
foo: ./path

Variable

AtributoTipoPadrãoDescrição
itselfstringA static value that will be set to the variable.
shstringA shell command. The output (STDOUT) will be assigned to the variable.
info

Static and dynamic variables have different syntaxes, like below:

vars:
STATIC: static
DYNAMIC:
sh: echo "dynamic"

Task

AtributoTipoPadrãoDescrição
cmds[]CommandA list of shell commands to be executed.
deps[]DependencyA list of dependencies of this task. Tasks defined here will run in parallel before this task.
labelstringOverrides the name of the task in the output when a task is run. Supports variables.
descstringA short description of the task. This is displayed when calling task --list.
promptstringA prompt that will be presented before a task is run. Declining will cancel running the current and any subsequent tasks.
summarystringA longer description of the task. This is displayed when calling task --summary [task].
aliases[]stringA list of alternative names by which the task can be called.
sources[]stringA list of sources to check before running this task. Relevant for checksum and timestamp methods. Can be file paths or star globs.
generates[]stringA list of files meant to be generated by this task. Relevant for timestamp method. Can be file paths or star globs.
status[]stringA list of commands to check if this task should run. The task is skipped otherwise. This overrides method, sources and generates.
requires[]stringA list of variables which should be set if this task is to run, if any of these variables are unset the task will error and not run.
preconditions[]PreconditionA list of commands to check if this task should run. If a condition is not met, the task will error.
requiresRequiresA list of required variables which should be set if this task is to run, if any variables listed are unset the task will error and not run.
dirstringThe directory in which this task should run. Defaults to the current working directory.
varsmap[string]VariableA set of variables that can be used in the task.
envmap[string]VariableA set of environment variables that will be made available to shell commands.
dotenv[]stringA list of .env file paths to be parsed.
silentboolfalseHides task name and command from output. The command's output will still be redirected to STDOUT and STDERR. When combined with the --list flag, task descriptions will be hidden.
interactiveboolfalseTells task that the command is interactive.
internalboolfalseStops a task from being callable on the command line. It will also be omitted from the output when used with --list.
methodstringchecksumDefines which method is used to check the task is up-to-date. timestamp will compare the timestamp of the sources and generates files. checksum will check the checksum (You probably want to ignore the .task folder in your .gitignore file). none skips any validation and always run the task.
prefixstringDefines a string to prefix the output of tasks running in parallel. Only used when the output mode is prefixed.
ignore_errorboolfalseContinue execution if errors happen while executing commands.
runstringThe one declared globally in the Taskfile or alwaysSpecifies whether the task should run again or not if called more than once. Available options: always, once and when_changed.
platforms[]stringAll platformsSpecifies which platforms the task should be run on. Valid GOOS and GOARCH values allowed. Task will be skipped otherwise.
set[]stringSpecify options for the set builtin.
shopt[]stringSpecify option for the shopt builtin.
info

These alternative syntaxes are available. They will set the given values to cmds and everything else will be set to their default values:

tasks:
foo: echo "foo"

foobar:
- echo "foo"
- echo "bar"

baz:
cmd: echo "baz"

Command

AtributoTipoPadrãoDescrição
cmdstringThe shell command to be executed.
taskstringSet this to trigger execution of another task instead of running a command. This cannot be set together with cmd.
forForRuns the command once for each given value.
silentboolfalseSkips some output for this command. Note that STDOUT and STDERR of the commands will still be redirected.
varsmap[string]VariableOptional additional variables to be passed to the referenced task. Only relevant when setting task instead of cmd.
ignore_errorboolfalseContinue execution if errors happen while executing the command.
deferstringAlternative to cmd, but schedules the command to be executed at the end of this task instead of immediately. This cannot be used together with cmd.
platforms[]stringAll platformsSpecifies which platforms the command should be run on. Valid GOOS and GOARCH values allowed. Command will be skipped otherwise.
set[]stringSpecify options for the set builtin.
shopt[]stringSpecify option for the shopt builtin.
info

If given as a a string, the value will be assigned to cmd:

tasks:
foo:
cmds:
- echo "foo"
- echo "bar"

Dependency

AtributoTipoPadrãoDescrição
taskstringThe task to be execute as a dependency.
varsmap[string]VariableOptional additional variables to be passed to this task.
silentboolfalseHides task name and command from output. The command's output will still be redirected to STDOUT and STDERR.
dica

If you don't want to set additional variables, it's enough to declare the dependency as a list of strings (they will be assigned to task):

tasks:
foo:
deps: [foo, bar]

For

The for parameter can be defined as a string, a list of strings or a map. If it is defined as a string, you can give it any of the following values:

  • source - Will run the command for each source file defined on the task. (Glob patterns will be resolved, so *.go will run for every Go file that matches).

If it is defined as a list of strings, the command will be run for each value.

Finally, the for parameter can be defined as a map when you want to use a variable to define the values to loop over:

AtributoTipoPadrãoDescrição
varstringThe name of the variable to use as an input.
splitstring(any whitespace)What string the variable should be split on.
asstringITEMThe name of the iterator variable.

Precondition

AttributeTypeDefaultDescription
shstringCommand to be executed. If a non-zero exit code is returned, the task errors without executing its commands.
msgstringOptional message to print if the precondition isn't met.
dica

If you don't want to set a different message, you can declare a precondition like this and the value will be assigned to sh:

tasks:
foo:
precondition: test -f Taskfile.yml

Requires

AttributeTypeDefaultDescription
vars[]stringList of variable or environment variable names that must be set if this task is to execute and run