Skip to content

Latest commit

 

History

History
1109 lines (838 loc) · 29.8 KB

azure-pipelines-task-lib.md

File metadata and controls

1109 lines (838 loc) · 29.8 KB

AZURE-PIPELINES-TASK-LIB TYPESCRIPT API

Dependencies

A cross platform agent OR a TFS 2015 Update 2 Windows agent (or higher) is required to run a Node task end-to-end. However, an agent is not required for interactively testing the task.

Importing

For now, the built azure-pipelines-task-lib (in _build) should be packaged with your task in a node_modules folder

The build generates a azure-pipelines-task-lib.d.ts file for use when compiling tasks In the example below, it is in a folder named definitions above the tasks lib

/// <reference path="../definitions/azure-pipelines-task-lib.d.ts" />
import tl = require('azure-pipelines-task-lib/task')

Index

Input Functions (v)

getInput
getBoolInput
getPathInput
filePathSupplied
getDelimitedInput
getVariable
VariableInfo
getVariables
setVariable
getTaskVariable
setTaskVariable

Execution (v)

tool
ToolRunner.arg
ToolRunner.line
ToolRunner.argIf
IExecOptions
ToolRunner.exec
ToolRunner.execSync
ToolRunner.pipeExecOutputToTool
IExecSyncResult
exec
execSync
setResult

Service Connections (v)

getEndpointUrl
getEndpointDataParameter
getEndpointAuthorizationScheme
getEndpointAuthorizationParameter
EndpointAuthorization
getEndpointAuthorization

Secrets (v)

setSecret

Secure Files (v)

getSecureFileName
getSecureFileTicket

Disk Functions (v)

which
checkPath
exist
cd
cp
mv
mkdirP
FindOptions
find
rmRF
pushd
popd
resolve
stats
writeFile

Globbing (v)

MatchOptions
match
findMatch
filter
legacyFindFiles

Localization (v)

setResourcePath
loc

Proxy (v)

getHttpProxyConfiguration


Input Functions


Functions for retrieving inputs for the task

task.getInput (^)

Gets the value of an input. The value is also trimmed. If required is true and the value is not set, it will throw.

@returns string

getInput(name:string, required?:boolean):string
Param Type Description
name string name of the input to get
required boolean whether input is required. optional, defaults to false

task.getBoolInput (^)

Gets the value of an input and converts to a bool. Convenience. If required is true and the value is not set, it will throw.

@returns string

getBoolInput(name:string, required?:boolean):boolean
Param Type Description
name string name of the bool input to get
required boolean whether input is required. optional, defaults to false

task.getPathInput (^)

Gets the value of a path input It will be quoted for you if it isn't already and contains spaces If required is true and the value is not set, it will throw. If check is true and the path does not exist, it will throw.

@returns string

getPathInput(name:string, required?:boolean, check?:boolean):string
Param Type Description
name string name of the input to get
required boolean whether input is required. optional, defaults to false
check boolean whether path is checked. optional, defaults to false

task.filePathSupplied (^)

Checks whether a path inputs value was supplied by the user File paths are relative with a picker, so an empty path is the root of the repo. Useful if you need to condition work (like append an arg) if a value was supplied

@returns boolean

filePathSupplied(name:string):boolean
Param Type Description
name string name of the path input to check

task.getDelimitedInput (^)

Gets the value of an input and splits the value using a delimiter (space, comma, etc). Empty values are removed. This function is useful for splitting an input containing a simple list of items - such as build targets. IMPORTANT: Do not use this function for splitting additional args! Instead use argString(), which follows normal argument splitting rules and handles values encapsulated by quotes. If required is true and the value is not set, it will throw.

@returns string[]

getDelimitedInput(name:string, delim:string, required?:boolean):string[]
Param Type Description
name string name of the input to get
delim string delimiter to split on
required boolean whether input is required. optional, defaults to false

task.getVariable (^)

Gets a variable value that is defined on the build/release definition or set at runtime.

@returns string

getVariable(name:string):string
Param Type Description
name string name of the variable to get

task.VariableInfo (^)

Snapshot of a variable at the time when getVariables was called.

Property Type Description
name string
value string
secret boolean

task.getVariables (^)

Gets a snapshot of the current state of all job variables available to the task. Requires a 2.104.1 agent or higher for full functionality.

Limitations on an agent prior to 2.104.1:

  1. The return value does not include all public variables. Only public variables that have been added using setVariable are returned.
  2. The name returned for each secret variable is the formatted environment variable name, not the actual variable name (unless it was set explicitly at runtime using setVariable).

@returns VariableInfo[]

getVariables():VariableInfo[]

task.setVariable (^)

Sets a variable which will be available to subsequent tasks as well.

@returns void

setVariable(name:string, val:string, secret?:boolean):void
Param Type Description
name string name of the variable to set
val string value to set
secret boolean whether variable is secret. Multi-line secrets are not allowed. Optional, defaults to false

task.getTaskVariable (^)

Gets a variable value that is set by previous step from the same wrapper task. Requires a 2.115.0 agent or higher.

@returns string

getTaskVariable(name:string):string
Param Type Description
name string name of the variable to get

task.setTaskVariable (^)

Sets a task variable which will only be available to subsequent steps belong to the same wrapper task. Requires a 2.115.0 agent or higher.

@returns void

setTaskVariable(name:string, val:string, secret?:boolean):void
Param Type Description
name string name of the variable to set
val string value to set
secret boolean whether variable is secret. optional, defaults to false

Execution


Tasks typically execute a series of tools (cli) and set the result of the task based on the outcome of those

/// <reference path="../definitions/azure-pipelines-task-lib.d.ts" />
import tl = require('azure-pipelines-task-lib/task');
import tr = require('azure-pipelines-task-lib/toolrunner');

try {
    var toolPath = tl.which('atool');
    var atool:tr.ToolRunner = tl.tool(toolPath).arg('--afile').line('arguments');
    var code: number = await atool.exec();
    console.log('rc=' + code);
}
catch (err) {
    tl.setResult(tl.TaskResult.Failed, err.message);
}

task.tool (^)

Convenience factory to create a ToolRunner.

@returns ToolRunner

tool(tool:string):ToolRunner
Param Type Description
tool string path to tool to exec

toolrunner.ToolRunner.arg (^)

Add argument Append an argument or an array of arguments returns ToolRunner for chaining

@returns ToolRunner

arg(val:string | string[]):ToolRunner
Param Type Description
val string | string[] string cmdline or array of strings

toolrunner.ToolRunner.line (^)

Parses an argument line into one or more arguments e.g. .line('"arg one" two -z') is equivalent to .arg(['arg one', 'two', '-z']) returns ToolRunner for chaining

@returns ToolRunner

line(val:string):ToolRunner
Param Type Description
val string string argument line

toolrunner.ToolRunner.argIf (^)

Add argument(s) if a condition is met Wraps arg(). See arg for details returns ToolRunner for chaining

@returns ToolRunner

argIf(condition:any, val:any):this
Param Type Description
condition any boolean condition
val any string cmdline or array of strings

toolrunner.IExecOptions (^)

Interface for exec options

Property Type Description
failOnStdErr boolean optional. whether to fail if output to stderr. defaults to false
ignoreReturnCode boolean optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller

toolrunner.ToolRunner.exec (^)

Exec a tool. Output will be streamed to the live console. Returns promise with return code

@returns number

exec(options?:IExecOptions):any
Param Type Description
options IExecOptions optional exec options. See IExecOptions

toolrunner.ToolRunner.execSync (^)

Exec a tool synchronously. Output will be not be streamed to the live console. It will be returned after execution is complete. Appropriate for short running tools Returns IExecSyncResult with output and return code

@returns IExecSyncResult

execSync(options?:IExecSyncOptions):IExecSyncResult
Param Type Description
options IExecSyncOptions optional exec options. See IExecSyncOptions

toolrunner.ToolRunner.pipeExecOutputToTool (^)

Pipe output of exec() to another tool @returns {ToolRunner}

pipeExecOutputToTool(tool:ToolRunner, file?:string):ToolRunner
Param Type Description
tool ToolRunner
file string optional filename to additionally stream the output to.

toolrunner.IExecSyncResult (^)

Interface for exec results returned from synchronous exec functions

Property Type Description
stdout string standard output
stderr string error output
code number return code
error Error Error on failure

task.exec (^)

Exec a tool. Convenience wrapper over ToolRunner to exec with args in one call. Output will be streamed to the live console. Returns promise with return code

@returns number

exec(tool:string, args:any, options?:IExecOptions):any
Param Type Description
tool string path to tool to exec
args any an arg string or array of args
options IExecOptions optional exec options. See IExecOptions

task.execSync (^)

Exec a tool synchronously. Convenience wrapper over ToolRunner to execSync with args in one call. Output will be not be streamed to the live console. It will be returned after execution is complete. Appropriate for short running tools Returns IExecResult with output and return code

@returns IExecSyncResult

execSync(tool:string, args:string | string[], options?:IExecSyncOptions):IExecSyncResult
Param Type Description
tool string path to tool to exec
args string | string[] an arg string or array of args
options IExecSyncOptions optional exec options. See IExecSyncOptions

task.setResult (^)

Sets the result of the task. Execution will continue. If not set, task will be Succeeded. If multiple calls are made to setResult the most pessimistic call wins (Failed) regardless of the order of calls.

@returns void

setResult(result:TaskResult, message:string):void
Param Type Description
result TaskResult TaskResult enum of Succeeded, SucceededWithIssues or Failed.
message string A message which will be logged as an error issue if the result is Failed.

Service Connections


Retrieve service connections (previously called "service endpoints") and authorization details

task.getEndpointUrl (^)

Gets the url for a service endpoint If the url was not set and is not optional, it will throw.

@returns string

getEndpointUrl(id:string, optional:boolean):string
Param Type Description
id string name of the service endpoint
optional boolean whether the url is optional

task.getEndpointDataParameter (^)

getEndpointDataParameter(id:string, key:string, optional:boolean):string
Param Type Description
id string
key string
optional boolean

task.getEndpointAuthorizationScheme (^)

Gets the endpoint authorization scheme for a service endpoint If the endpoint authorization scheme is not set and is not optional, it will throw.

@returns {string} value of the endpoint authorization scheme

getEndpointAuthorizationScheme(id:string, optional:boolean):string
Param Type Description
id string name of the service endpoint
optional boolean whether the endpoint authorization scheme is optional

task.getEndpointAuthorizationParameter (^)

Gets the endpoint authorization parameter value for a service endpoint with specified key If the endpoint authorization parameter is not set and is not optional, it will throw.

@returns {string} value of the endpoint authorization parameter value

getEndpointAuthorizationParameter(id:string, key:string, optional:boolean):string
Param Type Description
id string name of the service endpoint
key string key to find the endpoint authorization parameter
optional boolean optional whether the endpoint authorization scheme is optional

task.EndpointAuthorization (^)

Interface for EndpointAuthorization Contains a schema and a string/string dictionary of auth data

Property Type Description
parameters { [key: string]: string; } dictionary of auth data
scheme string auth scheme such as OAuth or username/password etc...

task.getEndpointAuthorization (^)

Gets the authorization details for a service endpoint If the authorization was not set and is not optional, it will throw.

@returns string

getEndpointAuthorization(id:string, optional:boolean):EndpointAuthorization
Param Type Description
id string name of the service endpoint
optional boolean whether the url is optional

Secrets


Functions for managing pipeline secrets

task.setSecret (^)

Registers a value with the logger, so the value will be masked from the logs. Multi-line secrets are not allowed.

setSecret(val:string):void
Param Type Description
val string value to register

Secure Files


Retrieve secure files details required to download the file

task.getSecureFileName (^)

Gets the name for a secure file

@returns string

getSecureFileName(id:string):string
Param Type Description
id string secure file id

task.getSecureFileTicket (^)

Gets the secure file ticket that can be used to download the secure file contents

@returns {string} secure file ticket

getSecureFileTicket(id:string):string
Param Type Description
id string name of the secure file

Disk Functions


Functions for disk operations

task.which (^)

Returns path of a tool had the tool actually been invoked. Resolves via paths. If you check and the tool does not exist, it will throw.

@returns string

which(tool:string, check?:boolean):string
Param Type Description
tool string name of the tool
check boolean whether to check if tool exists

task.checkPath (^)

Checks whether a path exists. If the path does not exist, it will throw.

@returns void

checkPath(p:string, name:string):void
Param Type Description
p string path to check
name string name only used in error message to identify the path

task.exist (^)

Returns whether a path exists.

@returns boolean

exist(path:string):boolean
Param Type Description
path string path to check

task.cd (^)

Change working directory.

@returns void

cd(path:string):void
Param Type Description
path string new working directory path

task.cp (^)

Copies a file or folder.

cp(source:string, dest:string, options?:string, continueOnError?:boolean):void
Param Type Description
source string source path
dest string destination path
options string string -r, -f or -rf for recursive and force
continueOnError boolean optional. whether to continue on error

task.mv (^)

Moves a path.

mv(source:string, dest:string, options?:string, continueOnError?:boolean):void
Param Type Description
source string source path
dest string destination path
options string string -f or -n for force and no clobber
continueOnError boolean optional. whether to continue on error

task.mkdirP (^)

Make a directory. Creates the full path with folders in between Will throw if it fails

@returns void

mkdirP(p:string):void
Param Type Description
p string path to create

task.FindOptions (^)

Interface for FindOptions Contains properties to control whether to follow symlinks

Property Type Description
allowBrokenSymbolicLinks boolean When true, broken symbolic link will not cause an error.
followSpecifiedSymbolicLink boolean Equivalent to the -H command line option. Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
followSymbolicLinks boolean Equivalent to the -L command line option. Indicates whether to traverse descendants of symbolic link directories.

task.find (^)

Recursively finds all paths a given path. Returns an array of paths.

@returns string[]

find(findPath:string, options?:FindOptions):string[]
Param Type Description
findPath string path to search
options FindOptions optional. defaults to { followSymbolicLinks: true }. following soft links is generally appropriate unless deleting files.

task.rmRF (^)

Remove a path recursively with force Returns whether it succeeds

@returns void

rmRF(path:string):void
Param Type Description
path string path to remove

task.pushd (^)

Change working directory and push it on the stack

@returns void

pushd(path:string):void
Param Type Description
path string new working directory path

task.popd (^)

Change working directory back to previously pushed directory

@returns void

popd():void

task.resolve (^)

Resolves a sequence of paths or path segments into an absolute path. Calls node.js path.resolve() Allows L0 testing with consistent path formats on Mac/Linux and Windows in the mock implementation @returns {string}

resolve(pathSegments:any[]):string
Param Type Description
pathSegments any[]

task.stats (^)

Get's stat on a path. Useful for checking whether a file or directory. Also getting created, modified and accessed time. see fs.stat

@returns fsStat

stats(path:string):FsStats
Param Type Description
path string path to check

task.writeFile (^)

writeFile(file:string, data:any, options?:string | FsOptions):void
Param Type Description
file string
data any
options string | FsOptions

Globbing


Functions for matching file paths

task.MatchOptions (^)

Property Type Description
debug boolean
nobrace boolean
noglobstar boolean
dot boolean
noext boolean
nocase boolean
nonull boolean
matchBase boolean
nocomment boolean
nonegate boolean
flipNegate boolean

task.match (^)

Applies glob patterns to a list of paths. Supports interleaved exclude patterns.

match(list:string[], patterns:string[] | string, patternRoot?:string, options?:MatchOptions):string[]
Param Type Description
list string[] array of paths
patterns string[] | string patterns to apply. supports interleaved exclude patterns.
patternRoot string optional. default root to apply to unrooted patterns. not applied to basename-only patterns when matchBase:true.
options MatchOptions optional. defaults to { dot: true, nobrace: true, nocase: process.platform == 'win32' }.

task.findMatch (^)

Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.

findMatch(defaultRoot:string, patterns:string[] | string, findOptions?:FindOptions, matchOptions?:MatchOptions):string[]
Param Type Description
defaultRoot string default path to root unrooted patterns. falls back to System.DefaultWorkingDirectory or process.cwd().
patterns string[] | string pattern or array of patterns to apply
findOptions FindOptions defaults to { followSymbolicLinks: true }. following soft links is generally appropriate unless deleting files.
matchOptions MatchOptions defaults to { dot: true, nobrace: true, nocase: process.platform == 'win32' }

task.filter (^)

Filter to apply glob patterns

filter(pattern:string, options?:MatchOptions):(element: string, indexed: number, array: string[]) => boolean
Param Type Description
pattern string pattern to apply
options MatchOptions optional. defaults to { dot: true, nobrace: true, nocase: process.platform == 'win32' }.

task.legacyFindFiles (^)

Prefer tl.find() and tl.match() instead. This function is for backward compatibility when porting tasks to Node from the PowerShell or PowerShell3 execution handler.

@returns string[]

legacyFindFiles(rootDirectory:string, pattern:string, includeFiles?:boolean, includeDirectories?:boolean):string[]
Param Type Description
rootDirectory string path to root unrooted patterns with
pattern string include and exclude patterns
includeFiles boolean whether to include files in the result. defaults to true when includeFiles and includeDirectories are both false
includeDirectories boolean whether to include directories in the result

Localization


Localization is optional but is supported using these functions at runtime

/// <reference path="../definitions/azure-pipelines-task-lib.d.ts" />

tl.setResourcePath(path.join( __dirname, 'task.json'));

...

var errMsg = tl.loc('FailedWithReturnCode', code));

// in the task.json
{
    "messages": {
        "FailedWithReturnCode": "Tool exited with return code: %d",
        "ToolFailed": "Tool failed with error: %s"
    }
}

task.setResourcePath (^)

Sets the location of the resources json. This is typically the task.json file. Call once at the beginning of the script before any calls to loc.

@returns void

setResourcePath(path:string):void
Param Type Description
path string Full path to the json.

task.loc (^)

Gets the localized string from the json resource file. Optionally formats with additional params.

@returns string

loc(key:string, param:any[]):string
Param Type Description
key string key of the resources string in the resource file
param any[] additional params for formatting the string

Proxy


Funtions for web proxy settings

task.getHttpProxyConfiguration (^)

Gets http proxy configuration used by Build/Release agent

@return ProxyConfiguration

getHttpProxyConfiguration(requestUrl?:string):ProxyConfiguration
Param Type Description
requestUrl string