Skip to content

Commit

Permalink
DotNetCoreCLI, restore auth, pack, nuget push
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Spillman committed Jun 13, 2017
1 parent 4bdbf05 commit e9c2c9a
Show file tree
Hide file tree
Showing 48 changed files with 2,336 additions and 491 deletions.
69 changes: 69 additions & 0 deletions Tasks/Common/nuget-task-common/Authentication.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,81 @@
import * as tl from "vsts-task-lib/task";

export interface IPackageSource {
feedName: string;
feedUri: string;
isInternal: boolean;
}

export class NuGetAuthInfo {
constructor(
public uriPrefixes: string[],
public accessToken: string) {
}
}

export class NuGetExtendedAuthInfo {
constructor(
public internalAuthInfo: InternalAuthInfo,
public externalAuthInfo?: ExternalAuthInfo[]) {
}
}

export class InternalAuthInfo
{
constructor(
public uriPrefixes: string[],
public accessToken: string,
public useCredProvider: string,
public useCredConfig: boolean) {
}
}

export class ExternalAuthInfo
{
constructor(
public packageSource: IPackageSource,
public authType: ExternalAuthType) {
}
}

export class TokenExternalAuthInfo extends ExternalAuthInfo
{
constructor(
public packageSource: IPackageSource,
public token: string)
{
super(packageSource, ExternalAuthType.Token);
}
}

export class UsernamePasswordExternalAuthInfo extends ExternalAuthInfo
{
constructor(
public packageSource: IPackageSource,
public username: string,
public password: string)
{
super(packageSource, ExternalAuthType.UsernamePassword);
}
}

export class ApiKeyExternalAuthInfo extends ExternalAuthInfo
{
constructor(
public packageSource: IPackageSource,
public apiKey: string)
{
super(packageSource, ExternalAuthType.ApiKey);
}
}

export enum ExternalAuthType
{
Token,
UsernamePassword,
ApiKey
}

export function getSystemAccessToken(): string {
tl.debug("Getting credentials for local feeds");
let auth = tl.getEndpointAuthorization("SYSTEMVSSCONNECTION", false);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,42 +1,13 @@
import * as path from "path";
import * as vsts from "vso-node-api/WebApi";
import locationHelpers = require("nuget-task-common/LocationHelpers");
import {VersionInfo} from "nuget-task-common/pe-parser/VersionResource";
import locationHelpers = require("./LocationHelpers");
import {VersionInfo} from "./pe-parser/VersionResource";
import * as tl from "vsts-task-lib/task";
import * as auth from "./Authentication";
import { IPackageSource } from "./Authentication";
import * as url from "url";

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 coreApi.vsoClient.getVersioningData(ApiVersion, PackagingAreaName, PackageAreaId, { feedId: feedId });

return data.requestUrl;
}

export function GetExternalAuthInfoArray(inputKey: string): auth.ExternalAuthInfo[]
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,41 @@ import * as tl from "vsts-task-lib/task";

import * as auth from "./Authentication";
import { IPackageSource } from "./Authentication";
import * as ngToolRunner from "./NuGetToolRunner";
import * as ngToolRunner from "./NuGetToolRunner2";

let xmlreader = require("xmlreader");

// NuGetConfigHelper2 handles authenticated scenarios where the user selects a source from the UI or from a service connection.
// It is used by the NuGetCommand >= v2.0.0 and DotNetCoreCLI >= v2.0.0

export class NuGetConfigHelper {
private tempNugetConfigBaseDir
= tl.getVariable("Agent.BuildDirectory")
|| tl.getVariable("Agent.ReleaseDirectory")
|| process.cwd();
private tempNugetConfigDir = path.join(this.tempNugetConfigBaseDir, "Nuget");
private tempNugetConfigFileName = "tempNuGet_" + tl.getVariable("build.buildId") + ".config";
export class NuGetConfigHelper2 {
public tempNugetConfigPath = undefined;

constructor(
private nugetPath: string,
private nugetConfigPath: string,
private authInfo: auth.NuGetAuthInfo,
private environmentSettings: ngToolRunner.NuGetEnvironmentSettings)
private authInfo: auth.NuGetExtendedAuthInfo,
private environmentSettings: ngToolRunner.NuGetEnvironmentSettings,
private tempConfigPath: string /*optional*/)
{
this.tempNugetConfigPath = tempConfigPath || this.getTempNuGetConfigPath();
}

public static getTempNuGetConfigBasePath() {
return tl.getVariable("Agent.BuildDirectory")
|| tl.getVariable("Agent.ReleaseDirectory")
|| process.cwd();
}

public ensureTempConfigCreated() {
// save nuget config file to agent build directory
console.log(tl.loc("Info_SavingTempConfig"));

if (!tl.exist(this.tempNugetConfigDir)) {
tl.mkdirP(this.tempNugetConfigDir);
let tempNuGetConfigDir = path.dirname(this.tempNugetConfigPath);
if (!tl.exist(tempNuGetConfigDir)) {
tl.mkdirP(tempNuGetConfigDir);
}

this.tempNugetConfigPath = path.join(this.tempNugetConfigDir, this.tempNugetConfigFileName);

if (!tl.exist(this.tempNugetConfigPath))
{
if (this.nugetConfigPath) {
Expand All @@ -62,15 +65,15 @@ export class NuGetConfigHelper {
public async setAuthForSourcesInTempNuGetConfigAsync(): Promise<void>
{
tl.debug('Setting auth in the temp nuget.config');

this.ensureTempConfigCreated();

let sources = await this.getSourcesFromTempNuGetConfig();
if (sources.length < 1)
{
tl.debug('Not setting up auth for temp nuget.config as there are no sources');
return;
}

this.ensureTempConfigCreated();
sources.forEach((source) => {
if (source.isInternal)
{
Expand Down Expand Up @@ -121,6 +124,12 @@ export class NuGetConfigHelper {
});
}

private getTempNuGetConfigPath(): string {
const tempNuGetConfigBaseDir = NuGetConfigHelper2.getTempNuGetConfigBasePath();
const tempNuGetConfigFileName = "tempNuGet_" + tl.getVariable("build.buildId") + ".config";
return path.join(tempNuGetConfigBaseDir, "Nuget", tempNuGetConfigFileName);
}

private getSourcesFromTempNuGetConfig(): Q.Promise<IPackageSource[]> {
// load content of the user's nuget.config
let configPath: string = this.tempNugetConfigPath ? this.tempNugetConfigPath : this.nugetConfigPath;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ import * as tl from "vsts-task-lib/task";
import {IExecOptions, IExecSyncResult, ToolRunner} from "vsts-task-lib/toolrunner";

import * as auth from "./Authentication";
import {NuGetQuirkName, NuGetQuirks, defaultQuirks} from "nuget-task-common/NuGetQuirks";
import * as ngutil from "nuget-task-common/Utility";
import * as util from "./utilities";
import * as peParser from "nuget-task-common/pe-parser";
import {NuGetQuirkName, NuGetQuirks, defaultQuirks} from "./NuGetQuirks";
import * as ngutil from "./Utility";
import * as peParser from "./pe-parser";
import * as commandHelper from "./CommandHelper";

// NuGetToolRunner2 can handle environment setup for new authentication scenarios where
// we are accessing internal or external package sources.
// It is used by the NuGetCommand >= v2.0.0 and DotNetCoreCLI >= v2.0.0

interface EnvironmentDictionary { [key: string]: string; }

Expand All @@ -18,7 +22,7 @@ export interface NuGetEnvironmentSettings {
function prepareNuGetExeEnvironment(
input: EnvironmentDictionary,
settings: NuGetEnvironmentSettings,
authInfo: auth.NuGetAuthInfo): EnvironmentDictionary {
authInfo: auth.NuGetExtendedAuthInfo): EnvironmentDictionary {

let env: EnvironmentDictionary = {};
let originalCredProviderPath: string;
Expand Down Expand Up @@ -73,11 +77,11 @@ function prepareNuGetExeEnvironment(
return env;
}

export class NuGetToolRunner extends ToolRunner {
export class NuGetToolRunner2 extends ToolRunner {
private settings: NuGetEnvironmentSettings;
private authInfo: auth.NuGetAuthInfo;
private authInfo: auth.NuGetExtendedAuthInfo;

constructor(nuGetExePath: string, settings: NuGetEnvironmentSettings, authInfo: auth.NuGetAuthInfo) {
constructor(nuGetExePath: string, settings: NuGetEnvironmentSettings, authInfo: auth.NuGetExtendedAuthInfo) {
if (tl.osType() === 'Windows_NT' || !nuGetExePath.trim().toLowerCase().endsWith(".exe")) {
super(nuGetExePath);
}
Expand All @@ -104,8 +108,8 @@ export class NuGetToolRunner extends ToolRunner {
}
}

export function createNuGetToolRunner(nuGetExePath: string, settings: NuGetEnvironmentSettings, authInfo: auth.NuGetAuthInfo): NuGetToolRunner {
let runner = new NuGetToolRunner(nuGetExePath, settings, authInfo);
export function createNuGetToolRunner(nuGetExePath: string, settings: NuGetEnvironmentSettings, authInfo: auth.NuGetExtendedAuthInfo): NuGetToolRunner2 {
let runner = new NuGetToolRunner2(nuGetExePath, settings, authInfo);
runner.on("debug", message => tl.debug(message));
return runner;
}
Expand Down Expand Up @@ -167,7 +171,7 @@ export function isCredentialProviderEnabled(quirks: NuGetQuirks): boolean {
return false;
}

if (util.isOnPremisesTfs() && (
if (commandHelper.isOnPremisesTfs() && (
quirks.hasQuirk(NuGetQuirkName.NoTfsOnPremAuthCredentialProvider))) {
tl.debug("Credential provider is disabled due to on-prem quirks.");
return false;
Expand All @@ -192,7 +196,7 @@ export function isCredentialConfigEnabled(quirks: NuGetQuirks): boolean {
return false;
}

if (util.isOnPremisesTfs() && (
if (commandHelper.isOnPremisesTfs() && (
quirks.hasQuirk(NuGetQuirkName.NoTfsOnPremAuthConfig))) {
tl.debug("Credential config is disabled due to on-prem quirks.");
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
"loc.messages.NGCommon_DetectedNuGetExtensionsPath": "Detected NuGet extensions loader path (NUGET_EXTENSIONS_PATH environment variable): %s",
"loc.messages.NGCommon_UnableToFindTool": "Unable to find tool %s",
"loc.messages.Info_AvailableVersions": "The available versions are: %s",
"loc.messages.Info_MatchingUrlWasFoundSettingAuth": "Using authentication information for the following URI: ",
"loc.messages.Info_ResolvedToolFromCache": "Resolved from tool cache: %s",
"loc.messages.Info_SavingTempConfig": "Saving NuGet.config to a temporary config file.",
"loc.messages.Info_UsingVersion": "Using version: %s",
"loc.messages.Info_UsingToolPath": "Using tool path: %s",
"loc.messages.Info_ExpectBehaviorChangeWhenUsingVersionQuery": "You are using a query match on the version string. Behavior changes or breaking changes might occur as NuGet updates to a new version.",
Expand Down
39 changes: 36 additions & 3 deletions Tasks/Common/nuget-task-common/Utility.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import * as path from "path";

import * as tl from "vsts-task-lib/task";

import * as ngToolRunner from "./NuGetToolRunner";
import * as vsts from "vso-node-api/WebApi";
import {VersionInfo} from "./pe-parser/VersionResource";
import locationHelpers = require("./LocationHelpers");
import * as url from "url";

// Attempts to resolve paths the same way the legacy PowerShell's Find-Files worked
export function resolveFilterSpec(filterSpec: string, basePath?: string, allowEmptyMatch?: boolean, includeFolders?: boolean): string[] {
Expand Down Expand Up @@ -184,4 +186,35 @@ export function setConsoleCodePage() {
if (tl.osType() === 'Windows_NT') {
tl.execSync(path.resolve(process.env.windir, "system32", "chcp.com"), ["65001"]);
}
}
}

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 coreApi.vsoClient.getVersioningData(ApiVersion, PackagingAreaName, PackageAreaId, { feedId: feedId });

return data.requestUrl;
}
2 changes: 2 additions & 0 deletions Tasks/Common/nuget-task-common/module.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
"NGCommon_DetectedNuGetExtensionsPath": "Detected NuGet extensions loader path (NUGET_EXTENSIONS_PATH environment variable): %s",
"NGCommon_UnableToFindTool": "Unable to find tool %s",
"Info_AvailableVersions": "The available versions are: %s",
"Info_MatchingUrlWasFoundSettingAuth": "Using authentication information for the following URI: ",
"Info_ResolvedToolFromCache": "Resolved from tool cache: %s",
"Info_SavingTempConfig": "Saving NuGet.config to a temporary config file.",
"Info_UsingVersion": "Using version: %s",
"Info_UsingToolPath": "Using tool path: %s",
"Info_ExpectBehaviorChangeWhenUsingVersionQuery": "You are using a query match on the version string. Behavior changes or breaking changes might occur as NuGet updates to a new version.",
Expand Down
22 changes: 22 additions & 0 deletions Tasks/DotNetCoreCLI/Common/utility.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import * as tl from "vsts-task-lib/task";
import nuGetGetter = require("nuget-task-common/NuGetToolGetter");

export function getProjectFiles(projectPattern: string[]): string[] {
var projectFiles = tl.findMatch(tl.getVariable("System.DefaultWorkingDirectory") || process.cwd(), projectPattern);
if (!projectFiles || !projectFiles.length) {
tl.warning(tl.loc("noProjectFilesFound"));
return [];
}

return projectFiles;
}

export async function getNuGetPath(): Promise<string> {
tl.debug('Getting NuGet');
return process.env[nuGetGetter.NUGET_EXE_TOOL_PATH_ENV_VAR] || await nuGetGetter.getNuGet("4.0.0");
}

export function getUtcDateString(): string {
let now: Date = new Date();
return `${now.getFullYear()}${now.getUTCMonth()}${now.getUTCDate()}-${now.getUTCHours()}${now.getUTCMinutes()}${now.getUTCSeconds()}`;
}
Loading

0 comments on commit e9c2c9a

Please sign in to comment.