Beispiel #1
0
        public async Task <bool> Execute()
        {
            Reports       = Options.Reports;
            LocalPackages = Options.SourcePackages ??
                            NuGetDependencyResolver.ResolveRepositoryPath(Directory.GetCurrentDirectory());

            Options.Reports.Quiet.WriteLine(string.Format("Adding NuGet package {0} to {1}",
                                                          Options.NuGetPackage.Bold(), LocalPackages.Bold()));

            var sw = new Stopwatch();

            sw.Start();

            var library = NuGetPackageUtils.CreateLibraryFromNupkg(Options.NuGetPackage);

            using (var stream = File.OpenRead(Options.NuGetPackage))
            {
                string packageHash = null;
                if (File.Exists(Options.PackageHashFilePath))
                {
                    packageHash = File.ReadAllText(Options.PackageHashFilePath);
                }
                await NuGetPackageUtils.InstallFromStream(stream, library, LocalPackages, Reports.Quiet, packageHash);
            }

            Reports.Quiet.WriteLine(
                "{0}, {1}ms elapsed",
                "Add complete".Green().Bold(),
                sw.ElapsedMilliseconds);

            return(true);
        }
Beispiel #2
0
        public async Task <bool> Execute()
        {
            Reports       = Options.Reports;
            LocalPackages = Options.SourcePackages ??
                            NuGetDependencyResolver.ResolveRepositoryPath(Directory.GetCurrentDirectory());

            Options.Reports.Information.WriteLine(string.Format("Adding NuGet package {0} to {1}",
                                                                Options.NuGetPackage.Bold(), LocalPackages.Bold()));

            var sw = new Stopwatch();

            sw.Start();

            var library = NuGetPackageUtils.CreateLibraryFromNupkg(Options.NuGetPackage);

            using (var sha512 = SHA512.Create())
                using (var stream = File.OpenRead(Options.NuGetPackage))
                {
                    Reports.Information.WriteLine("Installing {0} {1}", library.Name.Bold(), library.Version);
                    await NuGetPackageUtils.InstallFromStream(stream, library, LocalPackages, sha512);
                }

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

            return(true);
        }
Beispiel #3
0
        private string ResolvePackagesFolder()
        {
            var packagesFolder = PackagesFolder;

            if (string.IsNullOrEmpty(packagesFolder))
            {
                packagesFolder = NuGetDependencyResolver.ResolveRepositoryPath(_solutionRoot);
            }

            if (!Directory.Exists(packagesFolder))
            {
                _reports.WriteError($"Cannot find the packages folder '{packagesFolder}'.");
                return(null);
            }

            return(packagesFolder);
        }
Beispiel #4
0
        public bool ExecuteCommand()
        {
            var sw = new Stopwatch();

            sw.Start();

            var restoreDirectory = RestoreDirectory ?? Directory.GetCurrentDirectory();

            var projectJsonFiles = Directory.GetFiles(restoreDirectory, "project.json", SearchOption.AllDirectories);

            var rootDirectory = ProjectResolver.ResolveRootDirectory(restoreDirectory);

            ReadSettings(rootDirectory);

            string packagesDirectory = PackageFolder;

            if (string.IsNullOrEmpty(PackageFolder))
            {
                packagesDirectory = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);
            }

            var packagesFolderFileSystem = CreateFileSystem(packagesDirectory);
            var pathResolver             = new DefaultPackagePathResolver(packagesFolderFileSystem, useSideBySidePaths: true);
            var localRepository          = new LocalPackageRepository(pathResolver, packagesFolderFileSystem);

            int restoreCount = 0;
            int successCount = 0;

            foreach (var projectJsonPath in projectJsonFiles)
            {
                restoreCount += 1;
                var success = RestoreForProject(localRepository, projectJsonPath, rootDirectory, packagesDirectory).Result;
                if (success)
                {
                    successCount += 1;
                }
            }

            if (restoreCount > 1)
            {
                Reports.Information.WriteLine(string.Format("Total time {0}ms", sw.ElapsedMilliseconds));
            }

            return(restoreCount == successCount);
        }
Beispiel #5
0
        public ModuleLoaderContext(IServiceProvider serviceProvider,
                                   string projectDirectory)
        {
            ProjectDirectory = projectDirectory;
            RootDirectory    = Microsoft.Framework.Runtime.ProjectResolver.ResolveRootDirectory(ProjectDirectory);

            // A new project resolver is required. you cannot reuse the one from the
            // parent service provider as that will be for the parent context.
            ProjectResolver = new ProjectResolver(ProjectDirectory, RootDirectory);

            var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(new FrameworkReferenceResolver());

            // Need to pass through package directory incase you download a package from the gallary, this needs to know about it
            var nuGetDependencyProvider = new NuGetDependencyResolver(new PackageRepository(
                                                                          NuGetDependencyResolver.ResolveRepositoryPath(RootDirectory)));
            var gacDependencyResolver        = new GacDependencyResolver();
            var projectDepencyProvider       = new ProjectReferenceDependencyProvider(ProjectResolver);
            var unresolvedDependencyProvider = new UnresolvedDependencyProvider();

            var projectLockJsonPath = Path.Combine(ProjectDirectory, LockFileFormat.LockFileName);

            if (File.Exists(projectLockJsonPath))
            {
                var lockFileFormat = new LockFileFormat();
                var lockFile       = lockFileFormat.Read(projectLockJsonPath);
                nuGetDependencyProvider.ApplyLockFile(lockFile);
            }

            DependencyWalker = new DependencyWalker(new IDependencyProvider[] {
                projectDepencyProvider,
                nuGetDependencyProvider,
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                unresolvedDependencyProvider
            });

            LibraryExportProvider = new CompositeLibraryExportProvider(new ILibraryExportProvider[] {
                new ModuleProjectLibraryExportProvider(
                    ProjectResolver, serviceProvider),
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                nuGetDependencyProvider
            });
        }
Beispiel #6
0
        public ModuleLoaderContext(IServiceProvider serviceProvider,
                                   string projectDirectory,
                                   ICache cache)
        {
            _serviceProvider = serviceProvider;
            _cache           = cache;

            ProjectDirectory = projectDirectory;
            RootDirectory    = Microsoft.Framework.Runtime.ProjectResolver.ResolveRootDirectory(ProjectDirectory);

            // A new project resolver is required. you cannot reuse the one from the
            // parent service provider as that will be for the parent context.
            ProjectResolver = new ProjectResolver(ProjectDirectory, RootDirectory);

            var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(new FrameworkReferenceResolver());

            // Need to pass through package directory incase you download a package from the gallary, this needs to know about it
            var NuGetDependencyProvider = new NuGetDependencyResolver(
                NuGetDependencyResolver.ResolveRepositoryPath(RootDirectory), RootDirectory);
            var gacDependencyResolver        = new GacDependencyResolver();
            var ProjectDepencyProvider       = new ProjectReferenceDependencyProvider(ProjectResolver);
            var unresolvedDependencyProvider = new UnresolvedDependencyProvider();

            DependencyWalker = new DependencyWalker(new IDependencyProvider[] {
                ProjectDepencyProvider,
                NuGetDependencyProvider,
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                unresolvedDependencyProvider
            });

            LibraryExportProvider = new CompositeLibraryExportProvider(new ILibraryExportProvider[] {
                new ModuleProjectLibraryExportProvider(
                    ProjectResolver, _serviceProvider),
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                NuGetDependencyProvider
            });
        }
Beispiel #7
0
        private void WriteGlobalJson()
        {
            var rootDirectory   = ProjectResolver.ResolveRootDirectory(_project.ProjectDirectory);
            var projectResolver = new ProjectResolver(_project.ProjectDirectory, rootDirectory);
            var packagesDir     = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);
            var pathResolver    = new DefaultPackagePathResolver(packagesDir);
            var dependenciesObj = new JObject();

            // Generate SHAs for all package dependencies
            foreach (var deploymentPackage in Packages)
            {
                var library     = deploymentPackage.Library;
                var shaFilePath = pathResolver.GetHashPath(library.Name, library.Version);

                if (!File.Exists(shaFilePath))
                {
                    throw new FileNotFoundException("Expected SHA file doesn't exist", shaFilePath);
                }

                var sha = File.ReadAllText(shaFilePath);

                var shaObj = new JObject();
                shaObj["version"]             = library.Version.ToString();
                shaObj["sha"]                 = sha;
                dependenciesObj[library.Name] = shaObj;
            }

            // If "--no-source" is specified, project dependencies are packed to packages
            // So we also generate SHAs for them in this case
            foreach (var deploymentProject in Projects)
            {
                Runtime.Project project;
                if (!projectResolver.TryResolveProject(deploymentProject.Name, out project))
                {
                    throw new Exception("TODO: unable to resolve project named " + deploymentProject.Name);
                }

                var shaFilePath = pathResolver.GetHashPath(project.Name, project.Version);

                if (!File.Exists(shaFilePath))
                {
                    // This project is not packed to a package
                    continue;
                }

                var sha = File.ReadAllText(shaFilePath);

                var shaObj = new JObject();
                shaObj.Add(new JProperty("version", project.Version.ToString()));
                shaObj.Add(new JProperty("sha", sha));
                dependenciesObj.Add(new JProperty(project.Name, shaObj));
            }

            var rootObject = default(JObject);

            if (GlobalSettings.HasGlobalFile(rootDirectory))
            {
                rootObject = JObject.Parse(File.ReadAllText(Path.Combine(
                                                                rootDirectory,
                                                                GlobalSettings.GlobalFileName)));
            }
            else
            {
                rootObject = new JObject();
            }

            var applicationRoot = Path.Combine(OutputPath, BundleRoot.AppRootName);

            rootObject["dependencies"] = dependenciesObj;
            rootObject["packages"]     = PathUtility.GetRelativePath(
                PathUtility.EnsureTrailingForwardSlash(applicationRoot),
                TargetPackagesPath, separator: '/');

            File.WriteAllText(Path.Combine(applicationRoot, GlobalSettings.GlobalFileName),
                              rootObject.ToString());
        }
Beispiel #8
0
        public async Task <bool> ExecuteCommand()
        {
            try
            {
                var sw = Stopwatch.StartNew();

                // If the root argument is a project.json file
                if (string.Equals(
                        Runtime.Project.ProjectFileName,
                        Path.GetFileName(RestoreDirectory),
                        StringComparison.OrdinalIgnoreCase))
                {
                    RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(RestoreDirectory));
                }
                else if (!Directory.Exists(RestoreDirectory) && !string.IsNullOrEmpty(RestoreDirectory))
                {
                    throw new InvalidOperationException("The given root is invalid.");
                }

                var restoreDirectory = RestoreDirectory ?? Directory.GetCurrentDirectory();

                var rootDirectory = ProjectResolver.ResolveRootDirectory(restoreDirectory);
                ReadSettings(rootDirectory);

                string packagesDirectory = FeedOptions.TargetPackagesFolder;

                if (string.IsNullOrEmpty(packagesDirectory))
                {
                    packagesDirectory = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);
                }

                var packagesFolderFileSystem = CreateFileSystem(packagesDirectory);
                var pathResolver             = new DefaultPackagePathResolver(packagesFolderFileSystem, useSideBySidePaths: true);

                int restoreCount = 0;
                int successCount = 0;

                var projectJsonFiles = Directory.EnumerateFiles(
                    restoreDirectory,
                    Runtime.Project.ProjectFileName,
                    SearchOption.AllDirectories);
                Func <string, Task> restorePackage = async projectJsonPath =>
                {
                    Interlocked.Increment(ref restoreCount);
                    var success = await RestoreForProject(projectJsonPath, rootDirectory, packagesDirectory);

                    if (success)
                    {
                        Interlocked.Increment(ref successCount);
                    }
                };

                if (!Parallel || PlatformHelper.IsMono)
                {
                    // Restoring in parallel on Mono throws native exception
                    foreach (var projectJsonFile in projectJsonFiles)
                    {
                        await restorePackage(projectJsonFile);
                    }
                }
                else
                {
                    await ForEachAsync(
                        projectJsonFiles,
                        maxDegreesOfConcurrency : Environment.ProcessorCount,
                        body : restorePackage);
                }

                if (restoreCount > 1)
                {
                    Reports.Information.WriteLine(string.Format("Total time {0}ms", sw.ElapsedMilliseconds));
                }

                foreach (var category in ErrorMessages)
                {
                    Reports.Error.WriteLine("Errors in {0}".Red().Bold(), category.Key);
                    foreach (var message in category.Value)
                    {
                        Reports.Error.WriteLine("    {0}", message);
                    }
                }

                return(restoreCount == successCount);
            }
            catch (Exception ex)
            {
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine(ex.ToString());
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine("Restore failed");
                Reports.Information.WriteLine(ex.Message);
                return(false);
            }
        }
Beispiel #9
0
        public async Task <bool> ExecuteCommand()
        {
            try
            {
                var sw = Stopwatch.StartNew();

                // If the root argument is a project.json file
                if (string.Equals(
                        Runtime.Project.ProjectFileName,
                        Path.GetFileName(RestoreDirectory),
                        StringComparison.OrdinalIgnoreCase))
                {
                    RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(RestoreDirectory));
                }
                // If the root argument is a global.json file
                else if (string.Equals(
                             GlobalSettings.GlobalFileName,
                             Path.GetFileName(RestoreDirectory),
                             StringComparison.OrdinalIgnoreCase))
                {
                    GlobalJsonFile   = RestoreDirectory;
                    RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(RestoreDirectory));
                }
                else if (!Directory.Exists(RestoreDirectory) && !string.IsNullOrEmpty(RestoreDirectory))
                {
                    throw new InvalidOperationException("The given root is invalid.");
                }

                var restoreDirectory = RestoreDirectory ?? Directory.GetCurrentDirectory();

                var rootDirectory = ProjectResolver.ResolveRootDirectory(restoreDirectory);
                ReadSettings(rootDirectory);

                string packagesDirectory = PackageFolder;

                if (string.IsNullOrEmpty(PackageFolder))
                {
                    packagesDirectory = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);
                }

                var packagesFolderFileSystem = CreateFileSystem(packagesDirectory);
                var pathResolver             = new DefaultPackagePathResolver(packagesFolderFileSystem, useSideBySidePaths: true);

                int restoreCount = 0;
                int successCount = 0;

                if (string.IsNullOrEmpty(GlobalJsonFile))
                {
                    var projectJsonFiles = Directory.GetFiles(restoreDirectory, "project.json", SearchOption.AllDirectories);
                    foreach (var projectJsonPath in projectJsonFiles)
                    {
                        restoreCount += 1;
                        var success = await RestoreForProject(projectJsonPath, rootDirectory, packagesDirectory);

                        if (success)
                        {
                            successCount += 1;
                        }
                    }
                }
                else
                {
                    restoreCount = 1;
                    var success = await RestoreFromGlobalJson(rootDirectory, packagesDirectory);

                    if (success)
                    {
                        successCount = 1;
                    }
                }

                if (restoreCount > 1)
                {
                    Reports.Information.WriteLine(string.Format("Total time {0}ms", sw.ElapsedMilliseconds));
                }

                return(restoreCount == successCount);
            }
            catch (Exception ex)
            {
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine(ex.ToString());
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine("Restore failed");
                Reports.Information.WriteLine(ex.Message);
                return(false);
            }
        }
Beispiel #10
0
        private async Task <bool> Execute(string restoreDirectory, PackageFeedCache packageFeeds, SummaryContext summary)
        {
            try
            {
                var sw = Stopwatch.StartNew();

                IEnumerable <string> projectJsonFiles;
                if (!RestoreProjectsCollector.Find(restoreDirectory, out projectJsonFiles))
                {
                    var errorMessage = $"The given root {restoreDirectory.Red().Bold()} is invalid.";
                    summary.ErrorMessages.GetOrAdd(restoreDirectory, _ => new List <string>()).Add(errorMessage);
                    Reports.Error.WriteLine(errorMessage);
                    return(false);
                }

                var rootDirectory = ProjectResolver.ResolveRootDirectory(restoreDirectory);
                ReadSettings(rootDirectory);

                var settings = Config.Settings as Settings;
                if (settings != null)
                {
                    var configFiles = settings.GetConfigFiles();
                    foreach (var file in configFiles)
                    {
                        summary.InformationMessages.GetOrAdd("NuGet Config files used:", _ => new List <string>()).Add(file);
                    }
                }

                string packagesDirectory = FeedOptions.TargetPackagesFolder;

                if (string.IsNullOrEmpty(packagesDirectory))
                {
                    packagesDirectory = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);
                }

                var packagesFolderFileSystem = CreateFileSystem(packagesDirectory);
                var pathResolver             = new DefaultPackagePathResolver(packagesDirectory);

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

                var remoteProviders = new List <IWalkProvider>();
                AddRemoteProvidersFromSources(remoteProviders, effectiveSources, packageFeeds, summary);

                int restoreCount = 0;
                int successCount = 0;

                Func <string, Task> restorePackage = async projectJsonPath =>
                {
                    Interlocked.Increment(ref restoreCount);
                    var success = await RestoreForProject(projectJsonPath, rootDirectory, packagesDirectory, remoteProviders, summary);

                    if (success)
                    {
                        Interlocked.Increment(ref successCount);
                    }
                };

                if (!RestoringInParallel())
                {
                    // Restoring in parallel on Mono throws native exception
                    foreach (var projectJsonFile in projectJsonFiles)
                    {
                        await restorePackage(projectJsonFile);
                    }
                }
                else
                {
                    await ForEachAsync(
                        projectJsonFiles,
                        MaxDegreesOfConcurrency,
                        restorePackage);
                }

                if (restoreCount > 1)
                {
                    Reports.Information.WriteLine(string.Format("Total time {0}ms", sw.ElapsedMilliseconds));
                }

                if (summary.InstallCount > 0)
                {
                    summary.InformationMessages.GetOrAdd("Installed:", _ => new List <string>()).Add($"{summary.InstallCount} package(s) to {packagesDirectory}");
                }

                return(restoreCount == successCount);
            }
            catch (Exception ex)
            {
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine(ex.ToString());
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine("Restore failed");
                Reports.Information.WriteLine(ex.Message);
                return(false);
            }
        }
        public ProjectHostContext(IServiceProvider serviceProvider,
                                  string projectDirectory,
                                  string packagesDirectory,
                                  string[] sourcePaths,
                                  string configuration,
                                  FrameworkName targetFramework,
                                  ICache cache,
                                  ICacheContextAccessor cacheContextAccessor,
                                  INamedCacheDependencyProvider namedCacheDependencyProvider,
                                  IAssemblyLoadContextFactory loadContextFactory = null)
        {
            ProjectDirectory           = projectDirectory;
            Configuration              = configuration;
            RootDirectory              = Microsoft.Framework.Runtime.ProjectResolver.ResolveRootDirectory(ProjectDirectory);
            ProjectResolver            = new ProjectResolver(ProjectDirectory, RootDirectory, sourcePaths);
            FrameworkReferenceResolver = new FrameworkReferenceResolver();
            _serviceProvider           = new ServiceProvider(serviceProvider);

            PackagesDirectory = packagesDirectory ?? NuGetDependencyResolver.ResolveRepositoryPath(RootDirectory);

            var referenceAssemblyDependencyResolver = new ReferenceAssemblyDependencyResolver(FrameworkReferenceResolver);

            NuGetDependencyProvider = new NuGetDependencyResolver(PackagesDirectory, RootDirectory);
            var gacDependencyResolver = new GacDependencyResolver();

            ProjectDepencyProvider = new ProjectReferenceDependencyProvider(ProjectResolver);
            var unresolvedDependencyProvider = new UnresolvedDependencyProvider();

            DependencyWalker = new DependencyWalker(new IDependencyProvider[] {
                ProjectDepencyProvider,
                NuGetDependencyProvider,
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                unresolvedDependencyProvider
            });

            LibraryExportProvider = new CompositeLibraryExportProvider(new ILibraryExportProvider[] {
                new ProjectLibraryExportProvider(ProjectResolver, ServiceProvider),
                referenceAssemblyDependencyResolver,
                gacDependencyResolver,
                NuGetDependencyProvider
            });

            LibraryManager = new LibraryManager(targetFramework, configuration, DependencyWalker,
                                                LibraryExportProvider, cache);

            AssemblyLoadContextFactory = loadContextFactory ?? new AssemblyLoadContextFactory(ServiceProvider);

            var sourceCodeService = new SourceTextService(cache);

            var provider = new RoslynProjectReferenceProvider(cache, cacheContextAccessor, namedCacheDependencyProvider, loadContextFactory, _serviceProvider.GetService <IFileWatcher>(), _serviceProvider);

            // Default services
            _serviceProvider.Add(typeof(IApplicationEnvironment), new ApplicationEnvironment(Project, targetFramework, configuration));
            _serviceProvider.Add(typeof(ILibraryExportProvider), LibraryExportProvider, includeInManifest: false);
            _serviceProvider.Add(typeof(IProjectResolver), ProjectResolver);
            _serviceProvider.Add(typeof(IFileWatcher), NoopWatcher.Instance);

            _serviceProvider.Add(typeof(NuGetDependencyResolver), NuGetDependencyProvider, includeInManifest: false);
            _serviceProvider.Add(typeof(ProjectReferenceDependencyProvider), ProjectDepencyProvider, includeInManifest: false);
            _serviceProvider.Add(typeof(ILibraryManager), LibraryManager);
            _serviceProvider.Add(typeof(ICache), cache);
            _serviceProvider.Add(typeof(ICacheContextAccessor), cacheContextAccessor);
            _serviceProvider.Add(typeof(INamedCacheDependencyProvider), namedCacheDependencyProvider, includeInManifest: false);
            _serviceProvider.Add(typeof(IAssemblyLoadContextFactory), AssemblyLoadContextFactory);

            _serviceProvider.Add(typeof(IProjectReferenceProvider), provider);
            _serviceProvider.Add(typeof(ISourceTextService), sourceCodeService);
        }
Beispiel #12
0
        private void WriteGlobalJson()
        {
            var rootDirectory   = ProjectResolver.ResolveRootDirectory(_project.ProjectDirectory);
            var projectResolver = new ProjectResolver(_project.ProjectDirectory, rootDirectory);
            var packagesDir     = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);

            var nugetDependencyResolver = new NuGetDependencyResolver(packagesDir, new EmptyFrameworkResolver());
            var pathResolver            = new DefaultPackagePathResolver(PackagesPath);

            var dependenciesObj = new JObject();


            // Generate SHAs for all package dependencies
            foreach (var deploymentPackage in Packages)
            {
                // Use the exactly same approach in PackPackage.Emit() to
                // find the package actually in use
                var package = nugetDependencyResolver.FindCandidate(
                    deploymentPackage.Library.Name,
                    deploymentPackage.Library.Version);

                var shaFilePath = pathResolver.GetHashPath(package.Id, package.Version);
                var sha         = File.ReadAllText(shaFilePath);

                var shaObj = new JObject();
                shaObj.Add(new JProperty("version", package.Version.ToString()));
                shaObj.Add(new JProperty("sha", sha));
                dependenciesObj.Add(new JProperty(package.Id, shaObj));
            }

            // If "--no-source" is specified, project dependencies are packed to packages
            // So we also generate SHAs for them in this case
            foreach (var deploymentProject in Projects)
            {
                Runtime.Project project;
                if (!projectResolver.TryResolveProject(deploymentProject.Name, out project))
                {
                    throw new Exception("TODO: unable to resolve project named " + deploymentProject.Name);
                }

                var shaFilePath = pathResolver.GetHashPath(project.Name, project.Version);

                if (!File.Exists(shaFilePath))
                {
                    // This project is not packed to a package
                    continue;
                }

                var sha = File.ReadAllText(shaFilePath);

                var shaObj = new JObject();
                shaObj.Add(new JProperty("version", project.Version.ToString()));
                shaObj.Add(new JProperty("sha", sha));
                dependenciesObj.Add(new JProperty(project.Name, shaObj));
            }

            var rootObject = default(JObject);

            if (GlobalSettings.HasGlobalFile(rootDirectory))
            {
                rootObject = JObject.Parse(File.ReadAllText(Path.Combine(
                                                                rootDirectory,
                                                                GlobalSettings.GlobalFileName)));
            }
            else
            {
                rootObject = new JObject();
            }

            var applicationRoot = Path.Combine(OutputPath, PackRoot.AppRootName);

            rootObject["dependencies"] = dependenciesObj;
            rootObject["packages"]     = PathUtility.GetRelativePath(PathUtility.EnsureTrailingSlash(applicationRoot),
                                                                     PackagesPath);

            File.WriteAllText(Path.Combine(applicationRoot, GlobalSettings.GlobalFileName),
                              rootObject.ToString());
        }
Beispiel #13
0
        private async Task <bool> Execute(string restoreDirectory)
        {
            try
            {
                var sw = Stopwatch.StartNew();

                var projectJsonFiles = new List <string>();

                if (string.Equals(
                        Runtime.Project.ProjectFileName,
                        Path.GetFileName(restoreDirectory),
                        StringComparison.OrdinalIgnoreCase) && File.Exists(restoreDirectory))
                {
                    // If the path is a project.json file we don't do recursive search in subfolders
                    projectJsonFiles.Add(restoreDirectory);
                }
                else if (Directory.Exists(restoreDirectory))
                {
                    var projectJsonFile = Path.Combine(restoreDirectory, Runtime.Project.ProjectFileName);
                    if (File.Exists(projectJsonFile))
                    {
                        // If the path contains a project.json file we don't do recursive search in subfolders
                        projectJsonFiles.Add(projectJsonFile);
                    }
                    else
                    {
                        projectJsonFiles.AddRange(Directory.EnumerateFiles(
                                                      restoreDirectory,
                                                      Runtime.Project.ProjectFileName,
                                                      SearchOption.AllDirectories));
                    }
                }
                else
                {
                    var errorMessage = $"The given root {restoreDirectory.Red().Bold()} is invalid.";
                    ErrorMessages.GetOrAdd(restoreDirectory, _ => new List <string>()).Add(errorMessage);
                    Reports.Error.WriteLine(errorMessage);
                    return(false);
                }

                var rootDirectory = ProjectResolver.ResolveRootDirectory(restoreDirectory);
                ReadSettings(rootDirectory);

                string packagesDirectory = FeedOptions.TargetPackagesFolder;

                if (string.IsNullOrEmpty(packagesDirectory))
                {
                    packagesDirectory = NuGetDependencyResolver.ResolveRepositoryPath(rootDirectory);
                }

                var packagesFolderFileSystem = CreateFileSystem(packagesDirectory);
                var pathResolver             = new DefaultPackagePathResolver(packagesFolderFileSystem, useSideBySidePaths: true);

                int restoreCount = 0;
                int successCount = 0;

                Func <string, Task> restorePackage = async projectJsonPath =>
                {
                    Interlocked.Increment(ref restoreCount);
                    var success = await RestoreForProject(projectJsonPath, rootDirectory, packagesDirectory);

                    if (success)
                    {
                        Interlocked.Increment(ref successCount);
                    }
                };

                if (!RestoringInParallel())
                {
                    // Restoring in parallel on Mono throws native exception
                    foreach (var projectJsonFile in projectJsonFiles)
                    {
                        await restorePackage(projectJsonFile);
                    }
                }
                else
                {
                    await ForEachAsync(
                        projectJsonFiles,
                        MaxDegreesOfConcurrency,
                        restorePackage);
                }

                if (restoreCount > 1)
                {
                    Reports.Information.WriteLine(string.Format("Total time {0}ms", sw.ElapsedMilliseconds));
                }

                if (_installCount > 0)
                {
                    InformationMessages.GetOrAdd("Installed:", _ => new List <string>()).Add($"{_installCount} package(s) to {packagesDirectory}");
                    _installCount = 0;
                }

                return(restoreCount == successCount);
            }
            catch (Exception ex)
            {
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine(ex.ToString());
                Reports.Information.WriteLine("----------");
                Reports.Information.WriteLine("Restore failed");
                Reports.Information.WriteLine(ex.Message);
                return(false);
            }
        }