Ejemplo n.º 1
0
        public override async Task ExecuteCommandAsync()
        {
            // update with self as parameter
            if (Self)
            {
                var selfUpdater = new SelfUpdater(repositoryFactory: RepositoryFactory)
                {
                    Console = Console
                };
                selfUpdater.UpdateSelf(Prerelease);
                return;
            }

            string inputFile = GetInputFile();

            if (string.IsNullOrEmpty(inputFile))
            {
                throw new CommandLineException(NuGetResources.InvalidFile);
            }

            _msbuildDirectory = MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console).Value.Path;
            var context = new UpdateConsoleProjectContext(Console, FileConflictAction);

            string inputFileName = Path.GetFileName(inputFile);

            // update with packages.config as parameter
            if (CommandLineUtility.IsValidConfigFileName(inputFileName))
            {
                await UpdatePackagesAsync(inputFile, context);

                return;
            }

            // update with project file as parameter
            if (ProjectHelper.SupportedProjectExtensions.Contains(Path.GetExtension(inputFile) ?? string.Empty))
            {
                if (!File.Exists(inputFile))
                {
                    throw new CommandLineException(NuGetResources.UnableToFindProject, inputFile);
                }

                var projectSystem = new MSBuildProjectSystem(
                    _msbuildDirectory,
                    inputFile,
                    context);
                await UpdatePackagesAsync(projectSystem, GetRepositoryPath(projectSystem.ProjectFullPath));

                return;
            }

            if (!File.Exists(inputFile))
            {
                throw new CommandLineException(NuGetResources.UnableToFindSolution, inputFile);
            }

            // update with solution as parameter
            string solutionDir = Path.GetDirectoryName(inputFile);

            await UpdateAllPackages(solutionDir, context);
        }
Ejemplo n.º 2
0
        private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs)
        {
            restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath);
            restoreInputs.NameOfSolutionFile      = Path.GetFileNameWithoutExtension(solutionFileFullPath);

            // restore packages for the solution
            var solutionLevelPackagesConfig = Path.Combine(
                restoreInputs.DirectoryOfSolutionFile,
                NuGetConstants.NuGetSolutionSettingsFolder,
                Constants.PackageReferenceFile);

            if (File.Exists(solutionLevelPackagesConfig))
            {
                restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig);
            }

            var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, MsBuildDirectory.Value.Path);

            foreach (var projectFile in projectFiles)
            {
                if (!File.Exists(projectFile))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"),
                                                projectFile);
                    Console.LogWarning(message);
                    continue;
                }

                var normalizedProjectFile = Path.GetFullPath(projectFile);

                // Add everything
                restoreInputs.ProjectFiles.Add(normalizedProjectFile);
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        ///  Create a dg v2 file using msbuild.
        /// </summary>
        private async Task <DependencyGraphSpec> GetDependencyGraphSpecAsync(string[] projectsWithPotentialP2PReferences, string solutionDirectory, string configFile)
        {
            // Create requests based on the solution directory if a solution was used read settings for the solution.
            // If the solution directory is null, then use config file if present
            // Then use restore directory last
            // If all 3 are null, then the directory of the project will be used to evaluate the settings

            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.
            return(await MsBuildUtility.GetProjectReferencesAsync(
                       _msbuildDirectory.Value,
                       projectsWithPotentialP2PReferences,
                       scaleTimeout,
                       Console,
                       Recursive,
                       solutionDirectory,
                       configFile,
                       Source.ToArray(),
                       PackagesDirectory
                       ));
        }
        /// <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, project.json, or packages.config file
            var projectFileName = Path.GetFileName(projectFilePath);

            if (ProjectJsonPathUtilities.IsProjectConfig(projectFileName))
            {
                // project.json or projName.project.json
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (IsPackagesConfig(projectFileName))
            {
                // restoring from packages.config or packages.projectname.config file
                packageRestoreInputs.PackagesConfigFiles.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith("proj", StringComparison.OrdinalIgnoreCase))
            {
                // For msbuild files find the project.json or packages.config file,
                // if neither exist skip it
                var projectName = Path.GetFileNameWithoutExtension(projectFileName);
                var dir         = Path.GetDirectoryName(projectFilePath);

                var projectJsonPath    = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName);
                var packagesConfigPath = GetPackageReferenceFile(projectFilePath);

                // Check for project.json
                if (File.Exists(projectJsonPath))
                {
                    if (MsBuildUtility.IsMsBuildBasedProject(projectFilePath))
                    {
                        // Add the project file path if it allows p2ps
                        packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
                    }
                    else
                    {
                        // Unknown project type, add the project.json by itself
                        packageRestoreInputs.RestoreV3Context.Inputs.Add(projectJsonPath);
                    }
                }
                else if (File.Exists(packagesConfigPath))
                {
                    // Check for packages.config, if it exists add it directly
                    packageRestoreInputs.PackagesConfigFiles.Add(packagesConfigPath);
                }
            }
            else if (projectFileName.EndsWith(".dg", StringComparison.OrdinalIgnoreCase))
            {
                packageRestoreInputs.RestoreV3Context.Inputs.Add(projectFilePath);
            }
            else if (projectFileName.EndsWith(".sln", StringComparison.OrdinalIgnoreCase))
            {
                ProcessSolutionFile(projectFilePath, packageRestoreInputs);
            }
            else
            {
                // Not a file we know about. Try to be helpful without response.
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, RestoreRunner.GetInvalidInputErrorMessage(projectFileName), projectFileName));
            }
        }
Ejemplo n.º 5
0
        private void ProcessSolutionFile(string solutionFileFullPath, PackageRestoreInputs restoreInputs)
        {
            restoreInputs.DirectoryOfSolutionFile = Path.GetDirectoryName(solutionFileFullPath);

            // restore packages for the solution
            var solutionLevelPackagesConfig = Path.Combine(
                restoreInputs.DirectoryOfSolutionFile,
                NuGetConstants.NuGetSolutionSettingsFolder,
                Constants.PackageReferenceFile);

            if (File.Exists(solutionLevelPackagesConfig))
            {
                restoreInputs.PackagesConfigFiles.Add(solutionLevelPackagesConfig);
            }

            var projectFiles = MsBuildUtility.GetAllProjectFileNames(solutionFileFullPath, _msbuildDirectory.Value);

            foreach (var projectFile in projectFiles)
            {
                if (!File.Exists(projectFile))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"),
                                                projectFile);
                    Console.LogWarning(message);
                    continue;
                }

                var normalizedProjectFile = Path.GetFullPath(projectFile);

                // packages.config
                var packagesConfigFilePath = GetPackageReferenceFile(normalizedProjectFile);

                // project.json
                var dir             = Path.GetDirectoryName(normalizedProjectFile);
                var projectName     = Path.GetFileNameWithoutExtension(normalizedProjectFile);
                var projectJsonPath = ProjectJsonPathUtilities.GetProjectConfigPath(dir, projectName);

                // project.json overrides packages.config
                if (File.Exists(projectJsonPath))
                {
                    // project.json inputs are resolved again against the p2p file
                    // and are matched with the solution there
                    // For known msbuild project types use the project
                    if (MsBuildUtility.IsMsBuildBasedProject(normalizedProjectFile))
                    {
                        restoreInputs.RestoreV3Context.Inputs.Add(normalizedProjectFile);
                    }
                    else
                    {
                        // For unknown types restore the project.json file without p2ps
                        restoreInputs.RestoreV3Context.Inputs.Add(projectJsonPath);
                    }
                }
                else if (File.Exists(packagesConfigFilePath))
                {
                    restoreInputs.PackagesConfigFiles.Add(packagesConfigFilePath);
                }
            }
        }
Ejemplo n.º 6
0
        public void ProjectFactoryInitializesPropertiesForPreprocessor()
        {
            // arrange
            const string inputSpec = @"<?xml version=""1.0""?>
<package>
    <metadata>
        <id>$id$</id>
        <version>$version$</version>
        <description>$description$</description>
        <authors>$author$</authors>
        <copyright>$copyright$</copyright>
        <licenseUrl>https://aka.ms/nugetlicense</licenseUrl>
        <projectUrl>https://aka.ms/nugetprj</projectUrl>
        <tags>nuget</tags>
    </metadata>
</package>";
            var          metadata  = new ManifestMetadata
            {
                Id          = "ProjectFactoryTest",
                Version     = NuGetVersion.Parse("2.0.30619.9000"),
                Title       = "NuGet.Test",
                Description = "",
                Copyright   = "\x00a9 Outercurve. All rights reserved.",
                Authors     = new[] { "Outercurve Foundation" },
            };
            var projectMock      = new Mock <MockProject>();
            var msbuildDirectory = MsBuildUtility.GetMsBuildToolset(null, null).Path;
            var factory          = new ProjectFactory(msbuildDirectory, projectMock.Object);

            // act
            var author = factory.InitializeProperties(metadata);
            var actual = Preprocessor.Process(inputSpec.AsStream(), (e) => factory.GetPropertyValue(e));

            // assert
            Assert.Equal("Outercurve Foundation", author);

            var xdoc = XDocument.Load(new StringReader(actual));

            Assert.Equal(metadata.Id, xdoc.XPathSelectElement("/package/metadata/id").Value);
            Assert.Equal(metadata.Version.ToString(), xdoc.XPathSelectElement("/package/metadata/version").Value);
            Assert.Equal(metadata.Description, xdoc.XPathSelectElement("/package/metadata/description").Value);
            Assert.Equal(string.Join(",", metadata.Authors), xdoc.XPathSelectElement("/package/metadata/authors").Value);
            Assert.Equal(metadata.Copyright, xdoc.XPathSelectElement("/package/metadata/copyright").Value);
        }
Ejemplo n.º 7
0
        /// <summary>
        ///  Create a dg v2 file using msbuild.
        /// </summary>
        private async Task <DependencyGraphSpec> GetDependencyGraphSpecAsync(string[] projectsWithPotentialP2PReferences)
        {
            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.
            return(await MsBuildUtility.GetProjectReferencesAsync(
                       _msbuildDirectory.Value,
                       projectsWithPotentialP2PReferences,
                       scaleTimeout,
                       Console,
                       Recursive));
        }
Ejemplo n.º 8
0
        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);

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

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

            // 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.Deterministic             = Deterministic;
            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.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();
        }
Ejemplo n.º 9
0
        public override async Task ExecuteCommandAsync()
        {
            if (DisableParallelProcessing)
            {
                HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
            }

            CalculateEffectivePackageSaveMode();

            var restoreSummaries = new List <RestoreSummary>();

            _msbuildDirectory = MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console);

            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 v2RestoreResult = await PerformNuGetV2RestoreAsync(restoreInputs);

                restoreSummaries.Add(v2RestoreResult);
            }

            // 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();

                    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);
            }
        }
Ejemplo n.º 10
0
        public override async Task ExecuteCommandAsync()
        {
            // update with self as parameter
            if (Self)
            {
                var selfUpdater = new SelfUpdater(repositoryFactory: RepositoryFactory)
                {
                    Console = Console
                };
                selfUpdater.UpdateSelf(Prerelease);
                return;
            }

            string inputFile = GetInputFile();

            if (string.IsNullOrEmpty(inputFile))
            {
                throw new CommandLineException(NuGetResources.InvalidFile);
            }

            _msbuildDirectory = MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console).Value.Path;
            var context = new UpdateConsoleProjectContext(Console, FileConflictAction);

            var logger = new LoggerAdapter(context);
            var signedPackageVerifier         = new PackageSignatureVerifier(SignatureVerificationProviderFactory.GetSignatureVerificationProviders());
            var signedPackageVerifierSettings = SignedPackageVerifierSettings.GetClientPolicy(Settings, logger);

            context.PackageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Defaultv2,
                PackageExtractionBehavior.XmlDocFileSaveMode,
                logger,
                signedPackageVerifier,
                signedPackageVerifierSettings);

            string inputFileName = Path.GetFileName(inputFile);

            // update with packages.config as parameter
            if (CommandLineUtility.IsValidConfigFileName(inputFileName))
            {
                await UpdatePackagesAsync(inputFile, context);

                return;
            }

            // update with project file as parameter
            if (ProjectHelper.SupportedProjectExtensions.Contains(Path.GetExtension(inputFile) ?? string.Empty))
            {
                if (!File.Exists(inputFile))
                {
                    throw new CommandLineException(NuGetResources.UnableToFindProject, inputFile);
                }

                var projectSystem = new MSBuildProjectSystem(
                    _msbuildDirectory,
                    inputFile,
                    context);
                await UpdatePackagesAsync(projectSystem, GetRepositoryPath(projectSystem.ProjectFullPath));

                return;
            }

            if (!File.Exists(inputFile))
            {
                throw new CommandLineException(NuGetResources.UnableToFindSolution, inputFile);
            }

            // update with solution as parameter
            string solutionDir = Path.GetDirectoryName(inputFile);

            await UpdateAllPackages(solutionDir, context);
        }
Ejemplo n.º 11
0
        public int Main(string[] args)
        {
#if DEBUG
            if (args.Contains("--debug"))
            {
                args = args.Skip(1).ToArray();
                System.Diagnostics.Debugger.Launch();
            }
#endif

            // Set up logging
            _log = new CommandOutputLogger();

            var app = new CommandLineApplication();
            app.Name     = "nuget3";
            app.FullName = ".NET Package Manager";
            app.HelpOption("-h|--help");
            app.VersionOption("--version", GetType().GetTypeInfo().Assembly.GetName().Version.ToString());

            app.Command("restore", restore =>
            {
                restore.Description = "Restores packages for a project and writes a lock file";

                var sources           = restore.Option("-s|--source <source>", "Specifies a NuGet package source to use during the restore", CommandOptionType.MultipleValue);
                var packagesDirectory = restore.Option("--packages <packagesDirectory>", "Directory to install packages in", CommandOptionType.SingleValue);
                var parallel          = restore.Option("-p|--parallel <noneOrNumberOfParallelTasks>", $"The number of concurrent tasks to use when restoring. Defaults to {RestoreRequest.DefaultDegreeOfConcurrency}; pass 'none' to run without concurrency.", CommandOptionType.SingleValue);
                var projectFile       = restore.Argument("[project file]", "The path to the project to restore for, either a project.json or the directory containing it. Defaults to the current directory");

                restore.OnExecute(async() =>
                {
                    // Figure out the project directory
                    IEnumerable <string> externalProjects = null;

                    PackageSpec project;
                    var projectPath = Path.GetFullPath(projectFile.Value ?? ".");
                    if (string.Equals(PackageSpec.PackageSpecFileName, Path.GetFileName(projectPath), StringComparison.OrdinalIgnoreCase))
                    {
                        _log.LogVerbose($"Reading project file {projectFile.Value}");
                        projectPath = Path.GetDirectoryName(projectPath);
                        project     = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(projectFile.Value), Path.GetFileName(projectPath), projectFile.Value);
                    }
                    else if (MsBuildUtility.IsMsBuildBasedProject(projectPath))
                    {
#if DNXCORE50
                        throw new NotSupportedException();
#else
                        externalProjects = MsBuildUtility.GetProjectReferences(projectPath);

                        projectPath         = Path.GetDirectoryName(Path.GetFullPath(projectPath));
                        var packageSpecFile = Path.Combine(projectPath, PackageSpec.PackageSpecFileName);
                        project             = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(packageSpecFile), Path.GetFileName(projectPath), projectFile.Value);
                        _log.LogVerbose($"Reading project file {projectFile.Value}");
#endif
                    }
                    else
                    {
                        var file = Path.Combine(projectPath, PackageSpec.PackageSpecFileName);

                        _log.LogVerbose($"Reading project file {file}");
                        project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(file), Path.GetFileName(projectPath), file);
                    }
                    _log.LogVerbose($"Loaded project {project.Name} from {project.FilePath}");

                    // Resolve the root directory
                    var rootDirectory = PackageSpecResolver.ResolveRootDirectory(projectPath);
                    _log.LogVerbose($"Found project root directory: {rootDirectory}");

                    // Resolve the packages directory
                    var packagesDir = packagesDirectory.HasValue() ?
                                      packagesDirectory.Value() :
                                      Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), ".nuget", "packages");
                    _log.LogVerbose($"Using packages directory: {packagesDir}");

                    var packageSources = sources.Values.Select(s => new PackageSource(s));
                    if (!packageSources.Any())
                    {
                        var settings = Settings.LoadDefaultSettings(projectPath,
                                                                    configFileName: null,
                                                                    machineWideSettings: null);
                        var packageSourceProvider = new PackageSourceProvider(settings);
                        packageSources            = packageSourceProvider.LoadPackageSources();
                    }

                    var request = new RestoreRequest(
                        project,
                        packageSources,
                        packagesDir);

                    if (externalProjects != null)
                    {
                        foreach (var externalReference in externalProjects)
                        {
                            request.ExternalProjects.Add(
                                new ExternalProjectReference(
                                    externalReference,
                                    Path.Combine(Path.GetDirectoryName(externalReference), PackageSpec.PackageSpecFileName),
                                    projectReferences: Enumerable.Empty <string>()));
                        }
                    }


                    // Run the restore
                    if (parallel.HasValue())
                    {
                        int parallelDegree;
                        if (string.Equals(parallel.Value(), "none", StringComparison.OrdinalIgnoreCase))
                        {
                            request.MaxDegreeOfConcurrency = 1;
                        }
                        else if (int.TryParse(parallel.Value(), out parallelDegree))
                        {
                            request.MaxDegreeOfConcurrency = parallelDegree;
                        }
                    }
                    if (request.MaxDegreeOfConcurrency <= 1)
                    {
                        _log.LogInformation("Running non-parallel restore");
                    }
                    else
                    {
                        _log.LogInformation($"Running restore with {request.MaxDegreeOfConcurrency} concurrent jobs");
                    }
                    var command = new RestoreCommand(_log);
                    var sw      = Stopwatch.StartNew();
                    var result  = await command.ExecuteAsync(request);
                    sw.Stop();

                    _log.LogInformation($"Restore completed in {sw.ElapsedMilliseconds:0.00}ms!");

                    return(0);
                });
            });

            app.Command("diag", diag =>
            {
                diag.Description = "Diagnostic commands for debugging package dependency graphs";
                diag.Command("lockfile", lockfile =>
                {
                    lockfile.Description = "Dumps data from the project lock file";

                    var project = lockfile.Option("--project <project>", "Path containing the project lockfile, or the patht to the lockfile itself", CommandOptionType.SingleValue);
                    var target  = lockfile.Option("--target <target>", "View information about a specific project target", CommandOptionType.SingleValue);
                    var library = lockfile.Argument("<library>", "Optionally, get detailed information about a specific library");

                    lockfile.OnExecute(() =>
                    {
                        var diagnostics = new DiagnosticCommands(_log);
                        var projectFile = project.HasValue() ? project.Value() : Path.GetFullPath(".");
                        return(diagnostics.Lockfile(projectFile, target.Value(), library.Value));
                    });
                });
                diag.OnExecute(() =>
                {
                    diag.ShowHelp();
                    return(0);
                });
            });

            app.OnExecute(() =>
            {
                app.ShowHelp();
                return(0);
            });

            return(app.Execute(args));
        }
        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);
            }
        }
        /// <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);
        }
Ejemplo n.º 14
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();
        }