Skip to main content

Templating Reference

Task's templating engine uses Go's text/template package to interpolate values. For detailed information about the usage of Go's templating engine, we recommend reading the official documentation. However, we will provide a basic overview of the main features here.

Basic Usage​

Most string values in Task (though, not all) can be templated. The templating engine uses double curly braces {{ and }} to denote a template. Anything inside the curly braces will be executed as a Go template and the result will be inserted into the resulting string. For example:

version: '3'

tasks:
hello:
vars:
MESSAGE: 'Hello, World!'
cmds:
- 'echo {{.MESSAGE}}'

In this example, we have a task called hello with a single variable, MESSAGE defined. When the command is run, the templating engine will evaluate the variable and replace {{.MESSAGE}} with the variable's contents. This task will output Hello, World! to the terminal. Note that when referring to a variable, you must use dot notation.

You are also able to do more complex things in templates, such as conditional logic:

version: '3'

tasks:
maybe-happy:
vars:
SMILE: ':\)'
FROWN: ':\('
HAPPY: true
cmds:
- 'echo {{if .HAPPY}}{{.SMILE}}{{else}}{{.FROWN}}{{end}}'
:)

...calling functions and piping values:

version: '3'

tasks:
uniq:
vars:
NUMBERS: '0,1,1,1,2,2,3'
cmds:
- 'echo {{splitList "," .NUMBERS | uniq | join ", " }}!'
0, 1, 2, 3

...looping over values with control flow operators:

version: '3'

tasks:
loop:
vars:
NUMBERS: [0, 1, 1, 1, 2, 2, 3]
cmds:
# Ranges over NUMBERS and prints the index and value of each number until it finds a number greater than 1
- "{{range $index, $num := .NUMBERS}}{{if gt $num 1 }}{{break}}{{end}}echo {{$index}}: {{$num}}\n{{end}}"
0: 0
1: 1
2: 1
3: 1

Special Variables​

Task defines some special variables that are always available to the templating engine. If you define a variable with the same name as a special variable, the special variable will be overridden.

VarDescription
CLI_ARGSContain all extra arguments passed after -- when calling Task through the CLI.
CLI_FORCEA boolean containing whether the --force or --force-all flags were set.
CLI_SILENTA boolean containing whether the --silent flag was set.
CLI_VERBOSEA boolean containing whether the --verbose flag was set.
TASKThe name of the current task.
ALIASThe alias used for the current task, otherwise matches TASK.
TASK_EXEThe Task executable name or path.
ROOT_TASKFILEThe absolute path of the root Taskfile.
ROOT_DIRThe absolute path of the root Taskfile directory.
TASKFILEThe absolute path of the included Taskfile.
TASKFILE_DIRThe absolute path of the included Taskfile directory.
USER_WORKING_DIRThe absolute path of the directory task was called from.
CHECKSUMThe checksum of the files listed in sources. Only available within the status prop and if method is set to checksum.
TIMESTAMPThe date object of the greatest timestamp of the files listed in sources. Only available within the status prop and if method is set to timestamp.
TASK_VERSIONThe current version of task.
ITEMThe value of the current iteration when using the for property. Can be changed to a different variable name using as:.
EXIT_CODEAvailable exclusively inside the defer: command. Contains the failed command exit code. Only set when non-zero.

Functions​

Functions are provided at a few different levels in Task. Below, we list all the functions available for use in Task.

note

Functions marked with an asterisk (*) also have must variants that will panic rather than erroring.

Built-in Functions​

The first set of functions are provided by Golang itself:

FunctionDescription
andReturns the boolean AND of its arguments by returning the first empty argument or the last argument. That is, and x y behaves as if x then y else x. Evaluation proceeds through the arguments left to right and returns when the result is determined.
callReturns the result of calling the first argument, which must be a function, with the remaining arguments as parameters. Thus call .X.Y 1 2 is, in Go notation, dot.X.Y(1, 2) where Y is a func-valued field, map entry, or the like. The first argument must be the result of an evaluation that yields a value of function type (as distinct from a predefined function such as print). The function must return either one or two result values, the second of which is of type error. If the arguments don't match the function or the returned error value is non-nil, execution stops.
htmlReturns the escaped HTML equivalent of the textual representation of its arguments. This function is unavailable in html/template, with a few exceptions.
indexReturns the result of indexing its first argument by the following arguments. Thus index x 1 2 3 is, in Go syntax, x[1][2][3]. Each indexed item must be a map, slice, or array.
sliceslice returns the result of slicing its first argument by the remaining arguments. Thus slice x 1 2 is, in Go syntax, x[1:2], while slice x is x[:], slice x 1 is x[1:], and slice x 1 2 3 is x[1:2:3]. The first argument must be a string, slice, or array.
jsReturns the escaped JavaScript equivalent of the textual representation of its arguments.
lenReturns the integer length of its argument.
notReturns the boolean negation of its single argument.
orReturns the boolean OR of its arguments by returning the first non-empty argument or the last argument, that is, or x y behaves as if x then x else y. Evaluation proceeds through the arguments left to right and returns when the result is determined.
printAn alias for fmt.Sprint.
printfAn alias for fmt.Sprintf.
printlnAn alias for fmt.Sprintln.
urlqueryReturns the escaped value of the textual representation of its arguments in a form suitable for embedding in a URL query. This function is unavailable in html/template, with a few exceptions.

Slim-Sprig Functions​

In addition to the built-in functions, Task also provides a set of functions imported via the slim-sprig package. We only provide a very basic description here for completeness. For detailed usage, please refer to the slim-sprig documentation:

String Functions​

FunctionDescription
trimRemoves space from either side of a string.
trimAllRemoves given characters from the front or back of a string.
trimSuffixTrims just the suffix from a string.
trimPrefixTrims just the prefix from a string.
upperConverts the entire string to uppercase.
lowerConverts the entire string to lowercase.
titleConverts to title case.
repeatRepeats a string multiple times.
substrGets a substring from a string.
truncTruncates a string.
containsTests to see if one string is contained inside of another.
hasPrefixTests whether a string has a given prefix.
hasSuffixTests whether a string has a given suffix.
quoteWraps a string in double quotes.
squoteWraps a string in single quotes.
catConcatenates multiple strings together into one, separating them with spaces.
indentIndents every line in a given string to the specified indent width.
nindentIdentical to indent, but prepends a new line to the beginning of the string.
replaceReplaces a string.
pluralPluralizes a string.
regexMatch*Returns true if the input string contains any match of the regular expression.
regexFindAll*Returns a slice of all matches of the regular expression in the input string.
regexFind*Returns the first (left most) match of the regular expression in the input string.
regexReplaceAll*Returns a copy of the input string, replacing matches of the Regexp with the replacement string replacement.
regexReplaceAllLiteral*Returns a copy of the input string, replacing matches of the Regexp with the replacement string replacement without expanding $.
regexSplit*Slices the input string into substrings separated by the expression and returns a slice of the substrings between those expression matches.
regexQuoteMeta*Returns a string that escapes all regular expression metacharacters inside the argument text.

String Slice Functions​

FunctionDescription
joinJoins a list of strings into a single string, with the given separator.
splitListSplits a string into a list of strings.
splitSplits a string into a map of strings where each key is an index.
splitnIdentical to split, but stops splitting after n values.
sortAlphaSorts a list of strings into alphabetical (lexicographical) order.

Integer Functions​

FunctionDescription
addSum a set of numbers.
add1Increments a number by 1.
subSubtracts one number from another.
divPerforms integer division.
modModulo.
mulMultiplies a set of numbers.
maxReturns the largest of a set of integers.
minReturns the smallest of a set of integers.
floorReturns the greatest float value less than or equal to input value
ceilReturns the greatest float value greater than or equal to input value
roundReturns a float value with the remainder rounded to the given number to digits after the decimal point.
randIntReturns a random integer value from min (inclusive) to max (exclusive).

Integer Slice Functions​

FunctionDescription
untilBuilds a range of integers.
untilStepBuilds a range of integers, but allows you to define a start, stop and step
seqWorks like the bash seq command.

Date Functions​

FunctionDescription
nowGets the current date/time.
agoReturns the duration since the given date/time.
dateFormats a date.
dateInZoneIdentical to date, but with the given timezone.
durationFormats the number of seconds into a string.
durationRoundIdentical to duration, but rounds the duration to the most significant unit.
unixEpochReturns the seconds since the unix epoch for the given date/time.
dateModify*Modifies a date using the given input string.
htmlDateFormats a date for inserting into an HTML date picker input field.
htmlDateInZoneIdentical to htmlDate, but with the given timezone.
toDate*Converts a string to a date/time.

Default Functions​

FunctionDescription
defaultUses a default value if the given value is considered "zero" or "empty".
emptyReturns true if a value is considered "zero" or "empty".
coalesceTakes a list of values and returns the first non-empty one.
allReturns true if all values are non-empty.
anyReturns true if any value is non-empty.
ternaryThe ternary function takes two values, and a test value. If the test value is true, the first value will be returned. If the test value is empty, the second value will be returned.

Encoding Functions​

FunctionDescription
fromJson*Decodes a JSON string into an object.
toJson*Encodes an object as a JSON string.
toPrettyJson*Encodes an object as a JSON string with new lines and indentation.
toRawJson*Encodes an object as a JSON string with HTML characters unescaped.
b64encEncodes a string into base 64.
b64decDecodes a string from base 64.
b32encEncodes a string into base 32.
b32decDecodes a string from base 32.

List Functions​

FunctionDescription
listCreates a list from a set of values.
first*Gets the first value in a list.
rest*Gets all values except the first value in the list.
last*Gets the last value in the list.
initial*Get all values except the last value in the list.
append*Adds a new value to the end of the list.
prepend*Adds a new value to the start of the list.
concatJoins two or more lists together.
reverse*Reverses the order of a list.
uniq*Generate a list with all of the duplicates removed.
without*Filters matching items out of a list.
has*Tests to see if a list has a particular element.
compact*Removes entries with empty values.
slice*Returns a partial copy of a list given start and end parameters.
chunkSplits a list into chunks of given size.

Dictionary Functions​

FunctionDescription
dictCreates a dictionary from a set of key/value pairs.
getGets the value from the dictionary with the given key.
setAdds a new key/value pair to a dictionary.
unsetDeletes a key from a dictionary.
hasKeyReturns true if a dictionary contains the given key.
pluckGets a list of all of the matching values in a set of maps given a key.
digReturns the value in a nested map given a path of keys.
merge*Merges two or more dictionaries into one.
mergeOverwrite*Identical to merge, but giving precedence from right to left.
keysReturns a list of all of the keys in a dictionary.
pickCreates a new dictionary containing only the given keys of an existing map.
omitCreates a new dictionary containing all the keys of an existing map except the ones given.
valuesReturns a list of all the values in a dictionary.

Type Conversion Functions​

FunctionDescription
atoiConverts a string to an integer.
float64Converts to a float64.
intConverts to an int at the system's width.
int64Converts to an int64.
toDecimalConverts a unix octal to a int64.
toStringConverts to a string.
toStringsConverts a list, slice, or array to a list of strings.
toStringsProduces a slice of strings from any list.
toDecimalGiven a unix octal permission, produce a decimal.

Path and Filepath Functions​

FunctionDescription
baseReturns the last element of a path.
dirReturns the directory of a path.
cleanCleans up a path.
extReturns the file extension of a path.
isAbsChecks if a path is absolute.
osBaseReturns the last element of a filepath.
osDirReturns the directory of a filepath.
osCleanCleans up a filepath.
osExtReturns the file extension of a filepath.
osIsAbsChecks if a filepath is absolute.

Flow Control Functions​

FunctionDescription
failUnconditionally returns an empty string and an error with the specified text.

OS Functions​

FunctionDescription
envReads an environment variable.
expandenvSubstitutes environment variables in a string

Reflection Functions​

FunctionDescription
kindOfReturns the kind of a value.
kindIsVerifies that a value is a particular kind.
typeOfReturns the underlying type of a value.
typeIsVerifies that a value is of a particular type.
typeIsLikeIdentical to typeIs, but also dereferences pointers.
deepEqualReturns true if two values are "deeply equal".

Cryptographic and Security Functions​

FunctionDescription
sha1sumComputes a string's SHA1 digest.
sha256sumComputes a string's SHA256 digest.
adler32sumComputes a string's Adler-32 checksum.

Task Functions​

Lastly, Task itself provides a few functions:

FunctionDescription
OSReturns the operating system. Possible values are windows, linux, darwin (macOS) and freebsd.
ARCHreturn the architecture Task was compiled to: 386, amd64, arm or s390x.
splitLinesSplits Unix (\n) and Windows (\r\n) styled newlines.
catLinesReplaces Unix (\n) and Windows (\r\n) styled newlines with a space.
toSlashDoes nothing on Unix, but on Windows converts a string from \ path format to /.
fromSlashOpposite of toSlash. Does nothing on Unix, but on Windows converts a string from / path format to \.
exeExtReturns the right executable extension for the current OS (".exe" for Windows, "" for others).
shellQuote(aliased to q): Quotes a string to make it safe for use in shell scripts. Task uses this Go function for this. The Bash dialect is assumed.
splitArgsSplits a string as if it were a command's arguments. Task uses this Go function.
joinPathJoins any number of arguments into a path. The same as Go's filepath.Join.
relPathConverts an absolute path (second argument) into a relative path, based on a base path (first argument). The same as Go's filepath.Rel.
mergeCreates a new map that is a copy of the first map with the keys of each subsequent map merged into it. If there is a duplicate key, the value of the last map with that key is used.
spewReturns the Go representation of a specific variable. Useful for debugging. Uses the davecgh/go-spew package.