Пример #1
0
        /// <summary>
        /// Deletes a package from a FileSystem.
        /// </summary>
        /// <param name="fileSystem">The FileSystem where the specified package is deleted.</param>
        /// <param name="packageId">The package Id.</param>
        /// <param name="packageVersion">The package Id.</param>
        private static void DeletePackageFromFileSystem(IFileSystem fileSystem, string packageId, string packageVersion)
        {
            var pathResolver    = new DefaultPackagePathResolver(fileSystem);
            var packageFileName = pathResolver.GetPackageFileName(packageId, new SemanticVersion(packageVersion));

            fileSystem.DeleteFile(packageFileName);
        }
		void CreatePackageManager(IProject project, PackageReferenceRepositoryHelper packageRefRepositoryHelper)
		{
			options = new TestablePackageManagementOptions();
			options.PackagesDirectory = "packages";
			
			repositoryPaths = new SolutionPackageRepositoryPath(project, options);
			var pathResolver = new DefaultPackagePathResolver(repositoryPaths.PackageRepositoryPath);
			
			fakeFileSystem = new FakeFileSystem();
			
			fakeFeedSourceRepository = new FakePackageRepository();
			fakeSolutionSharedRepository = packageRefRepositoryHelper.FakeSharedSourceRepository;
			
			fakePackageOperationResolverFactory = new FakePackageOperationResolverFactory();
			
			var fakeSolutionPackageRepository = new FakeSolutionPackageRepository();
			fakeSolutionPackageRepository.FileSystem = fakeFileSystem;
			fakeSolutionPackageRepository.PackagePathResolver = pathResolver;
			fakeSolutionPackageRepository.FakeSharedRepository = fakeSolutionSharedRepository;
			
			packageManager = new SharpDevelopPackageManager(fakeFeedSourceRepository,
				packageRefRepositoryHelper.FakeProjectSystem,
				fakeSolutionPackageRepository,
				fakePackageOperationResolverFactory);
		}
Пример #3
0
        public NugetService(Solution solution)
        {
            //_defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl);

            var factory = new PackageRepositoryFactory();

            _remoteRepository = factory.CreateRepository(GalleryUrl);
            _localRepository = factory.CreateRepository(solution.PackagesFolder());

            _sourceRepository = new AggregateRepository(new[] { _remoteRepository, _localRepository });

            _fileSystem = new PhysicalFileSystem(solution.PackagesFolder());
            _pathResolver = new DefaultPackagePathResolver(_fileSystem);

            _console = new Console();
            _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){
                Logger = _console
            };

            _packages = new Cache<NugetDependency, IPackage>(dep =>
            {
                Install(dep);
                return _sourceRepository.FindPackage(dep.Name, dep.Version);
            });
        }
Пример #4
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="mapPath">A delegate method used to perform a Server.MapPath operation</param>
        public DefaultPackageContext(RebelSettings settings, Func<string, string> mapPath)
        {
            _settings = settings;

            _pluginInstallFolderPath = mapPath(_settings.PluginConfig.PluginsPath + "/Packages");
            _localPackageRepoFolderPath = mapPath(_settings.RebelFolders.LocalPackageRepositoryFolder);

            //create lazy instances of each
            _localPackageRepository = new Lazy<IPackageRepository>(
                () =>
                    {
                        //create a new path resolver with false as 'useSideBySidePaths' so that it doesn't install with version numbers.
                        var packageFileSys = new PhysicalFileSystem(_localPackageRepoFolderPath);
                        var packagePathResolver = new DefaultPackagePathResolver(packageFileSys, false);
                        return new LocalPackageRepository(packagePathResolver, packageFileSys, true);
                    });

            _localPackageManager = new Lazy<IPackageManager>(
                () =>
                    {
                        //create a new path resolver with false as 'useSideBySidePaths' so that it doesn't install with version numbers.
                        var packageFileSys = new PhysicalFileSystem(_pluginInstallFolderPath);
                        var packagePathResolver = new DefaultPackagePathResolver(packageFileSys, false);
                        return new PackageManager(_localPackageRepository.Value, packagePathResolver, packageFileSys);
                    });
            
            // Public packages
            _publicPackageRepository = new Lazy<IPackageRepository>(
                () => PackageRepositoryFactory.Default.CreateRepository(_settings.PublicPackageRepository.RepositoryAddress));
            
            _publicPackageManager = new Lazy<IPackageManager>(
                () => new PackageManager(_publicPackageRepository.Value, mapPath(_settings.PluginConfig.PluginsPath + "/Packages")));

        }
Пример #5
0
        public void GetRemotePackagesTest()
        {
            // Arrange
            var siteRoot = "x:\\";
            var localRepository = new MockPackageRepository();
            var sourceRepository = new MockServiceBasePackageRepository();
            var projectSystem = new WebProjectSystem(siteRoot);
            var pathResolver = new DefaultPackagePathResolver(projectSystem);
            var projectManager = new ProjectManager(sourceRepository, pathResolver, projectSystem, localRepository);

            var net40 = new FrameworkName(".NETFramework", new Version("4.0.0.0"));
            var net45 = new FrameworkName(".NETFramework", new Version("4.5.0.0"));

            IPackage packageA = PackageFactory.Create("A", new Version("1.0"), null, new FrameworkName[]{ net40 });
            IPackage packageB = PackageFactory.Create("B", new Version("1.0"), null, new FrameworkName[]{ net45 });
            IPackage packageC = PackageFactory.Create("C", new Version("1.0"));

            sourceRepository.AddPackage(packageA);
            sourceRepository.AddPackage(packageB);
            sourceRepository.AddPackage(packageC);

            // NOTE THAT target framework used by WebProjectManager would be .NETFramework, Version=4.0.0.0
            var webProjectManager = new WebProjectManager(projectManager, siteRoot);

            // Act
            var packages = webProjectManager.GetRemotePackages(null, false).ToList();

            // Assert
            Assert.Equal(2, packages.Count);
            Assert.Equal(packageA, packages[0]);
            Assert.Equal(packageC, packages[1]);
        }
Пример #6
0
        /// <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)
        {
            var resolver = new DefaultPackagePathResolver(root.TargetPackagesPath);

            if (root.PublishedLockFile == null)
            {
                return Enumerable.Empty<string>();
            }

            var directories = new HashSet<string>();

            foreach (var target in root.PublishedLockFile.Targets)
            {
                foreach (var library in target.Libraries)
                {
                    var packagesDir = resolver.GetInstallPath(library.Name, library.Version);

                    foreach (var path in library.RuntimeAssemblies)
                    {
                        var assemblyPath = CombinePath(packagesDir, path);
                        directories.Add(Path.GetDirectoryName(assemblyPath));
                    }
                }
            }

            return directories;
        }
Пример #7
0
        public void DnuPackagesAddOverwritesInstalledPackageWhenShasDoNotMatch(string flavor, string os, string architecture)
        {
            var runtimeHomeDir = TestUtils.GetRuntimeHomeDir(flavor, os, architecture);
            using (var tempSamplesDir = TestUtils.PrepareTemporarySamplesFolder(runtimeHomeDir))
            {
                var projectFilePath = Path.Combine(tempSamplesDir, ProjectName, Runtime.Project.ProjectFileName);
                var packagesDir = Path.Combine(tempSamplesDir, PackagesDirName);
                var packagePathResolver = new DefaultPackagePathResolver(packagesDir);
                var nuspecPath = packagePathResolver.GetManifestFilePath(ProjectName, ProjectVersion);

                SetProjectDescription(projectFilePath, "Old");
                BuildPackage(tempSamplesDir, runtimeHomeDir);

                string stdOut;
                var exitCode = DnuPackagesAddOutputPackage(tempSamplesDir, runtimeHomeDir, out stdOut);
                Assert.Equal(0, exitCode);
                Assert.Contains($"Installing {ProjectName}.{ProjectVersion}", stdOut);

                var lastInstallTime = new FileInfo(nuspecPath).LastWriteTimeUtc;

                SetProjectDescription(projectFilePath, "New");
                BuildPackage(tempSamplesDir, runtimeHomeDir);

                exitCode = DnuPackagesAddOutputPackage(tempSamplesDir, runtimeHomeDir, out stdOut);
                Assert.Equal(0, exitCode);
                Assert.Contains($"Overwriting {ProjectName}.{ProjectVersion}", stdOut);

                var xDoc = XDocument.Load(packagePathResolver.GetManifestFilePath(ProjectName, ProjectVersion));
                var actualDescription = xDoc.Root.Descendants()
                    .Single(x => string.Equals(x.Name.LocalName, "description")).Value;
                Assert.Equal("New", actualDescription);
                Assert.NotEqual(lastInstallTime, new FileInfo(nuspecPath).LastWriteTimeUtc);
            }
        }
Пример #8
0
        public void DnuPackagesAddSkipsInstalledPackageWhenShasMatch(string flavor, string os, string architecture)
        {
            var runtimeHomeDir = TestUtils.GetRuntimeHomeDir(flavor, os, architecture);
            using (var tempSamplesDir = TestUtils.PrepareTemporarySamplesFolder(runtimeHomeDir))
            {
                var projectFilePath = Path.Combine(tempSamplesDir, ProjectName, Runtime.Project.ProjectFileName);
                var packagesDir = Path.Combine(tempSamplesDir, PackagesDirName);
                var packagePathResolver = new DefaultPackagePathResolver(packagesDir);
                var nuspecPath = packagePathResolver.GetManifestFilePath(ProjectName, ProjectVersion);

                BuildPackage(tempSamplesDir, runtimeHomeDir);

                string stdOut;
                var exitCode = DnuPackagesAddOutputPackage(tempSamplesDir, runtimeHomeDir, out stdOut);
                Assert.Equal(0, exitCode);
                Assert.Contains($"Installing {ProjectName}.{ProjectVersion}", stdOut);

                var lastInstallTime = new FileInfo(nuspecPath).LastWriteTimeUtc;

                exitCode = DnuPackagesAddOutputPackage(tempSamplesDir, runtimeHomeDir, out stdOut);
                Assert.Equal(0, exitCode);
                Assert.Contains($"{ProjectName}.{ProjectVersion} already exists", stdOut);
                Assert.Equal(lastInstallTime, new FileInfo(nuspecPath).LastWriteTimeUtc);
            }
        }
Пример #9
0
        internal static async Task InstallFromStream(Stream stream, Library library, string packagesDirectory,
            SHA512 sha512)
        {
            var packagePathResolver = new DefaultPackagePathResolver(packagesDirectory);

            var targetPath = packagePathResolver.GetInstallPath(library.Name, library.Version);
            var targetNuspec = packagePathResolver.GetManifestFilePath(library.Name, library.Version);
            var targetNupkg = packagePathResolver.GetPackageFilePath(library.Name, library.Version);
            var hashPath = packagePathResolver.GetHashPath(library.Name, library.Version);

            // Acquire the lock on a nukpg before we extract it to prevent the race condition when multiple
            // processes are extracting to the same destination simultaneously
            await ConcurrencyUtilities.ExecuteWithFileLocked(targetNupkg, async createdNewLock =>
            {
                // If this is the first process trying to install the target nupkg, go ahead
                // After this process successfully installs the package, all other processes
                // waiting on this lock don't need to install it again
                if (createdNewLock)
                {
                    Directory.CreateDirectory(targetPath);
                    using (var nupkgStream = new FileStream(targetNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete))
                    {
                        await stream.CopyToAsync(nupkgStream);
                        nupkgStream.Seek(0, SeekOrigin.Begin);

                        ExtractPackage(targetPath, nupkgStream);
                    }

                    // Fixup the casing of the nuspec on disk to match what we expect
                    var nuspecFile = Directory.EnumerateFiles(targetPath, "*" + NuGet.Constants.ManifestExtension).Single();

                    if (!string.Equals(nuspecFile, targetNuspec, StringComparison.Ordinal))
                    {
                        Manifest manifest = null;
                        using (var nuspecStream = File.OpenRead(nuspecFile))
                        {
                            manifest = Manifest.ReadFrom(nuspecStream, validateSchema: false);
                            manifest.Metadata.Id = library.Name;
                        }

                        // Delete the previous nuspec file
                        File.Delete(nuspecFile);

                        // Write the new manifest
                        using (var targetNuspecStream = File.OpenWrite(targetNuspec))
                        {
                            manifest.Save(targetNuspecStream);
                        }
                    }

                    stream.Seek(0, SeekOrigin.Begin);
                    var nupkgSHA = Convert.ToBase64String(sha512.ComputeHash(stream));
                    File.WriteAllText(hashPath, nupkgSHA);
                }

                return 0;
            });
        }
Пример #10
0
        public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig)
        {
            if (rootDirectory == null) throw new ArgumentNullException(nameof(rootDirectory));
            if (configFile == null) throw new ArgumentNullException(nameof(configFile));
            if (overrideFile == null) throw new ArgumentNullException(nameof(overrideFile));

            // First try the override file with custom settings
            var configFileName = overrideFile;
            var configFilePath = Path.Combine(rootDirectory, configFileName);

            if (!File.Exists(configFilePath))
            {
                // Override file does not exist, fallback to default config file
                configFileName = configFile;
                configFilePath = Path.Combine(rootDirectory, configFileName);

                if (!File.Exists(configFilePath))
                {
                    throw new ArgumentException($"Invalid installation. Configuration file [{configFile}] not found", nameof(configFile));
                }
            }

            rootFileSystem = new PhysicalFileSystem(rootDirectory);
            Settings = NuGet.Settings.LoadDefaultSettings(rootFileSystem, configFileName, null);

            string installPath = Settings.GetRepositoryPath();
            packagesFileSystem = new PhysicalFileSystem(installPath);
            packageSourceProvider = new PackageSourceProvider(Settings);

            repositoryFactory = new PackageRepositoryFactory();
            SourceRepository = packageSourceProvider.CreateAggregateRepository(repositoryFactory, true);

            pathResolver = new DefaultPackagePathResolver(packagesFileSystem);

            Manager = new PackageManager(SourceRepository, pathResolver, packagesFileSystem);

            var mainPackageList = Settings.GetConfigValue(MainPackagesKey);
            if (string.IsNullOrWhiteSpace(mainPackageList))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{MainPackagesKey}] in config");
            }
            MainPackageIds = mainPackageList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            VSIXPluginId = Settings.GetConfigValue(VsixPluginKey);
            if (string.IsNullOrWhiteSpace(VSIXPluginId))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{VsixPluginKey}] in config");
            }

            RepositoryPath = Settings.GetConfigValue(RepositoryPathKey);
            if (string.IsNullOrWhiteSpace(RepositoryPath))
            {
                RepositoryPath = DefaultGamePackagesDirectory;
            }

            // Setup NugetCachePath in the cache folder
            Environment.SetEnvironmentVariable("NuGetCachePath", Path.Combine(rootDirectory, "Cache", RepositoryPath));
        }
Пример #11
0
 // Methods
 public WebProjectManager(string remoteSource, string siteRoot)
 {
     string webRepositoryDirectory = GetWebRepositoryDirectory(siteRoot);
     var sourceRepository = PackageRepositoryFactory.Default.CreateRepository(remoteSource);
     var pathResolver = new DefaultPackagePathResolver(webRepositoryDirectory);
     var localRepository = PackageRepositoryFactory.Default.CreateRepository(webRepositoryDirectory);
     IProjectSystem project = new WebProjectSystem(siteRoot);
     _projectManager = new ProjectManager(sourceRepository, pathResolver, project, localRepository);
 }
 public PackageInstaller(string localRepositoryPath, string projectPath, IConsole console, string projectName, bool addReferencesToProject)
 {
     _projectName = projectName;
     _localRepositoryPath                     = localRepositoryPath;
     IPackagePathResolver packagePathResolver = new DefaultPackagePathResolver(localRepositoryPath);
     IPackageRepository localRepository       = new UnzipedLocalPackageRepository(localRepositoryPath, _flagFileName);
     _projectSystem                           = new ModdedMSBuildProjectSystem(projectPath, addReferencesToProject) { Logger = console };
     _projectManager                          = new ProjectManager(localRepository, packagePathResolver, _projectSystem, localRepository) { Logger = console };
 }
        protected PackageManagerService()
        {
            var repo        = PackageRepositoryFactory.Default.CreateRepository(MyGetRepoUrl);
            var path        = new DefaultPackagePathResolver(MyGetRepoUrl);
            var fileSystem  = new PhysicalFileSystem(HostingEnvironment.MapPath("~/App_Plugins/Packages"));
            var localRepo   = PackageRepositoryFactory.Default.CreateRepository(HostingEnvironment.MapPath("~/App_Plugins/Packages"));

            //Create a NuGet Package Manager
            PackageManager = new PackageManager(repo, path, fileSystem, localRepo);
        }
Пример #14
0
        /// <summary>
        /// Pushes a package to a FileSystem.
        /// </summary>
        /// <param name="fileSystem">The FileSystem that the package is pushed to.</param>
        /// <param name="package">The package to be pushed.</param>
        private static void PushPackageToFileSystem(IFileSystem fileSystem, IPackage package)
        {
            var pathResolver    = new DefaultPackagePathResolver(fileSystem);
            var packageFileName = pathResolver.GetPackageFileName(package);

            using (var stream = package.GetStream())
            {
                fileSystem.AddFile(packageFileName, stream);
            }
        }
        public ExtensionManagerTests()
        {
            resharperApi = new FakeReSharperApi(Version.Parse("6.0.0.0"));

            localRepository = new FakePackageRepository(RepoPath);
            fileSystem = new FakeFileSystem(RepoPath);
            var pathResolver = new DefaultPackagePathResolver(fileSystem);
            packageManager = new PackageManager(new AggregateRepository(Enumerable.Empty<IPackageRepository>()), pathResolver, fileSystem, localRepository);
            manager = new ExtensionManager.Implementation.ExtensionManager(resharperApi, null, packageManager);
        }
		ISharpDevelopPackageManager CreatePackageManager(
			IFileSystem fileSystem, 
			IPackageRepository packageRepository, 
			MSBuildBasedProject project)
		{
			DefaultPackagePathResolver pathResolver = new DefaultPackagePathResolver(fileSystem);
			ISharedPackageRepository sharedRepository = CreateSharedRepository(pathResolver, fileSystem);
			IProjectSystem projectSystem = CreateProjectSystem(project);
			return new SharpDevelopPackageManager(packageRepository, projectSystem, fileSystem, sharedRepository, pathResolver);
		}
Пример #17
0
 public WebProjectManager(string remoteSource, string siteRoot)
 {
     string webRepositoryDirectory = GetWebRepositoryDirectory(siteRoot);
     Uri uri = new Uri(remoteSource);
     IPackageRepository repository = new DataServicePackageRepository(uri);//PackageRepositoryFactory.Default.CreateRepository(remoteSource);
     IPackagePathResolver resolver = new DefaultPackagePathResolver(webRepositoryDirectory);
     IPackageRepository repository2 = new LocalPackageRepository(webRepositoryDirectory, false); //PackageRepositoryFactory.Default.CreateRepository(webRepositoryDirectory);
     IProjectSystem system = new WebProjectSystem(siteRoot);
     ((DataServicePackageRepository)repository).ProgressAvailable += new EventHandler<ProgressEventArgs>(repository_ProgressAvailable);
     //((DataServicePackageRepository)repository).SendingRequest += new EventHandler<WebRequestEventArgs>(repository_sendingRequest);
     this._projectManager = new ProjectManager(repository, resolver, system, repository2);
     _projectManager.Logger = new LoggerController();
 }
Пример #18
0
        public void Emit(PackRoot root)
        {
            var package = _nugetDependencyResolver.FindCandidate(
                _libraryDescription.Identity.Name,
                _libraryDescription.Identity.Version);

            Console.WriteLine("Packing nupkg dependency {0} {1}", package.Id, package.Version);

            var resolver = new DefaultPackagePathResolver(root.PackagesPath);

            TargetPath = resolver.GetInstallPath(package.Id, package.Version);

            if (Directory.Exists(TargetPath))
            {
                if (root.Overwrite)
                {
                    root.Operations.Delete(TargetPath);
                }
                else
                {
                    Console.WriteLine("  {0} already exists.", TargetPath);
                    return;
                }
            }

            Console.WriteLine("  Target {0}", TargetPath);

            var targetNupkgPath = resolver.GetPackageFilePath(package.Id, package.Version);
            var hashPath = resolver.GetHashPath(package.Id, package.Version);

            using (var sourceStream = package.GetStream())
            {
                using (var archive = new ZipArchive(sourceStream, ZipArchiveMode.Read))
                {
                    root.Operations.ExtractNupkg(archive, TargetPath);
                }
            }
            using (var sourceStream = package.GetStream())
            {
                using (var targetStream = new FileStream(targetNupkgPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    sourceStream.CopyTo(targetStream);
                }

                sourceStream.Seek(0, SeekOrigin.Begin);
                var sha512Bytes = SHA512.Create().ComputeHash(sourceStream);
                File.WriteAllText(hashPath, Convert.ToBase64String(sha512Bytes));
            }
        }
Пример #19
0
        public void Emit(PublishRoot root)
        {
            root.Reports.Quiet.WriteLine("Using {0} dependency {1}", _libraryDescription.Type, Library);

            var packagePathResolver = new DefaultPackagePathResolver(root.SourcePackagesPath);
            var srcNupkgPath = packagePathResolver.GetPackageFilePath(_libraryDescription.Identity.Name, _libraryDescription.Identity.Version);

            var options = new Microsoft.Framework.PackageManager.Packages.AddOptions
            {
                NuGetPackage = srcNupkgPath,
                SourcePackages = root.TargetPackagesPath,
                Reports = root.Reports
            };

            var packagesAddCommand = new Microsoft.Framework.PackageManager.Packages.AddCommand(options);
            packagesAddCommand.Execute().GetAwaiter().GetResult();
        }
Пример #20
0
        public void Emit(PublishRoot root)
        {
            root.Reports.Quiet.WriteLine("Using {0} dependency {1}", _package.Type, Library);

            var srcPackagePathResolver = new DefaultPackagePathResolver(root.SourcePackagesPath);
            var targetPackagePathResolver = new DefaultPackagePathResolver(root.TargetPackagesPath);
            var srcPackageDir = srcPackagePathResolver.GetInstallPath(
                _package.Identity.Name,
                _package.Identity.Version);
            var targetPackageDir = targetPackagePathResolver.GetInstallPath(
                _package.Identity.Name,
                _package.Identity.Version);

            root.Reports.Quiet.WriteLine("    Source {0}", srcPackageDir.Bold());
            root.Reports.Quiet.WriteLine("    Target {0}", targetPackageDir);

            root.Operations.Copy(srcPackageDir, targetPackageDir);
        }
		void CreatePackageManager(IProject project, PackageReferenceRepositoryHelper packageRefRepositoryHelper)
		{
			options = new PackageManagementOptions(new Properties());
			options.PackagesDirectory = "packages";
			
			repositoryPaths = new PackageRepositoryPaths(project, options);
			var pathResolver = new DefaultPackagePathResolver(repositoryPaths.SolutionPackagesPath);
			
			fakeFileSystem = new FakeFileSystem();
			
			fakeFeedSourceRepository = new FakePackageRepository();
			fakeSolutionSharedRepository = packageRefRepositoryHelper.FakeSharedSourceRepository;
			
			packageManager = new SharpDevelopPackageManager(fakeFeedSourceRepository,
				packageRefRepositoryHelper.FakeProjectSystem,
				fakeFileSystem,
				fakeSolutionSharedRepository,
				pathResolver);
		}
Пример #22
0
        public IPackageManager CreatePackageManager(IEnumerable<string> remoteSources, string packagesPath)
        {
            if (remoteSources == null)
            {
                throw new ArgumentNullException("remoteSources");
            }
            if (!remoteSources.Any())
            {
                throw new ArgumentException("Must provide at least one remote source");
            }

            var sourceRepo = new AggregateRepository(PackageRepositoryFactory.Default, remoteSources, true);
            var pathResolver = new DefaultPackagePathResolver(packagesPath);
            var packageManagerFileSystem = new PhysicalFileSystem(packagesPath);

            return new PackageManager(sourceRepository: sourceRepo,
                                        pathResolver: pathResolver,
                                        fileSystem: packageManagerFileSystem);
        }
Пример #23
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;
        }
Пример #24
0
        public async Task Emit(PublishRoot root)
        {
            root.Reports.Quiet.WriteLine("Using {0} dependency {1}", _libraryDescription.Type, Library);

            var packagePathResolver = new DefaultPackagePathResolver(root.SourcePackagesPath);
            var srcNupkgPath = packagePathResolver.GetPackageFilePath(_libraryDescription.Identity.Name, _libraryDescription.Identity.Version);

            var options = new Packages.AddOptions
            {
                NuGetPackage = srcNupkgPath,
                PackageHashFilePath = Path.ChangeExtension(srcNupkgPath, NuGet.Constants.HashFileExtension),
                SourcePackages = root.TargetPackagesPath,
            };

            // Mute "packages add" subcommand
            options.Reports = Reports.Constants.NullReports;

            var packagesAddCommand = new Packages.AddCommand(options);
            await packagesAddCommand.Execute();
        }
Пример #25
0
        public IProjectManager CreateProjectManager(IEnumerable<string> remoteSources, string packagesPath, IProjectSystem project)
        {
            if(remoteSources == null)
            {
                throw new ArgumentNullException("remoteSources");
            }
            if (!remoteSources.Any())
            {
                throw new ArgumentException("Must provide at least one remote source");
            }

            var sourceRepo = new AggregateRepository(PackageRepositoryFactory.Default, remoteSources, true);
            var pathResolver = new DefaultPackagePathResolver(packagesPath);

            var packagesConfigRepo = new PackageReferenceRepository(project, project.ProjectName, new SharedPackageRepository(packagesPath));

            return new ProjectManager(sourceRepository: sourceRepo,
                                        pathResolver: pathResolver,
                                        localRepository: packagesConfigRepo,
                                        project: project);
        }
Пример #26
0
        //download the specified version of the package and update project reference to it. The newly downloaded package
        //will be located in /packages folder. The updated project reference can be checked in corresponding .csproj file.
        public bool Execute(string packageid, string projectFile, SemanticVersion version, string packages)
        {
            try
            {
                System.Console.WriteLine("-------------------------------------");
                System.Console.WriteLine("Project File " + projectFile);
                System.Console.WriteLine("Package "+packageid);
                System.Console.WriteLine("Version "+version);

                IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
                var packagePathResolver = new DefaultPackagePathResolver(packages);
                var packagesFolderFileSystem = new PhysicalFileSystem(packages);
                var projectSystem = new MSBuildProjectSystem(projectFile);
                var localRepository = new LocalPackageRepository(packagePathResolver, packagesFolderFileSystem);
                var projectManager = new ProjectManager(repo, packagePathResolver, projectSystem, localRepository);

                projectManager.RemovePackageReference(packageid,true,false);
                projectManager.AddPackageReference(packageid, version, true, false);
                projectSystem.Save();

                string filename = packageid + "." + version;
                string[] s = Directory.GetFiles(packages+ @"\"+filename);
                if (s.IsEmpty()) { System.Console.WriteLine("empty"); }
                else
                {
                    var nupkgFile = new PhysicalFileSystem(s[0]);
                    ZipPackage z = new ZipPackage(s[0]);
                    z.ExtractContents(nupkgFile, packages + @"\" + filename);
                }
                System.Console.WriteLine("Successfully updated");
                return true;
            }
            catch (Exception e)
            {
                System.Console.Write("failure");
                System.Console.Write(e.StackTrace);
                return false;
            }
        }
Пример #27
0
        public NugetService(Solution solution, IEnumerable<string> remoteFeeds)
        {
            var repoBuilder = new PackageRepositoryBuilder();

            _remoteRepository = repoBuilder.BuildRemote(remoteFeeds);
            _localRepository = repoBuilder.BuildLocal(solution.PackagesFolder());
            _sourceRepository = repoBuilder.BuildSource(_remoteRepository, _localRepository);

            _fileSystem = new PhysicalFileSystem(solution.PackagesFolder());
            _pathResolver = new DefaultPackagePathResolver(_fileSystem);

            _console = new Console();
            _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){
                Logger = _console
            };

            _packages = new Cache<NugetDependency, IPackage>(dep =>
            {
                Install(dep);
                return _sourceRepository.FindPackage(dep.Name, new SemanticVersion(dep.Version));
            });
        }
		public string GetInstallPath(IPackage package)
		{
			pathResolver = new DefaultPackagePathResolver(PackageRepositoryPath);
			return pathResolver.GetInstallPath(package);
		}
		void CreatePackagePathResolver()
		{
			packagePathResolver = new DefaultPackagePathResolver(repositoryPath.PackageRepositoryPath);
		}
Пример #30
0
 /// <summary>
 /// Deletes a package from a FileSystem.
 /// </summary>
 /// <param name="fileSystem">The FileSystem where the specified package is deleted.</param>
 /// <param name="packageId">The package Id.</param>
 /// <param name="packageVersion">The package Id.</param>
 private static void DeletePackageFromFileSystem(IFileSystem fileSystem, string packageId, string packageVersion)
 {
     var pathResolver = new DefaultPackagePathResolver(fileSystem);
     var packageFileName = pathResolver.GetPackageFileName(packageId, new SemanticVersion(packageVersion));
     fileSystem.DeleteFile(packageFileName);
 }
Пример #31
0
 /// <summary>
 /// Pushes a package to a FileSystem.
 /// </summary>
 /// <param name="fileSystem">The FileSystem that the package is pushed to.</param>
 /// <param name="package">The package to be pushed.</param>
 private static void PushPackageToFileSystem(IFileSystem fileSystem, IPackage package)
 {
     var pathResolver = new DefaultPackagePathResolver(fileSystem);
     var packageFileName = pathResolver.GetPackageFileName(package);
     using (var stream = package.GetStream())
     {
         fileSystem.AddFile(packageFileName, stream);
     }
 }
Пример #32
0
        public bool Execute()
        {
            var projectFile = ResolveProjectFile();
            if (string.IsNullOrEmpty(projectFile))
            {
                return false;
            }

            _solutionRoot = ProjectResolver.ResolveRootDirectory(projectFile);

            var globalFile = GlobalSettings.GetGlobalFilePath(_solutionRoot);
            if (!File.Exists(globalFile))
            {
                _reports.WriteError($"The '{GlobalSettings.GlobalFileName}' is missing from '{_solutionRoot}'.");
                return false;
            }

            var packagesFolder = ResolvePackagesFolder();
            if (string.IsNullOrEmpty(packagesFolder))
            {
                return false;
            }

            var packageVersion = ResolvePackageVersion(projectFile);
            if (packageVersion == null)
            {
                return false;
            }

            var packageResolver = new DefaultPackagePathResolver(packagesFolder);
            var packageFolder = packageResolver.GetPackageDirectory(_packageId, packageVersion);
            packageFolder = Path.Combine(packagesFolder, packageFolder);

            var snapshotInfo = ReadRepositoryInfo(packageFolder);
            if (snapshotInfo == null)
            {
                return false;
            }

            string repoType;
            if (!snapshotInfo.TryGetValue(Constants.RepoTypeKey, out repoType))
            {
                _reports.WriteError("Repository type information is missing from the repository information file.");
                return false;
            }

            var provider = SourceControlProviderFactory.ResolveProvider(repoType, _reports);
            if (provider == null)
            {
                _reports.WriteError($"Unknown repository type '{repoType}'");
                return false;
            }

            if (!provider.IsInstalled)
            {
                _reports.WriteError($"The '{repoType}' client application is not installed.");
                return false;
            }

            var sourcesFolder = ResolveSourcesFolder();

            var sourceFolderName = provider.CreateShortFolderName(snapshotInfo);
            var sourceDestinationFullPath = Path.Combine(sourcesFolder, sourceFolderName);

            if (!Directory.Exists(sourceDestinationFullPath))
            {
                _reports.WriteInformation($"Downloading sources in '{sourceDestinationFullPath}'...");
                if (!provider.GetSources(sourceDestinationFullPath, snapshotInfo))
                {
                    return false;
                }
            }
            else
            {
                _reports.WriteInformation($"Sources already found in '{sourceDestinationFullPath}'");
            }

            var srcFolder = provider.GetSourceFolderPath(snapshotInfo);
            srcFolder = Path.Combine(sourceDestinationFullPath, srcFolder);
            if (!Directory.Exists(srcFolder))
            {
                _reports.WriteError($"The source code folder '{srcFolder}' is missing.");
                return false;
            }

            _reports.Verbose.WriteLine($"Updating {GlobalSettings.GlobalFileName}...");
            ModifyJson(globalFile, jObj =>
                {
                    var projects = jObj["projects"] as JArray;
                    if (projects == null)
                    {
                        projects = new JArray();
                        projects.Add(srcFolder);
                        jObj.Add("projects", projects);
                    }
                    else
                    {
                        if (!projects.Any(t => t.ToString().Equals(srcFolder)))
                        {
                            projects.Add(srcFolder);
                        }
                    }
                });

            return true;
        }