本文整理汇总了TypeScript中vsts-task-lib/task.getInput函数的典型用法代码示例。如果您正苦于以下问题:TypeScript getInput函数的具体用法?TypeScript getInput怎么用?TypeScript getInput使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getInput函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: run
export function run(connection: ContainerConnection): any {
var command = connection.createCommand();
command.arg("build");
var dockerfilepath = tl.getInput("dockerFile", true);
var dockerFile = findDockerFile(dockerfilepath);
if(!tl.exist(dockerFile)) {
throw new Error(tl.loc('ContainerDockerFileNotFound', dockerfilepath));
}
command.arg(["-f", dockerFile]);
var addDefaultLabels = tl.getBoolInput("addDefaultLabels");
if (addDefaultLabels) {
var hostName = getReverseDNSName();
if (hostName) {
addCommonLabels(command, hostName);
var hostType = tl.getVariable("SYSTEM_HOSTTYPE");
if (hostType.toLowerCase() === "build") {
addBuildLabels(command, hostName);
}
else {
addReleaseLabels(command, hostName);
}
}
}
var commandArguments = tl.getInput("arguments", false);
command.line(commandArguments);
var imageName = utils.getImageName();
var qualifyImageName = tl.getBoolInput("qualifyImageName");
if (qualifyImageName) {
imageName = connection.qualifyImageName(imageName);
}
command.arg(["-t", imageName]);
var baseImageName = imageUtils.imageNameWithoutTag(imageName);
var includeSourceTags = tl.getBoolInput("includeSourceTags");
if (includeSourceTags) {
sourceUtils.getSourceTags().forEach(tag => {
command.arg(["-t", baseImageName + ":" + tag]);
});
}
var includeLatestTag = tl.getBoolInput("includeLatestTag");
if (baseImageName !== imageName && includeLatestTag) {
command.arg(["-t", baseImageName]);
}
var memoryLimit = tl.getInput("memoryLimit");
if (memoryLimit) {
command.arg(["-m", memoryLimit]);
}
var context: string;
var useDefaultContext = tl.getBoolInput("useDefaultContext");
if (useDefaultContext) {
context = path.dirname(dockerFile);
} else {
context = tl.getPathInput("buildContext");
}
command.arg(context);
return connection.execCommand(command);
}
示例2: main
async function main(): Promise<void> {
let buildIdentityDisplayName: string = null;
let buildIdentityAccount: string = null;
try {
tl.setResourcePath(path.join(__dirname, "task.json"));
// set the console code page to "UTF-8"
if (process.platform === "win32") {
tl.execSync(path.resolve(process.env.windir, "system32", "chcp.com"), ["65001"]);
}
// read inputs
let searchPattern = tl.getPathInput("searchPattern", true, false);
let filesList = nutil.resolveFilterSpec(
searchPattern,
tl.getVariable("System.DefaultWorkingDirectory") || process.cwd());
filesList.forEach(packageFile => {
if (!tl.stats(packageFile).isFile()) {
throw new Error(tl.loc("NotARegularFile", packageFile));
}
});
let connectedServiceName = tl.getInput("connectedServiceName");
let internalFeedUri = tl.getInput("feedName");
let nuGetAdditionalArgs = tl.getInput("nuGetAdditionalArgs");
let verbosity = tl.getInput("verbosity");
let nuGetFeedType = tl.getInput("nuGetFeedType") || "external";
// make sure the feed type is an expected one
let normalizedNuGetFeedType
= ["internal", "external"].find(x => nuGetFeedType.toUpperCase() === x.toUpperCase());
if (!normalizedNuGetFeedType) {
throw new Error(tl.loc("UnknownFeedType", nuGetFeedType));
}
nuGetFeedType = normalizedNuGetFeedType;
// due to a bug where we accidentally allowed nuGetPath to be surrounded by quotes before,
// locateNuGetExe() will strip them and check for existence there.
let userNuGetPath = tl.getPathInput("nuGetPath", false, false);
if (!tl.filePathSupplied("nuGetPath")) {
userNuGetPath = null;
}
let serviceUri = tl.getEndpointUrl("SYSTEMVSSCONNECTION", false);
// find nuget location to use
let nuGetPathToUse = ngToolRunner.locateNuGetExe(userNuGetPath);
let credProviderPath = ngToolRunner.locateCredentialProvider();
const quirks = await ngToolRunner.getNuGetQuirksAsync(nuGetPathToUse);
// clauses ordered in this way to avoid short-circuit evaluation, so the debug info printed by the functions
// is unconditionally displayed
const useCredProvider = ngToolRunner.isCredentialProviderEnabled(quirks) && credProviderPath;
const useCredConfig = ngToolRunner.isCredentialConfigEnabled(quirks) && !useCredProvider;
let accessToken = auth.getSystemAccessToken();
let urlPrefixes = await locationHelpers.assumeNuGetUriPrefixes(serviceUri);
tl.debug(`discovered URL prefixes: ${urlPrefixes}`);
// Note to readers: This variable will be going away once we have a fix for the location service for
// customers behind proxies
let testPrefixes = tl.getVariable("NuGetTasks.ExtraUrlPrefixesForTesting");
if (testPrefixes) {
urlPrefixes = urlPrefixes.concat(testPrefixes.split(";"));
tl.debug(`all URL prefixes: ${urlPrefixes}`);
}
const authInfo = new auth.NuGetAuthInfo(urlPrefixes, accessToken);
let environmentSettings: ngToolRunner.NuGetEnvironmentSettings = {
authInfo: authInfo,
credProviderFolder: useCredProvider ? path.dirname(credProviderPath) : null,
extensionsDisabled: !userNuGetPath,
};
let configFile = null;
let apiKey: string;
let feedUri: string;
let credCleanup = () => { return; };
if (nuGetFeedType === "internal") {
if (useCredConfig) {
let nuGetConfigHelper = new NuGetConfigHelper(nuGetPathToUse, null, authInfo, environmentSettings);
nuGetConfigHelper.setSources([{ feedName: "internalFeed", feedUri: internalFeedUri }]);
configFile = nuGetConfigHelper.tempNugetConfigPath;
credCleanup = () => tl.rmRF(nuGetConfigHelper.tempNugetConfigPath, true);
}
apiKey = "VSTS";
feedUri = internalFeedUri;
}
else {
feedUri = tl.getEndpointUrl(connectedServiceName, false);
let externalAuth = tl.getEndpointAuthorization(connectedServiceName, false);
apiKey = externalAuth.parameters["password"];
}
try {
let publishOptions = new PublishOptions(
nuGetPathToUse,
//.........这里部分代码省略.........
示例3: run
export function run(connection: DockerComposeConnection): any {
var command = connection.createComposeCommand();
command.line(tl.getInput("dockerComposeCommand", true));
return connection.execCommand(command);
}
示例4: require
"use strict";
import * as path from "path";
import * as tl from "vsts-task-lib/task";
import * as DockerComposeUtils from "./dockercomposeutils";
import AuthenticationTokenProvider from "docker-common/registryauthenticationprovider/authenticationtokenprovider"
import ACRAuthenticationTokenProvider from "docker-common/registryauthenticationprovider/acrauthenticationtokenprovider"
import DockerComposeConnection from "./dockercomposeconnection";
import GenericAuthenticationTokenProvider from "docker-common/registryauthenticationprovider/genericauthenticationtokenprovider"
import Q = require('q');
// Change to any specified working directory
tl.cd(tl.getInput("cwd"));
// get the registry server authentication provider
var registryType = tl.getInput("containerregistrytype", true);
var authenticationProvider: AuthenticationTokenProvider;
if (registryType == "Azure Container Registry") {
authenticationProvider = new ACRAuthenticationTokenProvider(tl.getInput("azureSubscriptionEndpoint"), tl.getInput("azureContainerRegistry"));
}
else {
authenticationProvider = new GenericAuthenticationTokenProvider(tl.getInput("dockerRegistryEndpoint"));
}
var registryAuthenticationToken = authenticationProvider.getAuthenticationToken();
var dockerComposeFile = tl.getInput("dockerComposeFile", true);
var nopIfNoDockerComposeFile = tl.getBoolInput("nopIfNoDockerComposeFile");
示例5: getKubeConfig
// get kubeconfig file path
private async getKubeConfig(): Promise<string> {
var connectionType = tl.getInput("connectionType", true);
return this.loadClusterType(connectionType).getKubeConfig().then((config) => {
return config;
});
}
示例6: main
async function main(): Promise<void> {
tl.setResourcePath(path.join(__dirname, 'task.json'));
let saveNpmrcPath: string;
let npmrc = tl.getInput(constants.NpmAuthenticateTaskInput.WorkingFile);
let workingDirectory = path.dirname(npmrc);
if (!(npmrc.endsWith('.npmrc'))) {
throw new Error(tl.loc('NpmrcNotNpmrc', npmrc));
}
else if (!tl.exist(npmrc)) {
throw new Error(tl.loc('NpmrcDoesNotExist', npmrc));
}
else {
console.log(tl.loc("AuthenticatingThisNpmrc", npmrc));
}
if (tl.getVariable("SAVE_NPMRC_PATH")) {
saveNpmrcPath = tl.getVariable("SAVE_NPMRC_PATH");
}
else {
let tempPath = tl.getVariable('Agent.BuildDirectory') || tl.getVariable('Agent.ReleaseDirectory') || process.cwd();
tempPath = path.join(tempPath, 'npmAuthenticate');
tl.mkdirP(tempPath);
saveNpmrcPath = fs.mkdtempSync(tempPath + path.sep);
tl.setVariable("SAVE_NPMRC_PATH", saveNpmrcPath, false);
tl.setVariable("NPM_AUTHENTICATE_TEMP_DIRECTORY", tempPath, false);
}
let npmrcTable: Object;
//The index file is a json object that keeps track of where .npmrc files are saved.
//There is a key-value pairing of filepaths of original npmrc files to IDs.
//This is important so multiple runs of the npm Authenticate task on the same .npmrc file actually reverts to the original after the build completes.
let indexFile = path.join(saveNpmrcPath, 'index.json');
if (fs.existsSync(indexFile)) { //If the file exists, add to it.
npmrcTable = JSON.parse(fs.readFileSync(indexFile, 'utf8'));
}
else { //If the file doesn't exist, create it.
npmrcTable = new Object();
npmrcTable['index'] = 0;
}
if (npmrcTable[npmrc] === undefined) {
npmrcTable[npmrc] = npmrcTable['index'];
npmrcTable['index']++;
fs.writeFileSync(indexFile, JSON.stringify(npmrcTable));
util.saveFileWithName(npmrc, npmrcTable[npmrc], saveNpmrcPath);
}
let endpointRegistries: npmregistry.INpmRegistry[] = [];
let endpointIds = tl.getDelimitedInput(constants.NpmAuthenticateTaskInput.CustomEndpoint, ',');
if (endpointIds && endpointIds.length > 0) {
await Promise.all(endpointIds.map(async e => {
endpointRegistries.push(await npmregistry.NpmRegistry.FromServiceEndpoint(e, true));
}));
}
let packagingLocation: pkgLocationUtils.PackagingLocation;
try {
packagingLocation = await pkgLocationUtils.getPackagingUris(pkgLocationUtils.ProtocolType.Npm);
} catch (error) {
tl.debug('Unable to get packaging URIs, using default collection URI');
tl.debug(JSON.stringify(error));
const collectionUrl = tl.getVariable('System.TeamFoundationCollectionUri');
packagingLocation = {
PackagingUris: [collectionUrl],
DefaultPackagingUri: collectionUrl
};
}
let LocalNpmRegistries = await npmutil.getLocalNpmRegistries(workingDirectory, packagingLocation.PackagingUris);
let npmrcFile = fs.readFileSync(npmrc, 'utf8').split(os.EOL);
for (let RegistryURLString of npmrcparser.GetRegistries(npmrc)) {
let registryURL = URL.parse(RegistryURLString);
let registry: npmregistry.NpmRegistry;
if (endpointRegistries && endpointRegistries.length > 0) {
for (let serviceEndpoint of endpointRegistries) {
if (util.toNerfDart(serviceEndpoint.url) == util.toNerfDart(RegistryURLString)) {
let serviceURL = URL.parse(serviceEndpoint.url);
console.log(tl.loc("AddingEndpointCredentials", registryURL.host));
registry = serviceEndpoint;
npmrcFile = clearFileOfReferences(npmrc, npmrcFile, serviceURL);
break;
}
}
}
if (!registry) {
for (let localRegistry of LocalNpmRegistries) {
if (util.toNerfDart(localRegistry.url) == util.toNerfDart(RegistryURLString)) {
let localURL = URL.parse(localRegistry.url);
console.log(tl.loc("AddingLocalCredentials"));
registry = localRegistry;
npmrcFile = clearFileOfReferences(npmrc, npmrcFile, localURL);
break;
}
}
}
if (registry) {
tl.debug(tl.loc('AddingAuthRegistry', registry.url));
//.........这里部分代码省略.........
示例7: doWork
async function doWork() {
function execEnableCodeCoverage(): Q.Promise<string> {
return enableCodeCoverage()
.then(function (resp) {
tl.debug("Enabled code coverage successfully");
return "CodeCoverage_9064e1d0";
}).catch(function (err) {
tl.warning("Failed to enable code coverage: " + err);
return "";
});
};
function enableCodeCoverage(): Q.Promise<any> {
if (!isCodeCoverageOpted) {
return Q.resolve(true);
}
const classFilter: string = tl.getInput('classFilter');
const classFilesDirectories: string = tl.getInput('classFilesDirectories', true);
const sourceDirectories: string = tl.getInput('srcDirectories');
// appending with small guid to keep it unique. Avoiding full guid to ensure no long path issues.
const reportDirectoryName = "CCReport43F6D5EF";
reportDirectory = path.join(buildRootPath, reportDirectoryName);
const reportBuildFileName = "CCReportBuildA4D283EG.xml";
reportBuildFile = path.join(buildRootPath, reportBuildFileName);
let summaryFileName = "";
if (ccTool.toLowerCase() == "jacoco") {
summaryFileName = "summary.xml";
}else if (ccTool.toLowerCase() == "cobertura") {
summaryFileName = "coverage.xml";
}
summaryFile = path.join(buildRootPath, reportDirectoryName, summaryFileName);
const coberturaCCFile = path.join(buildRootPath, "cobertura.ser");
let instrumentedClassesDirectory = path.join(buildRootPath, "InstrumentedClasses");
// clean any previous reports.
try {
tl.rmRF(coberturaCCFile);
tl.rmRF(reportDirectory);
tl.rmRF(reportBuildFile);
tl.rmRF(instrumentedClassesDirectory);
} catch (err) {
tl.debug("Error removing previous cc files: " + err);
}
let buildProps: { [key: string]: string } = {};
buildProps['buildfile'] = antBuildFile;
buildProps['classfilter'] = classFilter
buildProps['classfilesdirectories'] = classFilesDirectories;
buildProps['sourcedirectories'] = sourceDirectories;
buildProps['summaryfile'] = summaryFileName;
buildProps['reportdirectory'] = reportDirectory;
buildProps['ccreporttask'] = "CodeCoverage_9064e1d0"
buildProps['reportbuildfile'] = reportBuildFile;
let ccEnabler = new CodeCoverageEnablerFactory().getTool("ant", ccTool.toLowerCase());
return ccEnabler.enableCodeCoverage(buildProps);
}
async function publishCodeCoverage(codeCoverageOpted: boolean, ccReportTask: string) {
tl.debug("publishCodeCoverage f=" + failIfCodeCoverageEmpty + " opt=" + codeCoverageOpted + " task=" + ccReportTask);
if (failIfCodeCoverageEmpty && codeCoverageOpted && !ccReportTask) {
throw tl.loc('NoCodeCoverage');
}
else if (codeCoverageOpted && ccReportTask) {
tl.debug("Collecting code coverage reports");
var antRunner = tl.tool(anttool);
antRunner.arg('-buildfile');
if (pathExistsAsFile(reportBuildFile)) {
antRunner.arg(reportBuildFile);
antRunner.arg(ccReportTask);
}
else {
antRunner.arg(antBuildFile);
antRunner.arg(ccReportTask);
}
antRunner.exec().then(async function (code) {
if (failIfCodeCoverageEmpty && await ccUtils.isCodeCoverageFileEmpty(summaryFile, ccTool)) {
throw tl.loc('NoCodeCoverage');
}
if (pathExistsAsFile(summaryFile)) {
tl.debug("Summary file = " + summaryFile);
tl.debug("Report directory = " + reportDirectory);
tl.debug("Publishing code coverage results to TFS");
let ccPublisher = new tl.CodeCoveragePublisher();
ccPublisher.publish(ccTool, summaryFile, reportDirectory, "");
}
else {
tl.warning("No code coverage results found to be published. This could occur if there were no tests executed or there was a build failure. Check the ant output for details.");
}
}).fail(function (err) {
tl.warning("No code coverage results found to be published. This could occur if there were no tests executed or there was a build failure. Check the ant output for details.");
});
}
}
try {
var anttool = tl.which('ant', true);
var antv = tl.tool(anttool);
//.........这里部分代码省略.........
示例8: require
"use strict";
import path = require('path');
import * as tl from "vsts-task-lib/task";
import RegistryAuthenticationToken from "docker-common/registryauthenticationprovider/registryauthenticationtoken";
import ContainerConnection from 'docker-common/containerconnection';
import { getDockerRegistryEndpointAuthenticationToken } from "docker-common/registryauthenticationprovider/registryauthenticationtoken";
tl.setResourcePath(path.join(__dirname, 'task.json'));
let endpointId = tl.getInput("containerRegistry");
let registryAuthenticationToken: RegistryAuthenticationToken = getDockerRegistryEndpointAuthenticationToken(endpointId);
// Take the specified command
let command = tl.getInput("command", true).toLowerCase();
let isLogout = (command === "logout");
// Connect to any specified container registry
let connection = new ContainerConnection();
connection.open(null, registryAuthenticationToken, true, isLogout);
let dockerCommandMap = {
"buildandpush": "./dockerbuildandpush",
"build": "./dockerbuild",
"push": "./dockerpush",
"login": "./dockerlogin",
"logout": "./dockerlogout"
}
let telemetry = {
command: command,
示例9: GetCommits
private GetCommits(startBuildId: string, endBuildId: string): Q.Promise<string> {
let connection = tl.getInput("connection", true);
let definitionId = tl.getInput("definition", true);
var endpointUrl = tl.getEndpointUrl(connection, false);
let defer = Q.defer<string>();
let url: string = `${endpointUrl}/api/v1.1/project/${definitionId}/${startBuildId}`;
url = url.replace(/([^:]\/)\/+/g, "$1");
let commits = [];
this.executeWithRetries("getCommits", (url, headers) => { return this.webProvider.webClient.get(url, headers) }, url, { 'Accept': 'application/json' }).then((res: HttpClientResponse) => {
if (res && res.message.statusCode === 200) {
res.readBody().then((body: string) => {
let jsonResult = JSON.parse(body);
let branch;
if (!!jsonResult) {
branch = jsonResult.branch;
}
else {
defer.reject(tl.loc("BranchNotFound"));
return;
}
let buildsUrl = `${endpointUrl}/api/v1.1/project/${definitionId}/tree/${branch}`;
buildsUrl = buildsUrl.replace(/([^:]\/)\/+/g, "$1");
this.webProvider.webClient.get(buildsUrl, { 'Accept': 'application/json' }).then((res: HttpClientResponse) => {
res.readBody().then((body: string) => {
let builds = JSON.parse(body);
let commitsIdsMap = {};
if (!!builds) {
builds.forEach(build => {
if (Number(build.build_num) <= Number(endBuildId) && Number(build.build_num) >= Number(startBuildId) && build.all_commit_details[0]) {
build.all_commit_details.forEach(c => {
let commit = {
"Id": c.commit,
"Message": c.subject,
"Author": {
"displayName": c.author_name
},
"DisplayUri": c.commit_url,
"Timestamp": c.author_date
};
if (!commitsIdsMap[commit.Id]) {
commits.push(commit);
commitsIdsMap[commit.Id] = true;
}
});
}
});
}
tl.debug("Downloaded " + commits.length + " commits");
defer.resolve(JSON.stringify(commits));
}, (error) => {
defer.reject(error);
});
}, (error) => {
defer.reject(error);
});
});
}
});
return defer.promise;
}
示例10: catch
import * as tl from 'vsts-task-lib/task';
import * as models from './models';
import * as taskInputParser from './taskinputparser';
import * as localTest from './vstest';
import * as path from 'path';
import * as distributedTest from './distributedtest';
try {
tl.setResourcePath(path.join(__dirname, 'task.json'));
const parallelExecution = tl.getVariable('System.ParallelExecutionType');
tl.debug('Value of ParallelExecutionType :' + parallelExecution);
const testType = tl.getInput('testSelector');
tl.debug('Value of Test Selector :' + testType);
if ((parallelExecution && parallelExecution.toLowerCase() === 'multimachine')
|| testType.toLowerCase() === 'testplan' || testType.toLowerCase() === 'testrun') {
tl._writeLine(tl.loc('distributedTestWorkflow'));
tl._writeLine('======================================================');
const dtaTestConfig = taskInputParser.getDistributedTestConfigurations();
tl._writeLine('======================================================');
const test = new distributedTest.DistributedTest(dtaTestConfig);
test.runDistributedTest();
} else {
localTest.startTest();
}
} catch (error) {
tl.setResult(tl.TaskResult.Failed, error);
}