GetPackageReferences() private method

private GetPackageReferences ( ) : IEnumerable
return IEnumerable
Ejemplo n.º 1
0
        public static ICollection <PackageReference> GetPackageReferences(PackageReferenceFile file, string fileName, bool requireVersion)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            var packageReferences = file.GetPackageReferences(requireVersion).ToList();

            foreach (var package in packageReferences)
            {
                // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                // with malformed ids / Versions.
                if (String.IsNullOrEmpty(package.Id))
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandInvalidPackageReference, fileName));
                }
                if (requireVersion && (package.Version == null))
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandPackageReferenceInvalidVersion, package.Id));
                }
            }

            return(packageReferences);
        }
Ejemplo n.º 2
0
        public static ICollection<InstalledPackageReference> GetInstalledPackageReferences(PackageReferenceFile configFile, bool requireVersion)
        {
            if (configFile == null)
            {
                throw new ArgumentNullException("configFile");
            }

            var packageReferences = configFile.GetPackageReferences(requireVersion);
            foreach (var package in packageReferences)
            {
                // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                // with malformed ids / Versions.
                if (String.IsNullOrEmpty(package.Id))
                {
                    throw new InvalidDataException(
                        String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InstallCommandInvalidPackageReference"), 
                        configFile.FullPath));
                }
                if (requireVersion && (package.Version == null))
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InstallCommandPackageReferenceInvalidVersion"), package.Id));
                }
            }

            return packageReferences.Select(pr => CoreConverters.SafeToInstalledPackageReference(pr)).ToList();
        }
Ejemplo n.º 3
0
        public static ICollection <InstalledPackageReference> GetInstalledPackageReferences(PackageReferenceFile configFile, bool requireVersion)
        {
            if (configFile == null)
            {
                throw new ArgumentNullException("configFile");
            }

            var packageReferences = configFile.GetPackageReferences(requireVersion);

            foreach (var package in packageReferences)
            {
                // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                // with malformed ids / Versions.
                if (String.IsNullOrEmpty(package.Id))
                {
                    throw new InvalidDataException(
                              String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InstallCommandInvalidPackageReference"),
                                            configFile.FullPath));
                }
                if (requireVersion && (package.Version == null))
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InstallCommandPackageReferenceInvalidVersion"), package.Id));
                }
            }

            return(packageReferences.Select(pr => CoreConverters.SafeToInstalledPackageReference(pr)).ToList());
        }
        private IEnumerable <IPackage> GetPackagesCore()
        {
            foreach (var reference in _packageReferenceFile.GetPackageReferences())
            {
                IPackage package;

                if (String.IsNullOrEmpty(reference.Id) ||
                    reference.Version == null ||
                    !SourceRepository.TryFindPackage(reference.Id, reference.Version, out package))
                {
                    // Skip bad entries
                    continue;
                }
                else
                {
                    yield return(package);
                }
            }
        }
        /// <summary>
        /// Returns true if the package has a dependency on a project-level package.
        /// </summary>
        /// <param name="package">The package to check.</param>
        /// <returns>True if the package has a dependency on a project-level package.</returns>
        private bool HasProjectLevelPackageDependency(IPackage package)
        {
            var dependencies = package.DependencySets.SelectMany(p => p.Dependencies);

            if (dependencies.IsEmpty())
            {
                return(false);
            }

            HashSet <string> solutionLevelPackages = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            solutionLevelPackages.AddRange(
                PackageReferenceFile.GetPackageReferences().Select(packageReference => packageReference.Id));

            return(dependencies.Any(dependency => !solutionLevelPackages.Contains(dependency.Id)));
        }
Ejemplo n.º 6
0
        public IEnumerable<IPackageReference> FindReferences(string path)
        {
            var packageReferenceFile = new PackageReferenceFile(path);

            var references = packageReferenceFile.GetPackageReferences().ToList();
            if (references.Any())
            {
                foreach (var packageReference in references)
                {
                    yield return new PackageReference(
                            packageReference.Id,
                            packageReference.TargetFramework,
                            packageReference.Version.Version,
                            packageReference.Version.SpecialVersion);
                }

                yield break;
            }

            // No packages.config, check packages folder
            var packagesFolder = Path.Combine(_fileSystem.GetWorkingDirectory(path), Constants.PackagesFolder);
            if (!_fileSystem.DirectoryExists(packagesFolder))
            {
                yield break;
            }

            var repository = new LocalPackageRepository(packagesFolder);

            var arbitraryPackages = repository.GetPackages();
            if (!arbitraryPackages.Any())
            {
                yield break;
            }

            foreach (var arbitraryPackage in arbitraryPackages)
            {
                var newestFramework = GetNewestSupportedFramework(arbitraryPackage)
                    ?? VersionUtility.EmptyFramework;

                yield return new PackageReference(
                        arbitraryPackage.Id,
                        newestFramework,
                        arbitraryPackage.Version.Version,
                        arbitraryPackage.Version.SpecialVersion);
            }
        }
		public void CheckProjectPackages (IDotNetProject project)
		{
			packageReferenceFile = CreatePackageReferenceFile (project.GetPackagesConfigFilePath ());
			packageReferences = packageReferenceFile.GetPackageReferences ().ToList ();

			var targetFramework = new ProjectTargetFramework (project);
			compatibilityReport = new ProjectPackagesCompatibilityReport (targetFramework.TargetFrameworkName);

			foreach (PackageReference packageReference in packageReferences) {
				IPackage package = packageRepository.Repository.FindPackage (packageReference.Id);
				if (package != null) {
					if (PackageNeedsReinstall (project, package, packageReference.TargetFramework)) {
						packagesRequiringReinstallation.Add (package);
					}
				}
			}
		}
		public void CheckProjectPackages (IDotNetProject project)
		{
			IPackageManagementProject packageManagementProject = solution.GetProject (registeredRepositories.ActiveRepository, project);

			packageReferenceFile = CreatePackageReferenceFile (project.GetPackagesConfigFilePath ());
			packageReferences = packageReferenceFile.GetPackageReferences ().ToList ();

			compatibilityReport = new ProjectPackagesCompatibilityReport (packageManagementProject.TargetFramework);

			foreach (PackageReference packageReference in packageReferences) {
				IPackage package = packageManagementProject.FindPackage (packageReference.Id);
				if (package != null) {
					if (PackageNeedsReinstall (project, package, packageReference.TargetFramework)) {
						packagesRequiringReinstallation.Add (package);
					}
				}
			}
		}
Ejemplo n.º 9
0
        //string path)
        //reads all the packages.config files provided as input
        //and returns a map which contains every package mapped to list of project locations in which it is referenced.
        public Dictionary<PackageElement, List<string>> readConfig(List<string> packageFilePaths, string root)
        {
            Dictionary<PackageElement, List<string>> map = new Dictionary<PackageElement, List<string>>();
            string fileName;
            Console.WriteLine("In read config");
            foreach (string path in packageFilePaths)
            {
                //Ignore packages.config files in these folders
                if (path.Contains(@"\.nuget") || path.Contains(@"\packages") || path.Contains(@"\Samples\"))
                    continue;
                fileName = path + "packages.config";
                var file = new PackageReferenceFile(fileName);

                string path1 = path.Replace(root, "");
                Console.WriteLine(path1);
                foreach (PackageReference packageReference in file.GetPackageReferences())
                {
                    PackageElement pe = new PackageElement(packageReference.Id, packageReference.Version);
                    if (!map.ContainsKey(pe))
                    {
                        //Console.WriteLine("add to map: "+packageReference.Id);
                        List<string> ans = new List<string>();
                        ans.Add(path1);
                        map.Add(pe, ans);
                    }
                    else
                    {
                        List<string> ans= map[pe];
                        ans.Add(path1);
                        map[pe] = ans;
                        //Console.WriteLine(" contains key "+ packageReference .Id+" "+ ans.Count);
                    }
                    Console.WriteLine("PackageId={0}, Version={1}", packageReference.Id, packageReference.Version);
                }
            }

            return map;
        }
Ejemplo n.º 10
0
        public static ICollection<PackageReference> GetPackageReferences(PackageReferenceFile file, string fileName, bool requireVersion)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            var packageReferences = file.GetPackageReferences(requireVersion).ToList();
            foreach (var package in packageReferences)
            {
                // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                // with malformed ids / Versions.
                if (String.IsNullOrEmpty(package.Id))
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandInvalidPackageReference, fileName));
                }
                if (requireVersion && (package.Version == null))
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandPackageReferenceInvalidVersion, package.Id));
                }
            }

            return packageReferences;
        }
Ejemplo n.º 11
0
        public IEnumerable<IPackageReference> FindReferences(string path)
        {
            var packageReferenceFile = new PackageReferenceFile(path);
            var references = packageReferenceFile.GetPackageReferences();

            if (!references.Any())
            {
                var packagesFolder = Path.Combine(_fileSystem.GetWorkingDirectory(path), Constants.PackagesFolder);
                if (_fileSystem.DirectoryExists(packagesFolder))
                {
                    var repository = new LocalPackageRepository(packagesFolder);
                    var arbitraryPackages = repository.GetPackages().Where(i => i.GetSupportedFrameworks().Any(x => x.FullName == VersionUtility.ParseFrameworkName("net40").FullName)).ToList();
                    if (arbitraryPackages.Any())
                    {
                        return arbitraryPackages.Select(i => new PackageReference(i.Id, VersionUtility.ParseFrameworkName("net40"), i.Version.Version) { SpecialVersion = i.Version.SpecialVersion });
                    }
                }

                return Enumerable.Empty<IPackageReference>();
            }

            var packages = references.Select(i => new PackageReference(i.Id, i.TargetFramework, i.Version.Version) { SpecialVersion = i.Version.SpecialVersion });
            return packages;
        }
        /*<summary>
        *   Using Nuget.Core API, we gather all nuget`s packages that specific project depend on them.
        * </summary>
        * <returns></returns>
        */
        private static void addDependencies(string projectName, Module module, string localSource, string[] packageConfigPath, string Configuration)
        {
            if (packageConfigPath.Length != 0)
            {
                var sharedPackages = new LocalPackageRepository(localSource);
                var packageReferenceFile = new PackageReferenceFile(packageConfigPath[0]);
                IEnumerable<PackageReference> projectPackages = packageReferenceFile.GetPackageReferences();

                foreach (PackageReference package in projectPackages)
                {
                    var pack = sharedPackages.FindPackage(package.Id, package.Version);

                    using (Stream packageStream = ((NuGet.OptimizedZipPackage)(pack)).GetStream())
                    {
                        byte[] buf = new byte[packageStream.Length];
                        int byteread = packageStream.Read(buf, 0, buf.Length);

                        module.Dependencies.Add(new Dependency
                        {
                            type = "nupkg",
                            md5 = MD5CheckSum.GenerateMD5(buf),
                            sha1 = Sha1Reference.GenerateSHA1(buf),
                            scopes = new List<string> { Configuration },
                            id = pack.Id + ":" + pack.Version
                        });
                    }
                }
            }
        }
Ejemplo n.º 13
0
		protected virtual IEnumerable<PackageReference> GetPackageReferences ()
		{
			if (project.HasPackages ()) {
				var packageReferenceFile = new PackageReferenceFile (project.GetPackagesConfigFilePath ());
				return packageReferenceFile.GetPackageReferences ();
			}
			return new PackageReference [0];
		}
Ejemplo n.º 14
0
        public static IEnumerable<PackageReference> GetPackageReferences(this ICakeContext context, DirectoryPath path)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));
            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var file = new PackageReferenceFile(packagePath.FullPath);
            return file.GetPackageReferences();
        }
Ejemplo n.º 15
0
 public IEnumerable <NuGet.PackageReference> GetPackageReferences()
 {
     return(file.GetPackageReferences());
 }
Ejemplo n.º 16
0
        private static void WriteLicenseInformationToOutputFile(List<string> configDirs, string packageDir, string outputFile)
        {
            var packageBuilder = new StringBuilder();
            var licenseTemplate = EmbeddedResourceExtracter.LoadEmbeddedTextFile(
                Assembly.GetExecutingAssembly(),
                @"NTreva.Templates.LicenseInformation.xml");

            // Determine all the packages we need to scan from the packages.config files
            var usedPackages = new List<Tuple<string, string>>();
            foreach (var dir in configDirs)
            {
                var configFile = Path.Combine(dir, "packages.config");

                var file = new PackageReferenceFile(configFile);
                var packageReferences = file.GetPackageReferences().ToList();

                // Note that we ignore dependencies here because packages.config already contains the full closure
                foreach (var package in packageReferences)
                {
                    // GetPackageReferences returns all records without validating values. We'll throw if we encounter packages
                    // with malformed ids.
                    if (string.IsNullOrEmpty(package.Id))
                    {
                        throw new InvalidDataException(Resources.Exceptions_Messages_InvalidPackageId);
                    }

                    if (!usedPackages.Exists(t => string.Equals(t.Item1, package.Id)))
                    {
                        usedPackages.Add(new Tuple<string, string>(package.Id, package.Version.ToString()));
                    }
                }
            }

            usedPackages.Sort();
            foreach (var tuple in usedPackages)
            {
                WriteToConsole(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.Output_ProcessingPackage,
                        tuple.Item1));

                // Go find the package from the packages directory
                var packageFilePath = Path.Combine(
                    Path.Combine(
                        packageDir,
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "{0}.{1}",
                            tuple.Item1,
                            tuple.Item2)),
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "{0}.{1}.{2}",
                        tuple.Item1,
                        tuple.Item2,
                        "nupkg"));
                if (File.Exists(packageFilePath))
                {
                    var packageFile = new ZipPackage(packageFilePath);

                    var licenseBuilder = new StringBuilder(licenseTemplate);
                    licenseBuilder.Replace(@"${Package.Id}$", packageFile.Id);

                    var version = packageFile.Version ?? new SemanticVersion(new Version());
                    licenseBuilder.Replace(@"${Package.Version}$", version.ToString());

                    var projectUrl = packageFile.ProjectUrl
                            ?? new Uri(
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    Resources.GoogleSearchQuery,
                                    tuple.Item1.Replace(' ', '+')));
                    licenseBuilder.Replace(@"${Package.Url}$", projectUrl.ToString());

                    var licenseUrl = packageFile.LicenseUrl
                        ?? new Uri(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.GoogleSearchQuery,
                                tuple.Item1.Replace(' ', '+')));
                    licenseBuilder.Replace(@"${Package.LicenseUrl}$", licenseUrl.ToString());

                    if (packageBuilder.Length > 0)
                    {
                        packageBuilder.Append(Environment.NewLine);
                    }

                    packageBuilder.Append(licenseBuilder);
                }
            }

            var packagesTemplate = EmbeddedResourceExtracter.LoadEmbeddedTextFile(
                Assembly.GetExecutingAssembly(),
                @"NTreva.Templates.Packages.xml");

            var builder = new StringBuilder(packagesTemplate);
            builder.Replace(@"${Packages}$", packageBuilder.ToString());

            using (var writer = new StreamWriter(new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None), Encoding.UTF8))
            {
                writer.Write(builder.ToString());
            }

            WriteToConsole(
                string.Format(
                    CultureInfo.CurrentCulture,
                    Resources.Output_Completed,
                    outputFile));
        }
Ejemplo n.º 17
0
        public static PackageReference GetPackageReference(this ICakeContext context, DirectoryPath path, string packageId)
        {
            if (!path.IsRelative)
            {
                throw new CakeException("DirectoryPath must be relative!");
            }

            var packagePath = path.CombineWithFilePath(new FilePath("packages.config"));
            if (!System.IO.File.Exists(packagePath.FullPath))
            {
                throw new CakeException(string.Format("Could not find a packages.config file in '{0}'", path.FullPath));
            }

            var file = new PackageReferenceFile(packagePath.FullPath);
            return file.GetPackageReferences().FirstOrDefault(x => x.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase));
        }
Ejemplo n.º 18
0
 private IEnumerable <IPackage> GetPackagesCore()
 {
     return(_packageReferenceFile.GetPackageReferences()
            .Select(GetPackage)
            .Where(p => p != null));
 }
		void AssertPackageMarkedForReinstallationInPackagesConfigFile (string packageId, bool expectedReinstallationSetting)
		{
			var fileSystem = new FakeFileSystem ();
			fileSystem.FileExistsReturnValue = true;
			MemoryStream stream = runner.FileSystem.FilesAdded.First ().Value;
			string file = UTF8Encoding.UTF8.GetString (stream.ToArray ());
			fileSystem.FileToReturnFromOpenFile = file;
			var packageReferenceFile = new PackageReferenceFile (fileSystem, "packages.config");
			PackageReference matchedReference = packageReferenceFile
				.GetPackageReferences ()
				.FirstOrDefault (packageReference => packageReference.Id == packageId);

			Assert.AreEqual (expectedReinstallationSetting, matchedReference.RequireReinstallation);
		}
Ejemplo n.º 20
0
        static IEnumerable<PackageReference> GetDependencies() {

            if (string.IsNullOrEmpty(packages_config_path)) {
                var currentDir = Directory.GetCurrentDirectory();
                string[] files = Directory.GetFiles(currentDir, "packages.config");
                if (files.Length == 1) {
                    packages_config_path = files[0];
                    log.DebugFormat("packages.config found: {0}", packages_config_path);
                }
            }

            if (packages_config_path == null) return null;

            var packageReferenceFile = new PackageReferenceFile(packages_config_path);
            return packageReferenceFile.GetPackageReferences();
        }