當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript WebApi.getBearerHandler函數代碼示例

本文整理匯總了TypeScript中vso-node-api/WebApi.getBearerHandler函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript getBearerHandler函數的具體用法?TypeScript getBearerHandler怎麽用?TypeScript getBearerHandler使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了getBearerHandler函數的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: main

async function main(): Promise<void> {
	var feed = getProjectAndFeedIdFromInputParam("feed");
	if(feed.projectId) {
		throw new Error(tl.loc("UnsupportedProjectScopedFeeds"));
	}
	let feedId = feed.feedId;
	let regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
	let packageId = tl.getInput("definition");

	if(!regexGuid.test(packageId)){
		packageId = "Nuget_" + tl.getInput("definition");
	}

	let version = tl.getInput("version");
	let downloadPath = tl.getInput("downloadPath");
	let collectionUrl = tl.getVariable("System.TeamFoundationCollectionUri");

	var accessToken = getAuthToken();
	var credentialHandler = vsts.getBearerHandler(accessToken);
	var vssConnection = new vsts.WebApi(collectionUrl, credentialHandler);
	var coreApi = vssConnection.getCoreApi();
	const retryLimitValue: string = tl.getVariable("VSTS_HTTP_RETRY");
	const retryLimit: number = (!!retryLimitValue && !isNaN(parseInt(retryLimitValue))) ? parseInt(retryLimitValue) : 4;
	tl.debug(`RetryLimit set to ${retryLimit}`);

	await executeWithRetries("downloadPackage", () => downloadPackage(collectionUrl, accessToken, credentialHandler, feedId, packageId, version, downloadPath).catch((reason) => {
		throw reason;
	}), retryLimit);
}
開發者ID:Microsoft,項目名稱:vsts-tasks,代碼行數:29,代碼來源:download.ts

示例2: getNuGetFeedRegistryUrl

export async function getNuGetFeedRegistryUrl(accessToken:string, feedId: string, nuGetVersion: VersionInfo): Promise<string>
{
    const ApiVersion = "3.0-preview.1";
    let PackagingAreaName: string = "nuget";
    // If no version is received, V3 is assumed
    let PackageAreaId: string = nuGetVersion && nuGetVersion.productVersion.a < 3 ? "5D6FC3B3-EF78-4342-9B6E-B3799C866CFA" : "9D3A4E8E-2F8F-4AE1-ABC2-B461A51CB3B3";

    let credentialHandler = vsts.getBearerHandler(accessToken);
    let collectionUrl = tl.getVariable("System.TeamFoundationCollectionUri");
    // The second element contains the transformed packaging URL
    let packagingCollectionUrl = (await locationHelpers.assumeNuGetUriPrefixes(collectionUrl))[1];

    if (!packagingCollectionUrl)
    {
        packagingCollectionUrl = collectionUrl;
    }

    const overwritePackagingCollectionUrl = tl.getVariable("NuGet.OverwritePackagingCollectionUrl");
    if (overwritePackagingCollectionUrl) {
        tl.debug("Overwriting packaging collection URL");
        packagingCollectionUrl = overwritePackagingCollectionUrl;
    }

    let vssConnection = new vsts.WebApi(packagingCollectionUrl, credentialHandler);
    let coreApi = vssConnection.getCoreApi();

    let data = await Retry(async () => {
        return await coreApi.vsoClient.getVersioningData(ApiVersion, PackagingAreaName, PackageAreaId, { feedId: feedId });
    }, 4, 100);
    return data.requestUrl;
}
開發者ID:bleissem,項目名稱:vsts-tasks,代碼行數:31,代碼來源:Utility.ts

示例3: main

async function main(): Promise<void> {
	let feedId = tl.getInput("feed");
	let packageId = tl.getInput("definition");
	let version = tl.getInput("version");
	let downloadPath = tl.getInput("downloadPath");
	let collectionUrl = tl.getVariable("System.TeamFoundationCollectionUri");

	var accessToken = getAuthToken();
	var credentialHandler = vsts.getBearerHandler(accessToken);
	var vssConnection = new vsts.WebApi(collectionUrl, credentialHandler);
	var coreApi = vssConnection.getCoreApi();

	await downloadPackage(collectionUrl, credentialHandler, feedId, packageId, version, downloadPath);
}
開發者ID:colindembovsky,項目名稱:vsts-tasks,代碼行數:14,代碼來源:download.ts

示例4: getFeedRegistryUrl

export async function getFeedRegistryUrl(feedId: string): Promise<string> {
    const apiVersion = '3.0-preview.1';
    const area = 'npm';
    const locationId = 'D9B75B07-F1D9-4A67-AAA6-A4D9E66B3352';

    let accessToken = getSystemAccessToken();
    let credentialHandler = vsts.getBearerHandler(accessToken);
    let collectionUrl = await getPackagingCollectionUrl();
    let vssConnection = new vsts.WebApi(collectionUrl, credentialHandler);
    let coreApi = vssConnection.getCoreApi();
    let data = await coreApi.vsoClient.getVersioningData(apiVersion, area, locationId, { feedId: feedId });

    return data.requestUrl;
}
開發者ID:colindembovsky,項目名稱:vsts-tasks,代碼行數:14,代碼來源:util.ts

示例5: main

async function main(): Promise<void> {
	let feedId = tl.getInput("feed");
	let regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
	let packageId = tl.getInput("definition");

	if(!regexGuid.test(packageId)){
		packageId = "Nuget_" + tl.getInput("definition");
	}

	let version = tl.getInput("version");
	let downloadPath = tl.getInput("downloadPath");
	let collectionUrl = tl.getVariable("System.TeamFoundationCollectionUri");

	var accessToken = getAuthToken();
	var credentialHandler = vsts.getBearerHandler(accessToken);
	var vssConnection = new vsts.WebApi(collectionUrl, credentialHandler);
	var coreApi = vssConnection.getCoreApi();

	await downloadPackage(collectionUrl, accessToken, credentialHandler, feedId, packageId, version, downloadPath);
}
開發者ID:grawcho,項目名稱:vso-agent-tasks,代碼行數:20,代碼來源:download.ts

示例6: getServiceEndPoint

export function getServiceEndPoint(feedId: string, accessToken: string, area: string, locationId: string ): Q.Promise<string>{
	
	var collectionUrl = tl.getVariable("System.TeamFoundationCollectionUri");
	var oauth = vstsWebApi.getBearerHandler(accessToken);
	var connection = new vstsWebApi.WebApi(collectionUrl, oauth);
	var coreApi = connection.getCoreApi();
	var serviceURL = '';
			
	return coreApi.vsoClient.getVersioningData("3.0-preview.1", area, locationId,  { feedId: feedId })
	.then((versioningData) => {
	    tl._writeLine("Found " + area + " endpoint: " + versioningData.requestUrl);
		return versioningData.requestUrl;

	})
	.fail(err => {
		tl.error(tl.loc("CouldNotFindServiceEndpoint", area));
		tl.error(err);
		tl.exit(1);
		return '';

	})
}
開發者ID:ivyzhu,項目名稱:vsts-tasks,代碼行數:22,代碼來源:LocationHelpers.ts

示例7: createAgent

 public static async createAgent(environment: models.DtaEnvironment, retries: number) {
     var currentRetryCount = retries;
     while(currentRetryCount > 0) {
         currentRetryCount--;
         try {
             const envUrlRef: any = { Url: environment.environmentUri };
             const machineNameRef: any = { Name: environment.agentName };
             // TODO : Change any to appropriate types once promiseme package is avialable
             const testAgent: any = {
                                 Name: environment.agentName,
                                 Capabilities: [],
                                 DtlEnvironment: envUrlRef,
                                 DtlMachine: machineNameRef };
             const webapi: any = new webapim.WebApi(environment.tfsCollectionUrl, webapim.getBearerHandler(environment.patToken));
             const testApi: any = webapi.getTestApi();
             const registeredAgent = await testApi.createAgent(testAgent);
             tl.debug('created the test agent entry in DTA service, id : ' + registeredAgent.id);
             return registeredAgent.id;
         } catch (error) {
             tl.error('Error : created the test agent entry in DTA service, so retrying => retries pending  : ' + currentRetryCount
                     + 'error details :' + error);
             if(currentRetryCount === 0) {
                 throw new Error(tl.loc("configureDtaAgentFailed", retries, error));
             }
         }
     }
 }
開發者ID:bleissem,項目名稱:vsts-tasks,代碼行數:27,代碼來源:testagent.ts

示例8: getConnectionData

function getConnectionData(uri: string, accessToken: string): Q.Promise<locationApi.ConnectionData> {
    return new locationApi.QLocationApi(uri, [vstsWebApi.getBearerHandler(accessToken)]).getConnectionData();
}
開發者ID:PazSchori,項目名稱:vsts-tasks,代碼行數:3,代碼來源:LocationHelpers.ts

示例9: run

async function run() {
    try {
        tl.debug("Starting Coverage Gate task");

        var tpcUri = tl.getVariable("System.TeamFoundationCollectionUri");
        var teamProject = tl.getVariable("System.TeamProject");
        var buildId = parseInt(tl.getVariable("Build.BuildId"));
        var minDelta = parseInt(tl.getInput("minDelta", true));
        var operator = tl.getInput("operator", true);
        var username = tl.getInput("username", false);
        var password = tl.getInput("password", false);
        tl.debug(`minDelta: ${minDelta}`);
        tl.debug(`operator: ${operator}`);
        tl.debug(`username: ${username}`);

        // handle creds
        var credOk = true;
        var credHandler: vstsInterfaces.IRequestHandler;
        var accessToken = tl.getVariable("System.AccessToken");
        if (!accessToken || accessToken.length === 0) {
            if (username && username.length > 0) {
                tl.debug("Detected username: creating basic cred handler");
                credHandler = webApi.getBasicHandler(username, password);
            } else {
                tl.setResult(tl.TaskResult.Failed, "Could not find token for autheniticating. Please enable OAuth token in Build/Release Options or supply username/password.");
                credOk = false;
            }
        } else {
            tl.debug("Detected token: creating bearer cred handler");
            credHandler = webApi.getBearerHandler(accessToken);
        }

        if (credOk) {
            var vsts = new webApi.WebApi(tpcUri, credHandler);

            // get previous successful builds
            tl.debug("Connecting to test API");
            var testApi = vsts.getTestApi();

            tl.debug("Getting coverage data");
            // 1 = modules, 2 = function, 4 = block
            var covData = await testApi.getCodeCoverageSummary(teamProject, buildId);

            tl.debug("Analyzing coverage data");
            if (covData) {
                var data = covData.coverageData[0];
                var trends = data.coverageStats.filter(c => c.isDeltaAvailable)
                    .map(u => {
                        return {
                            Label: u.label,
                            Delta: u.delta
                        };
                    });
                if (trends.length === 0){
                    tl.setResult(tl.TaskResult.Failed, `There are no coverage deltas. Make sure you have at least 2 builds.`);
                }
                var fail = trends.some(t => operator === 'lt' ? t.Delta < minDelta : t.Delta <= minDelta);
                if (fail) {
                    tl.setResult(tl.TaskResult.Failed, `Coverage delta is below the threshold of ${minDelta}`);
                }
            } else {
                tl.setResult(tl.TaskResult.Failed, "No coverage data for build. Cannot determine trend.");
            }
            tl.setResult(tl.TaskResult.Succeeded, `Code coverage delta is above the threshold of ${minDelta}`);
        }
    } catch (err) {
        tl.debug("Caught an error - logging");
        let msg = err;
        if (err.message) {
            msg = err.message;
        }
        tl.setResult(tl.TaskResult.Failed, msg);
    }
    tl.debug("Leaving Coverage Gate task");
}
開發者ID:xiangyan99,項目名稱:cols-agent-tasks,代碼行數:75,代碼來源:coverageGate.ts

示例10: run

async function run() {
    tl.debug("Starting Tag Build/Release task");

    let tpcUri = tl.getVariable("System.TeamFoundationCollectionUri");
    // try to get the build team project, in case it's different from the release team project
    let teamProject = tl.getVariable("Build.ProjectName");
    if (!teamProject || teamProject.length === 0) {
        // fall back on the release team project
        teamProject = tl.getVariable("System.TeamProject");
    }
    let type = tl.getInput("type", true);
    let tags = tl.getDelimitedInput("tags", '\n', true);

    let buildId = -1;
    let bId = tl.getVariable("Build.BuildId");
    // just for tests
    if (bId === "-1") {
        bId = null;
    }
    if (bId) {
        buildId = parseInt(bId);
        tl.debug(`Build ID = ${buildId}`);
    } else {
        if (type === "Build") {
            return completeTask(false, "No build ID found - perhaps Type should be 'Release' not 'Build'?");
        }
    }
    
    let releaseId = -1;
    let rId = tl.getVariable("Release.ReleaseId");
    if (rId) {
        releaseId = parseInt(rId);
        tl.debug(`Release ID = ${releaseId}`);
    } else {
        if (type === "Release") {
            return completeTask(false, "No release ID found - perhaps Type should be 'Build' not 'Release'?");
        } 
    }
        
    // handle creds
    let credHandler: vstsInterfaces.IRequestHandler;
    let accessToken = tl.getVariable("System.AccessToken");
    if (!accessToken || accessToken.length === 0) {
        tl.setResult(tl.TaskResult.Failed, "Could not find token for autheniticating. Please enable OAuth token in Build/Release Options.");
        tl.debug("Leaving Tag Build task");
        return;
    } else {
        tl.debug("Detected token: creating bearer cred handler");
        credHandler = webApi.getBearerHandler(accessToken);
    }

    let vsts = new webApi.WebApi(tpcUri, credHandler);
    
    if (type === "Build") {
        tl.debug("Getting build api client");
        let buildApi = vsts.getBuildApi();
        
        console.info(`Setting tags on build [${buildId}]`);
        await buildApi.addBuildTags(tags, teamProject, buildId)
            .then(tags => {
                tl.debug(`New tags: ${tags.join(',')}`);
                return completeTask(true, `Successfully added tags to the ${type}`);
            })
            .catch(e => tl.setResult(tl.TaskResult.Failed, e));
    } else {
        tl.debug("Getting release api client");

        let releaseResourceArea;
        try {
            let locationClient = vsts.getLocationsApi();
            releaseResourceArea = await locationClient.getResourceArea("efc2f575-36ef-48e9-b672-0c6fb4a48ac5");
        } catch (e) {
            console.warn("Could not get releaseResourceArea resource area: this may cause the task to fail.");
        }
        let releaseApi = vsts.getReleaseApi(releaseResourceArea ? releaseResourceArea.locationUrl : null);

        console.info(`Setting tags on release [${releaseId}]`);
        await releaseApi.addReleaseTags(tags, teamProject, releaseId)
            .then(tags => {
                tl.debug(`New tags: ${tags.join(',')}`);
                return completeTask(true, `Successfully added tags to the ${type}`);
            })
            .catch(e => completeTask(false, e));
    }
}
開發者ID:xiangyan99,項目名稱:cols-agent-tasks,代碼行數:85,代碼來源:tagBuild.ts

示例11: parseInt

    var promise = new Promise<void>(async (resolve, reject) => {

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

        tl.debug("Starting Tag ChangedBuildArtifacts task");

        let tpcUri = tl.getVariable("System.TeamFoundationCollectionUri");
        let teamProject = tl.getVariable("System.TeamProject");
        let hostType = tl.getVariable("system.hostType");
        let releaseId: number = parseInt(tl.getVariable("Release.ReleaseId"));
        let releaseDefinitionId: number = parseInt(tl.getVariable("Release.DefinitionId"));
        let releaseDefinitionEnvironmentId: number = parseInt(tl.getVariable("Release.DefinitionEnvironmentId"));
        let releaseEnvironmentName = tl.getVariable("Release.EnvironmentName");

        // Get the credential handler
        var accessToken: string = tl.getVariable("System.AccessToken");
        let credHandler: vstsInterfaces.IRequestHandler;
        if (!accessToken || accessToken.length === 0) {
            reject("Unable to locate access token.  Please make sure you have enabled the \"Allow scripts to access OAuth token\" setting.");
            return;
        } else {
            tl.debug("Creating the credential handler");
            // used for local debugging.  Allows switching between PAT token and Bearer Token for debugging
            credHandler = accessToken.length === 52 ? webApi.getPersonalAccessTokenHandler(accessToken) :
                                                    webApi.getBearerHandler(accessToken);
        }

        let vsts = new webApi.WebApi(tpcUri, credHandler);
        var releaseApi: IReleaseApi = await vsts.getReleaseApi();

        console.log("Getting the current release details");
        var currentRelease = await releaseApi.getRelease(teamProject, releaseId).catch((reason) => {
            reject(reason);
            return;
        });

        console.log(`Getting the all the successful deployments to release definition id ${releaseDefinitionEnvironmentId}`);
        // Gets the latest successful deployments in order
        var successfulDeployments = await releaseApi.getDeployments(teamProject, releaseDefinitionId, releaseDefinitionEnvironmentId, null, null, null, DeploymentStatus.Succeeded, null, true, null, null, null, null).catch((reason) => {
            reject(reason);
            return;
        });

        // We want to compare the artifacts between the two definitions to see which ones are different.
        if (currentRelease) {
            console.log(`Getting all artifacts in the current release...`);
            var arifactsInThisRelease = getArtifactArray(currentRelease.artifacts);
            console.log(`Found ${arifactsInThisRelease.length}`);

            if (successfulDeployments && successfulDeployments.length > 0) {
                // loop through every artifact in this release
                for (var artifactInCurrentRelease of arifactsInThisRelease) {
                    console.log(`Looking for artifact ${artifactInCurrentRelease.buildNumber} in previous successful deployments...`);
                    for (var deployment of successfulDeployments) {

                        // We need to check the status of this release
                        var releaseForDeployment = await releaseApi.getRelease(teamProject, deployment.release.id).catch((reason) => {
                            reject(reason);
                            return;
                        });

                        if (releaseForDeployment && releaseForDeployment.status !== ReleaseStatus.Active) {
                            // the release is not active
                            console.log(`Skipping this deployment because release [${deployment.release.name}] has a status of [${ReleaseStatus[releaseForDeployment.status]}]`);
                            continue;
                        }

                        if (!artifactInCurrentRelease.previouslyDeployed) {
                            console.log(`Searching for artifact ${artifactInCurrentRelease.buildNumber} in release ${deployment.release.name}`);
                            var artifactsInDeployment = getArtifactArray(deployment.release.artifacts);

                            for (var artifactInDeployment of artifactsInDeployment) {
                                if (artifactInCurrentRelease.buildDefinitionId === artifactInDeployment.buildDefinitionId &&
                                    artifactInCurrentRelease.buildNumber === artifactInDeployment.buildNumber) {
                                    console.log(`Found artifact ${artifactInCurrentRelease.buildNumber} deployed in ${deployment.release.name}`);
                                    artifactInCurrentRelease.previouslyDeployed = true;
                                    break;
                                }
                            }
                        } else {
                            console.log(`Skipping remaining releases because the property previouslyDeployed for artifact ${artifactInCurrentRelease.buildNumber} was false.`);
                            break;
                        }
                    }
                }
            }
            else {
                // There are no successful releases - we need to add all the artifacts
                console.log(`Past successful releases for id ${releaseDefinitionId} and environment id ${releaseDefinitionEnvironmentId} not found.`);
            }

            for (var artifactInCurrentRelease2 of arifactsInThisRelease) {
                var safeAlias = artifactInCurrentRelease2.artifactAlias.replace(/\./gi, "_");
                var variableName = ("RELEASE_ARTIFACTS_" + safeAlias + "_PreviouslyDeployed").toUpperCase();
                console.log(`Setting variable ${variableName} with value ${artifactInCurrentRelease2.previouslyDeployed}`);
                tl.setVariable(variableName, artifactInCurrentRelease2.previouslyDeployed.toString());
            }

        }
        else {
//.........這裏部分代碼省略.........
開發者ID:gregpakes,項目名稱:ArtifactVariables,代碼行數:101,代碼來源:ArtifactDeploymentDetectorTask.ts


注:本文中的vso-node-api/WebApi.getBearerHandler函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。