当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript task.getVariable函数代码示例

本文整理汇总了TypeScript中vsts-task-lib/task.getVariable函数的典型用法代码示例。如果您正苦于以下问题:TypeScript getVariable函数的具体用法?TypeScript getVariable怎么用?TypeScript getVariable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了getVariable函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: main

async function main(): Promise<void> {
    tl.setResourcePath(path.join(__dirname, "task.json"));

    let buildIdentityDisplayName: string = null;
    let buildIdentityAccount: string = null;
    
    let command: string = tl.getInput("command", true);
    let args: string = tl.getInput("arguments", false);

    // Getting NuGet
    tl.debug('Getting NuGet');
    let nuGetPath: string = undefined;
    try {
        nuGetPath = process.env[nuGetGetter.NUGET_EXE_TOOL_PATH_ENV_VAR];
        if (!nuGetPath){
            nuGetPath = await nuGetGetter.getNuGet("4.0.0");
        }
    }
    catch (error) {
        tl.setResult(tl.TaskResult.Failed, error.message);
        return;
    }

    const version = await peParser.getFileVersionInfoAsync(nuGetPath);
    if(version.productVersion.a < 3 || (version.productVersion.a <= 3 && version.productVersion.b < 5))
    {
        tl.setResult(tl.TaskResult.Failed, tl.loc("Info_NuGetSupportedAfter3_5", version.strings.ProductVersion));
        return;
    }

    try {
        nutil.setConsoleCodePage();

        let credProviderPath = nutil.locateCredentialProvider();

        // Clauses ordered in this way to avoid short-circuit evaluation, so the debug info printed by the functions
        // is unconditionally displayed
        const quirks = await ngToolRunner.getNuGetQuirksAsync(nuGetPath);
        const useCredProvider = ngToolRunner.isCredentialProviderEnabled(quirks) && credProviderPath;
        // useCredConfig not placed here: This task will only support NuGet versions >= 3.5.0 which support credProvider both hosted and OnPrem

        let accessToken = auth.getSystemAccessToken();
        let serviceUri = tl.getEndpointUrl("SYSTEMVSSCONNECTION", false);
        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: true
        };

        let executionOptions = new NuGetExecutionOptions(
            nuGetPath,
            environmentSettings,
            command,
            args);
            
        await runNuGetAsync(executionOptions);
    } catch (err) {
        tl.error(err);

        if (buildIdentityDisplayName || buildIdentityAccount) {
            tl.warning(tl.loc("BuildIdentityPermissionsHint", buildIdentityDisplayName, buildIdentityAccount));
        }

        tl.setResult(tl.TaskResult.Failed, "");
    }
}
开发者ID:DarqueWarrior,项目名称:vsts-tasks,代码行数:78,代码来源:nuget.ts

示例2: getBasicHandler

    var promise = new Promise<void>(async (resolve, reject) => {
        var connection = tl.getInput("connection", true);
        var projectId = tl.getInput("project", true);
        var definitionId = tl.getInput("definition", true);
        var buildId = tl.getInput("version", true);
        var itemPattern = tl.getInput("itemPattern", true);
        var downloadPath = tl.getInput("downloadPath", true);

        var endpointUrl = tl.getEndpointUrl(connection, false);
        var username = tl.getEndpointAuthorizationParameter(connection, 'username', true);
        var accessToken = tl.getEndpointAuthorizationParameter(connection, 'apitoken', true)
            || tl.getEndpointAuthorizationParameter(connection, 'password', true);
        var credentialHandler = getBasicHandler(username, accessToken);
        var vssConnection = new WebApi(endpointUrl, credentialHandler);
        var debugMode = tl.getVariable('System.Debug');
        var verbose = debugMode ? debugMode.toLowerCase() != 'false' : false;
        var parallelLimit: number = +tl.getVariable("release.artifact.download.parallellimit");

        var templatePath = path.join(__dirname, 'vsts.handlebars');
        var buildApi = vssConnection.getBuildApi();

        var artifacts = await executeWithRetries("getArtifacts", () => buildApi.getArtifacts(parseInt(buildId), projectId), 3).catch((reason) => {
            reject(reason);
        });

        if (artifacts) {
            var downloadPromises: Array<Promise<any>> = [];
            console.log("Linked artifacts count: " + artifacts.length);
            artifacts.forEach(async function (artifact, index, artifacts) {
                let downloaderOptions = new engine.ArtifactEngineOptions();
                downloaderOptions.itemPattern = itemPattern;
                downloaderOptions.verbose = verbose;

                if (parallelLimit) {
                    downloaderOptions.parallelProcessingLimit = parallelLimit;
                }

                if (artifact.resource.type.toLowerCase() === "container") {
                    let downloader = new engine.ArtifactEngine();
                    var containerParts: string[] = artifact.resource.data.split('/', 3);
                    if (containerParts.length !== 3) {
                        throw new Error(tl.loc("FileContainerInvalidArtifactData"));
                    }

                    var containerId: number = parseInt(containerParts[1]);
                    var containerPath: string = containerParts[2];

                    var itemsUrl = endpointUrl + "/_apis/resources/Containers/" + containerId + "?itemPath=" + encodeURIComponent(containerPath) + "&isShallow=true";
                    itemsUrl = itemsUrl.replace(/([^:]\/)\/+/g, "$1");
                    console.log(tl.loc("DownloadArtifacts", itemsUrl));

                    var variables = {};

                    var handler = username ? new webHandlers.BasicCredentialHandler(username, accessToken) : new webHandlers.PersonalAccessTokenCredentialHandler(accessToken);
                    var webProvider = new providers.WebProvider(itemsUrl, templatePath, variables, handler);
                    var fileSystemProvider = new providers.FilesystemProvider(downloadPath);

                    downloadPromises.push(downloader.processItems(webProvider, fileSystemProvider, downloaderOptions).catch((reason) => {
                        reject(reason);
                    }));
                }
                else if (artifact.resource.type.toLowerCase() === "filepath") {
                    let downloader = new engine.ArtifactEngine();
                    let downloadUrl = artifact.resource.data;
                    let artifactLocation = downloadUrl + '/' + artifact.name;
                    if (!fs.existsSync(artifactLocation)) {
                        console.log(tl.loc("ArtifactNameDirectoryNotFound", artifactLocation, downloadUrl));
                        artifactLocation = downloadUrl;
                    }

                    console.log(tl.loc("DownloadArtifacts", artifactLocation));
                    var fileShareProvider = new providers.FilesystemProvider(artifactLocation);
                    var fileSystemProvider = new providers.FilesystemProvider(downloadPath + '\\' + artifact.name);

                    downloadPromises.push(downloader.processItems(fileShareProvider, fileSystemProvider, downloaderOptions).catch((reason) => {
                        reject(reason);
                    }));
                }
                else {
                    console.log(tl.loc('UnsupportedArtifactType', artifact.resource.type));
                }
            });

            Promise.all(downloadPromises).then(() => {
                console.log(tl.loc('ArtifactsSuccessfullyDownloaded', downloadPath));
                resolve();
            }).catch((error) => {
                reject(error);
            });
        }
    });
开发者ID:Microsoft,项目名称:vsts-rm-extensions,代码行数:91,代码来源:download.ts

示例3: getTempNpmrcPath

export function getTempNpmrcPath(): string {
    const id: string = tl.getVariable('Build.BuildId') || tl.getVariable('Release.ReleaseId');
    const tempUserNpmrcPath: string = path.join(getTempPath(), `${id}.npmrc`);

    return tempUserNpmrcPath;
}
开发者ID:shubham90,项目名称:vsts-tasks,代码行数:6,代码来源:util.ts

示例4: run

export async function run(nuGetPath: string): Promise<void> {
    let packagingLocation: pkgLocationUtils.PackagingLocation;
    try {
        packagingLocation = await pkgLocationUtils.getPackagingUris(pkgLocationUtils.ProtocolType.NuGet);
    } 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};
    }

    nutil.setConsoleCodePage();

    const buildIdentityDisplayName: string = null;
    const buildIdentityAccount: string = null;

    const args: string = tl.getInput("arguments", false);

    const version = await peParser.getFileVersionInfoAsync(nuGetPath);
    if(version.productVersion.a < 3 || (version.productVersion.a <= 3 && version.productVersion.b < 5))
    {
        tl.setResult(tl.TaskResult.Failed, tl.loc("Info_NuGetSupportedAfter3_5", version.strings.ProductVersion));
        return;
    }

    try {
        // Clauses ordered in this way to avoid short-circuit evaluation, so the debug info printed by the functions
        // is unconditionally displayed
        const quirks = await ngToolRunner.getNuGetQuirksAsync(nuGetPath);
        const useV1CredProvider: boolean = ngToolRunner.isCredentialProviderEnabled(quirks);
        const useV2CredProvider: boolean = ngToolRunner.isCredentialProviderV2Enabled(quirks);
        const credProviderPath: string = nutil.locateCredentialProvider(useV2CredProvider);
        // useCredConfig not placed here: This task will only support NuGet versions >= 3.5.0
        // which support credProvider both hosted and OnPrem

        const accessToken = auth.getSystemAccessToken();
        let urlPrefixes = packagingLocation.PackagingUris;
        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
        const testPrefixes = tl.getVariable("NuGetTasks.ExtraUrlPrefixesForTesting");
        if (testPrefixes) {
            urlPrefixes = urlPrefixes.concat(testPrefixes.split(";"));
            tl.debug(`All URL prefixes: ${urlPrefixes}`);
        }
        const authInfo = new auth.NuGetExtendedAuthInfo(
            new auth.InternalAuthInfo(
                urlPrefixes,
                accessToken,
                ((useV1CredProvider || useV2CredProvider) ? credProviderPath : null),
                false),
            []);

        const environmentSettings: ngToolRunner.NuGetEnvironmentSettings = {
            credProviderFolder: useV2CredProvider === false ? credProviderPath : null,
            V2CredProviderPath: useV2CredProvider === true ? credProviderPath : null,
            extensionsDisabled: true,
        };

        const executionOptions = new NuGetExecutionOptions(
            nuGetPath,
            environmentSettings,
            args,
            authInfo);

        runNuGet(executionOptions);
    } catch (err) {
        tl.error(err);

        if (buildIdentityDisplayName || buildIdentityAccount) {
            tl.warning(tl.loc("BuildIdentityPermissionsHint", buildIdentityDisplayName, buildIdentityAccount));
        }

        tl.setResult(tl.TaskResult.Failed, "");
    }
}
开发者ID:shubham90,项目名称:vsts-tasks,代码行数:79,代码来源:nugetcustom.ts

示例5: getDefaultProps

function getDefaultProps() {
    var hostType = (tl.getVariable('SYSTEM.HOSTTYPE') || "").toLowerCase();
    return {
        hostType: hostType,
        definitionName: '[NonEmail:' + (hostType === 'release' ? tl.getVariable('RELEASE.DEFINITIONNAME') : tl.getVariable('BUILD.DEFINITIONNAME')) + ']',
        processId: hostType === 'release' ? tl.getVariable('RELEASE.RELEASEID') : tl.getVariable('BUILD.BUILDID'),
        processUrl: hostType === 'release' ? tl.getVariable('RELEASE.RELEASEWEBURL') : (tl.getVariable('SYSTEM.TEAMFOUNDATIONSERVERURI') + tl.getVariable('SYSTEM.TEAMPROJECT') + '/_build?buildId=' + tl.getVariable('BUILD.BUILDID')),
        taskDisplayName: tl.getVariable('TASK.DISPLAYNAME'),
        jobid: tl.getVariable('SYSTEM.JOBID'),
        agentVersion: tl.getVariable('AGENT.VERSION'),
        agentOS: tl.getVariable('AGENT.OS'),
        agentName: tl.getVariable('AGENT.NAME'),
        version: taskJson.version
    };
}
开发者ID:Microsoft,项目名称:vsts-rm-extensions,代码行数:15,代码来源:download.ts

示例6: run

async function run() {
    try {
        tl.debug("Starting Version Assemblies step");

        // get the task lets
        let filePattern = tl.getInput("filePattern", true);
        let versionSource = tl.getInput("versionSource", true);
        let versionFormat = tl.getInput("versionFormat", true);
        let customNumberVariable = tl.getInput("customNumberVariable", false);
        let customBuildRegex = tl.getInput("customBuildRegex", false);
        let buildRegexIndex = tl.getInput("buildRegexIndex", false);
        let replaceVersionFormat = tl.getInput("replaceVersionFormat", true);
        let customReplaceRegex = tl.getInput("customReplaceRegex", false);
        let replacePrefix = tl.getInput("replacePrefix", false);
        let replacePostfix = tl.getInput("replacePostfix", false);
        let failIfNoMatchFound = tl.getBoolInput("failIfNoMatchFound", false);

        let sourcePath = tl.getPathInput("sourcePath");
        if (!sourcePath || sourcePath.length === 0) {
            sourcePath = tl.getVariable("Build.SourcesDirectory");
        }
        tl.checkPath(sourcePath, "sourcePath");
        // clear leading and trailing quotes for paths with spaces
        sourcePath = sourcePath.replace(/"/g, "");

        // get the build number from the env lets
        let buildNumber = tl.getVariable("Build.BuildNumber");

        // these will be null if not specified - change to empty string
        if (!replacePrefix) replacePrefix = "";
        if (!replacePostfix) replacePostfix = "";

        tl.debug(`replacePrefix: ${replacePrefix}`);
        tl.debug(`replacePostfix: ${replacePostfix}`);
        tl.debug(`buildNumber: ${buildNumber}`);

        let buildRegex = customBuildRegex;
        switch (versionFormat) {
            default:
            case "fourParts": buildRegex = "\\d+\\.\\d+\\.\\d+\\.\\d+"; break;
            case "threeParts": buildRegex = "\\d+\\.\\d+\\.\\d+"; break;
            case "custom": buildRegex = customBuildRegex; break;
        }
        let replaceRegex = customReplaceRegex;
        switch (replaceVersionFormat) {
            default:
            case "fourParts": replaceRegex = "\\d+\\.\\d+\\.\\d+\\.\\d+"; break;
            case "threeParts": replaceRegex = "\\d+\.\\d+\\.\\d+"; break;
            case "custom": replaceRegex = customReplaceRegex; break;
        }

        tl.debug(`Using ${buildRegex} as the build regex`);
        tl.debug(`Using ${replaceRegex} as the replacement regex`);

        if (!buildRegexIndex || buildRegexIndex.length === 0){
            buildRegexIndex = "0";
        }
        tl.debug(`Using ${buildRegexIndex} as the build regex group index`);

        let separator = os.platform() === "win32" ? "\\" : "/";

        let versionNum = "";
        let skip = false;
        switch (versionSource) {
            case "variable": {
                versionNum = tl.getVariable(customNumberVariable);
                console.info(`Using ${versionNum} for the custom version number`);
                break;
            }
            default:
            case "buildNumber": {
                let buildRegexObj = new RegExp(buildRegex);
                if (buildRegexObj.test(buildNumber)) {
                    versionNum = buildRegexObj.exec(buildNumber)[buildRegexIndex];
                } else {
                    skip = true;
                    tl.warning(`Could not extract a version from [${buildNumber}] using pattern [${buildRegex}]`);
                }
                break;
            }
        }

        if (!skip) {
            console.info(`Using prefix [${replacePrefix}] and version [${versionNum}] and postfix [${replacePostfix}] in folder [${sourcePath}]`);
            
            if (os.platform() !== "win32") {
                // replace \ with /
                filePattern = filePattern.replace(/\\/g, "/");
            }
            let filesToReplace = tl.findMatch(sourcePath, filePattern);
            
            if (!filesToReplace || filesToReplace.length === 0) {
                tl.warning("No files found");
            } else {
                for (let i = 0; i < filesToReplace.length; i++) {
                    let file = filesToReplace[i];
                    console.info(`Changing version in ${file}`);
                    
                    let contents = fs.readFileSync(file, 'utf8').toString();
                    let checkMatches = new RegExp(replaceRegex).exec(contents);
//.........这里部分代码省略.........
开发者ID:xiangyan99,项目名称:cols-agent-tasks,代码行数:101,代码来源:versionAssemblies.ts

示例7: initDtaEnvironment

function initDtaEnvironment(): models.DtaEnvironment {
    const dtaEnvironment = {} as models.DtaEnvironment;
    dtaEnvironment.tfsCollectionUrl = tl.getVariable('System.TeamFoundationCollectionUri');
    dtaEnvironment.patToken = tl.getEndpointAuthorization('SystemVssConnection', true).parameters['AccessToken'];
    dtaEnvironment.agentName = tl.getVariable('Agent.MachineName') + '-' + tl.getVariable('Agent.Name') + '-' + tl.getVariable('Agent.Id');

    //TODO : Consider build scenario
    const releaseId = tl.getVariable('Release.ReleaseId');
    const phaseId = tl.getVariable('Release.DeployPhaseId');
    const projectName = tl.getVariable('System.TeamProject');
    const taskInstanceId = getDtaInstanceId();
    const parallelExecution = tl.getVariable('System.ParallelExecutionType');

    if (releaseId) {
        if (parallelExecution && parallelExecution.toLowerCase() === 'multiconfiguration') {
            const jobId = tl.getVariable('System.JobId');
            dtaEnvironment.environmentUri = 'dta://env/' + projectName + '/_apis/release/' + releaseId + '/' + phaseId + '/' + jobId + '/' + taskInstanceId;
        } else {
            dtaEnvironment.environmentUri = 'dta://env/' + projectName + '/_apis/release/' + releaseId + '/' + phaseId + '/' + taskInstanceId;
        }
    } else {
        const buildId = tl.getVariable('Build.BuildId');
        dtaEnvironment.environmentUri = 'dta://env/' + projectName + '/_apis/build/' + buildId + '/' + taskInstanceId;
    }

    dtaEnvironment.dtaHostLogFilePath = path.join(tl.getVariable('System.DefaultWorkingDirectory'), 'DTAExecutionHost.exe.log');
    return dtaEnvironment;
}
开发者ID:DarqueWarrior,项目名称:vsts-tasks,代码行数:28,代码来源:taskinputparser.ts

示例8: getTiaConfiguration

function getTiaConfiguration(): models.TiaConfiguration {
    const tiaConfiguration = {} as models.TiaConfiguration;
    tiaConfiguration.tiaEnabled = tl.getBoolInput('runOnlyImpactedTests');
    tiaConfiguration.tiaRebaseLimit = tl.getInput('runAllTestsAfterXBuilds');
    tiaConfiguration.fileLevel = tl.getVariable('tia.filelevel');
    tiaConfiguration.sourcesDir = tl.getVariable('build.sourcesdirectory');
    tiaConfiguration.tiaFilterPaths = tl.getVariable('TIA_IncludePathFilters');
    tiaConfiguration.runIdFile = path.join(os.tmpdir(), uuid.v1() + '.txt');
    tiaConfiguration.baseLineBuildIdFile = path.join(os.tmpdir(), uuid.v1() + '.txt');
    tiaConfiguration.useNewCollector = false;
    const useNewCollector = tl.getVariable('tia.useNewCollector');
    if (useNewCollector && useNewCollector.toUpperCase() === 'TRUE') {
        tiaConfiguration.useNewCollector = true;
    }

    var buildReason = tl.getVariable('Build.Reason');

    // https://www.visualstudio.com/en-us/docs/build/define/variables
    if (buildReason && buildReason === "PullRequest") {
        tiaConfiguration.isPrFlow = "true";
    }
    else {
        tiaConfiguration.isPrFlow = tl.getVariable('tia.isPrFlow');
    }
    tiaConfiguration.useTestCaseFilterInResponseFile = tl.getVariable('tia.useTestCaseFilterInResponseFile');

    const releaseuri = tl.getVariable('release.releaseUri')
    tiaConfiguration.context = 'CI';
    if (releaseuri) {
        tiaConfiguration.context = 'CD';
    }

    // User map file
    tiaConfiguration.userMapFile = tl.getVariable('tia.usermapfile');

    // disable editing settings file to switch on data collector
    if (tl.getVariable('tia.disabletiadatacollector') && tl.getVariable('tia.disabletiadatacollector').toUpperCase() === 'TRUE') {
        tiaConfiguration.disableEnablingDataCollector = true;
    } else {
        tiaConfiguration.disableEnablingDataCollector = false;
    }

    return tiaConfiguration;
}
开发者ID:colindembovsky,项目名称:vsts-tasks,代码行数:44,代码来源:taskinputparser.ts

示例9: downloadSecureFile

 async downloadSecureFile(secureFileId: string) {
     tl.debug('Mock downloadSecureFile with id = ' + secureFileId);
     let fileName: string = secureFileId + '.filename';
     let tempDownloadPath: string = tl.resolve(tl.getVariable('Agent.TempDirectory'), fileName);
     return tempDownloadPath;
 }
开发者ID:DarqueWarrior,项目名称:vsts-tasks,代码行数:6,代码来源:securefiles-common-mock.ts

示例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);
}
开发者ID:colindembovsky,项目名称:vsts-tasks,代码行数:31,代码来源:runvstest.ts


注:本文中的vsts-task-lib/task.getVariable函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。