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); }
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); }
public Program( IApplicationEnvironment appEnv, IServiceProvider services, NuGetDependencyResolver nuget) { GraphicsTest.Setup = container => { container.Map(nuget).Map(appEnv); }; xunitRunner = new Xunit.Runner.Dnx.Program(appEnv, services); }
public async Task ResolveAsync_WithExistingPackage_ReturnsPackages() { // Arrange var repository = NugetRepository.FromSourceUrl(NugetRepositoryTests.TestNugetFeed); var provider = new NuGetDependencyResolver(new AggregateNugetRepository(new[] { repository })); // Act var result = await provider.ResolveAsync(NugetRepositoryTests.TestPackageName); // Assert Assert.NotEmpty(result.FoundDependencies); Assert.Empty(result.NotFoundDependencies); }
public async Task ResolveAsync_WithNoPackage_ReturnsMissing() { // Arrange var repository = NugetRepository.FromSourceUrl(NugetRepositoryTests.TestNugetFeed); var provider = new NuGetDependencyResolver(new AggregateNugetRepository(new[] { repository })); // Act var result = await provider.ResolveAsync("this.package.does.not.exist"); // Assert Assert.NotEmpty(result.NotFoundDependencies); Assert.Empty(result.FoundDependencies); }
/// <summary> /// This is a helper method for looking up directories that directly contains assemblies that would be loaded /// given the published runtime framework. We should run crossgen on these folders /// </summary> private IEnumerable <string> ResolveOutputAssemblies(PublishRoot root, NuGetDependencyResolver resolver) { var outputPathsMap = root.Packages .ToDictionary( pkg => pkg.Library, pkg => pkg.TargetPath ); var result = new HashSet <string>(); var libraryNotInOutput = new List <Library>(); var missingOutputFolder = new List <string>(); foreach (var dependency in resolver.PackageAssemblyLookup.Values) { var libId = dependency.Library.Identity; var libPath = dependency.Library.Path; var assemblyDir = Path.GetDirectoryName(dependency.Path); var assemblySelection = assemblyDir.Substring(libPath.Length); string outputLibLocation; if (!outputPathsMap.TryGetValue(libId, out outputLibLocation)) { libraryNotInOutput.Add(libId); continue; } var output = outputLibLocation + assemblySelection; if (!Directory.Exists(output)) { missingOutputFolder.Add(output); } else { result.Add(output); } } if (libraryNotInOutput.Any()) { throw new InvalidOperationException(string.Format("Library {0} cannot be found in the published output.", string.Join(", ", libraryNotInOutput))); } if (missingOutputFolder.Any()) { throw new InvalidOperationException("Published output does not contain directory:\n" + string.Join("\n", missingOutputFolder)); } return(result); }
private bool TryPopulateMetadataReferences(PackageDescription library, FrameworkName targetFramework, IDictionary <string, IMetadataReference> paths) { foreach (var assemblyPath in library.LockFileLibrary.CompileTimeAssemblies) { if (NuGetDependencyResolver.IsPlaceholderFile(assemblyPath)) { continue; } var name = Path.GetFileNameWithoutExtension(assemblyPath); var path = Path.Combine(library.Path, assemblyPath); paths[name] = new MetadataFileReference(name, path); } return(true); }
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); }
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); }
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 }); }
private int RunTests(TestOptions options) { if (options.Sink != null) { var parts = options.Sink.Split('|'); var packagesPath = Path.GetFullPath(parts[0]); var dependencyResolver = new NuGetDependencyResolver(packagesPath); var lib = dependencyResolver.GetDescription(new LibraryRange { Name = parts[1] }, _environment.RuntimeFramework); dependencyResolver.Initialize(new[] { lib }, _environment.RuntimeFramework); var dependencyLoader = new NuGetAssemblyLoader(_loadContextAccessor, dependencyResolver); var referenceLoader = new ReferenceLoader(_frameworkReferenceResolver, _environment.RuntimeFramework); using (_container.AddLoader(dependencyLoader)) using (_container.AddLoader(referenceLoader)) using (var context = _loadContextFactory.Create()) { var assembly = dependencyLoader.Load(parts[1], context); var locator = assembly.GetCustomAttributes() .OfType <ITestSinkFactory>() .FirstOrDefault(); if (locator == null) { throw new InvalidOperationException($"No assembly attribute found that implements the interface 'ITestSinkLocator' in the assembly ${assembly.GetName().Name}"); } var testServices = new ServiceProvider(_services); testServices.Add(typeof(ITestSinkFactory), locator); return(RunTestAssembly(options, ".", _container, testServices) ? 0 : -1); } } else { return(RunTestAssembly(options, ".", _container, _services) ? 0 : -1); } }
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 }); }
public FontLoader( NuGetDependencyResolver nuget, IContentProvider contentProvider = null, string defaultFont = null, int baseFontSize = 72, int textureSize = 512) { if (nuget == null) { throw new ArgumentNullException(nameof(nuget)); } if (baseFontSize <= 1 || baseFontSize > textureSize) { throw new ArgumentOutOfRangeException(nameof(baseFontSize)); } if (textureSize <= 1) { throw new ArgumentOutOfRangeException(nameof(textureSize)); } this.dependencyResolver = nuget; this.defaultFont = defaultFont ?? "Consola"; this.contentProvider = contentProvider; this.baseFontSize = baseFontSize; this.textureSize = textureSize; this.freetype = new Lazy <Library>(LoadFreeTypeLibrary); }
public void LibrariesAreResolvedCorrectly(string packageName, string framework, bool resolved) { var repo = new PackageRepository("path/to/packages"); var resolver = new NuGetDependencyResolver(repo); var net45Target = new LockFileTarget { TargetFramework = new FrameworkName(".NETFramework,Version=v4.5"), Libraries = new List<LockFileTargetLibrary> { new LockFileTargetLibrary { Name = "MetaPackage", Version = SemanticVersion.Parse("1.0.0"), }, new LockFileTargetLibrary { Name = "Net451LibPackage", Version = SemanticVersion.Parse("1.0.0"), }, new LockFileTargetLibrary { Name = "Net451RefPackage", Version = SemanticVersion.Parse("1.0.0"), }, new LockFileTargetLibrary { Name = "AssemblyPlaceholderPackage", Version = SemanticVersion.Parse("1.0.0"), CompileTimeAssemblies = new List<LockFileItem> { Path.Combine("ref", "net45", "_._") }, RuntimeAssemblies = new List<LockFileItem> { Path.Combine("lib", "net45", "_._") } } } }; var dnx451Target = new LockFileTarget { TargetFramework = new FrameworkName("DNX,Version=v4.5.1"), Libraries = new List<LockFileTargetLibrary> { new LockFileTargetLibrary { Name = "MetaPackage", Version = SemanticVersion.Parse("1.0.0") }, new LockFileTargetLibrary { Name = "Net451LibPackage", Version = SemanticVersion.Parse("1.0.0"), CompileTimeAssemblies = new List<LockFileItem> { Path.Combine("lib", "net451", "Net451LibPackage.dll") }, RuntimeAssemblies = new List<LockFileItem> { Path.Combine("lib", "net451", "Net451LibPackage.dll") } }, new LockFileTargetLibrary { Name = "Net451RefPackage", Version = SemanticVersion.Parse("1.0.0"), CompileTimeAssemblies = new List<LockFileItem> { Path.Combine("ref", "net451", "Net451LibPackage.dll") } }, new LockFileTargetLibrary { Name = "AssemblyPlaceholderPackage", Version = SemanticVersion.Parse("1.0.0") } } }; var metaPackageLibrary = new LockFilePackageLibrary { Name = "MetaPackage", Version = SemanticVersion.Parse("1.0.0") }; var net451LibPackageLibrary = new LockFilePackageLibrary { Name = "Net451LibPackage", Version = SemanticVersion.Parse("1.0.0"), Files = new List<string> { Path.Combine("lib", "net451", "Net451LibPackage.dll"), Path.Combine("lib", "net451", "Net451LibPackage.xml") } }; var net451RefPackageLibrary = new LockFilePackageLibrary { Name = "Net451RefPackage", Version = SemanticVersion.Parse("1.0.0"), Files = new List<string> { Path.Combine("ref", "net451", "Net451LibPackage.dll") } }; var assemblyPlaceholderPackageLibrary = new LockFilePackageLibrary { Name = "AssemblyPlaceholderPackage", Version = SemanticVersion.Parse("1.0.0"), Files = new List<string> { Path.Combine("lib", "net45", "_._"), Path.Combine("ref", "net45", "_._"), } }; var lockFile = new LockFile() { Targets = new List<LockFileTarget> { net45Target, dnx451Target }, PackageLibraries = new List<LockFilePackageLibrary> { metaPackageLibrary, net451LibPackageLibrary, net451RefPackageLibrary, assemblyPlaceholderPackageLibrary } }; resolver.ApplyLockFile(lockFile); var libToLookup = new LibraryRange(packageName, frameworkReference: false); Assert.Equal(resolved, resolver.GetDescription(libToLookup, new FrameworkName(framework)).Resolved); }
public void AddLoader(NuGetDependencyResolver nugetLoader) { Loaders.Add(nugetLoader); }
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); } }
public NuGetAssemblyLoader(IAssemblyLoaderEngine loaderEngine, NuGetDependencyResolver dependencyResolver) { _dependencyResolver = dependencyResolver; _loaderEngine = loaderEngine; }
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); } }
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); } }
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); }
public NuGetAssemblyLoader(IAssemblyLoadContextAccessor loadContextAccessor, NuGetDependencyResolver dependencyResolver) { _dependencyResolver = dependencyResolver; _loadContextAccessor = loadContextAccessor; }
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()); }
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()); }
public void LibrariesAreResolvedCorrectly(string packageName, string framework, bool resolved) { var repo = new PackageRepository("path/to/packages"); var resolver = new NuGetDependencyResolver(repo); var net45Target = new LockFileTarget { TargetFramework = new FrameworkName(".NETFramework,Version=v4.5"), Libraries = new List <LockFileTargetLibrary> { new LockFileTargetLibrary { Name = "MetaPackage", Version = SemanticVersion.Parse("1.0.0"), }, new LockFileTargetLibrary { Name = "Net451LibPackage", Version = SemanticVersion.Parse("1.0.0"), }, new LockFileTargetLibrary { Name = "Net451RefPackage", Version = SemanticVersion.Parse("1.0.0"), }, new LockFileTargetLibrary { Name = "AssemblyPlaceholderPackage", Version = SemanticVersion.Parse("1.0.0"), CompileTimeAssemblies = new List <LockFileItem> { Path.Combine("ref", "net45", "_._") }, RuntimeAssemblies = new List <LockFileItem> { Path.Combine("lib", "net45", "_._") } } } }; var dnx451Target = new LockFileTarget { TargetFramework = new FrameworkName("DNX,Version=v4.5.1"), Libraries = new List <LockFileTargetLibrary> { new LockFileTargetLibrary { Name = "MetaPackage", Version = SemanticVersion.Parse("1.0.0") }, new LockFileTargetLibrary { Name = "Net451LibPackage", Version = SemanticVersion.Parse("1.0.0"), CompileTimeAssemblies = new List <LockFileItem> { Path.Combine("lib", "net451", "Net451LibPackage.dll") }, RuntimeAssemblies = new List <LockFileItem> { Path.Combine("lib", "net451", "Net451LibPackage.dll") } }, new LockFileTargetLibrary { Name = "Net451RefPackage", Version = SemanticVersion.Parse("1.0.0"), CompileTimeAssemblies = new List <LockFileItem> { Path.Combine("ref", "net451", "Net451LibPackage.dll") } }, new LockFileTargetLibrary { Name = "AssemblyPlaceholderPackage", Version = SemanticVersion.Parse("1.0.0") } } }; var metaPackageLibrary = new LockFilePackageLibrary { Name = "MetaPackage", Version = SemanticVersion.Parse("1.0.0") }; var net451LibPackageLibrary = new LockFilePackageLibrary { Name = "Net451LibPackage", Version = SemanticVersion.Parse("1.0.0"), Files = new List <string> { Path.Combine("lib", "net451", "Net451LibPackage.dll"), Path.Combine("lib", "net451", "Net451LibPackage.xml") } }; var net451RefPackageLibrary = new LockFilePackageLibrary { Name = "Net451RefPackage", Version = SemanticVersion.Parse("1.0.0"), Files = new List <string> { Path.Combine("ref", "net451", "Net451LibPackage.dll") } }; var assemblyPlaceholderPackageLibrary = new LockFilePackageLibrary { Name = "AssemblyPlaceholderPackage", Version = SemanticVersion.Parse("1.0.0"), Files = new List <string> { Path.Combine("lib", "net45", "_._"), Path.Combine("ref", "net45", "_._"), } }; var lockFile = new LockFile() { Targets = new List <LockFileTarget> { net45Target, dnx451Target }, PackageLibraries = new List <LockFilePackageLibrary> { metaPackageLibrary, net451LibPackageLibrary, net451RefPackageLibrary, assemblyPlaceholderPackageLibrary } }; resolver.ApplyLockFile(lockFile); var libToLookup = new LibraryRange(packageName, frameworkReference: false); Assert.Equal(resolved, resolver.GetDescription(libToLookup, new FrameworkName(framework)).Resolved); }
public NuGetAssemblyLoader(IAssemblyLoadContextAccessor loadContextAccessor, NuGetDependencyResolver dependencyResolver) { _dependencyResolver = dependencyResolver; _loadContextAccessor = loadContextAccessor; }
public PackPackage(NuGetDependencyResolver nugetDependencyResolver, LibraryDescription libraryDescription) { _nugetDependencyResolver = nugetDependencyResolver; _libraryDescription = libraryDescription; }