Пример #1
0
 private void AddRemoteProvidersFromSources(List <IWalkProvider> remoteProviders, List <PackageSource> effectiveSources)
 {
     foreach (var source in effectiveSources)
     {
         var feed = PackageSourceUtils.CreatePackageFeed(source, NoCache, IgnoreFailedSources, Reports);
         if (feed != null)
         {
             remoteProviders.Add(new RemoteWalkProvider(feed));
         }
     }
 }
Пример #2
0
 private void AddRemoteProvidersFromSources(List <IWalkProvider> remoteProviders, List <PackageSource> effectiveSources)
 {
     foreach (var source in effectiveSources)
     {
         var feed = PackageSourceUtils.CreatePackageFeed(
             source,
             FeedOptions.NoCache,
             FeedOptions.IgnoreFailedSources,
             Reports);
         if (feed != null)
         {
             remoteProviders.Add(new RemoteWalkProvider(feed));
             var list = InformationMessages.GetOrAdd("Feeds used:", _ => new List <string>());
             if (!list.Contains(feed.Source))
             {
                 list.Add(feed.Source);
             }
         }
     }
 }
Пример #3
0
        private async Task <bool> RestoreForProject(string projectJsonPath, string rootDirectory, string packagesDirectory)
        {
            var success = true;

            Reports.Information.WriteLine(string.Format("Restoring packages for {0}", projectJsonPath.Bold()));

            var sw = new Stopwatch();

            sw.Start();

            var projectFolder       = Path.GetDirectoryName(projectJsonPath);
            var projectLockFilePath = Path.Combine(projectFolder, LockFileFormat.LockFileName);

            Runtime.Project project;
            if (!Runtime.Project.TryGetProject(projectJsonPath, out project))
            {
                throw new Exception("TODO: project.json parse error");
            }

            var lockFile = await ReadLockFile(projectLockFilePath);

            var useLockFile = false;

            if (Lock == false &&
                Unlock == false &&
                lockFile != null &&
                lockFile.Islocked)
            {
                useLockFile = true;
            }

            if (useLockFile && !lockFile.IsValidForProject(project))
            {
                // Exhibit the same behavior as if it has been run with "dnu restore --lock"
                Reports.Information.WriteLine("Updating the invalid lock file with {0}",
                                              "dnu restore --lock".Yellow().Bold());
                useLockFile = false;
                Lock        = true;
            }

            Func <string, string> getVariable = key =>
            {
                return(null);
            };

            if (!ScriptExecutor.Execute(project, "prerestore", getVariable))
            {
                ErrorMessages.GetOrAdd("prerestore", _ => new List <string>()).Add(ScriptExecutor.ErrorMessage);
                Reports.Error.WriteLine(ScriptExecutor.ErrorMessage);
                return(false);
            }

            var projectDirectory  = project.ProjectDirectory;
            var projectResolver   = new ProjectResolver(projectDirectory, rootDirectory);
            var packageRepository = new PackageRepository(packagesDirectory);
            var restoreOperations = new RestoreOperations(Reports.Verbose);
            var projectProviders  = new List <IWalkProvider>();
            var localProviders    = new List <IWalkProvider>();
            var remoteProviders   = new List <IWalkProvider>();
            var contexts          = new List <RestoreContext>();

            projectProviders.Add(
                new LocalWalkProvider(
                    new ProjectReferenceDependencyProvider(
                        projectResolver)));

            localProviders.Add(
                new LocalWalkProvider(
                    new NuGetDependencyResolver(packageRepository)));

            var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(
                SourceProvider,
                FeedOptions.Sources,
                FeedOptions.FallbackSources);

            AddRemoteProvidersFromSources(remoteProviders, effectiveSources);

            var tasks = new List <Task <GraphNode> >();

            if (useLockFile)
            {
                Reports.Information.WriteLine(string.Format("Following lock file {0}", projectLockFilePath.White().Bold()));

                var context = new RestoreContext
                {
                    FrameworkName           = ApplicationEnvironment.RuntimeFramework,
                    ProjectLibraryProviders = projectProviders,
                    LocalLibraryProviders   = localProviders,
                    RemoteLibraryProviders  = remoteProviders,
                };

                contexts.Add(context);

                foreach (var lockFileLibrary in lockFile.Libraries)
                {
                    var projectLibrary = new LibraryRange
                    {
                        Name         = lockFileLibrary.Name,
                        VersionRange = new SemanticVersionRange
                        {
                            MinVersion           = lockFileLibrary.Version,
                            MaxVersion           = lockFileLibrary.Version,
                            IsMaxInclusive       = true,
                            VersionFloatBehavior = SemanticVersionFloatBehavior.None,
                        }
                    };
                    tasks.Add(restoreOperations.CreateGraphNode(context, projectLibrary, _ => false));
                }
            }
            else
            {
                foreach (var configuration in project.GetTargetFrameworks())
                {
                    var context = new RestoreContext
                    {
                        FrameworkName           = configuration.FrameworkName,
                        ProjectLibraryProviders = projectProviders,
                        LocalLibraryProviders   = localProviders,
                        RemoteLibraryProviders  = remoteProviders,
                    };
                    contexts.Add(context);
                }

                if (!contexts.Any())
                {
                    contexts.Add(new RestoreContext
                    {
                        FrameworkName           = ApplicationEnvironment.RuntimeFramework,
                        ProjectLibraryProviders = projectProviders,
                        LocalLibraryProviders   = localProviders,
                        RemoteLibraryProviders  = remoteProviders,
                    });
                }

                foreach (var context in contexts)
                {
                    var projectLibrary = new LibraryRange
                    {
                        Name         = project.Name,
                        VersionRange = new SemanticVersionRange(project.Version)
                    };

                    tasks.Add(restoreOperations.CreateGraphNode(context, projectLibrary, _ => true));
                }
            }

            var graphs = await Task.WhenAll(tasks);

            foreach (var graph in graphs)
            {
                Reduce(graph);
            }

            if (!useLockFile)
            {
                var runtimeFormatter   = new RuntimeFileFormatter();
                var projectRuntimeFile = runtimeFormatter.ReadRuntimeFile(projectJsonPath);
                if (projectRuntimeFile.Runtimes.Any())
                {
                    var runtimeTasks = new List <Task <GraphNode> >();

                    foreach (var pair in contexts.Zip(graphs, (context, graph) => new { context, graph }))
                    {
                        var runtimeFileTasks = new List <Task <RuntimeFile> >();
                        ForEach(pair.graph, node =>
                        {
                            var match = node?.Item?.Match;
                            if (match == null)
                            {
                                return;
                            }
                            runtimeFileTasks.Add(match.Provider.GetRuntimes(node.Item.Match, pair.context.FrameworkName));
                        });

                        var libraryRuntimeFiles = await Task.WhenAll(runtimeFileTasks);

                        var runtimeFiles = new List <RuntimeFile> {
                            projectRuntimeFile
                        };
                        runtimeFiles.AddRange(libraryRuntimeFiles.Where(file => file != null));

                        foreach (var runtimeName in projectRuntimeFile.Runtimes.Keys)
                        {
                            var runtimeSpecs = new List <RuntimeSpec>();
                            FindRuntimeSpecs(
                                runtimeName,
                                runtimeFiles,
                                runtimeSpecs,
                                _ => false);

                            var runtimeContext = new RestoreContext
                            {
                                FrameworkName           = pair.context.FrameworkName,
                                ProjectLibraryProviders = pair.context.ProjectLibraryProviders,
                                LocalLibraryProviders   = pair.context.LocalLibraryProviders,
                                RemoteLibraryProviders  = pair.context.RemoteLibraryProviders,
                                RuntimeName             = runtimeName,
                                RuntimeSpecs            = runtimeSpecs
                            };
                            var projectLibrary = new LibraryRange
                            {
                                Name         = project.Name,
                                VersionRange = new SemanticVersionRange(project.Version)
                            };
                            Reports.Information.WriteLine(string.Format("Graph for {0} on {1}", runtimeContext.FrameworkName, runtimeContext.RuntimeName));
                            runtimeTasks.Add(restoreOperations.CreateGraphNode(runtimeContext, projectLibrary, _ => true));
                        }
                    }

                    var runtimeGraphs = await Task.WhenAll(runtimeTasks);

                    foreach (var runtimeGraph in runtimeGraphs)
                    {
                        Reduce(runtimeGraph);
                    }

                    graphs = graphs.Concat(runtimeGraphs).ToArray();
                }
            }

            var graphItems   = new List <GraphItem>();
            var installItems = new List <GraphItem>();
            var missingItems = new HashSet <LibraryRange>();

            ForEach(graphs, node =>
            {
                if (node == null ||
                    node.LibraryRange == null ||
                    node.Disposition == GraphNode.DispositionType.Rejected)
                {
                    return;
                }

                if (node.Item == null || node.Item.Match == null)
                {
                    if (!node.LibraryRange.IsGacOrFrameworkReference &&
                        node.LibraryRange.VersionRange != null &&
                        missingItems.Add(node.LibraryRange))
                    {
                        var errorMessage = string.Format("Unable to locate {0} {1}",
                                                         node.LibraryRange.Name.Red().Bold(),
                                                         node.LibraryRange.VersionRange);
                        ErrorMessages.GetOrAdd(projectJsonPath, _ => new List <string>()).Add(errorMessage);
                        Reports.Error.WriteLine(errorMessage);
                        success = false;
                    }

                    return;
                }

                if (!string.Equals(node.Item.Match.Library.Name, node.LibraryRange.Name, StringComparison.Ordinal))
                {
                    // Fix casing of the library name to be installed
                    node.Item.Match.Library.Name = node.LibraryRange.Name;
                }

                var isRemote      = remoteProviders.Contains(node.Item.Match.Provider);
                var isInstallItem = installItems.Any(item => item.Match.Library == node.Item.Match.Library);

                if (!isInstallItem && isRemote)
                {
                    installItems.Add(node.Item);
                }

                var isGraphItem = graphItems.Any(item => item.Match.Library == node.Item.Match.Library);
                if (!isGraphItem)
                {
                    graphItems.Add(node.Item);
                }
            });

            await InstallPackages(installItems, packagesDirectory, packageFilter : (library, nupkgSHA) => true);

            if (!useLockFile)
            {
                Reports.Information.WriteLine(string.Format("Writing lock file {0}", projectLockFilePath.White().Bold()));

                // Collect target frameworks
                var frameworks = new HashSet <FrameworkName>();
                foreach (var item in graphItems)
                {
                    Runtime.Project dependencyProject;
                    if (projectProviders.Contains(item.Match.Provider) && projectResolver.TryResolveProject(item.Match.Library.Name, out dependencyProject))
                    {
                        frameworks.AddRange(dependencyProject.GetTargetFrameworks().Select(t => t.FrameworkName));
                    }
                }

                WriteLockFile(projectLockFilePath, project, graphItems, new PackageRepository(packagesDirectory), frameworks);
            }

            if (!ScriptExecutor.Execute(project, "postrestore", getVariable))
            {
                ErrorMessages.GetOrAdd("postrestore", _ => new List <string>()).Add(ScriptExecutor.ErrorMessage);
                Reports.Error.WriteLine(ScriptExecutor.ErrorMessage);
                return(false);
            }

            if (!ScriptExecutor.Execute(project, "prepare", getVariable))
            {
                ErrorMessages.GetOrAdd("prepare", _ => new List <string>()).Add(ScriptExecutor.ErrorMessage);
                Reports.Error.WriteLine(ScriptExecutor.ErrorMessage);
                return(false);
            }

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Restore complete".Green().Bold(), sw.ElapsedMilliseconds));

            return(success);
        }
Пример #4
0
        private async Task <bool> RestoreFromGlobalJson(string rootDirectory, string packagesDirectory)
        {
            var success = true;

            Reports.Information.WriteLine(string.Format("Restoring packages for {0}", Path.GetFullPath(GlobalJsonFile).Bold()));

            var sw = new Stopwatch();

            sw.Start();

            var restoreOperations = new RestoreOperations(Reports.Information);
            var localProviders    = new List <IWalkProvider>();
            var remoteProviders   = new List <IWalkProvider>();

            localProviders.Add(
                new LocalWalkProvider(
                    new NuGetDependencyResolver(
                        packagesDirectory)));

            var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(SourceProvider,
                                                                                 Sources, FallbackSources);

            AddRemoteProvidersFromSources(remoteProviders, effectiveSources);

            var context = new RestoreContext
            {
                FrameworkName           = ApplicationEnvironment.RuntimeFramework,
                ProjectLibraryProviders = new List <IWalkProvider>(),
                LocalLibraryProviders   = localProviders,
                RemoteLibraryProviders  = remoteProviders,
            };

            var    dependencies     = new Dictionary <Library, string>();
            JToken dependenciesNode = null;
            var    globalJson       = JObject.Parse(File.ReadAllText(GlobalJsonFile));

            dependenciesNode = globalJson["dependencies"];
            if (dependenciesNode != null)
            {
                dependencies = dependenciesNode
                               .OfType <JProperty>()
                               .ToDictionary(d => new Library()
                {
                    Name    = d.Name,
                    Version = SemanticVersion.Parse(d.Value.Value <string>("version"))
                },
                                             d => d.Value.Value <string>("sha"));
            }

            var libsToRestore = new List <Library>(dependencies.Keys);
            var tasks         = new List <Task <GraphItem> >();

            foreach (var lib in libsToRestore)
            {
                tasks.Add(restoreOperations.FindLibraryCached(context,
                                                              new Library {
                    Name = lib.Name, Version = lib.Version
                }));
            }
            var resolvedItems = await Task.WhenAll(tasks);

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Resolving complete".Green(),
                                                        sw.ElapsedMilliseconds));

            var installItems = new List <GraphItem>();
            var missingItems = new List <Library>();

            for (int i = 0; i < resolvedItems.Length; i++)
            {
                var item = resolvedItems[i];
                var lib  = libsToRestore[i];
                if (item == null || item.Match == null || item.Match.Library.Version != lib.Version)
                {
                    missingItems.Add(lib);
                    Reports.Error.WriteLine(string.Format("Unable to locate {0} {1}",
                                                          lib.Name.Red().Bold(), lib.Version));
                    success = false;
                    continue;
                }
                var isRemote = remoteProviders.Contains(item.Match.Provider);
                var isAdded  = installItems.Any(x => x.Match.Library == item.Match.Library);
                if (!isAdded && isRemote)
                {
                    installItems.Add(item);
                }
            }

            await InstallPackages(installItems, packagesDirectory, packageFilter : (library, nupkgSHA) =>
            {
                string expectedSHA = dependencies[library];
                if (!string.Equals(expectedSHA, nupkgSHA, StringComparison.Ordinal))
                {
                    Reports.Error.WriteLine(
                        string.Format("SHA of downloaded package {0} doesn't match expected value.".Red().Bold(),
                                      library.ToString()));
                    success = false;
                    return(false);
                }
                return(true);
            });

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Restore complete".Green().Bold(), sw.ElapsedMilliseconds));

            return(success);
        }
Пример #5
0
        private async Task <bool> RestoreForProject(string projectJsonPath, string rootDirectory, string packagesDirectory)
        {
            var success = true;

            Reports.Information.WriteLine(string.Format("Restoring packages for {0}", projectJsonPath.Bold()));

            var sw = new Stopwatch();

            sw.Start();

            Runtime.Project project;
            if (!Runtime.Project.TryGetProject(projectJsonPath, out project))
            {
                throw new Exception("TODO: project.json parse error");
            }

            Func <string, string> getVariable = key =>
            {
                return(null);
            };

            ScriptExecutor.Execute(project, "prerestore", getVariable);

            var projectDirectory  = project.ProjectDirectory;
            var restoreOperations = new RestoreOperations(Reports.Verbose);
            var projectProviders  = new List <IWalkProvider>();
            var localProviders    = new List <IWalkProvider>();
            var remoteProviders   = new List <IWalkProvider>();
            var contexts          = new List <RestoreContext>();

            projectProviders.Add(
                new LocalWalkProvider(
                    new ProjectReferenceDependencyProvider(
                        new ProjectResolver(
                            projectDirectory,
                            rootDirectory))));

            localProviders.Add(
                new LocalWalkProvider(
                    new NuGetDependencyResolver(
                        packagesDirectory)));

            var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(SourceProvider,
                                                                                 Sources, FallbackSources);

            AddRemoteProvidersFromSources(remoteProviders, effectiveSources);

            foreach (var configuration in project.GetTargetFrameworks())
            {
                var context = new RestoreContext
                {
                    FrameworkName           = configuration.FrameworkName,
                    ProjectLibraryProviders = projectProviders,
                    LocalLibraryProviders   = localProviders,
                    RemoteLibraryProviders  = remoteProviders,
                };
                contexts.Add(context);
            }
            if (!contexts.Any())
            {
                contexts.Add(new RestoreContext
                {
                    FrameworkName           = ApplicationEnvironment.RuntimeFramework,
                    ProjectLibraryProviders = projectProviders,
                    LocalLibraryProviders   = localProviders,
                    RemoteLibraryProviders  = remoteProviders,
                });
            }

            var tasks = new List <Task <GraphNode> >();

            foreach (var context in contexts)
            {
                tasks.Add(restoreOperations.CreateGraphNode(context, new Library {
                    Name = project.Name, Version = project.Version
                }, _ => true));
            }
            var graphs = await Task.WhenAll(tasks);

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Resolving complete".Green(), sw.ElapsedMilliseconds));

            var installItems = new List <GraphItem>();
            var missingItems = new HashSet <Library>();

            ForEach(graphs, node =>
            {
                if (node == null || node.Library == null)
                {
                    return;
                }
                if (node.Item == null || node.Item.Match == null)
                {
                    if (!node.Library.IsGacOrFrameworkReference &&
                        node.Library.Version != null &&
                        missingItems.Add(node.Library))
                    {
                        Reports.Error.WriteLine(string.Format("Unable to locate {0} >= {1}", node.Library.Name.Red().Bold(), node.Library.Version));
                        success = false;
                    }
                    return;
                }
                // "kpm restore" is case-sensitive
                if (!string.Equals(node.Item.Match.Library.Name, node.Library.Name, StringComparison.Ordinal))
                {
                    if (missingItems.Add(node.Library))
                    {
                        Reports.Error.WriteLine("Unable to locate {0} >= {1}. Do you mean {2}?",
                                                node.Library.Name.Red().Bold(), node.Library.Version, node.Item.Match.Library.Name.Bold());
                        success = false;
                    }
                    return;
                }
                var isRemote = remoteProviders.Contains(node.Item.Match.Provider);
                var isAdded  = installItems.Any(item => item.Match.Library == node.Item.Match.Library);
                if (!isAdded && isRemote)
                {
                    installItems.Add(node.Item);
                }
            });

            await InstallPackages(installItems, packagesDirectory, packageFilter : (library, nupkgSHA) => true);

            ScriptExecutor.Execute(project, "postrestore", getVariable);

            ScriptExecutor.Execute(project, "prepare", getVariable);

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Restore complete".Green().Bold(), sw.ElapsedMilliseconds));

            for (int i = 0; i < contexts.Count; i++)
            {
                PrintDependencyGraph(graphs[i], contexts[i].FrameworkName);
            }

            return(success);
        }
Пример #6
0
        public async Task <bool> ExecuteCommand()
        {
            if (string.IsNullOrEmpty(_addCommand.Name))
            {
                Reports.Error.WriteLine("Name of dependency to install is required.".Red());
                return(false);
            }

            SemanticVersion version = null;

            if (!string.IsNullOrEmpty(_addCommand.Version))
            {
                version = SemanticVersion.Parse(_addCommand.Version);
            }

            // Create source provider from solution settings
            _addCommand.ProjectDir = _addCommand.ProjectDir ?? Directory.GetCurrentDirectory();

            var rootDir    = ProjectResolver.ResolveRootDirectory(_addCommand.ProjectDir);
            var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());
            var settings   = SettingsUtils.ReadSettings(solutionDir: rootDir,
                                                        nugetConfigFile: null,
                                                        fileSystem: fileSystem,
                                                        machineWideSettings: new CommandLineMachineWideSettings());
            var sourceProvider = PackageSourceBuilder.CreateSourceProvider(settings);

            var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(sourceProvider,
                                                                                 _restoreCommand.FeedOptions.Sources, _restoreCommand.FeedOptions.FallbackSources);

            var packageFeeds = new List <IPackageFeed>();

            foreach (var source in effectiveSources)
            {
                var feed = PackageSourceUtils.CreatePackageFeed(
                    source,
                    _restoreCommand.FeedOptions.NoCache,
                    _restoreCommand.FeedOptions.IgnoreFailedSources,
                    Reports);
                if (feed != null)
                {
                    packageFeeds.Add(feed);
                }
            }

            PackageInfo result = null;

            if (version == null)
            {
                result = await PackageSourceUtils.FindLatestPackage(packageFeeds, _addCommand.Name);
            }
            else
            {
                result = await PackageSourceUtils.FindBestMatchPackage(packageFeeds, _addCommand.Name, new SemanticVersionRange(version));
            }

            if (result == null)
            {
                Reports.Error.WriteLine("Unable to locate {0} >= {1}",
                                        _addCommand.Name.Red().Bold(), _addCommand.Version);
                return(false);
            }

            if (string.IsNullOrEmpty(_addCommand.Version))
            {
                _addCommand.Version = result.Version.ToString();
            }

            return(_addCommand.ExecuteCommand() && (await _restoreCommand.ExecuteCommand()));
        }
Пример #7
0
        private async Task <Tuple <string, string> > ResolvePackageIdAndVersion(string packageId, string packageVersion)
        {
            if (string.IsNullOrEmpty(packageId))
            {
                return(null);
            }

            // For nupkgs, get the id and version from the package
            if (packageId.EndsWith(".nupkg", StringComparison.OrdinalIgnoreCase))
            {
                if (!File.Exists(packageId))
                {
                    WriteError(string.Format("Could not find the file {0}.", packageId));
                    return(null);
                }

                var packagePath      = Path.GetFullPath(packageId);
                var packageDirectory = Path.GetDirectoryName(packagePath);
                var zipPackage       = new NuGet.ZipPackage(packagePath);
                FeedOptions.FallbackSources.Add(packageDirectory);

                return(new Tuple <string, string>(
                           zipPackage.Id,
                           zipPackage.Version.ToString()));
            }

            // If the version is missing, try to find the latest version
            if (string.IsNullOrEmpty(packageVersion))
            {
                var rootDirectory = ProjectResolver.ResolveRootDirectory(_commandsRepository.Root.Root);
                var config        = NuGetConfig.ForSolution(rootDirectory, RestoreCommand.FileSystem);

                var packageFeeds = new List <IPackageFeed>();

                var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(
                    config.Sources,
                    FeedOptions.Sources,
                    FeedOptions.FallbackSources);

                foreach (var source in effectiveSources)
                {
                    var feed = PackageSourceUtils.CreatePackageFeed(
                        source,
                        FeedOptions.NoCache,
                        FeedOptions.IgnoreFailedSources,
                        Reports);
                    if (feed != null)
                    {
                        packageFeeds.Add(feed);
                    }
                }

                var package = await PackageSourceUtils.FindLatestPackage(packageFeeds, packageId);

                if (package == null)
                {
                    Reports.Error.WriteLine("Unable to locate the package {0}".Red(), packageId);
                    return(null);
                }

                return(new Tuple <string, string>(
                           packageId,
                           package.Version.ToString()));
            }

            // Otherwise, just assume that what you got is correct
            return(new Tuple <string, string>(packageId, packageVersion));
        }
Пример #8
0
        private async Task <bool> RestoreForProject(string projectJsonPath, string rootDirectory, string packagesDirectory)
        {
            var success = true;

            Reports.Information.WriteLine(string.Format("Restoring packages for {0}", projectJsonPath.Bold()));

            var sw = new Stopwatch();

            sw.Start();

            var projectFolder       = Path.GetDirectoryName(projectJsonPath);
            var projectLockFilePath = Path.Combine(projectFolder, LockFileFormat.LockFileName);

            Runtime.Project project;
            var             diagnostics = new List <ICompilationMessage>();

            if (!Runtime.Project.TryGetProject(projectJsonPath, out project, diagnostics))
            {
                throw new Exception("TODO: project.json parse error");
            }

            if (diagnostics.HasErrors())
            {
                var errorMessages = diagnostics
                                    .Where(x => x.Severity == CompilationMessageSeverity.Error)
                                    .Select(x => x.Message);
                ErrorMessages.GetOrAdd(projectJsonPath, _ => new List <string>()).AddRange(errorMessages);
            }

            var lockFile = await ReadLockFile(projectLockFilePath);

            var useLockFile = false;

            if (Lock == false &&
                Unlock == false &&
                lockFile != null &&
                lockFile.Islocked)
            {
                useLockFile = true;
            }

            if (useLockFile && !lockFile.IsValidForProject(project))
            {
                // Exhibit the same behavior as if it has been run with "dnu restore --lock"
                Reports.Information.WriteLine("Updating the invalid lock file with {0}",
                                              "dnu restore --lock".Yellow().Bold());
                useLockFile = false;
                Lock        = true;
            }

            Func <string, string> getVariable = key =>
            {
                return(null);
            };

            if (!SkipRestoreEvents)
            {
                if (!ScriptExecutor.Execute(project, "prerestore", getVariable))
                {
                    ErrorMessages.GetOrAdd("prerestore", _ => new List <string>()).Add(ScriptExecutor.ErrorMessage);
                    Reports.Error.WriteLine(ScriptExecutor.ErrorMessage);
                    return(false);
                }
            }

            var projectDirectory  = project.ProjectDirectory;
            var projectResolver   = new ProjectResolver(projectDirectory, rootDirectory);
            var packageRepository = new PackageRepository(packagesDirectory)
            {
                CheckHashFile = CheckHashFile
            };
            var restoreOperations = new RestoreOperations(Reports.Verbose);
            var projectProviders  = new List <IWalkProvider>();
            var localProviders    = new List <IWalkProvider>();
            var remoteProviders   = new List <IWalkProvider>();
            var contexts          = new List <RestoreContext>();
            var cache             = new Dictionary <LibraryRange, Task <WalkProviderMatch> >();

            projectProviders.Add(
                new LocalWalkProvider(
                    new ProjectReferenceDependencyProvider(
                        projectResolver)));

            localProviders.Add(
                new LocalWalkProvider(
                    new NuGetDependencyResolver(packageRepository)));

            var effectiveSources = PackageSourceUtils.GetEffectivePackageSources(
                Config.Sources,
                FeedOptions.Sources,
                FeedOptions.FallbackSources);

            AddRemoteProvidersFromSources(remoteProviders, effectiveSources);

            var tasks = new List <Task <TargetContext> >();

            if (useLockFile)
            {
                Reports.Information.WriteLine(string.Format("Following lock file {0}", projectLockFilePath.White().Bold()));

                var context = new RestoreContext
                {
                    FrameworkName           = FallbackFramework,
                    ProjectLibraryProviders = projectProviders,
                    LocalLibraryProviders   = localProviders,
                    RemoteLibraryProviders  = remoteProviders,
                    MatchCache = cache
                };

                contexts.Add(context);

                foreach (var lockFileLibrary in lockFile.Libraries)
                {
                    var projectLibrary = new LibraryRange(lockFileLibrary.Name, frameworkReference: false)
                    {
                        VersionRange = new SemanticVersionRange
                        {
                            MinVersion           = lockFileLibrary.Version,
                            MaxVersion           = lockFileLibrary.Version,
                            IsMaxInclusive       = true,
                            VersionFloatBehavior = SemanticVersionFloatBehavior.None,
                        }
                    };

                    tasks.Add(CreateGraphNode(restoreOperations, context, projectLibrary, _ => false));
                }
            }
            else
            {
                var frameworks = TargetFrameworks.Count == 0 ? project.GetTargetFrameworks().Select(f => f.FrameworkName) : TargetFrameworks;

                foreach (var frameworkName in frameworks)
                {
                    var context = new RestoreContext
                    {
                        FrameworkName           = frameworkName,
                        ProjectLibraryProviders = projectProviders,
                        LocalLibraryProviders   = localProviders,
                        RemoteLibraryProviders  = remoteProviders,
                        MatchCache = cache
                    };
                    contexts.Add(context);
                }

                if (!contexts.Any())
                {
                    contexts.Add(new RestoreContext
                    {
                        FrameworkName           = FallbackFramework,
                        ProjectLibraryProviders = projectProviders,
                        LocalLibraryProviders   = localProviders,
                        RemoteLibraryProviders  = remoteProviders,
                        MatchCache = cache
                    });
                }

                foreach (var context in contexts)
                {
                    var projectLibrary = new LibraryRange(project.Name, frameworkReference: false)
                    {
                        VersionRange = new SemanticVersionRange(project.Version)
                    };

                    tasks.Add(CreateGraphNode(restoreOperations, context, projectLibrary, _ => true));
                }
            }

            var targetContexts = await Task.WhenAll(tasks);

            foreach (var targetContext in targetContexts)
            {
                Reduce(targetContext.Root);
            }

            if (!useLockFile)
            {
                var runtimeFormatter   = new RuntimeFileFormatter();
                var projectRuntimeFile = runtimeFormatter.ReadRuntimeFile(projectJsonPath);
                if (projectRuntimeFile.Runtimes.Any())
                {
                    var runtimeTasks = new List <Task <TargetContext> >();

                    foreach (var pair in contexts.Zip(targetContexts, (context, graph) => new { context, graph }))
                    {
                        var runtimeFileTasks = new List <Task <RuntimeFile> >();
                        ForEach(pair.graph.Root, node =>
                        {
                            var match = node?.Item?.Match;
                            if (match == null)
                            {
                                return;
                            }
                            runtimeFileTasks.Add(match.Provider.GetRuntimes(node.Item.Match, pair.context.FrameworkName));
                        });

                        var libraryRuntimeFiles = await Task.WhenAll(runtimeFileTasks);

                        var runtimeFiles = new List <RuntimeFile> {
                            projectRuntimeFile
                        };
                        runtimeFiles.AddRange(libraryRuntimeFiles.Where(file => file != null));

                        foreach (var runtimeName in projectRuntimeFile.Runtimes.Keys)
                        {
                            var runtimeSpecs = new List <RuntimeSpec>();
                            FindRuntimeSpecs(
                                runtimeName,
                                runtimeFiles,
                                runtimeSpecs,
                                _ => false);

                            var runtimeContext = new RestoreContext
                            {
                                FrameworkName           = pair.context.FrameworkName,
                                ProjectLibraryProviders = pair.context.ProjectLibraryProviders,
                                LocalLibraryProviders   = pair.context.LocalLibraryProviders,
                                RemoteLibraryProviders  = pair.context.RemoteLibraryProviders,
                                RuntimeName             = runtimeName,
                                RuntimeSpecs            = runtimeSpecs,
                                MatchCache = cache
                            };
                            var projectLibrary = new LibraryRange(project.Name, frameworkReference: false)
                            {
                                VersionRange = new SemanticVersionRange(project.Version)
                            };
                            Reports.Information.WriteLine(string.Format("Graph for {0} on {1}", runtimeContext.FrameworkName, runtimeContext.RuntimeName));
                            runtimeTasks.Add(CreateGraphNode(restoreOperations, runtimeContext, projectLibrary, _ => true));
                        }
                    }

                    var runtimeTragetContexts = await Task.WhenAll(runtimeTasks);

                    foreach (var runtimeTargetContext in runtimeTragetContexts)
                    {
                        Reduce(runtimeTargetContext.Root);
                    }

                    targetContexts = targetContexts.Concat(runtimeTragetContexts).ToArray();
                }
            }

            var graphItems   = new List <GraphItem>();
            var installItems = new List <GraphItem>();
            var missingItems = new HashSet <LibraryRange>();

            foreach (var context in targetContexts)
            {
                ForEach(context.Root, node =>
                {
                    if (node == null || node.LibraryRange == null)
                    {
                        return;
                    }

                    if (node.Item == null || node.Item.Match == null)
                    {
                        // This is a workaround for #1322. Since we use restore to generate the lock file
                        // after publish, it's possible to fail restore after copying the closure
                        if (!IgnoreMissingDependencies)
                        {
                            if (!node.LibraryRange.IsGacOrFrameworkReference &&
                                node.LibraryRange.VersionRange != null &&
                                missingItems.Add(node.LibraryRange))
                            {
                                var errorMessage = string.Format("Unable to locate {0} {1}",
                                                                 node.LibraryRange.Name.Red().Bold(),
                                                                 node.LibraryRange.VersionRange);
                                ErrorMessages.GetOrAdd(projectJsonPath, _ => new List <string>()).Add(errorMessage);
                                Reports.Error.WriteLine(errorMessage);
                                success = false;
                            }
                        }

                        return;
                    }

                    if (!string.Equals(node.Item.Match.Library.Name, node.LibraryRange.Name, StringComparison.Ordinal))
                    {
                        // Fix casing of the library name to be installed
                        node.Item.Match.Library.Name = node.LibraryRange.Name;
                    }

                    var isRemote      = remoteProviders.Contains(node.Item.Match.Provider);
                    var isInstallItem = installItems.Any(item => item.Match.Library == node.Item.Match.Library);

                    if (!isInstallItem && isRemote)
                    {
                        // It's ok to download rejected nodes so we avoid downloading them in the future
                        // The trade off is that subsequent restores avoid going to any remotes
                        installItems.Add(node.Item);
                    }

                    // Don't add rejected nodes since we only want to write reduced nodes
                    // to the lock file
                    if (node.Disposition != GraphNode.DispositionType.Rejected)
                    {
                        var isGraphItem = graphItems.Any(item => item.Match.Library == node.Item.Match.Library);

                        if (!isGraphItem)
                        {
                            graphItems.Add(node.Item);
                        }

                        context.Libraries.Add(node.Item.Match.Library);
                    }
                });
            }

            if (!SkipInstall)
            {
                await InstallPackages(installItems, packagesDirectory);
            }

            if (!useLockFile)
            {
                Reports.Information.WriteLine(string.Format("Writing lock file {0}", projectLockFilePath.White().Bold()));

                var repository = new PackageRepository(packagesDirectory);

                WriteLockFile(lockFile,
                              projectLockFilePath,
                              project,
                              graphItems,
                              repository,
                              targetContexts);
            }

            if (!SkipRestoreEvents)
            {
                if (!ScriptExecutor.Execute(project, "postrestore", getVariable))
                {
                    ErrorMessages.GetOrAdd("postrestore", _ => new List <string>()).Add(ScriptExecutor.ErrorMessage);
                    Reports.Error.WriteLine(ScriptExecutor.ErrorMessage);
                    return(false);
                }

                if (!ScriptExecutor.Execute(project, "prepare", getVariable))
                {
                    ErrorMessages.GetOrAdd("prepare", _ => new List <string>()).Add(ScriptExecutor.ErrorMessage);
                    Reports.Error.WriteLine(ScriptExecutor.ErrorMessage);
                    return(false);
                }
            }

            Reports.Information.WriteLine(string.Format("{0}, {1}ms elapsed", "Restore complete".Green().Bold(), sw.ElapsedMilliseconds));

            return(success);
        }