Exemplo n.º 1
0
 public Task<PackageDownloadMetadata> GetNupkgUrlForDownload(PackageIdentity identity)
 {
   //*TODOs: Temp implementation. Need to do erorr handling and stuff.
   return Task.Factory.StartNew(() =>
  {
      if(V2Client is DataServicePackageRepository)            
      {
          //TODOs:Not sure if there is some other standard way to get the Url from a dataservice repo. DataServicePackage has downloadurl property but not sure how to get it.
          return new PackageDownloadMetadata(new Uri(Path.Combine(V2Client.Source, "api/v2/" + identity.Id + "." + identity.Version + ".nupkg")));      
      }
      else if(V2Client is LocalPackageRepository)
      {
          LocalPackageRepository lrepo = V2Client as LocalPackageRepository;
          SemanticVersion semVer = new SemanticVersion(identity.Version.Version);
          return new PackageDownloadMetadata(new Uri(Path.Combine(V2Client.Source,  lrepo.PathResolver.GetPackageFileName(identity.Id, semVer))));
      }
      else
      {
          // TODO: move the string into a resoure file
          throw new InvalidOperationException(string.Format(
              CultureInfo.CurrentCulture,
              "Unable to get download metadata for package {0}",identity.Id));
      }
  });
 }
Exemplo n.º 2
0
        public int GetHashCode(SemanticVersion obj)
        {
            NuGetVersion version = obj as NuGetVersion;

            return String.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}-{3}GIT{4}",
                version.Major, version.Minor, version.Patch, version.Release, GetCommitFromMetadata(version.Metadata)).GetHashCode();
        }
Exemplo n.º 3
0
    public void Write(
        Version version,
        DateTimeOffset versionTime,
        IChangelogLinkBuilder linkBuilder,
        IEnumerable <ConventionalCommit> commits,
        ChangelogOptions changelogOptions)
    {
        string markdown = GenerateMarkdown(version, versionTime, linkBuilder, commits, changelogOptions);

        if (File.Exists(FilePath))
        {
            var contents = File.ReadAllText(FilePath);

            var firstReleaseHeadlineIdx = contents.IndexOf("<a name=\"", StringComparison.Ordinal);

            if (firstReleaseHeadlineIdx >= 0)
            {
                markdown = contents.Insert(firstReleaseHeadlineIdx, markdown);
            }
            else
            {
                markdown = contents + "\n\n" + markdown;
            }

            File.WriteAllText(FilePath, markdown);
        }
        else
        {
            File.WriteAllText(FilePath, changelogOptions.Header + "\n" + markdown);
        }
    }
Exemplo n.º 4
0
        /// <summary>
        /// Resolve package from online and local repository
        /// Used for Install-Package and Update-Package command to verify the specified package version exists in the repo.
        /// </summary>
        /// <param name="sourceRepository"></param>
        /// <param name="localRepository"></param>
        /// <param name="identity"></param>
        /// <param name="allowPrereleaseVersions"></param>
        /// <returns></returns>
        public static PackageIdentity ResolvePackage(SourceRepository sourceRepository, IPackageRepository localRepository,
            PackageIdentity identity, bool allowPrereleaseVersions)
        {
            string packageId = identity.Id;
            NuGetVersion nVersion = identity.Version;
            string version = identity.Version.ToNormalizedString();

            if (String.IsNullOrEmpty(identity.Id))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
            }

            PackageIdentity resolvedIdentity = null;

            // If we're looking for an exact version of a package then try local first
            if (version != null)
            {
                SemanticVersion sVersion = new SemanticVersion(version);
                IPackage package = localRepository.FindPackage(packageId, sVersion, allowPrereleaseVersions, allowUnlisted: false);
                if (package != null)
                {
                    resolvedIdentity = new PackageIdentity(packageId, NuGetVersion.Parse(package.Version.ToString()));
                }
            }

            if (resolvedIdentity == null)
            {
                if (nVersion == null)
                {
                    throw new InvalidOperationException(
                        String.Format(CultureInfo.CurrentCulture,
                        NuGetResources.UnknownPackageSpecificVersion, packageId, version));
                }
                else
                {
                    Task<JObject> task = sourceRepository.GetPackageMetadata(packageId, nVersion);
                    JObject package = task.Result;
                    if (package == null)
                    {
                        if (version != null)
                        {
                            throw new InvalidOperationException(
                                String.Format(CultureInfo.CurrentCulture,
                                NuGetResources.UnknownPackageSpecificVersion, packageId, version));
                        }
                        throw new InvalidOperationException(
                            String.Format(CultureInfo.CurrentCulture,
                            NuGetResources.UnknownPackage, packageId));
                    }
                    else
                    {
                        resolvedIdentity = new PackageIdentity(packageId, nVersion);
                    }
                }
            }

            return resolvedIdentity;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Parse a version string
        /// </summary>
        /// <returns>false if the version is not a strict semver</returns>
        public static bool TryParse(string value, out SemanticVersion version)
        {
            version = null;

            if (value != null)
            {
                Version systemVersion = null;

                var sections = ParseSections(value);

                // null indicates the string did not meet the rules
                if (sections != null
                    && Version.TryParse(sections.Item1, out systemVersion))
                {
                    // validate the version string
                    var parts = sections.Item1.Split('.');

                    if (parts.Length != 3)
                    {
                        // versions must be 3 parts
                        return false;
                    }

                    foreach (var part in parts)
                    {
                        if (!IsValidPart(part, false))
                        {
                            // leading zeros are not allowed
                            return false;
                        }
                    }

                    // labels
                    if (sections.Item2 != null
                        && !sections.Item2.All(s => IsValidPart(s, false)))
                    {
                        return false;
                    }

                    // build metadata
                    if (sections.Item3 != null
                        && !IsValid(sections.Item3, true))
                    {
                        return false;
                    }

                    var ver = NormalizeVersionValue(systemVersion);

                    version = new SemanticVersion(version: ver,
                        releaseLabels: sections.Item2,
                        metadata: sections.Item3 ?? string.Empty);

                    return true;
                }
            }

            return false;
        }
 private static NuGetVersion SafeToNuGetVer(SemanticVersion semanticVersion)
 {
     if (semanticVersion == null)
     {
         return null;
     }
     return new NuGetVersion(
         semanticVersion.Version,
         semanticVersion.SpecialVersion);
 }
Exemplo n.º 7
0
        public static NuGetVersion SafeToNuGetVer(SemanticVersion semanticVersion)
        {
            if (semanticVersion == null)
            {
                return null;
            }

            // Parse using the original version string to support non-normalized scenarios.
            return NuGetVersion.Parse(semanticVersion.ToString());
        }
Exemplo n.º 8
0
    public static string GenerateMarkdown(
        Version version,
        DateTimeOffset versionTime,
        IChangelogLinkBuilder linkBuilder,
        IEnumerable <ConventionalCommit> commits,
        ChangelogOptions changelogOptions)
    {
        var versionTagLink = string.IsNullOrWhiteSpace(linkBuilder.BuildVersionTagLink(version))
            ? version.ToString()
            : $"[{version}]({linkBuilder.BuildVersionTagLink(version)})";

        var markdown = $"<a name=\"{version}\"></a>";

        markdown += "\n";
        markdown += $"## {versionTagLink} ({versionTime.Year}-{versionTime.Month}-{versionTime.Day})";
        markdown += "\n";
        markdown += "\n";

        var visibleChangelogSections = changelogOptions.Sections.Where(x => !x.Hidden);

        foreach (var changelogSection in visibleChangelogSections)
        {
            var matchingCommits = commits.Where(commit => commit.Type == changelogSection.Type);
            var buildBlock      = BuildBlock(changelogSection.Section, linkBuilder, matchingCommits);
            if (!string.IsNullOrWhiteSpace(buildBlock))
            {
                markdown += buildBlock;
                markdown += "\n";
            }
        }

        var breaking = BuildBlock("Breaking Changes", linkBuilder, commits.Where(commit => commit.IsBreakingChange));

        if (!string.IsNullOrWhiteSpace(breaking))
        {
            markdown += breaking;
            markdown += "\n";
        }

        if (changelogOptions.IncludeAllCommits)
        {
            var other = BuildBlock(
                "Other",
                linkBuilder,
                commits.Where(commit => !visibleChangelogSections.Any(x => x.Type == commit.Type) && !commit.IsBreakingChange));

            if (!string.IsNullOrWhiteSpace(other))
            {
                markdown += other;
                markdown += "\n";
            }
        }

        return(markdown);
    }
Exemplo n.º 9
0
        public int Compare(SemanticVersion x, SemanticVersion y)
        {
            NuGetVersion versionX = x as NuGetVersion;
            NuGetVersion versionY = y as NuGetVersion;

            // compare without metadata
            int result = VersionComparer.VersionRelease.Compare(x, y);

            if (result != 0)
                return result;

            // compare git commits, form: buildmachine-gitcommit
            return GitCommitOrder(GetCommitFromMetadata(versionX.Metadata)).CompareTo(GitCommitOrder(GetCommitFromMetadata(versionY.Metadata)));
        }
Exemplo n.º 10
0
        private static string GetNormalizedString(SemanticVersion version)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(Format('V', version));

            if (version.IsPrerelease)
            {
                sb.Append('-');
                sb.Append(version.Release);
            }

            if (version.HasMetadata)
            {
                sb.Append('+');
                sb.Append(version.Metadata);
            }

            return sb.ToString();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Parses a version string using loose semantic versioning rules that allows 2-4 version components followed by an optional special version.
        /// </summary>
        public static bool TryParse(string value, out SemanticVersion version)
        {
            if (!String.IsNullOrEmpty(value))
            {
                var match = Constants.SemanticVersionStrictRegex.Match(value.Trim());

                Version versionValue;
                if (match.Success && Version.TryParse(match.Groups["Version"].Value, out versionValue))
                {
                    Version ver = NormalizeVersionValue(versionValue);

                    version = new SemanticVersion(version: ver,
                                                releaseLabels: ParseReleaseLabels(match.Groups["Release"].Value.TrimStart('-')),
                                                metadata: match.Groups["Metadata"].Value.TrimStart('+'));
                    return true;
                }
            }

            version = null;
            return false;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gives a hash code based on the normalized version string.
        /// </summary>
        public int GetHashCode(SemanticVersion version)
        {
            if (ReferenceEquals(version, null))
            {
                return 0;
            }

            var combiner = new HashCodeCombiner();

            combiner.AddObject(version.Major);
            combiner.AddObject(version.Minor);
            combiner.AddObject(version.Patch);

            var nuGetVersion = version as NuGetVersion;
            if (nuGetVersion != null
                && nuGetVersion.Revision > 0)
            {
                combiner.AddObject(nuGetVersion.Revision);
            }

            if (_mode == VersionComparison.Default
                || _mode == VersionComparison.VersionRelease
                || _mode == VersionComparison.VersionReleaseMetadata)
            {
                if (version.IsPrerelease)
                {
                    combiner.AddObject(version.Release.ToUpperInvariant());
                }
            }

            if (_mode == VersionComparison.VersionReleaseMetadata)
            {
                if (version.HasMetadata)
                {
                    combiner.AddObject(version.Metadata);
                }
            }

            return combiner.CombinedHash;
        }
        public  Task<VisualStudioUIPackageMetadata> GetPackageMetadataForVisualStudioUI(string packageId, NuGetVersion version)
        {
            return Task.Factory.StartNew(() =>
            {              
                var semver = new SemanticVersion(version.ToNormalizedString());
                var package = V2Client.FindPackage(packageId, semver);

                // Sometimes, V2 APIs seem to fail to return a value for Packages(Id=,Version=) requests...
                if (package == null)
                {
                    var packages = V2Client.FindPackagesById(packageId);
                    package = packages.FirstOrDefault(p => Equals(p.Version, semver));
                }

                // If still null, fail
                if (package == null)
                {
                    return null;
                }

                return GetVisualStudioUIPackageMetadata(package);
            });
        }
Exemplo n.º 14
0
 public virtual string GetPackageFileName(string packageId, SemanticVersion version)
 {
     return string.Format("{0}.{1}.nupkg", packageId, version);
 }
Exemplo n.º 15
0
 public string BuildVersionTagLink(Version version)
 {
     return(string.Empty);
 }
Exemplo n.º 16
0
 public string BuildVersionTagLink(Version version)
 {
     return($"https://gitlab.com/{_organization}/{_repository}/-/tags/v{version}");
 }
Exemplo n.º 17
0
        private static bool ValidateSpecialVersionLength(SemanticVersion version)
        {
            if (!version.IsPrerelease)
            {
                return true;
            }

            return version == null || version.Release.Length <= 20;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates a SemanticVersion from an existing SemanticVersion
        /// </summary>
        public SemanticVersion(SemanticVersion version)
            : this(version.Major, version.Minor, version.Patch, version.ReleaseLabels, version.Metadata)
        {

        }
Exemplo n.º 19
0
        private static string Format(char c, SemanticVersion version)
        {
            string s = null;

            switch (c)
            {
                case 'N':
                    s = GetNormalizedString(version);
                    break;
                case 'R':
                    s = version.Release;
                    break;
                case 'M':
                    s = version.Metadata;
                    break;
                case 'V':
                    s = FormatVersion(version);
                    break;
                case 'x':
                    s = String.Format(CultureInfo.InvariantCulture, "{0}", version.Major);
                    break;
                case 'y':
                    s = String.Format(CultureInfo.InvariantCulture, "{0}", version.Minor);
                    break;
                case 'z':
                    s = String.Format(CultureInfo.InvariantCulture, "{0}", version.Patch);
                    break;
                case 'r':
                    NuGetVersion nuGetVersion = version as NuGetVersion;
                    s = String.Format(CultureInfo.InvariantCulture, "{0}", nuGetVersion != null && nuGetVersion.IsLegacyVersion ? nuGetVersion.Version.Revision : 0);
                    break;
            }

            return s;
        }
Exemplo n.º 20
0
 /// <summary>
 /// Compares the given versions using the VersionComparison mode.
 /// </summary>
 public static int Compare(SemanticVersion version1, SemanticVersion version2, VersionComparison versionComparison)
 {
     IVersionComparer comparer = new VersionComparer(versionComparison);
     return comparer.Compare(version1, version2);
 }
Exemplo n.º 21
0
        internal static void ValidateDependencySets(SemanticVersion version, IEnumerable<PackageDependencySet> dependencies)
        {
            if (version == null)
            {
                // We have independent validation for null-versions.
                return;
            }

            foreach (var dep in dependencies.SelectMany(s => s.Dependencies))
            {
                PackageIdValidator.ValidatePackageId(dep.Id);
            }

            // REVIEW: Do we want to keep enfocing this?
            /*if (version.IsPrerelease)
            {
                // If we are creating a production package, do not allow any of the dependencies to be a prerelease version.
                var prereleaseDependency = dependencies.SelectMany(set => set.Dependencies).FirstOrDefault(IsPrereleaseDependency);
                if (prereleaseDependency != null)
                {
                    throw new InvalidDataException(String.Format(CultureInfo.CurrentCulture, "NuGetResources.Manifest_InvalidPrereleaseDependency", prereleaseDependency.ToString()));
                }
            }*/
        }
Exemplo n.º 22
0
 /// <summary>
 /// The safe range is defined as the highest build and revision for a given major and minor version
 /// </summary>
 public static VersionRange GetSafeRange(NuGetVersion version, bool includePrerelease)
 {
     SemanticVersion max = new SemanticVersion(new Version(version.Major, version.Minor + 1));
     NuGetVersion maxVersion = NuGetVersion.Parse(max.ToString());
     return new VersionRange(version, true, maxVersion, false, includePrerelease);
 }
Exemplo n.º 23
0
        private static string GetSimpleNuspecString(string packageId, string packageVersion, bool frameworkAssemblies, SemanticVersion minClientVersion, bool dependencies)
        {
            string frameworkAssemblyReferences = frameworkAssemblies ?
                String.Format(FrameworkAssembliesStringFormat, "System.Xml", "net45") : String.Empty;

            string minClientVersionString = minClientVersion == null ? String.Empty :
                String.Format(MinClientVersionStringFormat, minClientVersion.ToNormalizedString());

            string dependenciesString = dependencies ?
                String.Format(DependenciesStringFormat, "Owin", "1.0") : String.Empty;
            return String.Format(NuspecStringFormat, packageId, packageVersion,
                String.Join(Environment.NewLine, frameworkAssemblyReferences, dependenciesString),
                minClientVersionString);
        }
Exemplo n.º 24
0
 public static void SetSimpleNuspec(ZipFile zipFile, string packageId, string packageVersion, bool frameworkAssemblies = false, SemanticVersion minClientVersion = null, bool dependencies = false)
 {
     zipFile.AddEntry(packageId + ".nuspec", GetSimpleNuspecString(packageId, packageVersion, frameworkAssemblies, minClientVersion, dependencies), Encoding.UTF8);
 }
Exemplo n.º 25
0
        public static FileInfo GetPackageWithMinClientVersion(string path, string packageId, string packageVersion, SemanticVersion minClientVersion)
        {
            ZipFile zipFile;
            FileInfo fileInfo = GetFileInfo(path, packageId, packageVersion, out zipFile);

            SetSimpleNuspec(zipFile, packageId, packageVersion, false, minClientVersion);
            zipFile.Save();

            return fileInfo;
        }
Exemplo n.º 26
0
 internal static PackageIdentity SafeToPackageIdentity(string id, SemanticVersion version)
 {
     return new PackageIdentity(id, SafeToNuGetVer(version));
 }
Exemplo n.º 27
0
        private static string FormatVersion(SemanticVersion version)
        {
            NuGetVersion nuGetVersion = version as NuGetVersion;
            bool legacy = nuGetVersion != null && nuGetVersion.IsLegacyVersion;

            return String.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}{3}", version.Major, version.Minor, version.Patch, 
                legacy ? String.Format(CultureInfo.InvariantCulture, ".{0}", nuGetVersion.Version.Revision) : null);
        }
Exemplo n.º 28
0
 public virtual string GetPackageDirectory(string packageId, SemanticVersion version)
 {
     return Path.Combine(packageId, version.ToString());
 }
Exemplo n.º 29
0
        /// <summary>
        /// Compare versions.
        /// </summary>
        public int Compare(SemanticVersion x, SemanticVersion y)
        {
            if (ReferenceEquals(x, y))
            {
                return 0;
            }

            if (ReferenceEquals(y, null))
            {
                return 1;
            }

            if (ReferenceEquals(x, null))
            {
                return -1;
            }

            // compare version
            var result = x.Major.CompareTo(y.Major);
            if (result != 0)
            {
                return result;
            }

            result = x.Minor.CompareTo(y.Minor);
            if (result != 0)
            {
                return result;
            }

            result = x.Patch.CompareTo(y.Patch);
            if (result != 0)
            {
                return result;
            }

            var legacyX = x as NuGetVersion;
            var legacyY = y as NuGetVersion;

            result = CompareLegacyVersion(legacyX, legacyY);
            if (result != 0)
            {
                return result;
            }

            if (_mode != VersionComparison.Version)
            {
                // compare release labels
                if (x.IsPrerelease
                    && !y.IsPrerelease)
                {
                    return -1;
                }

                if (!x.IsPrerelease
                    && y.IsPrerelease)
                {
                    return 1;
                }

                if (x.IsPrerelease
                    && y.IsPrerelease)
                {
                    result = CompareReleaseLabels(x.ReleaseLabels, y.ReleaseLabels);
                    if (result != 0)
                    {
                        return result;
                    }
                }

                // compare the metadata
                if (_mode == VersionComparison.VersionReleaseMetadata)
                {
                    result = StringComparer.OrdinalIgnoreCase.Compare(x.Metadata ?? string.Empty, y.Metadata ?? string.Empty);
                    if (result != 0)
                    {
                        return result;
                    }
                }
            }

            return 0;
        }
Exemplo n.º 30
0
 public string GetHashPath(string packageId, SemanticVersion version)
 {
     return Path.Combine(GetInstallPath(packageId, version),
         string.Format("{0}.{1}.nupkg.sha512", packageId, version));
 }
Exemplo n.º 31
0
 public virtual string GetManifestFileName(string packageId, SemanticVersion version)
 {
     return packageId + ".nuspec";
 }
Exemplo n.º 32
0
 public string BuildVersionTagLink(Version version)
 {
     return($"https://www.github.com/{_organization}/{_repository}/releases/tag/v{version}");
 }
Exemplo n.º 33
0
 public string BuildVersionTagLink(Version version)
 {
     return($"https://bitbucket.{_domain}/{_organization}/{_repository}/src/v{version}");
 }
Exemplo n.º 34
0
        public static string GetLastestVersionForPackage(SourceRepository repo, string packageId, IEnumerable<FrameworkName> names, bool allowPrerelease,
            NuGetVersion nugetVersion = null, bool isSafe = false, int skip = 0, int take = 30)
        {
            string version = string.Empty;
            try
            {
                JObject package = GetJObjectForPackageId(repo, packageId, names, allowPrerelease, skip, take);
                // Return latest version if Safe is not required and latestVersion is not null or empty.
                if (package != null)
                {
                    version = package.Value<String>(Properties.LatestVersion);
                }

                if (!isSafe && !string.IsNullOrEmpty(version))
                {
                    return version;
                }

                // Continue to get the latest version when above condition is not met.
                IEnumerable<NuGetVersion> allVersions = Enumerable.Empty<NuGetVersion>();
                var versionList = GetAllVersionsForPackageId(package);

                if (isSafe && nugetVersion != null)
                {
                    VersionRange spec = GetSafeRange(nugetVersion, allowPrerelease);
                    allVersions = versionList.Where(p =>
                    {
                        var sVersion = new SemanticVersion(p.ToNormalizedString());
                        return p < spec.MaxVersion && p >= spec.MinVersion;
                    });
                }
                version = allVersions.OrderByDescending(v => v).FirstOrDefault().ToNormalizedString();
            }
            catch (Exception)
            {
                if (string.IsNullOrEmpty(version))
                {
                    throw new InvalidOperationException(
                        String.Format(CultureInfo.CurrentCulture,
                        NuGetResources.UnknownPackage, packageId));
                }
            }
            return version;
        }
Exemplo n.º 35
0
 /// <summary>
 /// Creates a SemanticVersion from an existing SemanticVersion
 /// </summary>
 public SemanticVersion(SemanticVersion version)
     : this(version.Major, version.Minor, version.Patch, version.ReleaseLabels, version.Metadata)
 {
 }
Exemplo n.º 36
0
 public static bool IsPrereleaseVersion(string version)
 {
     SemanticVersion sVersion = new SemanticVersion(version);
     bool isPrerelease = !String.IsNullOrEmpty(sVersion.SpecialVersion);
     return isPrerelease;
 }
Exemplo n.º 37
0
 /// <summary>
 /// Determines if both versions are equal.
 /// </summary>
 public bool Equals(SemanticVersion x, SemanticVersion y)
 {
     return Compare(x, y) == 0;
 }