コード例 #1
0
        /// <summary>
        /// Search a directory for v2 or v3 inputs, only the first type is taken.
        /// </summary>
        private void GetInputsFromDirectory(string directory, PackageRestoreInputs packageRestoreInputs)
        {
            var topLevelFiles = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);

            //  Solution files
            var solutionFiles = topLevelFiles.Where(file =>
                                                    file.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
                                .ToArray();

            if (solutionFiles.Length > 0)
            {
                if (solutionFiles.Length != 1)
                {
                    throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_MultipleSolutions"));
                }

                var file = solutionFiles[0];

                if (Verbosity == Verbosity.Detailed)
                {
                    Console.WriteLine(
                        LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesForSolution"),
                        file);
                }

                ProcessSolutionFile(file, packageRestoreInputs);

                return;
            }

            // Packages.config
            var packagesConfigFile = Path.Combine(directory, Constants.PackageReferenceFile);

            if (File.Exists(packagesConfigFile))
            {
                if (Verbosity == Verbosity.Detailed)
                {
                    Console.WriteLine(
                        LocalizedResourceManager.GetString(
                            "RestoreCommandRestoringPackagesFromPackagesConfigFile"));
                }

                // packages.confg with no solution file
                packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigFile);

                return;
            }

            // Project.json is any directory
            if (Directory.GetFiles(
                    directory,
                    $"*{ProjectJsonPathUtilities.ProjectConfigFileName}",
                    SearchOption.AllDirectories).Length > 0)
            {
                // V3 recursive project.json search
                packageRestoreInputs.RestoreV3Context.Inputs.Add(directory);

                return;
            }

            // The directory did not contain a valid target, fail!
            var noInputs = string.Format(
                CultureInfo.CurrentCulture,
                LocalizedResourceManager.GetString(
                    "Error_UnableToLocateRestoreTarget"),
                directory);

            throw new InvalidOperationException(noInputs);
        }
コード例 #2
0
ファイル: InstallCommand.cs プロジェクト: ruanzb/NuGet.Client
        private async Task InstallPackageAsync(
            string packageId,
            NuGetVersion version,
            string installPath)
        {
            if (version == null)
            {
                // Avoid searching for the highest version in the global packages folder,
                // it needs to come from the feeds instead. Once found it may come from
                // the global packages folder unless NoCache is true.
                ExcludeCacheAsSource = true;
            }

            var framework = GetTargetFramework();

            // Create the project and set the framework if available.
            var project = new InstallCommandProject(
                root: installPath,
                packagePathResolver: new PackagePathResolver(installPath, !ExcludeVersion),
                targetFramework: framework);

            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath);

            var packageSources      = GetPackageSources(Settings);
            var primaryRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);

            Console.PrintPackageSources(packageSources);

            var allowPrerelease = Prerelease || (version != null && version.IsPrerelease);

            var dependencyBehavior = GetDependencyBehavior();

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var resolutionContext = new ResolutionContext(
                    dependencyBehavior,
                    includePrelease: allowPrerelease,
                    includeUnlisted: true,
                    versionConstraints: VersionConstraints.None,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                if (version == null)
                {
                    // Write out a helpful message before the http messages are shown
                    Console.Log(LogLevel.Minimal, string.Format(
                                    CultureInfo.CurrentCulture,
                                    LocalizedResourceManager.GetString("InstallPackageMessage"), packageId, installPath));

                    // Find the latest version using NuGetPackageManager
                    var resolvePackage = await NuGetPackageManager.GetLatestVersionAsync(
                        packageId,
                        project,
                        resolutionContext,
                        primaryRepositories,
                        Console,
                        CancellationToken.None);

                    if (resolvePackage == null || resolvePackage.LatestVersion == null)
                    {
                        var message = string.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("InstallCommandUnableToFindPackage"),
                            packageId);

                        throw new CommandLineException(message);
                    }

                    version = resolvePackage.LatestVersion;
                }

                // Get a list of packages already in the folder.
                var installedPackages = await project.GetFolderPackagesAsync(CancellationToken.None);

                // Find existing versions of the package
                var alreadyInstalledVersions = new HashSet <NuGetVersion>(installedPackages
                                                                          .Where(e => StringComparer.OrdinalIgnoreCase.Equals(packageId, e.PackageIdentity.Id))
                                                                          .Select(e => e.PackageIdentity.Version));

                var packageIdentity = new PackageIdentity(packageId, version);

                // Check if the package already exists or a higher version exists already.
                var skipInstall = project.PackageExists(packageIdentity);

                // For SxS allow other versions to install. For non-SxS skip if a higher version exists.
                skipInstall |= (ExcludeVersion && alreadyInstalledVersions.Any(e => e >= version));

                if (skipInstall)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"),
                        packageIdentity);

                    Console.LogMinimal(message);
                }
                else
                {
                    var signedPackageVerifier = new PackageSignatureVerifier(
                        SignatureVerificationProviderFactory.GetSignatureVerificationProviders(),
                        SignedPackageVerifierSettings.Default);

                    var projectContext = new ConsoleProjectContext(Console)
                    {
                        PackageExtractionContext = new PackageExtractionContext(
                            Packaging.PackageSaveMode.Defaultv2,
                            PackageExtractionBehavior.XmlDocFileSaveMode,
                            Console,
                            signedPackageVerifier)
                    };

                    if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
                    {
                        projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
                    }

                    resolutionContext.SourceCacheContext.NoCache        = NoCache;
                    resolutionContext.SourceCacheContext.DirectDownload = DirectDownload;

                    var downloadContext = new PackageDownloadContext(resolutionContext.SourceCacheContext, installPath, DirectDownload);

                    await packageManager.InstallPackageAsync(
                        project,
                        packageIdentity,
                        resolutionContext,
                        projectContext,
                        downloadContext,
                        primaryRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

                    if (downloadContext.DirectDownload)
                    {
                        GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                    }
                }
            }
        }
コード例 #3
0
        public override void ExecuteCommand()
        {
            var    manifest    = new CoreV2.NuGet.Manifest();
            string projectFile = null;
            string fileName    = null;

            if (!String.IsNullOrEmpty(AssemblyPath))
            {
                // Extract metadata from the assembly
                string           path     = Path.Combine(CurrentDirectory, AssemblyPath);
                AssemblyMetadata metadata = AssemblyMetadataExtractor.GetMetadata(path);
                manifest.Metadata.Id          = metadata.Name;
                manifest.Metadata.Version     = metadata.Version.ToString();
                manifest.Metadata.Authors     = metadata.Company;
                manifest.Metadata.Description = metadata.Description;
            }
            else
            {
                if (!ProjectHelper.TryGetProjectFile(CurrentDirectory, out projectFile))
                {
                    manifest.Metadata.Id      = Arguments.Any() ? Arguments[0] : "Package";
                    manifest.Metadata.Version = "1.0.0";
                }
                else
                {
                    fileName                      = Path.GetFileNameWithoutExtension(projectFile);
                    manifest.Metadata.Id          = "$id$";
                    manifest.Metadata.Title       = "$title$";
                    manifest.Metadata.Version     = "$version$";
                    manifest.Metadata.Description = "$description$";
                    manifest.Metadata.Authors     = "$author$";
                }
            }

            // Get the file name from the id or the project file
            fileName = fileName ?? manifest.Metadata.Id;

            // If we're using a project file then we want the a minimal nuspec
            if (String.IsNullOrEmpty(projectFile))
            {
                manifest.Metadata.Description = manifest.Metadata.Description ?? SampleDescription;
                if (String.IsNullOrEmpty(manifest.Metadata.Authors))
                {
                    manifest.Metadata.Authors = Environment.UserName;
                }
                manifest.Metadata.DependencySets = new List <CoreV2.NuGet.ManifestDependencySet>();
                manifest.Metadata.DependencySets.Add(new CoreV2.NuGet.ManifestDependencySet
                {
                    Dependencies = new List <CoreV2.NuGet.ManifestDependency> {
                        SampleManifestDependency
                    }
                });
            }

            manifest.Metadata.ProjectUrl   = SampleProjectUrl;
            manifest.Metadata.LicenseUrl   = SampleLicenseUrl;
            manifest.Metadata.IconUrl      = SampleIconUrl;
            manifest.Metadata.Tags         = SampleTags;
            manifest.Metadata.Copyright    = "Copyright " + DateTime.Now.Year;
            manifest.Metadata.ReleaseNotes = SampleReleaseNotes;
            string nuspecFile = fileName + CoreV2.NuGet.Constants.ManifestExtension;

            // Skip the creation if the file exists and force wasn't specified
            if (File.Exists(nuspecFile) && !Force)
            {
                Console.WriteLine(LocalizedResourceManager.GetString("SpecCommandFileExists"), nuspecFile);
            }
            else
            {
                try
                {
                    using (var stream = new MemoryStream())
                    {
                        manifest.Save(stream, validate: false);
                        stream.Seek(0, SeekOrigin.Begin);
                        string content = stream.ReadToEnd();
                        File.WriteAllText(nuspecFile, RemoveSchemaNamespace(content));
                    }

                    Console.WriteLine(LocalizedResourceManager.GetString("SpecCommandCreatedNuSpec"), nuspecFile);
                }
                catch
                {
                    // Cleanup the file if it fails to save for some reason
                    File.Delete(nuspecFile);
                    throw;
                }
            }
        }
コード例 #4
0
        internal async Task UpdateSelfFromVersionAsync(string exePath, bool prerelease, NuGetVersion currentVersion, string source, CancellationToken cancellationToken)
        {
            var sourceCacheContext = new SourceCacheContext();

            _console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCheckingForUpdates"), source);

            var sourceRepository = Repository.Factory.GetCoreV3(source);
            var metadataResource = await sourceRepository.GetResourceAsync <MetadataResource>(cancellationToken);

            var latestVersion = await metadataResource.GetLatestVersion(NuGetCommandLinePackageId, prerelease, includeUnlisted : false, sourceCacheContext, _console, cancellationToken);

            _console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandCurrentlyRunningNuGetExe"), currentVersion);

            // Check to see if an update is needed
            if (latestVersion == null || currentVersion >= latestVersion)
            {
                _console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandNuGetUpToDate"));
            }
            else
            {
                _console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandUpdatingNuGet"), latestVersion);

                var packageIdentity = new PackageIdentity(NuGetCommandLinePackageId, latestVersion);

                var tempDir   = Path.Combine(NuGetEnvironment.GetFolderPath(NuGetFolderPath.Temp), "updateSelf");
                var nupkgPath = FileUtility.GetTempFilePath(tempDir);
                try
                {
                    DirectoryUtility.CreateSharedDirectory(tempDir);

                    DownloadResourceResult downloadResourceResult = await PackageDownloader.GetDownloadResourceResultAsync(
                        sourceRepository,
                        packageIdentity,
                        new PackageDownloadContext(sourceCacheContext),
                        tempDir,
                        _console,
                        cancellationToken);

                    // Get the exe path and move it to a temp file (NuGet.exe.old) so we can replace the running exe with the bits we got
                    // from the package repository
                    IEnumerable <string> packageFiles = await downloadResourceResult.PackageReader.GetFilesAsync(CancellationToken.None);

                    string nugetExeInPackageFilePath = packageFiles.FirstOrDefault(f => Path.GetFileName(f).Equals(NuGetExe, StringComparison.OrdinalIgnoreCase));

                    // If for some reason this package doesn't have NuGet.exe then we don't want to use it
                    if (nugetExeInPackageFilePath == null)
                    {
                        throw new CommandLineException(LocalizedResourceManager.GetString("UpdateCommandUnableToLocateNuGetExe"));
                    }

                    string renamedPath = exePath + ".old";

                    FileUtility.Move(exePath, renamedPath);

                    using (Stream fromStream = await downloadResourceResult.PackageReader.GetStreamAsync(nugetExeInPackageFilePath, cancellationToken), toStream = File.Create(exePath))
                    {
                        fromStream.CopyTo(toStream);
                    }
                }
                finally
                {
                    // Delete the temporary directory
                    try
                    {
                        Directory.Delete(tempDir, recursive: true);
                    }
                    catch
                    {
                    }
                }
            }
            _console.WriteLine(LocalizedResourceManager.GetString("UpdateCommandUpdateSuccessful"));
        }
コード例 #5
0
ファイル: InstallCommand.cs プロジェクト: ruanzb/NuGet.Client
        private async Task PerformV2RestoreAsync(string packagesConfigFilePath, string installPath)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, installPath, ExcludeVersion);

            var installedPackageReferences = GetInstalledPackageReferences(
                packagesConfigFilePath,
                allowDuplicatePackageIds: true);

            var packageRestoreData = installedPackageReferences.Select(reference =>
                                                                       new PackageRestoreData(
                                                                           reference,
                                                                           new[] { packagesConfigFilePath },
                                                                           isMissing: true));

            var packageSources = GetPackageSources(Settings);

            Console.PrintPackageSources(packageSources);

            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: null,
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: packageSources.Select(sourceRepositoryProvider.CreateRepository),
                maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).Any();

            if (!missingPackageReferences)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    packagesConfigFilePath);

                Console.LogMinimal(message);
            }
            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var downloadContext = new PackageDownloadContext(cacheContext, installPath, DirectDownload);

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    new ConsoleProjectContext(Console),
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                // Use failure count to determine errors. result.Restored will be false for noop restores.
                if (failedEvents.Count > 0)
                {
                    // Log errors if they exist
                    foreach (var message in failedEvents.Select(e => new RestoreLogMessage(LogLevel.Error, NuGetLogCode.Undefined, e.Exception.Message)))
                    {
                        await Console.LogAsync(message);
                    }

                    throw new ExitCodeException(1);
                }
            }
        }
コード例 #6
0
        private void EnableOrDisableSource(bool enabled)
        {
            if (String.IsNullOrEmpty(Name))
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNameRequired"));
            }

            var sourceList     = SourceProvider.LoadPackageSources().ToList();
            var existingSource = sourceList.Where(ps => String.Equals(Name, ps.Name, StringComparison.OrdinalIgnoreCase));

            if (!existingSource.Any())
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("SourcesCommandNoMatchingSourcesFound"), Name);
            }

            foreach (var source in existingSource)
            {
                source.IsEnabled = enabled;
            }

            SourceProvider.SavePackageSources(sourceList);
            Console.WriteLine(
                enabled ? LocalizedResourceManager.GetString("SourcesCommandSourceEnabledSuccessfully") : LocalizedResourceManager.GetString("SourcesCommandSourceDisabledSuccessfully"),
                Name);
        }
コード例 #7
0
        private async Task <IReadOnlyList <RestoreSummary> > PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = Path.GetFullPath(GetPackagesFolder(packageRestoreInputs));

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            // EffectivePackageSaveMode is None when -PackageSaveMode is not provided by the user. None is treated as
            // Defaultv3 for V3 restore and should be treated as Defaultv2 for V2 restore. This is the case in the
            // actual V2 restore flow and should match in this preliminary missing packages check.
            var packageSaveMode = EffectivePackageSaveMode == Packaging.PackageSaveMode.None ?
                                  Packaging.PackageSaveMode.Defaultv2 :
                                  EffectivePackageSaveMode;

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);

                var restoreSummaries = new List <RestoreSummary>();

                ValidatePackagesConfigLockFiles(
                    packageRestoreInputs.PackagesConfigFiles,
                    packageRestoreInputs.ProjectReferenceLookup.Projects,
                    packagesFolderPath,
                    restoreSummaries);

                if (restoreSummaries.Count == 0)
                {
                    restoreSummaries.Add(new RestoreSummary(success: true));
                }

                return(restoreSummaries);
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

            var repositories = packageSources
                               .Select(sourceRepositoryProvider.CreateRepository)
                               .ToArray();

            var installCount    = 0;
            var failedEvents    = new ConcurrentQueue <PackageRestoreFailedEventArgs>();
            var collectorLogger = new RestoreCollectorLogger(Console);

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism,
                logger: collectorLogger);

            CheckRequireConsent();

            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, collectorLogger);
            var projectContext      = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(
                    Packaging.PackageSaveMode.Defaultv2,
                    PackageExtractionBehavior.XmlDocFileSaveMode,
                    clientPolicyContext,
                    collectorLogger)
            };

            if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
            {
                projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
            }

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache        = NoCache;
                cacheContext.DirectDownload = DirectDownload;

                var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload)
                {
                    ClientPolicyContext = clientPolicyContext
                };

                var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                    packageRestoreContext,
                    projectContext,
                    downloadContext);

                if (downloadContext.DirectDownload)
                {
                    GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext);
                }

                IReadOnlyList <IRestoreLogMessage> errors = collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToList();
                var restoreSummaries = new List <RestoreSummary>()
                {
                    new RestoreSummary(
                        result.Restored,
                        "packages.config projects",
                        Settings.GetConfigFilePaths().ToList().AsReadOnly(),
                        packageSources.Select(x => x.Source).ToList().AsReadOnly(),
                        installCount,
                        errors)
                };

                if (result.Restored)
                {
                    ValidatePackagesConfigLockFiles(
                        packageRestoreInputs.PackagesConfigFiles,
                        packageRestoreInputs.ProjectReferenceLookup.Projects,
                        packagesFolderPath,
                        restoreSummaries);
                }

                return(restoreSummaries);
            }
        }
コード例 #8
0
        /// <summary>
        /// Returns the msbuild directory. If <paramref name="userVersion"/> is null, then the directory containing
        /// the highest installed msbuild version is returned. Otherwise, the directory containing msbuild
        /// whose version matches <paramref name="userVersion"/> is returned. If no match is found,
        /// an exception will be thrown. Note that we use Microsoft.Build types as
        /// </summary>
        /// <param name="userVersion">version string as passed by user (so may be empty)</param>
        /// <param name="console">The console used to output messages.</param>
        /// <returns>The msbuild directory.</returns>
        public static MsBuildToolset GetMsBuildToolset(string userVersion, IConsole console)
        {
            var            currentDirectoryCache = Directory.GetCurrentDirectory();
            var            installedToolsets     = new List <MsBuildToolset>();
            MsBuildToolset toolset = null;

            try
            {
                // If Mono, test well known paths and bail if found
                toolset = GetMsBuildFromMonoPaths(userVersion);
                if (toolset != null)
                {
                    return(toolset);
                }

                // If the userVersion is not specified, favor the value in the $Path Env variable
                if (string.IsNullOrEmpty(userVersion))
                {
                    var msbuildExe = GetMSBuild(EnvironmentVariableWrapper.Instance);

                    if (msbuildExe != null)
                    {
                        var msBuildDirectory = Path.GetDirectoryName(msbuildExe);
                        var msbuildVersion   = FileVersionInfo.GetVersionInfo(msbuildExe)?.FileVersion;
                        return(toolset = new MsBuildToolset(msbuildVersion, msBuildDirectory));
                    }
                }

                using (var projectCollection = LoadProjectCollection())
                {
                    var installed = ((dynamic)projectCollection)?.Toolsets;
                    if (installed != null)
                    {
                        foreach (var item in installed)
                        {
                            installedToolsets.Add(new MsBuildToolset(version: item.ToolsVersion, path: item.ToolsPath));
                        }

                        installedToolsets = installedToolsets.ToList();
                    }
                }

                // In a non-Mono environment, we have the potential for SxS installs of MSBuild 15.1+. Let's add these here.
                if (!RuntimeEnvironmentHelper.IsMono)
                {
                    var installedSxsToolsets = GetInstalledSxsToolsets();
                    if (installedToolsets == null)
                    {
                        installedToolsets = installedSxsToolsets;
                    }
                    else if (installedSxsToolsets != null)
                    {
                        installedToolsets.AddRange(installedSxsToolsets);
                    }
                }

                if (!installedToolsets.Any())
                {
                    throw new CommandException(
                              LocalizedResourceManager.GetString(
                                  nameof(NuGetResources.Error_CannotFindMsbuild)));
                }

                toolset = GetMsBuildDirectoryInternal(
                    userVersion, console, installedToolsets.OrderByDescending(t => t), (IEnvironmentVariableReader reader) => GetMSBuild(reader));

                Directory.SetCurrentDirectory(currentDirectoryCache);
                return(toolset);
            }
            finally
            {
                LogToolsetToConsole(console, toolset);
            }
        }
コード例 #9
0
        private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable <string> enumerateFiles, IConsole console)
        {
            foreach (var item in enumerateFiles)
            {
                AssemblyCatalog assemblyCatalog = null;
                try
                {
                    assemblyCatalog = new AssemblyCatalog(item);

                    // get the parts - throw if something went wrong
                    var parts = assemblyCatalog.Parts;

                    // load all the types - throw if assembly cannot load (missing dependencies is a good example)
                    var assembly = Assembly.LoadFile(item);
                    assembly.GetTypes();

                    catalog.Catalogs.Add(assemblyCatalog);
                }
                catch (BadImageFormatException ex)
                {
                    if (assemblyCatalog != null)
                    {
                        assemblyCatalog.Dispose();
                    }

                    // Ignore if the dll wasn't a valid assembly
                    console.WriteWarning(ex.Message);
                }
                catch (FileLoadException ex)
                {
                    // Ignore if we couldn't load the assembly.

                    if (assemblyCatalog != null)
                    {
                        assemblyCatalog.Dispose();
                    }

                    var message =
                        String.Format(LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtension)),
                                      item);

                    console.WriteWarning(message);
                    console.WriteWarning(ex.Message);
                }
                catch (ReflectionTypeLoadException rex)
                {
                    // ignore if the assembly is missing dependencies

                    var resource =
                        LocalizedResourceManager.GetString(nameof(NuGetResources.FailedToLoadExtensionDuringMefComposition));

                    var perAssemblyError = string.Empty;

                    if (rex?.LoaderExceptions.Length > 0)
                    {
                        var builder = new StringBuilder();

                        builder.AppendLine(string.Empty);

                        var errors = rex.LoaderExceptions.Select(e => e.Message).Distinct(StringComparer.Ordinal);

                        foreach (var error in errors)
                        {
                            builder.AppendLine(error);
                        }

                        perAssemblyError = builder.ToString();
                    }

                    var warning = string.Format(resource, item, perAssemblyError);

                    console.WriteWarning(warning);
                }
            }
        }
コード例 #10
0
        // This method is called by GetMsbuildDirectory(). This method is not intended to be called directly.
        // It's marked public so that it can be called by unit tests.
        public static string GetMsbuildDirectoryInternal(
            string userVersion,
            IConsole console,
            IEnumerable <MsbuildToolSet> installedToolsets)
        {
            if (string.IsNullOrEmpty(userVersion))
            {
                var msbuildVersion = GetMSBuildVersionInPath();
                var toolset        = SelectMsbuildToolset(msbuildVersion, installedToolsets);

                if (console != null)
                {
                    if (console.Verbosity == Verbosity.Detailed)
                    {
                        console.WriteLine(
                            LocalizedResourceManager.GetString(
                                nameof(NuGetResources.MSBuildAutoDetection_Verbose)),
                            toolset.ToolsVersion,
                            toolset.ToolsPath);
                    }
                    else
                    {
                        console.WriteLine(
                            LocalizedResourceManager.GetString(
                                nameof(NuGetResources.MSBuildAutoDetection)),
                            toolset.ToolsVersion,
                            toolset.ToolsPath);
                    }
                }

                return(toolset.ToolsPath);
            }
            else
            {
                // append ".0" if the userVersion is a number
                string userVersionString = userVersion;
                int    unused;

                if (int.TryParse(userVersion, out unused))
                {
                    userVersionString = userVersion + ".0";
                }

                Version ver;
                bool    hasNumericVersion = Version.TryParse(userVersionString, out ver);

                var selectedToolset = installedToolsets.FirstOrDefault(
                    toolset =>
                {
                    // first match by string comparison
                    if (string.Equals(userVersionString, toolset.ToolsVersion, StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }

                    // then match by Major & Minor version numbers.
                    Version toolsVersion;
                    if (hasNumericVersion && Version.TryParse(toolset.ToolsVersion, out toolsVersion))
                    {
                        return(toolsVersion.Major == ver.Major &&
                               toolsVersion.Minor == ver.Minor);
                    }

                    return(false);
                });

                if (selectedToolset == null)
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString(
                            nameof(NuGetResources.Error_CannotFindMsbuild)),
                        userVersion);

                    throw new CommandLineException(message);
                }

                return(selectedToolset.ToolsPath);
            }
        }
コード例 #11
0
        /// <summary>
        /// Returns the closure of project references for projects specified in <paramref name="projectPaths"/>.
        /// </summary>
        public static MSBuildProjectReferenceProvider GetProjectReferences(
            string msbuildDirectory,
            string[] projectPaths,
            int timeOut)
        {
            string msbuildPath = GetMsbuild(msbuildDirectory);

            if (!File.Exists(msbuildPath))
            {
                throw new CommandLineException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              LocalizedResourceManager.GetString(nameof(NuGetResources.MsBuildDoesNotExistAtPath)),
                              msbuildPath));
            }

            var nugetExePath = Assembly.GetEntryAssembly().Location;

            using (var entryPointTargetPath = new TempFile(".targets"))
                using (var customAfterBuildTargetPath = new TempFile(".targets"))
                    using (var resultsPath = new TempFile(".result"))
                    {
                        ExtractResource(GetProjectReferencesEntryPointTarget, entryPointTargetPath);
                        ExtractResource(GetProjectReferencesTarget, customAfterBuildTargetPath);

                        var argumentBuilder = new StringBuilder(
                            "/t:NuGet_GetProjectsReferencingProjectJson " +
                            "/nologo /nr:false /v:q " +
                            "/p:BuildProjectReferences=false");

                        argumentBuilder.Append(" /p:NuGetTasksAssemblyPath=");
                        AppendQuoted(argumentBuilder, nugetExePath);

                        argumentBuilder.Append(" /p:NuGetCustomAfterBuildTargetPath=");
                        AppendQuoted(argumentBuilder, customAfterBuildTargetPath);

                        argumentBuilder.Append(" /p:ResultsFile=");
                        AppendQuoted(argumentBuilder, resultsPath);

                        bool isMono = RuntimeEnvironmentHelper.IsMono && !RuntimeEnvironmentHelper.IsWindows;

                        // /p: foo = "bar;baz" doesn't work on bash.
                        // /p: foo = /"bar/;baz/" works.
                        // Need to escape quotes and semicolon on bash.
                        if (isMono)
                        {
                            argumentBuilder.Append(" /p:NuGet_ProjectReferenceToResolve=\\\"");
                        }
                        else
                        {
                            argumentBuilder.Append(" /p:NuGet_ProjectReferenceToResolve=\"");
                        }

                        for (var i = 0; i < projectPaths.Length; i++)
                        {
                            if (isMono)
                            {
                                argumentBuilder.Append(projectPaths[i])
                                .Append("\\;");
                            }
                            else
                            {
                                argumentBuilder.Append(projectPaths[i])
                                .Append(";");
                            }
                        }

                        if (isMono)
                        {
                            argumentBuilder.Append("\\\" ");
                        }
                        else
                        {
                            argumentBuilder.Append("\" ");
                        }

                        AppendQuoted(argumentBuilder, entryPointTargetPath);

                        var processStartInfo = new ProcessStartInfo
                        {
                            UseShellExecute       = false,
                            FileName              = msbuildPath,
                            Arguments             = argumentBuilder.ToString(),
                            RedirectStandardError = true
                        };

                        using (var process = Process.Start(processStartInfo))
                        {
                            var finished = process.WaitForExit(timeOut);

                            if (!finished)
                            {
                                try
                                {
                                    process.Kill();
                                }
                                catch (Exception ex)
                                {
                                    throw new CommandLineException(
                                              LocalizedResourceManager.GetString(nameof(NuGetResources.Error_CannotKillMsBuild)) + " : " +
                                              ex.Message,
                                              ex);
                                }

                                throw new CommandLineException(
                                          LocalizedResourceManager.GetString(nameof(NuGetResources.Error_MsBuildTimedOut)));
                            }

                            if (process.ExitCode != 0)
                            {
                                throw new CommandLineException(process.StandardError.ReadToEnd());
                            }
                        }

                        var lines = new string[0];

                        if (File.Exists(resultsPath))
                        {
                            lines = File.ReadAllLines(resultsPath);
                        }

                        return(new MSBuildProjectReferenceProvider(lines));
                    }
        }
コード例 #12
0
        /// <summary>
        /// Returns the msbuild directory. If <paramref name="userVersion"/> is null, then the directory containing
        /// the highest installed msbuild version is returned. Otherwise, the directory containing msbuild
        /// whose version matches <paramref name="userVersion"/> is returned. If no match is found,
        /// an exception will be thrown.
        /// </summary>
        /// <param name="userVersion">The user specified version. Can be null</param>
        /// <param name="console">The console used to output messages.</param>
        /// <returns>The msbuild directory.</returns>
        public static string GetMsbuildDirectory(string userVersion, IConsole console)
        {
            // Try to find msbuild for mono from hard code path.
            // Mono always tell user we are on unix even user is on Mac.
            if (RuntimeEnvironmentHelper.IsMono)
            {
                if (userVersion != null)
                {
                    switch (userVersion)
                    {
                    case "14.1": return(CommandLineConstants.MsbuildPathOnMac14);

                    case "15":
                    case "15.0": return(CommandLineConstants.MsbuildPathOnMac15);
                    }
                }
                else
                {
                    var path = new[] { new MsbuildToolSet("15.0", CommandLineConstants.MsbuildPathOnMac15),
                                       new MsbuildToolSet("14.1", CommandLineConstants.MsbuildPathOnMac14) }
                    .FirstOrDefault(p => Directory.Exists(p.ToolsPath));

                    if (path != null)
                    {
                        if (console != null)
                        {
                            if (console.Verbosity == Verbosity.Detailed)
                            {
                                console.WriteLine(
                                    LocalizedResourceManager.GetString(
                                        nameof(NuGetResources.MSBuildAutoDetection_Verbose)),
                                    path.ToolsVersion,
                                    path.ToolsPath);
                            }
                            else
                            {
                                console.WriteLine(
                                    LocalizedResourceManager.GetString(
                                        nameof(NuGetResources.MSBuildAutoDetection)),
                                    path.ToolsVersion,
                                    path.ToolsPath);
                            }
                        }

                        return(path.ToolsPath);
                    }
                }
            }

            try
            {
                List <MsbuildToolSet> installedToolsets = new List <MsbuildToolSet>();
                var assembly = Assembly.Load(
                    "Microsoft.Build, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                Type projectCollectionType = assembly.GetType(
                    "Microsoft.Build.Evaluation.ProjectCollection",
                    throwOnError: true);
                var projectCollection = Activator.CreateInstance(projectCollectionType) as IDisposable;


                using (projectCollection)
                {
                    var installed = ((dynamic)projectCollection).Toolsets;

                    foreach (dynamic item in installed)
                    {
                        installedToolsets.Add(new MsbuildToolSet(item.ToolsVersion, item.ToolsPath));
                    }

                    installedToolsets = installedToolsets.OrderByDescending(toolset => SafeParseVersion(toolset.ToolsVersion)).ToList();
                }

                return(GetMsbuildDirectoryInternal(userVersion, console, installedToolsets));
            }
            catch (Exception e)
            {
                throw new CommandLineException(LocalizedResourceManager.GetString(
                                                   nameof(NuGetResources.MsbuildLoadToolSetError)), e);
            }
        }
コード例 #13
0
        private static TVal GetPartialOptionMatch <TVal>(IEnumerable <TVal> source, Func <TVal, string> getDisplayName, Func <TVal, string> getAltName, string option, string value)
        {
            var results = from item in source
                          where getDisplayName(item).StartsWith(value, StringComparison.OrdinalIgnoreCase) ||
                          (getAltName(item) ?? String.Empty).StartsWith(value, StringComparison.OrdinalIgnoreCase)
                          select item;
            var result = results.FirstOrDefault();

            if (!results.Any())
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("UnknownOptionError"), option);
            }
            else if (results.Skip(1).Any())
            {
                try
                {
                    // When multiple results are found, if there's an exact match, return it.
                    result = results.First(c => value.Equals(getDisplayName(c), StringComparison.OrdinalIgnoreCase) ||
                                           value.Equals(getAltName(c), StringComparison.OrdinalIgnoreCase));
                }
                catch (InvalidOperationException)
                {
                    throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("AmbiguousOption"), value,
                                                                 String.Join(" ", from c in results select getDisplayName(c))));
                }
            }
            return(result);
        }
コード例 #14
0
        public override void ExecuteCommand()
        {
            string            sampleProjectUrl         = "http://project_url_here_or_delete_this_line/";
            string            sampleIconFile           = "icon.png";
            string            sampleTags               = "Tag1 Tag2";
            string            sampleReleaseNotes       = "Summary of changes made in this release of the package.";
            string            sampleDescription        = "Package description";
            NuGetFramework    sampleTfm                = NuGet.Frameworks.FrameworkConstants.CommonFrameworks.NetStandard21;
            PackageDependency sampleManifestDependency = new PackageDependency("SampleDependency", new VersionRange(new NuGetVersion("1.0.0")));

            var    manifest       = new Manifest(new ManifestMetadata());
            string projectFile    = null;
            string fileName       = null;
            bool   hasProjectFile = false;

            if (!string.IsNullOrEmpty(AssemblyPath))
            {
                // Extract metadata from the assembly
                string           path     = Path.Combine(CurrentDirectory, AssemblyPath);
                AssemblyMetadata metadata = new AssemblyMetadataExtractor(Console).GetMetadata(path);
                manifest.Metadata.Id      = metadata.Name;
                manifest.Metadata.Authors = new List <string>()
                {
                    metadata.Company
                };
                manifest.Metadata.Description = metadata.Description;

                // using InformationalVersion if possible, fallback to Version otherwise
                if (NuGetVersion.TryParse(metadata.InformationalVersion, out var informationalVersion))
                {
                    manifest.Metadata.Version = informationalVersion;
                }
                else
                {
                    Console.LogInformation(string.Format(
                                               CultureInfo.CurrentCulture, NuGetResources.InvalidAssemblyInformationalVersion,
                                               metadata.InformationalVersion, path, metadata.Version));
                    manifest.Metadata.Version = NuGetVersion.Parse(metadata.Version);
                }
            }
            else
            {
                if (!ProjectHelper.TryGetProjectFile(CurrentDirectory, out projectFile))
                {
                    manifest.Metadata.Id      = Arguments.Any() ? Arguments[0] : "Package";
                    manifest.Metadata.Version = NuGetVersion.Parse("1.0.0");
                }
                else
                {
                    hasProjectFile          = true;
                    fileName                = Path.GetFileNameWithoutExtension(projectFile);
                    manifest.Metadata.Id    = "mydummyidhere123123123";
                    manifest.Metadata.Title = "$title$";
                    // This is replaced with `$version$` below.
                    manifest.Metadata.Version     = new NuGetVersion("1.0.0");
                    manifest.Metadata.Description = "$description$";
                    manifest.Metadata.Authors     = new List <string>()
                    {
                        "$author$"
                    };
                }
            }

            // Get the file name from the id or the project file
            fileName = fileName ?? manifest.Metadata.Id;

            // If we're using a project file then we want the a minimal nuspec
            if (string.IsNullOrEmpty(projectFile))
            {
                manifest.Metadata.Description = manifest.Metadata.Description ?? sampleDescription;
                if (!manifest.Metadata.Authors.Any() || string.IsNullOrEmpty(manifest.Metadata.Authors.First()))
                {
                    manifest.Metadata.Authors = new List <string>()
                    {
                        Environment.UserName
                    };
                }
                manifest.Metadata.DependencyGroups = new List <PackageDependencyGroup>()
                {
                    new PackageDependencyGroup(sampleTfm, new List <PackageDependency>()
                    {
                        sampleManifestDependency
                    })
                };
            }

            manifest.Metadata.SetProjectUrl(sampleProjectUrl);
            manifest.Metadata.LicenseMetadata = new LicenseMetadata(LicenseType.Expression, "MIT", NuGetLicenseExpression.Parse("MIT"), Array.Empty <string>(), LicenseMetadata.CurrentVersion);
            manifest.Metadata.Tags            = sampleTags;
            manifest.Metadata.Copyright       = "$copyright$";
            manifest.Metadata.ReleaseNotes    = sampleReleaseNotes;
            string nuspecFile = fileName + PackagingConstants.ManifestExtension;

            // Skip the creation if the file exists and force wasn't specified
            if (File.Exists(nuspecFile) && !Force)
            {
                Console.WriteLine(LocalizedResourceManager.GetString("SpecCommandFileExists"), nuspecFile);
            }
            else
            {
                try
                {
                    using (var stream = new MemoryStream())
                    {
                        manifest.Save(stream, generateBackwardsCompatible: false);
                        stream.Seek(0, SeekOrigin.Begin);
                        string content = stream.ReadToEnd();
                        // We have to replace it here because we can't have
                        // arbitrary string versions in ManifestMetadata
                        if (hasProjectFile)
                        {
                            content = content.Replace("<id>mydummyidhere123123123</id>", "<id>$id$</id>");
                            content = content.Replace("<version>1.0.0</version>", "<version>$version$</version>");
                        }
                        File.WriteAllText(nuspecFile, RemoveSchemaNamespace(AddCommentedIconAttribute(content, sampleIconFile)));
                    }

                    Console.WriteLine(LocalizedResourceManager.GetString("SpecCommandCreatedNuSpec"), nuspecFile);
                }
                catch
                {
                    // Cleanup the file if it fails to save for some reason
                    File.Delete(nuspecFile);
                    throw;
                }
            }
        }
コード例 #15
0
        public override async Task ExecuteCommandAsync()
        {
            CalculateEffectivePackageSaveMode();

            var restoreSummaries = new List <RestoreSummary>();

            _msbuildDirectory = new Lazy <string>(() => MsBuildUtility.GetMsbuildDirectory(MSBuildVersion, Console));

            if (!string.IsNullOrEmpty(PackagesDirectory))
            {
                PackagesDirectory = Path.GetFullPath(PackagesDirectory);
            }

            if (!string.IsNullOrEmpty(SolutionDirectory))
            {
                SolutionDirectory = Path.GetFullPath(SolutionDirectory);
            }

            var restoreInputs = DetermineRestoreInputs();

            var hasPackagesConfigFiles = restoreInputs.PackagesConfigFiles.Count > 0;
            var hasProjectJsonFiles    = restoreInputs.RestoreV3Context.Inputs.Any();

            if (!hasPackagesConfigFiles && !hasProjectJsonFiles)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("RestoreCommandNoPackagesConfigOrProjectJson"));
                throw new CommandLineException(message);
            }

            // packages.config
            if (hasPackagesConfigFiles)
            {
                var v2RestoreResult = await PerformNuGetV2RestoreAsync(restoreInputs);

                restoreSummaries.Add(v2RestoreResult);
            }

            // project.json
            if (hasProjectJsonFiles)
            {
                // Read the settings outside of parallel loops.
                ReadSettings(restoreInputs);

                // Check if we can restore based on the nuget.config settings
                CheckRequireConsent();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = restoreInputs.RestoreV3Context;

                    var providerCache = new RestoreCommandProvidersCache();

                    // Add restore args to the restore context
                    cacheContext.NoCache               = NoCache;
                    restoreContext.CacheContext        = cacheContext;
                    restoreContext.DisableParallel     = DisableParallelProcessing;
                    restoreContext.ConfigFile          = ConfigFile;
                    restoreContext.MachineWideSettings = MachineWideSettings;
                    restoreContext.Sources             = Source.ToList();
                    restoreContext.Log = Console;
                    restoreContext.CachingSourceProvider = GetSourceRepositoryProvider();

                    var packageSaveMode = EffectivePackageSaveMode;
                    if (packageSaveMode != Packaging.PackageSaveMode.None)
                    {
                        restoreContext.PackageSaveMode = EffectivePackageSaveMode;
                    }

                    // Override packages folder
                    var globalPackagesFolder = SettingsUtility.GetGlobalPackagesFolder(Settings);
                    restoreContext.GlobalPackagesFolder = GetEffectiveGlobalPackagesFolder(
                        PackagesDirectory,
                        SolutionDirectory,
                        restoreInputs,
                        globalPackagesFolder);

                    // Providers
                    // Use the settings loaded above in ReadSettings(restoreInputs)
                    restoreContext.RequestProviders.Add(new MSBuildCachedRequestProvider(
                                                            providerCache,
                                                            restoreInputs.ProjectReferenceLookup,
                                                            Settings));

                    restoreContext.RequestProviders.Add(new MSBuildP2PRestoreRequestProvider(providerCache));
                    restoreContext.RequestProviders.Add(new ProjectJsonRestoreRequestProvider(providerCache));

                    // Run restore
                    var v3Summaries = await RestoreRunner.Run(restoreContext);

                    restoreSummaries.AddRange(v3Summaries);
                }
            }

            // Summaries
            RestoreSummary.Log(Console, restoreSummaries);

            if (restoreSummaries.Any(x => !x.Success))
            {
                throw new ExitCodeException(exitCode: 1);
            }
        }
コード例 #16
0
        public static int MainCore(string workingDirectory, string[] args)
        {
            // First, optionally disable localization in resources.
            if (args.Any(arg => string.Equals(arg, ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase)))
            {
                CultureUtility.DisableLocalization();
            }

            // set output encoding to UTF8 if -utf8 is specified
            var oldOutputEncoding = System.Console.OutputEncoding;

            if (args.Any(arg => string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)))
            {
                args = args.Where(arg => !string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)).ToArray();
                SetConsoleOutputEncoding(Encoding.UTF8);
            }

            // Increase the maximum number of connections per server.
            if (!RuntimeEnvironmentHelper.IsMono)
            {
                ServicePointManager.DefaultConnectionLimit = 64;
            }
            else
            {
                // Keep mono limited to a single download to avoid issues.
                ServicePointManager.DefaultConnectionLimit = 1;
            }

            NetworkProtocolUtility.ConfigureSupportedSslProtocols();

            var console         = new Console();
            var fileSystem      = new CoreV2.NuGet.PhysicalFileSystem(workingDirectory);
            var logStackAsError = console.Verbosity == Verbosity.Detailed;

            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;
                command.CurrentDirectory = workingDirectory;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    SetConsoleInteractivity(console, command as Command);
                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                var unwrappedEx = ExceptionUtility.Unwrap(exception);
                if (unwrappedEx is ExitCodeException)
                {
                    // Return the exit code without writing out the exception type
                    var exitCodeEx = unwrappedEx as ExitCodeException;
                    return(exitCodeEx.ExitCode);
                }

                // Log the exception and stack trace.
                ExceptionUtilities.LogException(unwrappedEx, console, logStackAsError);
                return(1);
            }
            catch (Exception exception)
            {
                ExceptionUtilities.LogException(exception, console, logStackAsError);
                return(1);
            }
            finally
            {
                CoreV2.NuGet.OptimizedZipPackage.PurgeCache();
                SetConsoleOutputEncoding(oldOutputEncoding);
            }

            return(0);
        }
コード例 #17
0
        private void PrintRegisteredSourcesDetailed()
        {
            var sourcesList = SourceProvider.LoadPackageSources().ToList();

            if (!sourcesList.Any())
            {
                Console.WriteLine(LocalizedResourceManager.GetString("SourcesCommandNoSources"));
                return;
            }
            Console.PrintJustified(0, LocalizedResourceManager.GetString("SourcesCommandRegisteredSources"));
            Console.WriteLine();
            var sourcePadding = new String(' ', 6);

            for (int i = 0; i < sourcesList.Count; i++)
            {
                var source      = sourcesList[i];
                var indexNumber = i + 1;
                var namePadding = new String(' ', i >= 9 ? 1 : 2);
                Console.WriteLine(
                    "  {0}.{1}{2} [{3}]",
                    indexNumber,
                    namePadding,
                    source.Name,
                    source.IsEnabled ? LocalizedResourceManager.GetString("SourcesCommandEnabled") : LocalizedResourceManager.GetString("SourcesCommandDisabled"));
                Console.WriteLine("{0}{1}", sourcePadding, source.Source);
            }
        }
コード例 #18
0
        public ICommand GetCommand(string commandName)
        {
            if (String.IsNullOrEmpty(commandName))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, commandName);
            }

            IEnumerable <ICommand> results = from command in _commands
                                             where command.CommandAttribute.CommandName.StartsWith(commandName, StringComparison.OrdinalIgnoreCase) ||
                                             (command.CommandAttribute.AltName ?? String.Empty).StartsWith(commandName, StringComparison.OrdinalIgnoreCase)
                                             select command;

            if (!results.Any())
            {
                throw new CommandLineException(LocalizedResourceManager.GetString("UnknowCommandError"), commandName);
            }

            var matchedCommand = results.First();

            if (results.Skip(1).Any())
            {
                // Were there more than one results found?
                matchedCommand = results.FirstOrDefault(c => c.CommandAttribute.CommandName.Equals(commandName, StringComparison.OrdinalIgnoreCase) ||
                                                        commandName.Equals(c.CommandAttribute.AltName, StringComparison.OrdinalIgnoreCase));

                if (matchedCommand == null)
                {
                    // No exact match was found and the result returned multiple prefixes.
                    throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("AmbiguousCommand"), commandName,
                                                                 String.Join(" ", from c in results select c.CommandAttribute.CommandName)));
                }
            }
            return(matchedCommand);
        }
コード例 #19
0
        public override async Task ExecuteCommandAsync()
        {
            if (DisableParallelProcessing)
            {
                HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
            }

            CalculateEffectivePackageSaveMode();

            var restoreSummaries = new List <RestoreSummary>();

            if (!string.IsNullOrEmpty(SolutionDirectory))
            {
                SolutionDirectory = Path.GetFullPath(SolutionDirectory);
            }

            var restoreInputs = await DetermineRestoreInputsAsync();

            var hasPackagesConfigFiles            = restoreInputs.PackagesConfigFiles.Count > 0;
            var hasProjectJsonOrPackageReferences = restoreInputs.RestoreV3Context.Inputs.Any();

            if (!hasPackagesConfigFiles && !hasProjectJsonOrPackageReferences)
            {
                Console.LogMinimal(LocalizedResourceManager.GetString(restoreInputs.RestoringWithSolutionFile
                        ? "SolutionRestoreCommandNoPackagesConfigOrProjectJson"
                        : "ProjectRestoreCommandNoPackagesConfigOrProjectJson"));
                return;
            }

            // packages.config
            if (hasPackagesConfigFiles)
            {
                var v2RestoreResults = await PerformNuGetV2RestoreAsync(restoreInputs);

                restoreSummaries.AddRange(v2RestoreResults);

                foreach (var restoreResult in v2RestoreResults.Where(r => !r.Success))
                {
                    restoreResult
                    .Errors
                    .Where(l => l.Level == LogLevel.Warning)
                    .ForEach(l => Console.LogWarning(l.FormatWithCode()));
                }
            }

            // project.json and PackageReference
            if (hasProjectJsonOrPackageReferences)
            {
                // Read the settings outside of parallel loops.
                ReadSettings(restoreInputs);

                // Check if we can restore based on the nuget.config settings
                CheckRequireConsent();

                using (var cacheContext = new SourceCacheContext())
                {
                    cacheContext.NoCache        = NoCache;
                    cacheContext.DirectDownload = DirectDownload;

                    var restoreContext = restoreInputs.RestoreV3Context;
                    var providerCache  = new RestoreCommandProvidersCache();

                    // Add restore args to the restore context
                    restoreContext.CacheContext        = cacheContext;
                    restoreContext.DisableParallel     = DisableParallelProcessing;
                    restoreContext.AllowNoOp           = !Force; // if force, no-op is not allowed
                    restoreContext.ConfigFile          = ConfigFile;
                    restoreContext.MachineWideSettings = MachineWideSettings;
                    restoreContext.Log = Console;
                    restoreContext.CachingSourceProvider = GetSourceRepositoryProvider();
                    restoreContext.RestoreForceEvaluate  = ForceEvaluate;

                    var packageSaveMode = EffectivePackageSaveMode;
                    if (packageSaveMode != Packaging.PackageSaveMode.None)
                    {
                        restoreContext.PackageSaveMode = EffectivePackageSaveMode;
                    }

                    // Providers
                    // Use the settings loaded above in ReadSettings(restoreInputs)
                    if (restoreInputs.ProjectReferenceLookup.Restore.Count > 0)
                    {
                        // Remove input list, everything has been loaded already
                        restoreContext.Inputs.Clear();

                        restoreContext.PreLoadedRequestProviders.Add(new DependencyGraphSpecRequestProvider(
                                                                         providerCache,
                                                                         restoreInputs.ProjectReferenceLookup));
                    }
                    else
                    {
                        // Allow an external .dg file
                        restoreContext.RequestProviders.Add(new DependencyGraphFileRequestProvider(providerCache));
                    }

                    // Run restore
                    var v3Summaries = await RestoreRunner.RunAsync(restoreContext);

                    restoreSummaries.AddRange(v3Summaries);
                }
            }

            // Summaries
            RestoreSummary.Log(Console, restoreSummaries, logErrors: true);

            if (restoreSummaries.Any(x => !x.Success))
            {
                throw new ExitCodeException(exitCode: 1);
            }
        }
コード例 #20
0
        private async Task UpdatePackagesAsync(MSBuildProjectSystem project, string packagesDirectory)
        {
            var sourceRepositoryProvider = GetSourceRepositoryProvider();
            var packageManager           = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesDirectory);
            var nugetProject             = new MSBuildNuGetProject(project, packagesDirectory, project.ProjectFullPath);

            if (!nugetProject.PackagesConfigNuGetProject.PackagesConfigExists())
            {
                throw new CommandException(LocalizedResourceManager.GetString("NoPackagesConfig"));
            }

            var versionConstraints = Safe ?
                                     VersionConstraints.ExactMajor | VersionConstraints.ExactMinor :
                                     VersionConstraints.None;

            var projectActions = new List <NuGetProjectAction>();

            using (var sourceCacheContext = new SourceCacheContext())
            {
                var dependencyBehavior = DependencyBehaviorHelper.GetDependencyBehavior(DependencyBehavior.Highest, DependencyVersion, Settings);
                var resolutionContext  = new ResolutionContext(
                    dependencyBehavior,
                    Prerelease,
                    includeUnlisted: false,
                    versionConstraints: versionConstraints,
                    gatherCache: new GatherCache(),
                    sourceCacheContext: sourceCacheContext);

                var packageSources = GetPackageSources();

                Console.PrintPackageSources(packageSources);

                var sourceRepositories = packageSources.Select(sourceRepositoryProvider.CreateRepository);
                if (Id.Count > 0)
                {
                    var targetIds = new HashSet <string>(Id, StringComparer.OrdinalIgnoreCase);

                    var installed = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None);

                    // If -Id has been specified and has exactly one package, use the explicit version requested
                    var targetVersion = Version != null && Id != null && Id.Count == 1 ? new NuGetVersion(Version) : null;

                    var targetIdentities = installed
                                           .Select(pr => pr.PackageIdentity.Id)
                                           .Where(id => targetIds.Contains(id))
                                           .Select(id => new PackageIdentity(id, targetVersion))
                                           .ToList();

                    if (targetIdentities.Any())
                    {
                        var actions = await packageManager.PreviewUpdatePackagesAsync(
                            targetIdentities,
                            new[] { nugetProject },
                            resolutionContext,
                            project.NuGetProjectContext,
                            sourceRepositories,
                            Enumerable.Empty <SourceRepository>(),
                            CancellationToken.None);

                        projectActions.AddRange(actions);
                    }
                }
                else
                {
                    var actions = await packageManager.PreviewUpdatePackagesAsync(
                        new[] { nugetProject },
                        resolutionContext,
                        project.NuGetProjectContext,
                        sourceRepositories,
                        Enumerable.Empty <SourceRepository>(),
                        CancellationToken.None);

                    projectActions.AddRange(actions);
                }

                await packageManager.ExecuteNuGetProjectActionsAsync(
                    nugetProject,
                    projectActions,
                    project.NuGetProjectContext,
                    sourceCacheContext,
                    CancellationToken.None);
            }

            project.Save();
        }
コード例 #21
0
        /// <summary>
        /// Determine if a file is v2 or v3
        /// </summary>
        private void GetInputsFromFile(string projectFilePath, PackageRestoreInputs packageRestoreInputs)
        {
            // An argument was passed in. It might be a solution file or directory,
            // project file, or packages.config file
            var projectFileName = Path.GetFileName(projectFilePath);

            if (IsPackagesConfig(projectFileName))
            {
                // restoring from packages.config or packages.projectname.config file
                packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.ProjectFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
            {
                ProcessSolutionFile(projectFilePath, packageRestoreInputs);
            }
            else if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName))
            {
                // project.json is no longer allowed
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("Error_ProjectJsonNotAllowed"), projectFileName));
            }
            else
            {
                // Not a file we know about. Try to be helpful without response.
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName));
            }
        }
コード例 #22
0
        public override void ExecuteCommand()
        {
            PackArgs packArgs = new PackArgs();

            packArgs.Logger          = Console;
            packArgs.Arguments       = Arguments;
            packArgs.OutputDirectory = OutputDirectory;

            // The directory that contains msbuild
            packArgs.MsBuildDirectory = new Lazy <string>(() => MsBuildUtility.GetMsbuildDirectory(MSBuildVersion, Console));

            // Get the input file
            packArgs.Path = PackCommandRunner.GetInputFile(packArgs);

            // Set the current directory if the files being packed are in a different directory
            PackCommandRunner.SetupCurrentDirectory(packArgs);

            Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildPackage"), Path.GetFileName(packArgs.Path));

            // If the BasePath is not specified, use the directory of the input file (nuspec / proj) file
            BasePath = String.IsNullOrEmpty(BasePath) ? Path.GetDirectoryName(Path.GetFullPath(packArgs.Path)) : BasePath;
            BasePath = BasePath.TrimEnd(Path.DirectorySeparatorChar);

            if (!String.IsNullOrEmpty(MinClientVersion))
            {
                if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue))
                {
                    throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidMinClientVersion"));
                }
            }

            packArgs.BasePath = BasePath;
            packArgs.Build    = Build;
            packArgs.Exclude  = Exclude;
            packArgs.ExcludeEmptyDirectories   = ExcludeEmptyDirectories;
            packArgs.IncludeReferencedProjects = IncludeReferencedProjects;
            switch (Verbosity)
            {
            case Verbosity.Detailed:
            {
                packArgs.LogLevel = Common.LogLevel.Verbose;
                break;
            }

            case Verbosity.Normal:
            {
                packArgs.LogLevel = Common.LogLevel.Information;
                break;
            }

            case Verbosity.Quiet:
            {
                packArgs.LogLevel = Common.LogLevel.Minimal;
                break;
            }
            }
            packArgs.MinClientVersion  = _minClientVersionValue;
            packArgs.NoDefaultExcludes = NoDefaultExcludes;
            packArgs.NoPackageAnalysis = NoPackageAnalysis;
            if (Properties.Any())
            {
                packArgs.Properties.AddRange(Properties);
            }
            packArgs.Suffix  = Suffix;
            packArgs.Symbols = Symbols;
            packArgs.Tool    = Tool;

            if (!string.IsNullOrEmpty(Version))
            {
                NuGetVersion version;
                if (!NuGetVersion.TryParse(Version, out version))
                {
                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandPackageReferenceInvalidVersion, Version));
                }
                packArgs.Version = version.ToNormalizedString();
            }

            PackCommandRunner packCommandRunner = new PackCommandRunner(packArgs, ProjectFactory.ProjectCreator);

            packCommandRunner.BuildPackage();
        }
コード例 #23
0
ファイル: PackCommand.cs プロジェクト: tjackprime/NuGet
        public override void ExecuteCommand()
        {
            var packArgs = new PackArgs();

            packArgs.Logger           = Console;
            packArgs.Arguments        = Arguments;
            packArgs.OutputDirectory  = OutputDirectory;
            packArgs.BasePath         = BasePath;
            packArgs.MsBuildDirectory = new Lazy <string>(() => MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console).Value.Path);

            // Get the input file
            packArgs.Path = PackCommandRunner.GetInputFile(packArgs);

            // Set the current directory if the files being packed are in a different directory
            PackCommandRunner.SetupCurrentDirectory(packArgs);

            Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildPackage"), Path.GetFileName(packArgs.Path));

            if (!string.IsNullOrEmpty(MinClientVersion))
            {
                if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue))
                {
                    throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidMinClientVersion"));
                }
            }

            if (!string.IsNullOrEmpty(SymbolPackageFormat))
            {
                packArgs.SymbolPackageFormat = PackArgs.GetSymbolPackageFormat(SymbolPackageFormat);
            }

            packArgs.Build   = Build;
            packArgs.Exclude = Exclude;
            packArgs.ExcludeEmptyDirectories   = ExcludeEmptyDirectories;
            packArgs.IncludeReferencedProjects = IncludeReferencedProjects;
            switch (Verbosity)
            {
            case Verbosity.Detailed:
            {
                packArgs.LogLevel = LogLevel.Verbose;
                break;
            }

            case Verbosity.Normal:
            {
                packArgs.LogLevel = LogLevel.Information;
                break;
            }

            case Verbosity.Quiet:
            {
                packArgs.LogLevel = LogLevel.Minimal;
                break;
            }
            }
            packArgs.MinClientVersion  = _minClientVersionValue;
            packArgs.NoCompression     = NoCompression;
            packArgs.NoDefaultExcludes = NoDefaultExcludes;
            packArgs.NoPackageAnalysis = NoPackageAnalysis;
            if (Properties.Any())
            {
                packArgs.Properties.AddRange(Properties);
            }
            packArgs.Suffix  = Suffix;
            packArgs.Symbols = Symbols;
            packArgs.Tool    = Tool;
            packArgs.InstallPackageToOutputPath    = InstallPackageToOutputPath;
            packArgs.OutputFileNamesWithoutVersion = OutputFileNamesWithoutVersion;

            if (!string.IsNullOrEmpty(Version))
            {
                NuGetVersion version;
                if (!NuGetVersion.TryParse(Version, out version))
                {
                    throw new PackagingException(NuGetLogCode.NU5010, string.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandPackageReferenceInvalidVersion, Version));
                }
                packArgs.Version = version.ToFullString();
            }

            var packCommandRunner = new PackCommandRunner(packArgs, ProjectFactory.ProjectCreator);

            packCommandRunner.BuildPackage();
        }
コード例 #24
0
        private async Task <RestoreSummary> PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs)
        {
            ReadSettings(packageRestoreInputs);
            var packagesFolderPath = GetPackagesFolder(packageRestoreInputs);

            var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider);
            var nuGetPackageManager      = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath);

            var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer());

            if (packageRestoreInputs.RestoringWithSolutionFile)
            {
                installedPackageReferences.AddRange(packageRestoreInputs
                                                    .PackagesConfigFiles
                                                    .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true)));
            }
            else if (packageRestoreInputs.PackagesConfigFiles.Count > 0)
            {
                // By default the PackageReferenceFile does not throw
                // if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1,
                             "Only one packages.config file is allowed to be specified " +
                             "at a time when not performing solution restore.");

                var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0];
                if (!File.Exists(packageReferenceFile))
                {
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        packageReferenceFile);

                    throw new InvalidOperationException(message);
                }

                installedPackageReferences.AddRange(
                    GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true));
            }

            var missingPackageReferences = installedPackageReferences.Where(reference =>
                                                                            !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity)).ToArray();

            if (missingPackageReferences.Length == 0)
            {
                var message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandNothingToInstall"),
                    "packages.config");

                Console.LogMinimal(message);
                return(new RestoreSummary(true));
            }

            var packageRestoreData = missingPackageReferences.Select(reference =>
                                                                     new PackageRestoreData(
                                                                         reference,
                                                                         new[] { packageRestoreInputs.RestoringWithSolutionFile
                                ? packageRestoreInputs.DirectoryOfSolutionFile
                                : packageRestoreInputs.PackagesConfigFiles[0] },
                                                                         isMissing: true));

            var packageSources = GetPackageSources(Settings);

            var repositories = packageSources
                               .Select(sourceRepositoryProvider.CreateRepository)
                               .ToArray();

            var installCount = 0;
            var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>();

            var packageRestoreContext = new PackageRestoreContext(
                nuGetPackageManager,
                packageRestoreData,
                CancellationToken.None,
                packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); },
                packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); },
                sourceRepositories: repositories,
                maxNumberOfParallelTasks: DisableParallelProcessing
                        ? 1
                        : PackageManagementConstants.DefaultMaxDegreeOfParallelism);

            CheckRequireConsent();

            var collectorLogger = new CollectorLogger(Console);
            var projectContext  = new ConsoleProjectContext(collectorLogger)
            {
                PackageExtractionContext = new PackageExtractionContext(collectorLogger)
            };

            if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None)
            {
                projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode;
            }

            var result = await PackageRestoreManager.RestoreMissingPackagesAsync(
                packageRestoreContext,
                projectContext);

            return(new RestoreSummary(
                       result.Restored,
                       "packages.config projects",
                       Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)),
                       packageSources.Select(x => x.Source),
                       installCount,
                       collectorLogger.Errors.Concat(failedEvents.Select(e => e.Exception.Message))));
        }
コード例 #25
0
ファイル: InstallCommand.cs プロジェクト: ruanzb/NuGet.Client
        private DependencyBehavior TryGetDependencyBehavior(string behaviorStr)
        {
            DependencyBehavior dependencyBehavior;

            if (!Enum.TryParse <DependencyBehavior>(behaviorStr, ignoreCase: true, result: out dependencyBehavior) || !Enum.IsDefined(typeof(DependencyBehavior), dependencyBehavior))
            {
                throw new CommandLineException(string.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InstallCommandUnknownDependencyVersion"), behaviorStr));
            }

            return(dependencyBehavior);
        }
コード例 #26
0
        /// <summary>
        /// Discover all restore inputs, this checks for both v2 and v3
        /// </summary>
        private PackageRestoreInputs DetermineRestoreInputs()
        {
            var packageRestoreInputs = new PackageRestoreInputs();

            if (Arguments.Count == 0)
            {
                // If no arguments were provided use the current directory
                GetInputsFromDirectory(Directory.GetCurrentDirectory(), packageRestoreInputs);
            }
            else
            {
                // Restore takes multiple arguments, each could be a file or directory
                var argument = Arguments.Single();
                var fullPath = Path.GetFullPath(argument);

                if (Directory.Exists(fullPath))
                {
                    // Dir
                    GetInputsFromDirectory(fullPath, packageRestoreInputs);
                }
                else if (File.Exists(fullPath))
                {
                    // File
                    GetInputsFromFile(fullPath, packageRestoreInputs);
                }
                else
                {
                    // Not found
                    var message = string.Format(
                        CultureInfo.CurrentCulture,
                        LocalizedResourceManager.GetString("RestoreCommandFileNotFound"),
                        argument);

                    throw new InvalidOperationException(message);
                }
            }

            // Find P2P graph for v3 inputs.
            var projectsWithPotentialP2PReferences = packageRestoreInputs.RestoreV3Context.Inputs
                                                     .Where(MsBuildUtility.IsMsBuildBasedProject)
                                                     .ToArray();

            if (projectsWithPotentialP2PReferences.Length > 0)
            {
                int scaleTimeout;

                if (Project2ProjectTimeOut > 0)
                {
                    scaleTimeout = Project2ProjectTimeOut * 1000;
                }
                else
                {
                    scaleTimeout = MsBuildUtility.MsBuildWaitTime *
                                   Math.Max(10, projectsWithPotentialP2PReferences.Length / 2) / 10;
                }

                Console.LogVerbose($"MSBuild P2P timeout [ms]: {scaleTimeout}");

                // Call MSBuild to resolve P2P references.
                var referencesLookup = MsBuildUtility.GetProjectReferences(
                    _msbuildDirectory.Value,
                    projectsWithPotentialP2PReferences,
                    scaleTimeout);

                packageRestoreInputs.ProjectReferenceLookup = referencesLookup;
            }

            return(packageRestoreInputs);
        }
コード例 #27
0
ファイル: MsBuildUtility.cs プロジェクト: mfyuce/NuGet.Client
        /// <summary>
        /// Returns the closure of project references for projects specified in <paramref name="projectPaths"/>.
        /// </summary>
        public static async Task <DependencyGraphSpec> GetProjectReferencesAsync(
            string msbuildDirectory,
            string[] projectPaths,
            int timeOut,
            IConsole console,
            bool recursive,
            string solutionDirectory,
            string restoreConfigFile,
            string[] sources,
            string packagesDirectory)
        {
            var msbuildPath = GetMsbuild(msbuildDirectory);

            if (!File.Exists(msbuildPath))
            {
                throw new CommandLineException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              LocalizedResourceManager.GetString(nameof(NuGetResources.MsBuildDoesNotExistAtPath)),
                              msbuildPath));
            }

            var nugetExePath = Assembly.GetEntryAssembly().Location;

            // Check for the non-ILMerged path
            var buildTasksPath = Path.Combine(Path.GetDirectoryName(nugetExePath), "NuGet.Build.Tasks.dll");

            if (File.Exists(buildTasksPath))
            {
                nugetExePath = buildTasksPath;
            }

            using (var inputTargetPath = new TempFile(".nugetinputs.targets"))
                using (var entryPointTargetPath = new TempFile(".nugetrestore.targets"))
                    using (var resultsPath = new TempFile(".output.dg"))
                    {
                        // Read NuGet.targets from nuget.exe and write it to disk for msbuild.exe
                        ExtractResource(NuGetTargets, entryPointTargetPath);

                        // Build a .targets file of all restore inputs, this is needed to avoid going over the limit on command line arguments.
                        var properties = new Dictionary <string, string>()
                        {
                            { "RestoreUseCustomAfterTargets", "true" },
                            { "RestoreGraphOutputPath", resultsPath },
                            { "RestoreRecursive", recursive.ToString().ToLowerInvariant() },
                            { "RestoreProjectFilterMode", "exclusionlist" }
                        };

                        var inputTargetXML = GetRestoreInputFile(entryPointTargetPath, properties, projectPaths);

                        inputTargetXML.Save(inputTargetPath);

                        // Create msbuild parameters and include global properties that cannot be set in the input targets path
                        var arguments = GetMSBuildArguments(entryPointTargetPath, inputTargetPath, nugetExePath, solutionDirectory, restoreConfigFile, sources, packagesDirectory);

                        var processStartInfo = new ProcessStartInfo
                        {
                            UseShellExecute        = false,
                            FileName               = msbuildPath,
                            Arguments              = arguments,
                            RedirectStandardError  = true,
                            RedirectStandardOutput = true
                        };

                        console.LogDebug($"{processStartInfo.FileName} {processStartInfo.Arguments}");

                        using (var process = Process.Start(processStartInfo))
                        {
                            var errors   = new StringBuilder();
                            var output   = new StringBuilder();
                            var excluded = new string[] { "msb4011", entryPointTargetPath };

                            // Read console output
                            var errorTask  = ConsumeStreamReaderAsync(process.StandardError, errors, filter: null);
                            var outputTask = ConsumeStreamReaderAsync(process.StandardOutput, output, filter: (line) => IsIgnoredOutput(line, excluded));

                            // Run msbuild
                            var finished = process.WaitForExit(timeOut);

                            // Handle timeouts
                            if (!finished)
                            {
                                try
                                {
                                    process.Kill();
                                }
                                catch (Exception ex)
                                {
                                    throw new CommandLineException(
                                              LocalizedResourceManager.GetString(nameof(NuGetResources.Error_CannotKillMsBuild)) + " : " +
                                              ex.Message,
                                              ex);
                                }
                            }

                            // Read all console output from msbuild.
                            await Task.WhenAll(outputTask, errorTask);

                            // By default log msbuild output so that it is only
                            // displayed under -Verbosity detailed
                            var logLevel = LogLevel.Verbose;

                            if (process.ExitCode != 0 || !finished)
                            {
                                // If a problem occurred log all msbuild output as an error
                                // so that the user can see it.
                                // By default this runs with /v:q which means that only
                                // errors and warnings will be in the output.
                                logLevel = LogLevel.Error;
                            }

                            // MSBuild writes errors to the output stream, parsing the console output to find
                            // the errors would be error prone so here we log all output combined with any
                            // errors on the error stream (haven't seen the error stream used to date)
                            // to give the user the complete info.
                            await console.LogAsync(logLevel, output.ToString() + errors.ToString());

                            if (!finished)
                            {
                                // MSBuild timed out
                                throw new CommandLineException(
                                          LocalizedResourceManager.GetString(nameof(NuGetResources.Error_MsBuildTimedOut)));
                            }

                            await outputTask;

                            if (process.ExitCode != 0)
                            {
                                // Do not continue if msbuild failed.
                                throw new ExitCodeException(1);
                            }
                        }

                        DependencyGraphSpec spec = null;

                        if (File.Exists(resultsPath) && new FileInfo(resultsPath).Length != 0)
                        {
                            spec = DependencyGraphSpec.Load(resultsPath);
                            File.Delete(resultsPath);
                        }
                        else
                        {
                            spec = new DependencyGraphSpec();
                        }

                        return(spec);
                    }
        }
コード例 #28
0
        public static int MainCore(string workingDirectory, string[] args)
        {
            // First, optionally disable localization in resources.
            if (args.Any(arg => string.Equals(arg, ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase)))
            {
                CultureUtility.DisableLocalization();
            }

            // This is to avoid applying weak event pattern usage, which breaks under Mono or restricted environments, e.g. Windows Azure Web Sites.
            EnvironmentUtility.SetRunningFromCommandLine();

            // set output encoding to UTF8 if -utf8 is specified
            var oldOutputEncoding = System.Console.OutputEncoding;

            if (args.Any(arg => string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)))
            {
                args = args.Where(arg => !string.Equals(arg, Utf8Option, StringComparison.OrdinalIgnoreCase)).ToArray();
                SetConsoleOutputEncoding(Encoding.UTF8);
            }

            // Increase the maximum number of connections per server.
            if (!EnvironmentUtility.IsMonoRuntime)
            {
                ServicePointManager.DefaultConnectionLimit = 64;
            }
            else
            {
                // Keep mono limited to a single download to avoid issues.
                ServicePointManager.DefaultConnectionLimit = 1;
            }

            NetworkProtocolUtility.ConfigureSupportedSslProtocols();

            var console    = new Console();
            var fileSystem = new PhysicalFileSystem(workingDirectory);

            Func <Exception, string> getErrorMessage = ExceptionUtilities.DisplayMessage;

            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;
                command.CurrentDirectory = workingDirectory;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    SetConsoleInteractivity(console, command as Command);

                    // When we're detailed, get the whole exception including the stack
                    // This is useful for debugging errors.
                    if (console.Verbosity == Verbosity.Detailed || ExceptionLogger.Instance.ShowStack)
                    {
                        getErrorMessage = e => e.ToString();
                    }

                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
                if (unwrappedEx is ExitCodeException)
                {
                    // Return the exit code without writing out the exception type
                    var exitCodeEx = unwrappedEx as ExitCodeException;
                    return(exitCodeEx.ExitCode);
                }

                console.WriteError(getErrorMessage(exception));
                return(1);
            }
            catch (Exception exception)
            {
                console.WriteError(getErrorMessage(exception));
                return(1);
            }
            finally
            {
                OptimizedZipPackage.PurgeCache();
                SetConsoleOutputEncoding(oldOutputEncoding);
            }

            return(0);
        }