Пример #1
0
        /// <summary>
        /// Resolves a package from nuget using a specified name and version.
        /// </summary>
        /// <param name="name">Name of the package to find</param>
        /// <param name="version">Version of the package</param>
        /// <returns>File path if the nuget package is found</returns>
        protected string ResolvePackage(string name, Version version)
        {
            SemanticVersion vers    = SemanticVersion.ParseOptionalVersion($"{version.Major}.{version.Minor}.*");
            IPackage        package = ResolvePackage(name, vers);

            if (package != null)
            {
                string installPath = packageManager.PathResolver.GetInstallPath(package);
                string libPath     = Path.Combine(installPath, "lib", "net45", name + ".dll");

                if (File.Exists(libPath))
                {
                    OnResolved?.Invoke(this, new NugetAssemblyResolvedEventArgs()
                    {
                        FilePath = libPath
                    });
                    return(libPath);
                }
                else
                {
                    var files = Directory.EnumerateFiles(installPath, "*.dll", SearchOption.AllDirectories);
                    if (files.Count() == 1)
                    {
                        libPath = files.Single();
                        OnResolved?.Invoke(this, new NugetAssemblyResolvedEventArgs()
                        {
                            FilePath = libPath
                        });
                        return(libPath);
                    }
                }
            }

            return(null);
        }
        private static void InstallPackage(string packageId, string packageVersion)
        {
            var realVersion = packageVersion != Constants.NuGetLatestVersion
                ? packageVersion
                : null;

            LogMessage($"Installing NuGet {packageId}.{packageVersion}");
            packageManager.InstallPackage(packageId, SemanticVersion.ParseOptionalVersion(realVersion),
                                          ignoreDependencies: true, allowPrereleaseVersions: false);
        }
        private void ExtractMetadataFromProject(PackageBuilder builder)
        {
            builder.Id = builder.Id ??
                        _project.GetPropertyValue("AssemblyName") ??
                        Path.GetFileNameWithoutExtension(_project.FullPath);

            string version = _project.GetPropertyValue("Version");
            builder.Version = builder.Version ??
                              SemanticVersion.ParseOptionalVersion(version) ??
                              new SemanticVersion("1.0");
        }
Пример #4
0
        public override void Curate(Package galleryPackage, INupkg nugetPackage, bool commitChanges)
        {
            if (!galleryPackage.Dependencies.Any())
            {
                return;
            }

            var curatedFeedService = GetService <ICuratedFeedService>();

            var entitiesContext = GetService <IEntitiesContext>();
            var curatedFeeds    = entitiesContext.CuratedFeeds
                                  .ToList()
                                  .Select(feed => new { Match = curatedFeedNameParser.Match(feed.Name), Feed = feed })
                                  .Where(x => x.Match.Success)
                                  .Select(x => new
            {
                Name    = x.Match.Value,
                Id      = x.Match.Groups["name"].Value,
                Version = SemanticVersion.ParseOptionalVersion(x.Match.Groups["version"].Value),
                x.Feed
            })
                                  .ToList();

            var feedDependencies = (from d in galleryPackage.Dependencies
                                    from cf in curatedFeeds
                                    where string.Equals(d.Id, cf.Id, StringComparison.OrdinalIgnoreCase) &&
                                    (CuratedFeedWantsAllVersions(cf.Version) || CuratedFeedSatisfiesDependency(cf.Version, d))
                                    select new { Dependency = d, cf.Feed, FeedId = cf.Id }).ToList();

            // Packages that should also be curated to satisfy the dependencies
            var feedDependencyNames = feedDependencies.Select(fd => fd.FeedId).ToList();
            var packageDependencies = (from d in galleryPackage.Dependencies
                                       where !feedDependencyNames.Contains(d.Id, StringComparer.OrdinalIgnoreCase)
                                       from p in GetMatchingPackages(d.Id, d.VersionSpec)
                                       select p).ToList();

            foreach (var feedDependency in feedDependencies)
            {
                var curatedFeed = feedDependency.Feed;

                curatedFeedService.CreatedCuratedPackage(curatedFeed, galleryPackage,
                                                         included: true, automaticallyCurated: true, commitChanges: commitChanges);

                // Now add all packageDependencies
                foreach (var packageDependency in packageDependencies)
                {
                    curatedFeedService.CreatedCuratedPackage(curatedFeed, packageDependency, included: true,
                                                             automaticallyCurated: true, commitChanges: commitChanges);
                }
            }
        }
Пример #5
0
        public void InstallPackagesFromConfigFile(DeployMessage.Item[] items, out string packagesDirectory, out string packagesFile, out string version)
        {
            version           = null;
            packagesFile      = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + "\\packages.config");
            packagesDirectory = Path.GetDirectoryName(packagesFile);
            if (!Directory.Exists(packagesDirectory))
            {
                Directory.CreateDirectory(packagesDirectory);
            }
            var referenceFile = new PackageReferenceFile(packagesFile);

            foreach (var item in items)
            {
                referenceFile.AddEntry(item.PackageId, (SemanticVersion.ParseOptionalVersion(item.Version) ?? _emptySemanticVersion));
            }
        }
Пример #6
0
        /// <summary>
        /// Resolves a package from nuget using a specified name and version.
        /// </summary>
        /// <param name="name">Name of the package to find</param>
        /// <param name="version">Version of the package</param>
        /// <returns>File path if the nuget package is found</returns>
        protected string ResolvePackage(string name, Version version)
        {
            SemanticVersion vers    = SemanticVersion.ParseOptionalVersion($"{version.Major}.{version.Minor}.*");
            IPackage        package = ResolvePackage(name, vers);

            if (package != null)
            {
                string installPath = packageManager.PathResolver.GetInstallPath(package);
                string libPath     = Path.Combine(installPath, "lib", "net45", name + ".dll");

                if (File.Exists(libPath))
                {
                    OnResolved?.Invoke(this, new NugetAssemblyResolvedEventArgs()
                    {
                        FilePath = libPath
                    });
                    return(libPath);
                }
                else
                {
                    var files = Directory.EnumerateFiles(installPath, "*.dll", SearchOption.AllDirectories);
                    if (files.Count() == 1)
                    {
                        libPath = files.Single();
                        OnResolved?.Invoke(this, new NugetAssemblyResolvedEventArgs()
                        {
                            FilePath = libPath
                        });
                        return(libPath);
                    }
                }
            }
            else
            {
                foreach (var file in Directory.EnumerateFiles(Environment.CurrentDirectory, name + ".*"))
                {
                    var extension = Path.GetExtension(file).ToLower();
                    if (new[] { ".exe", ".dll" }.Contains(extension))
                    {
                        Console.WriteLine($" * Found {name} locally");
                        return(file);
                    }
                }
            }

            return(null);
        }
Пример #7
0
        public Tuple <SemanticVersion, string> Load(DllReference parentAssembly, string Dependency)
        {
            var path = parentAssembly.Id.Item1 + _sectionSeparator + parentAssembly.Id.Item2 + _sectionSeparator + Dependency + ".ini";

            if (!File.Exists(@"cache\" + path))
            {
                return(null);
            }

            var parser  = new FileIniDataParser();
            var iniData = parser.ReadFile(@"cache\" + path);

            var section = iniData.Sections["Dependency"];
            var version = SemanticVersion.ParseOptionalVersion(section["version"]);
            var name    = section["name"];

            return(new Tuple <SemanticVersion, string>(version, name));
        }
Пример #8
0
        static PackageReference ParseExtraPackageReference(string input)
        {
            // Syntax: ID [ "@" VERSION ] ["++"]
            // Examples:
            //   Foo                 => Latest release of Foo
            //   [email protected]             => Foo release 2.1
            //   Foo++               => Latest pre-release of Foo
            //   [email protected]++           => Foo 3.0 pre-release

            const string plusplus   = "++";
            var          prerelease = input.EndsWith(plusplus, StringComparison.Ordinal);

            if (prerelease)
            {
                input = input.Substring(0, input.Length - plusplus.Length);
            }
            return(input.Split('@', (id, version) => new PackageReference(id, SemanticVersion.ParseOptionalVersion(version), prerelease)));
        }
Пример #9
0
        static T Compile <T>(string queryFilePath, IPackageRepository repo, string packagesPath,
                             IEnumerable <PackageReference> extraPackageReferences,
                             IEnumerable <string> extraImports,
                             FrameworkName targetFramework,
                             bool verbose, IndentingLineWriter writer,
                             Func <QueryLanguage, string, IEnumerable <string>, IEnumerable <Reference>, T> selector)
        {
            var eomLineNumber = LinqPad.GetEndOfMetaLineNumber(queryFilePath);
            var lines         = File.ReadLines(queryFilePath);

            var xml = string.Join(Environment.NewLine,
                                  // ReSharper disable once PossibleMultipleEnumeration
                                  lines.Take(eomLineNumber));

            var query = XElement.Parse(xml);

            if (verbose)
            {
                writer.Write(query);
            }

            QueryLanguage queryKind;

            if (!Enum.TryParse((string)query.Attribute("Kind"), true, out queryKind) ||
                (queryKind != QueryLanguage.Statements &&
                 queryKind != QueryLanguage.Expression &&
                 queryKind != QueryLanguage.Program))
            {
                throw new NotSupportedException("Only LINQPad " +
                                                "C# Statements and Expression queries are fully supported " +
                                                "and C# Program queries partially in this version.");
            }

            var nrs =
                from nrsq in new[]
            {
                from nr in query.Elements("NuGetReference")
                select new PackageReference((string)nr,
                                            SemanticVersion.ParseOptionalVersion((string)nr.Attribute("Version")),
                                            (bool?)nr.Attribute("Prerelease") ?? false),
                extraPackageReferences,
            }
            from nr in nrsq
                select new
            {
                nr.Id,
                nr.Version,
                nr.IsPrereleaseAllowed,
                Title = string.Join(" ", Seq.Return(nr.Id,
                                                    nr.Version?.ToString(),
                                                    nr.IsPrereleaseAllowed ? "(pre-release)" : null)
                                    .Filter()),
            };

            nrs = nrs.ToArray();

            if (verbose && nrs.Any())
            {
                writer.WriteLine($"Packages referenced ({nrs.Count():N0}):");
                writer.Indent().WriteLines(from nr in nrs select nr.Title);
            }

            writer.WriteLine($"Packages directory: {packagesPath}");
            var pm = new PackageManager(repo, packagesPath);

            pm.PackageInstalling += (_, ea) =>
                                    writer.WriteLine($"Installing {ea.Package}...");
            pm.PackageInstalled += (_, ea) =>
                                   writer.Indent().WriteLine($"Installed at {ea.InstallPath}");

            writer.WriteLine($"Packages target: {targetFramework}");

            var resolutionList = Enumerable.Repeat(new { Package      = default(IPackage),
                                                         AssemblyPath = default(string) }, 0)
                                 .ToList();

            foreach (var nr in nrs)
            {
                var pkg = pm.LocalRepository.FindPackage(nr.Id, nr.Version,
                                                         allowPrereleaseVersions: nr.IsPrereleaseAllowed,
                                                         allowUnlisted: false);
                if (pkg == null)
                {
                    pkg = repo.FindPackage(nr.Id, nr.Version,
                                           allowPrereleaseVersions: nr.IsPrereleaseAllowed,
                                           allowUnlisted: false);

                    if (pkg == null)
                    {
                        throw new Exception("Package not found: " + nr.Title);
                    }

                    pm.InstallPackage(pkg.Id, pkg.Version);
                }

                writer.WriteLine("Resolving references...");
                resolutionList.AddRange(GetReferencesTree(pm.LocalRepository, pkg, targetFramework, writer.Indent(), (r, p) => new
                {
                    Package      = p,
                    AssemblyPath = r != null
                                 ? Path.Combine(pm.PathResolver.GetInstallPath(p), r.Path)
                                 : null
                }));
            }

            var packagesPathWithTrailer = packagesPath + Path.DirectorySeparatorChar;

            var resolution =
                resolutionList
                .GroupBy(r => r.Package)
                .Select(g => g.First())
                .Select(r => new
            {
                r.Package,
                AssemblyPath = r.AssemblyPath != null
                            ? MakeRelativePath(queryFilePath, packagesPathWithTrailer)
                               + MakeRelativePath(packagesPathWithTrailer, r.AssemblyPath)
                            : null,
            })
                .Partition(r => r.AssemblyPath == null, (ok, nok) => new
            {
                ResolvedReferences    = ok,
                ReferencelessPackages = from r in nok
                                        select r.Package.GetFullName(),
            });

            resolution.ReferencelessPackages.StartIter(e =>
            {
                writer.WriteLine($"Warning! Packages with no references for {targetFramework}:");
                writer.Indent().WriteLines(e.ResumeFromCurrent());
            });

            var references = resolution.ResolvedReferences.ToArray();

            references.Select(r => r.AssemblyPath).StartIter(e =>
            {
                writer.WriteLine($"Resolved references ({references.Length:N0}):");
                writer.Indent().WriteLines(e.ResumeFromCurrent());
            });

            return
                (selector(
                     queryKind,
                     // ReSharper disable once PossibleMultipleEnumeration
                     string.Join(Environment.NewLine, lines.Skip(eomLineNumber)),
                     LinqPad.DefaultNamespaces
                     .Concat(from ns in query.Elements("Namespace")
                             select(string) ns)
                     .Concat(extraImports),
                     LinqPad.DefaultReferences.Select(r => new Reference(r))
                     .Concat(from r in query.Elements("Reference")
                             select(string) r into r
                             select r.StartsWith(LinqPad.RuntimeDirToken, StringComparison.OrdinalIgnoreCase)
                                        ? r.Substring(LinqPad.RuntimeDirToken.Length)
                                        : r into r
                             select new Reference(r))
                     .Concat(from r in references
                             select new Reference(r.AssemblyPath, r.Package))));
        }
Пример #10
0
 internal NuGetInfo(string id, string version = LatestVersion)
 {
     Name    = id;
     Version = SemanticVersion.ParseOptionalVersion(version);
 }