Example #1
0
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};
    }

    const buildIdentityDisplayName: string = null;
    const buildIdentityAccount: string = null;
    try {
        nutil.setConsoleCodePage();

        // Get list of files to pusblish
        const searchPatternInput = tl.getPathInput("searchPatternPush", true, false);

        const useLegacyFind: boolean = tl.getVariable("NuGet.UseLegacyFindFiles") === "true";
        let filesList: string[] = [];
        if (!useLegacyFind) {
            const findOptions: tl.FindOptions = {} as tl.FindOptions;
            const matchOptions: tl.MatchOptions = {} as tl.MatchOptions;
            const searchPatterns: string[] = nutil.getPatternsArrayFromInput(searchPatternInput);
            filesList = tl.findMatch(undefined, searchPatterns, findOptions, matchOptions);
        }
        else {
            filesList = nutil.resolveFilterSpec(searchPatternInput);
        }

        filesList.forEach((packageFile) => {
            if (!tl.stats(packageFile).isFile()) {
                throw new Error(tl.loc("Error_PushNotARegularFile", packageFile));
            }
        });

        if (filesList && filesList.length < 1)
        {
            tl.warning(tl.loc("Info_NoPackagesMatchedTheSearchPattern"));
            return;
        }

        // Get the info the type of feed
        let nugetFeedType = tl.getInput("nuGetFeedType") || "internal";
        // Make sure the feed type is an expected one
        const normalizedNuGetFeedType = ["internal", "external"]
            .find((x) => nugetFeedType.toUpperCase() === x.toUpperCase());
        if (!normalizedNuGetFeedType) {
            throw new Error(tl.loc("UnknownFeedType", nugetFeedType));
        }
        nugetFeedType = normalizedNuGetFeedType;

        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}`);
        }

        // Setting up auth info
        const accessToken = pkgLocationUtils.getSystemAccessToken();
        const quirks = await ngToolRunner.getNuGetQuirksAsync(nuGetPath);

        // Clauses ordered in this way to avoid short-circuit evaluation, so the debug info printed by the functions
        // is unconditionally displayed
        const useV1CredProvider: boolean = ngToolRunner.isCredentialProviderEnabled(quirks);
        const useV2CredProvider: boolean = ngToolRunner.isCredentialProviderV2Enabled(quirks);
        const credProviderPath: string = nutil.locateCredentialProvider(useV2CredProvider);
        const useCredConfig = ngToolRunner.isCredentialConfigEnabled(quirks)
                                && (!useV1CredProvider && !useV2CredProvider);

        const internalAuthInfo = new auth.InternalAuthInfo(
            urlPrefixes,
            accessToken,
            ((useV1CredProvider || useV2CredProvider) ? credProviderPath : null),
            useCredConfig);

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

        let configFile = null;
        let apiKey: string;
        let credCleanup = () => { return; };

        let feedUri: string;
        const isInternalFeed: boolean = nugetFeedType === "internal";

        let authInfo: auth.NuGetExtendedAuthInfo;
        let nuGetConfigHelper: NuGetConfigHelper2;

        if (isInternalFeed)
        {
            authInfo = new auth.NuGetExtendedAuthInfo(internalAuthInfo);
            nuGetConfigHelper = new NuGetConfigHelper2(nuGetPath, null, authInfo, environmentSettings, null);
            const feed = getProjectAndFeedIdFromInputParam('feedPublish');
            const nuGetVersion: VersionInfo = await peParser.getFileVersionInfoAsync(nuGetPath);
            feedUri = await nutil.getNuGetFeedRegistryUrl(
                packagingLocation.DefaultPackagingUri,
                feed.feedId,
                feed.projectId,
                nuGetVersion,
                accessToken,
                true /* useSession */);
            if (useCredConfig) {
                nuGetConfigHelper.addSourcesToTempNuGetConfig([
                    // tslint:disable-next-line:no-object-literal-type-assertion
                    {
                        feedName: feed.feedId,
                        feedUri,
                        isInternal: true,
                    } as auth.IPackageSource]);
                configFile = nuGetConfigHelper.tempNugetConfigPath;
                credCleanup = () => tl.rmRF(nuGetConfigHelper.tempNugetConfigPath);
            }

            apiKey = "VSTS";
        } else {
            const externalAuthArr = commandHelper.GetExternalAuthInfoArray("externalEndpoint");
            authInfo = new auth.NuGetExtendedAuthInfo(internalAuthInfo, externalAuthArr);
            nuGetConfigHelper = new NuGetConfigHelper2(nuGetPath, null, authInfo, environmentSettings, null);

            const externalAuth = externalAuthArr[0];

            if (!externalAuth)
            {
                tl.setResult(tl.TaskResult.Failed, tl.loc("Error_NoSourceSpecifiedForPush"));
                return;
            }

            nuGetConfigHelper.addSourcesToTempNuGetConfig([externalAuth.packageSource]);
            feedUri = externalAuth.packageSource.feedUri;
            configFile = nuGetConfigHelper.tempNugetConfigPath;
            credCleanup = () => tl.rmRF(nuGetConfigHelper.tempNugetConfigPath);

            const authType: auth.ExternalAuthType = externalAuth.authType;
            switch(authType) {
                case (auth.ExternalAuthType.UsernamePassword):
                case (auth.ExternalAuthType.Token):
                    apiKey = "RequiredApiKey";
                    break;
                case (auth.ExternalAuthType.ApiKey):
                    const apiKeyAuthInfo =  externalAuth as auth.ApiKeyExternalAuthInfo;
                    apiKey = apiKeyAuthInfo.apiKey;
                    break;
                default:
                    break;
            }
        }

        if (isInternalFeed === false || useCredConfig) {
            nuGetConfigHelper.setAuthForSourcesInTempNuGetConfig();
        }

        environmentSettings.registryUri = feedUri;

        const verbosity = tl.getInput("verbosityPush");

        const continueOnConflict: boolean = tl.getBoolInput("allowPackageConflicts");
        const useVstsNuGetPush = shouldUseVstsNuGetPush(isInternalFeed, continueOnConflict, nuGetPath);
        let vstsPushPath: string;
        if (useVstsNuGetPush) {
            vstsPushPath = vstsNuGetPushToolUtilities.getBundledVstsNuGetPushLocation();

            if (!vstsPushPath)
            {
                tl.warning(tl.loc("Warning_FallBackToNuGet"));
            }
        }

        try {
            if (useVstsNuGetPush && vstsPushPath) {
                tl.debug("Using VstsNuGetPush.exe to push the packages");
                const vstsNuGetPushSettings: vstsNuGetPushToolRunner.VstsNuGetPushSettings =
                {
                    continueOnConflict,
                };

                const publishOptions: IVstsNuGetPushOptions = {
                    vstsNuGetPushPath: vstsPushPath,
                    feedUri,
                    internalAuthInfo: authInfo.internalAuthInfo,
                    verbosity,
                    settings: vstsNuGetPushSettings,
                };

                for (const packageFile of filesList) {
                    publishPackageVstsNuGetPush(packageFile, publishOptions);
                }
            }
            else {
                tl.debug("Using NuGet.exe to push the packages");           
                const publishOptions = new PublishOptions(
                    nuGetPath,
                    feedUri,
                    apiKey,
                    configFile,
                    verbosity,
                    authInfo,
                    environmentSettings);

                for (const packageFile of filesList) {
                    publishPackageNuGet(packageFile, publishOptions, authInfo, continueOnConflict);
                }
            }

        } finally {
            credCleanup();
        }

        tl.setResult(tl.TaskResult.Succeeded, tl.loc("PackagesPublishedSuccessfully"));

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

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

        tl.setResult(tl.TaskResult.Failed, tl.loc("PackagesFailedToPublish"));
    }
}
Example #2
0
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 = pkgLocationUtils.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, "");
    }
}