Example #1
1
        public async Task<Hash> PutAsync(long id, SemanticVersion version, IPackage package)
        {
            #region Preconditions

            if (package == null) throw new ArgumentNullException(nameof(package));

            #endregion

            var key = id.ToString() + "/" + version.ToString();

            using (var ms = new MemoryStream())
            {
                await package.ZipToStreamAsync(ms).ConfigureAwait(false);

                var hash = Hash.ComputeSHA256(ms, leaveOpen: true);

                var blob = new Blob(ms) {
                    ContentType = "application/zip"
                };

                await bucket.PutAsync(key, blob).ConfigureAwait(false);

                return hash;
            }
        }
 public void VersionString_carried_through()
 {
     // Ensure the version string is available, even if the value is not a valid SemVer
     SemanticVersion semVer = new SemanticVersion("7.3.2");
     Assert.Equal("7.3.2", semVer.VersionString);
     Assert.True(semVer.IsValid);
 }
 public void Ctor_String()
 {
     var sv = new SemanticVersion("1.2", "-pre", "+mybuild");
     Assert.Equal(new Version(1, 2), sv.Version);
     Assert.Equal("-pre", sv.Prerelease);
     Assert.Equal("+mybuild", sv.BuildMetadata);
 }
Example #4
0
        public SemanticVersion FindVersion(GitVersionContext context)
        {
            var versionOnMasterFinder = new VersionOnMasterFinder();
            var tip = context.CurrentCommit;
            var versionFromMaster = versionOnMasterFinder.Execute(context, tip.When());

            var f = new CommitFilter
            {
                Since = tip,
                Until = context.Repository.FindBranch("master").Tip,
                SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time
            };

            var c = context.Repository.Commits.QueryBy(f);
            var numberOfCommitsSinceRelease = c.Count();

            var semanticVersion = new SemanticVersion
            {
                Major = versionFromMaster.Major,
                Minor = versionFromMaster.Minor + 1,
                Patch = 0,
                PreReleaseTag = context.Configuration.DevelopBranchTag + numberOfCommitsSinceRelease,
                BuildMetaData = new SemanticVersionBuildMetaData(numberOfCommitsSinceRelease, context.CurrentBranch.Name,tip.Sha,tip.When()),
            };

            semanticVersion.OverrideVersionManuallyIfNeeded(context.Repository, context.Configuration);

            return semanticVersion;
        }
 public void VersionString_carried_through_even_if_invalid()
 {
     // Ensure the version string is available, even if the value is not a valid SemVer
     SemanticVersion semVer = new SemanticVersion("1.2.3*3.2213312-invalid");
     Assert.Equal("1.2.3*3.2213312-invalid", semVer.VersionString);
     Assert.False(semVer.IsValid);
 }
        public static bool Matches(IVersionSpec versionSpec, SemanticVersion version)
        {
            if (versionSpec == null)
                return true; // I CAN'T DEAL WITH THIS

            bool minVersion;
            if (versionSpec.MinVersion == null) {
                minVersion = true; // no preconditon? LET'S DO IT
            } else if (versionSpec.IsMinInclusive) {
                minVersion = version >= versionSpec.MinVersion;
            } else {
                minVersion = version > versionSpec.MinVersion;
            }

            bool maxVersion;
            if (versionSpec.MaxVersion == null) {
                maxVersion = true; // no preconditon? LET'S DO IT
            } else if (versionSpec.IsMaxInclusive) {
                maxVersion = version <= versionSpec.MaxVersion;
            } else {
                maxVersion = version < versionSpec.MaxVersion;
            }

            return maxVersion && minVersion;
        }
        protected SemanticVersion FindVersion(
            GitVersionContext context,
            BranchType branchType)
        {
            var ancestor = FindCommonAncestorWithDevelop(context.Repository, context.CurrentBranch, branchType);

            if (!IsThereAnyCommitOnTheBranch(context.Repository, context.CurrentBranch))
            {
                var developVersionFinder = new DevelopVersionFinder();
                return developVersionFinder.FindVersion(context);
            }

            var versionOnMasterFinder = new VersionOnMasterFinder();
            var versionFromMaster = versionOnMasterFinder.Execute(context, context.CurrentBranch.Tip.Committer.When);

            var numberOfCommitsOnBranchSinceCommit = NumberOfCommitsOnBranchSinceCommit(context, ancestor);
            var sha = context.CurrentBranch.Tip.Sha;
            var releaseDate = ReleaseDateFinder.Execute(context.Repository, sha, 0);
            var semanticVersion = new SemanticVersion
            {
                Major = versionFromMaster.Major,
                Minor = versionFromMaster.Minor + 1,
                Patch = 0,
                PreReleaseTag = "unstable0",
                BuildMetaData = new SemanticVersionBuildMetaData(
                    numberOfCommitsOnBranchSinceCommit,
                    context.CurrentBranch.Name, releaseDate)
            };

            return semanticVersion;
        }
Example #8
0
        public int GetHashCode(SemanticVersion obj)
        {
            var 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();
        }
 /// <summary>
 /// Throws if collation value is not null and collations are not supported.
 /// </summary>
 /// <param name="serverVersion">The server version.</param>
 /// <param name="value">The value.</param>
 public void ThrowIfNotSupported(SemanticVersion serverVersion, Collation value)
 {
     if (value != null && !base.IsSupported(serverVersion))
     {
         throw new NotSupportedException($"Server version {serverVersion} does not support collations.");
     }
 }
		void CreatePackageReference (
			string packageId = "Id",
			bool requireReinstallation = false)
		{
			var version = new SemanticVersion ("1.2.3");
			packageReference = new PackageReference (packageId, version, null, null, false, requireReinstallation);
		}
Example #11
0
 public VersionSpec(SemanticVersion version)
 {
     IsMinInclusive = true;
     IsMaxInclusive = true;
     MinVersion = version;
     MaxVersion = version;
 }
Example #12
0
 public void BumpPatchVersion()
 {
    
     var semver = new SemanticVersion(Version);
     var newVer = new SemanticVersion(semver.Major, semver.Minor, semver.Patch+1,build:null, preRelease: null);
     Version = FileVersion = newVer.ToString();
 }
        public async Task InstallPackage(string id, SemanticVersion version = null, Uri source = null, bool force = false)
        {
            this.StartProgressDialog("Installing", "Building chocolatey command...", id);

            var arguments = new StringBuilder();
            arguments.AppendFormat("install {0} -y", id);

            if (version != null)
            {
                arguments.AppendFormat(" --version {0}", version);
            }

            if (source != null)
            {
                arguments.AppendFormat(" --source {0}", source);
            }

            if (force)
            {
                arguments.Append(" --force");
            }

            await ProcessEx.RunAsync(this.chocoExePath, arguments.ToString());

            var newPackage =
                (await this.GetInstalledPackages(true)).OrderByDescending(p => p.Version)
                    .FirstOrDefault(
                        p =>
                        string.Compare(p.Id, id, StringComparison.OrdinalIgnoreCase) == 0
                        && (version == null || version == p.Version));

            this.UpdatePackageLists(id, source, newPackage, version);
        }
    static void AssertVariablesAreWrittenToFile(string f)
    {
        var writes = new List<string>();
        var semanticVersion = new SemanticVersion
            {
                Major = 1,
                Minor = 2,
                Patch = 3,
                PreReleaseTag = "beta1",
                BuildMetaData = "5"
            };

        semanticVersion.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z");
        semanticVersion.BuildMetaData.Sha = "commitSha";

        var config = new TestEffectiveConfiguration();

        var variables = VariableProvider.GetVariablesFor(semanticVersion, config, false);

        var j = new Jenkins(f);

        j.WriteIntegration(writes.Add, variables);

        writes[1].ShouldBe("1.2.3-beta.1+5");

        File.Exists(f).ShouldBe(true);

        var props = File.ReadAllText(f);

        props.ShouldContain("GitVersion_Major=1");
        props.ShouldContain("GitVersion_Minor=2");
    }
        private IEnumerable<ITaskItem> ResolvePackage(ITaskItem package)
        {
            string id = package.ItemSpec;
            string version = package.GetMetadata("Version");

            Log.LogMessage(MessageImportance.Normal, "Resolving Package Reference {0} {1}...", id, version);

            // Initial version just searches a machine-level repository

            var localFs = new PhysicalFileSystem(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Lib"));
            var defaultResolver = new DefaultPackagePathResolver(localFs);
            var machineRepo = new LocalPackageRepository(defaultResolver, localFs);
            var buildRepo = new BuildPackageRepository();
            var remoteRepo = new DataServicePackageRepository(new Uri("https://nuget.org/api/v2"));
            var project = new BuildProjectSystem(ProjectDirectory, new FrameworkName(TargetFramework), CurrentReferences);
            var manager = new PackageManager(remoteRepo, defaultResolver, localFs, machineRepo);
            var projectManager = new ProjectManager(remoteRepo, defaultResolver, project, buildRepo);

            // Install the package
            var ver = new SemanticVersion(version);
            manager.PackageInstalling += manager_PackageInstalling;
            manager.InstallPackage(id, ver);
            projectManager.AddPackageReference(id, ver);

            return project.OutputReferences.Select(item =>
            {
                var name = AssemblyName.GetAssemblyName(item);
                return new TaskItem(name.FullName, new Dictionary<string, string>() {
                    {"HintPath", item },
                    {"Private", "true"}
                });
            });
        }
 public void VerifyCreatedCode()
 {
     var semanticVersion = new SemanticVersion
     {
         Major = 1,
         Minor = 2,
         Patch = 3,
         PreReleaseTag = "unstable4",
         BuildMetaData = new SemanticVersionBuildMetaData(5,
             "feature1",
             new ReleaseDate
             {
                 OriginalCommitSha = "originalCommitSha",
                 OriginalDate = DateTimeOffset.Parse("2014-03-01 00:00:01Z"),
                 CommitSha = "commitSha",
                 Date = DateTimeOffset.Parse("2014-03-06 23:59:59Z")
             })
     };
     var assemblyInfoBuilder = new AssemblyInfoBuilder
         {
             SemanticVersion = semanticVersion
         };
     var assemblyInfoText = assemblyInfoBuilder.GetAssemblyInfoText();
     Approvals.Verify(assemblyInfoText);
     var syntaxTree = SyntaxTree.ParseText(assemblyInfoText);
     var references = new[] {new MetadataFileReference(typeof(object).Assembly.Location), };
     var compilation = Compilation.Create("Greeter.dll", new CompilationOptions(OutputKind.NetModule), new[] { syntaxTree }, references);
     var emitResult = compilation.Emit(new MemoryStream());
     Assert.IsTrue(emitResult.Success, string.Join(Environment.NewLine, emitResult.Diagnostics.Select(x => x.Info)));
 }
		void CreateUpdatePackageInAllProjects(string packageId, SemanticVersion version)
		{
			fakeSolution = new FakePackageManagementSolution();
			fakeSourceRepository = new FakePackageRepository();
			var packageReference = new PackageReference(packageId, version, null, null, false, false);
			updatePackageInAllProjects = new UpdatePackageInAllProjects(packageReference, fakeSolution, fakeSourceRepository);
		}
        public SemanticVersion NextVersion()
        {
            var versionZero = new SemanticVersion();
            var lastRelease = lastTaggedReleaseFinder.GetVersion().SemVer;
            var fileVersion = nextVersionTxtFileFinder.GetNextVersion();
            var mergedBranchVersion = mergedBranchesWithVersionFinder.GetVersion();
            var otherBranchVersion = unknownBranchFinder.FindVersion(context);
            if (otherBranchVersion != null && otherBranchVersion.PreReleaseTag != null && otherBranchVersion.PreReleaseTag.Name == "release")
                otherBranchVersion.PreReleaseTag.Name = "beta";

            var maxCalculated = new[]{ fileVersion, otherBranchVersion, mergedBranchVersion }.Max();

            if (lastRelease == versionZero && maxCalculated == versionZero)
            {
                return new SemanticVersion
                {
                    Minor = 1
                };
            }

            if (maxCalculated <= lastRelease)
            {
                return new SemanticVersion
                {
                    Major = lastRelease.Major,
                    Minor = lastRelease.Minor,
                    Patch = lastRelease.Patch + 1
                };
            }

            return maxCalculated;
        }
        private IEnumerable<NuDeployPackageInfo> GetAllPackages()
        {
            IEnumerable<PackageInfo> installedPackages = this.packageConfigurationAccessor.GetInstalledPackages();

            foreach (PackageInfo package in installedPackages)
            {
                string packagePrefix = string.Format("{0}.", package.Id);

                var packageDirectories =
                    this.filesystemAccessor.GetSubDirectories(this.applicationInformation.StartupFolder).Where(
                        dir => dir.Name.StartsWith(packagePrefix, StringComparison.OrdinalIgnoreCase));

                foreach (DirectoryInfo packageDirectory in packageDirectories)
                {
                    string packageVersionString = packageDirectory.Name.Replace(string.Format("{0}.", package.Id), string.Empty);
                    var packageVersion = new SemanticVersion(packageVersionString);
                    var isInstalled = packageVersion.ToString().Equals(package.Version);

                    yield return new NuDeployPackageInfo
                        {
                            Id = package.Id,
                            Version = packageVersion,
                            Folder = packageDirectory.FullName,
                            IsInstalled = isInstalled
                        };
                }
            }
        }
        public UncompressedPackage(IPackageRepository source,
                                   IFile originalPackageFile,
                                   IDirectory wrapCacheDirectory)
        {
            Check.NotNull(source, "source");
            if (originalPackageFile == null || originalPackageFile.Exists == false)
            {
                IsValid = false;
                return;
            }
            _originalPackageFile = originalPackageFile;
            BaseDirectory = wrapCacheDirectory;
            // get the descriptor file inside the package

            Source = source;
            var wrapDescriptor = wrapCacheDirectory.Files("*.wrapdesc").SingleOrDefault();

            if (wrapDescriptor == null)
            {
                IsValid = false;
                return;
            }

            var versionFile = wrapCacheDirectory.GetFile("version");
            _descriptor = new PackageDescriptorReader().Read(wrapDescriptor);
            _semver = _descriptor.SemanticVersion ?? _descriptor.Version.ToSemVer();
            if (_semver == null)
                _semver = versionFile.Exists ? versionFile.ReadString().ToSemVer() : null;

            IsValid = string.IsNullOrEmpty(Name) == false && _semver != null;
            if (IsValid)
                Identifier = new PackageIdentifier(Name, _semver);
        }
        public static AssemblyMetaData Process(
            SemanticVersion sv,
            AssemblyVersioningScheme scheme,
            bool addNumberOfCommitsSinceTagOnMasterBranchToFileVersion)
        {
            var fileVersion = GetStrictAssemblyFileVersion(sv, addNumberOfCommitsSinceTagOnMasterBranchToFileVersion);
            string version;

            switch (scheme)
            {
                case AssemblyVersioningScheme.None:
                    version = "1.0.0.0";
                    break;

                case AssemblyVersioningScheme.Major:
                    version = string.Format("{0}.0.0.0", sv.Major);
                    break;

                case AssemblyVersioningScheme.MajorMinor:
                    version = string.Format("{0}.{1}.0.0", sv.Major, sv.Minor);
                    break;

                case AssemblyVersioningScheme.MajorMinorPatch:
                    version = GetStrictAssemblyFileVersion(sv, false);
                    break;

                default:
                    throw new ArgumentException(string.Format("Unexpected value ({0}).", scheme), "scheme");
            }

            return new AssemblyMetaData(version, fileVersion);
        }
        public void GetHashCodeNotEqualNoBuildNoPrerelease()
        {
            SemanticVersion left = new SemanticVersion(1, 0, 0);
            SemanticVersion right = new SemanticVersion(2, 0, 0);

            Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
        }
Example #23
0
        public SemanticVersion FindVersion(IRepository repository, Commit tip)
        {
            int major;
            int minor;
            int patch;
            foreach (var tag in repository.TagsByDate(tip))
            {
                if (ShortVersionParser.TryParse(tag.Name, out major, out minor, out patch))
                {
                    return BuildVersion(repository, tip, major, minor, patch);
                }
            }

            var semanticVersion = new SemanticVersion();

            string versionString;
            if (MergeMessageParser.TryParse(tip, out versionString))
            {
                if (ShortVersionParser.TryParse(versionString, out major, out minor, out patch))
                {
                    semanticVersion = BuildVersion(repository, tip, major, minor, patch);
                }
            }

            semanticVersion.OverrideVersionManuallyIfNeeded(repository);

            if (semanticVersion == null || semanticVersion.IsEmpty())
            {
                throw new WarningException("The head of a support branch should always be a merge commit if you follow gitflow. Please create one or work around this by tagging the commit with SemVer compatible Id.");
            }

            return semanticVersion;
        }
        public void GetHashCodeNotEqual()
        {
            SemanticVersion left = new SemanticVersion(1, 0, 0, "foo", "bar");
            SemanticVersion right = new SemanticVersion(2, 0, 0, "foo", "bar");

            Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
        }
Example #25
0
 public void semantic_from_version()
 {
     var version = new Version("1.0.0.23");
     var sem = new SemanticVersion(version);
     var sem2 = new SemanticVersion("1.0.0");
     Assert.Equal(sem2,sem);
 }
Example #26
0
    public static bool TryGetVersion(string directory, out SemanticVersion versionAndBranch)
    {
        var gitDirectory = GitDirFinder.TreeWalkForGitDir(directory);

        if (string.IsNullOrEmpty(gitDirectory))
        {
            var message =
                "No .git directory found in provided solution path. This means the assembly may not be versioned correctly. " +
                "To fix this warning either clone the repository using git or remove the `GitVersionTask` nuget package. " +
                "To temporarily work around this issue add a AssemblyInfo.cs with an appropriate `AssemblyVersionAttribute`. " +
                "If it is detected that this build is occurring on a CI server an error may be thrown.";
            Logger.WriteWarning(message);
            versionAndBranch = null;
            return false;
        }

        if (!processedDirectories.Contains(directory))
        {
            processedDirectories.Add(directory);
            var authentication = new Authentication();
            foreach (var buildServer in BuildServerList.GetApplicableBuildServers(authentication))
            {
                Logger.WriteInfo(string.Format("Executing PerformPreProcessingSteps for '{0}'.", buildServer.GetType().Name));
                buildServer.PerformPreProcessingSteps(gitDirectory);
            }
        }
        versionAndBranch = VersionCache.GetVersion(gitDirectory);
        return true;
    }
            public void WillReturnConflictIfAPackageWithTheIdAndSemanticVersionAlreadyExists()
            {
                var version = new SemanticVersion("1.0.42");
                var nuGetPackage = new Mock<IPackage>();
                nuGetPackage.Setup(x => x.Id).Returns("theId");
                nuGetPackage.Setup(x => x.Version).Returns(version);

                var user = new User();

                var packageRegistration = new PackageRegistration
                {
                    Packages = new List<Package> { new Package { Version = version.ToString() } },
                    Owners = new List<User> { user }
                };

                var packageSvc = new Mock<IPackageService>();
                packageSvc.Setup(x => x.FindPackageRegistrationById(It.IsAny<string>())).Returns(packageRegistration);
                var userSvc = new Mock<IUserService>();
                userSvc.Setup(x => x.FindByApiKey(It.IsAny<Guid>())).Returns(user);
                var controller = CreateController(userSvc: userSvc, packageSvc: packageSvc, packageFromInputStream: nuGetPackage.Object);

                // Act
                var result = controller.CreatePackagePut(Guid.NewGuid().ToString());

                // Assert
                Assert.IsType<HttpStatusCodeWithBodyResult>(result);
                var statusCodeResult = (HttpStatusCodeWithBodyResult)result;
                Assert.Equal(409, statusCodeResult.StatusCode);
                Assert.Equal(String.Format(Strings.PackageExistsAndCannotBeModified, "theId", "1.0.42"), statusCodeResult.StatusDescription);
            }
Example #28
0
        private bool TryResolvePartialName(string name, SemanticVersion version, FrameworkName targetFramework, out string assemblyLocation)
        {
            foreach (var gacPath in GetGacSearchPaths(targetFramework))
            {
                var di = new DirectoryInfo(Path.Combine(gacPath, name));

                if (!di.Exists)
                {
                    continue;
                }

                foreach (var assemblyFile in di.EnumerateFiles("*.dll", SearchOption.AllDirectories))
                {
                    if (!Path.GetFileNameWithoutExtension(assemblyFile.Name).Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    SemanticVersion assemblyVersion = VersionUtility.GetAssemblyVersion(assemblyFile.FullName);
                    if (version == null || assemblyVersion == version)
                    {
                        assemblyLocation = assemblyFile.FullName;
                        return true;
                    }
                }
            }

            assemblyLocation = null;
            return false;
        }
        public SemanticVersion FindVersion(GitVersionContext context)
        {
            // If current commit is tagged, don't do anything except add build metadata
            if (context.IsCurrentCommitTagged)
            {
                // Will always be 0, don't bother with the +0 on tags
                var semanticVersionBuildMetaData = metaDataCalculator.Create(context.CurrentCommit, context);
                semanticVersionBuildMetaData.CommitsSinceTag = null;
                var semanticVersion = new SemanticVersion(context.CurrentCommitTaggedVersion)
                {
                    BuildMetaData = semanticVersionBuildMetaData
                };
                return semanticVersion;
            }

            var baseVersion = baseVersionFinder.GetBaseVersion(context);
            var semver = baseVersion.SemanticVersion;
            var increment = IncrementStrategyFinder.DetermineIncrementedField(context, baseVersion);
            if (increment != null)
            {
                semver = semver.IncrementVersion(increment.Value);
            }
            else Logger.WriteInfo("Skipping version increment");

            if (!semver.PreReleaseTag.HasTag() && !string.IsNullOrEmpty(context.Configuration.Tag))
            {
                UpdatePreReleaseTag(context, semver, baseVersion.BranchNameOverride);
            }

            semver.BuildMetaData = metaDataCalculator.Create(baseVersion.BaseVersionSource, context);

            return semver;
        }
 protected void remove_hook_should_be_called(string expectedRepository, string expectedName, string expectedScope, SemanticVersion expectedVersion)
 {
     RemoveCalls.FirstOrDefault(x => x.Repository == expectedRepository &&
                                     x.Name == expectedName &&
                                     x.Scope == expectedScope &&
                                     x.Version == expectedVersion).ShouldNotBeNull();
 }
Example #31
0
    public void PrepareRelease_Master(
        // data for initial setup (version and release options configured in version.json)
        string initialVersion,
        string releaseOptionsBranchName,
        ReleaseVersionIncrement?releaseOptionsVersionIncrement,
        string releaseOptionsFirstUnstableTag,
        // arguments passed to PrepareRelease()
        string releaseUnstableTag,
        string nextVersion,
        ReleaseVersionIncrement?parameterVersionIncrement,
        // expected versions and branch name after running PrepareRelease()
        string expectedBranchName,
        string resultingReleaseVersion,
        string resultingMainVersion)
    {
        // create and configure repository
        this.InitializeSourceControl();

        // create version.json
        var initialVersionOptions = new VersionOptions()
        {
            Version = SemanticVersion.Parse(initialVersion),
            Release = new ReleaseOptions()
            {
                VersionIncrement = releaseOptionsVersionIncrement,
                BranchName       = releaseOptionsBranchName,
                FirstUnstableTag = releaseOptionsFirstUnstableTag
            }
        };

        this.WriteVersionFile(initialVersionOptions);

        var expectedVersionOptionsReleaseBranch = new VersionOptions()
        {
            Version = SemanticVersion.Parse(resultingReleaseVersion),
            Release = new ReleaseOptions()
            {
                VersionIncrement = releaseOptionsVersionIncrement,
                BranchName       = releaseOptionsBranchName,
                FirstUnstableTag = releaseOptionsFirstUnstableTag
            }
        };

        var expectedVersionOptionsCurrentBrach = new VersionOptions()
        {
            Version = SemanticVersion.Parse(resultingMainVersion),
            Release = new ReleaseOptions()
            {
                VersionIncrement = releaseOptionsVersionIncrement,
                BranchName       = releaseOptionsBranchName,
                FirstUnstableTag = releaseOptionsFirstUnstableTag
            }
        };

        var initialBranchName       = this.Repo.Head.FriendlyName;
        var tipBeforePrepareRelease = this.Repo.Head.Tip;

        // prepare release
        var releaseManager = new ReleaseManager();

        releaseManager.PrepareRelease(this.RepoPath, releaseUnstableTag, (nextVersion == null ? null : Version.Parse(nextVersion)), parameterVersionIncrement);

        // check if a branch was created
        Assert.Contains(this.Repo.Branches, branch => branch.FriendlyName == expectedBranchName);

        // PrepareRelease should switch back to the initial branch
        Assert.Equal(initialBranchName, this.Repo.Head.FriendlyName);

        // check if release branch contains a new commit
        // parent of new commit must be the commit before preparing the release
        var releaseBranch = this.Repo.Branches[expectedBranchName];

        {
            // If the original branch had no -prerelease tag, the release branch has no commit to author.
            if (string.IsNullOrEmpty(initialVersionOptions.Version.Prerelease))
            {
                Assert.Equal(releaseBranch.Tip.Id, tipBeforePrepareRelease.Id);
            }
            else
            {
                Assert.NotEqual(releaseBranch.Tip.Id, tipBeforePrepareRelease.Id);
                Assert.Equal(releaseBranch.Tip.Parents.Single().Id, tipBeforePrepareRelease.Id);
            }
        }

        if (string.IsNullOrEmpty(initialVersionOptions.Version.Prerelease))
        {
            // Verify that one commit was authored.
            var incrementCommit = this.Repo.Head.Tip;
            Assert.Single(incrementCommit.Parents);
            Assert.Equal(tipBeforePrepareRelease.Id, incrementCommit.Parents.Single().Id);
        }
        else
        {
            // check if current branch contains new commits
            // - one commit that updates the version (parent must be the commit before preparing the release)
            // - one commit merging the release branch back to master and resolving the conflict
            var mergeCommit = this.Repo.Head.Tip;
            Assert.Equal(2, mergeCommit.Parents.Count());
            Assert.Equal(releaseBranch.Tip.Id, mergeCommit.Parents.Skip(1).First().Id);

            var updateVersionCommit = mergeCommit.Parents.First();
            Assert.Single(updateVersionCommit.Parents);
            Assert.Equal(tipBeforePrepareRelease.Id, updateVersionCommit.Parents.First().Id);
        }

        // check version on release branch
        {
            var releaseBranchVersion = VersionFile.GetVersion(releaseBranch.Tip);
            Assert.Equal(expectedVersionOptionsReleaseBranch, releaseBranchVersion);
        }

        // check version on master branch
        {
            var currentBranchVersion = VersionFile.GetVersion(this.Repo.Head.Tip);
            Assert.Equal(expectedVersionOptionsCurrentBrach, currentBranchVersion);
        }
    }
Example #32
0
 public RequireServer VersionLessThan(string version)
 {
     return(VersionLessThan(SemanticVersion.Parse(version)));
 }
Example #33
0
        private WriteCommandOperation <BsonDocument> CreateOperation(SemanticVersion serverVersion)
        {
            var command = CreateCommand(serverVersion);

            return(new WriteCommandOperation <BsonDocument>(_collectionNamespace.DatabaseNamespace, command, BsonDocumentSerializer.Instance, _messageEncoderSettings));
        }
Example #34
0
        protected virtual RootResource EstablishSession()
        {
            RootResource server;

            var       watch     = Stopwatch.StartNew();
            Exception lastError = null;

            // 60 second limit using Stopwatch alone makes debugging impossible.
            var retries = 3;

            while (true)
            {
                if (retries <= 0 && TimeSpan.FromMilliseconds(watch.ElapsedMilliseconds) > TimeSpan.FromSeconds(60))
                {
                    if (lastError == null)
                    {
                        throw new Exception("Unable to connect to the Octopus Deploy server.");
                    }

                    throw new Exception("Unable to connect to the Octopus Deploy server. See the inner exception for details.", lastError);
                }

                try
                {
                    server = Get <RootResource>("~/api");
                    break;
                }
                catch (WebException ex)
                {
                    Thread.Sleep(1000);
                    lastError = ex;
                }
                catch (OctopusServerException ex)
                {
                    if (ex.HttpStatusCode != 503)
                    {
                        // 503 means the service is starting, so give it some time to start
                        throw;
                    }

                    Thread.Sleep(500);
                    lastError = ex;
                }
                retries--;
            }

            if (string.IsNullOrWhiteSpace(server.ApiVersion))
            {
                throw new UnsupportedApiVersionException("This Octopus Deploy server uses an older API specification than this tool can handle. Please check for updates to the Octo tool.");
            }

            var min     = SemanticVersion.Parse(ApiConstants.SupportedApiSchemaVersionMin);
            var max     = SemanticVersion.Parse(ApiConstants.SupportedApiSchemaVersionMax);
            var current = SemanticVersion.Parse(server.ApiVersion);

            if (current < min || current > max)
            {
                throw new UnsupportedApiVersionException(string.Format("This Octopus Deploy server uses a newer API specification ({0}) than this tool can handle ({1} to {2}). Please check for updates to this tool.", server.ApiVersion, ApiConstants.SupportedApiSchemaVersionMin, ApiConstants.SupportedApiSchemaVersionMax));
            }

            return(server);
        }
Example #35
0
 public EntryKey(string id, SemanticVersion version)
 {
     Id      = id;
     Version = version;
 }
Example #36
0
 public static string AppDirForVersion(string rootAppDirectory, SemanticVersion version)
 {
     return(Path.Combine(rootAppDirectory, "app-" + version.ToString()));
 }
Example #37
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // This custom provider allows able to use just [Authorize] instead of having to define [Authorize(AuthenticationSchemes = "Bearer")] above every API controller
            // without this Bearer authorization will not work
            services.AddSingleton <IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();

            services.AddRedis(Configuration);

            services.AddSignalR().AddPushNotifications(Configuration);

            services.AddOptions <PlatformOptions>().Bind(Configuration.GetSection("VirtoCommerce")).ValidateDataAnnotations();
            services.AddOptions <DistributedLockOptions>().Bind(Configuration.GetSection("DistributedLock"));
            services.AddOptions <TranslationOptions>().Configure(options =>
            {
                options.PlatformTranslationFolderPath = WebHostEnvironment.MapPath(options.PlatformTranslationFolderPath);
            });
            //Get platform version from GetExecutingAssembly
            PlatformVersion.CurrentVersion = SemanticVersion.Parse(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion);

            services.AddPlatformServices(Configuration);
            services.AddSecurityServices();
            services.AddSingleton <LicenseProvider>();


            var mvcBuilder = services.AddMvc(mvcOptions =>
            {
                //Disable 204 response for null result. https://github.com/aspnet/AspNetCore/issues/8847
                var noContentFormatter = mvcOptions.OutputFormatters.OfType <HttpNoContentOutputFormatter>().FirstOrDefault();
                if (noContentFormatter != null)
                {
                    noContentFormatter.TreatNullValueAsNoContent = false;
                }
            })
                             .AddNewtonsoftJson(options =>
            {
                //Next line needs to represent custom derived types in the resulting swagger doc definitions. Because default SwaggerProvider used global JSON serialization settings
                //we should register this converter globally.
                options.SerializerSettings.ContractResolver = new PolymorphJsonContractResolver();
                //Next line allow to use polymorph types as parameters in API controller methods
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.Converters.Add(new ModuleIdentityJsonConverter());
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                options.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling       = DateTimeZoneHandling.Utc;
                options.SerializerSettings.NullValueHandling          = NullValueHandling.Ignore;
                options.SerializerSettings.Formatting = Formatting.None;
            }
                                                );

            services.AddSingleton(js =>
            {
                var serv = js.GetService <IOptions <MvcNewtonsoftJsonOptions> >();
                return(JsonSerializer.Create(serv.Value.SerializerSettings));
            });

            services.AddDbContext <SecurityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("VirtoCommerce"));
                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            // Enable synchronous IO if using Kestrel:
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Enable synchronous IO if using IIS:
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var authBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                              //Add the second ApiKey auth schema to handle api_key in query string
                              .AddScheme <ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.DefaultScheme, options => { })
                              .AddCookie();

            services.AddSecurityServices(options =>
            {
            });

            services.AddIdentity <ApplicationUser, Role>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores <SecurityDbContext>()
            .AddDefaultTokenProviders();

            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.RoleClaimType     = OpenIdConnectConstants.Claims.Role;
            });

            // Support commonly used forwarded headers
            // X-Forwarded-For - Holds Client IP (optionally port number) across proxies and ends up in HttpContext.Connection.RemoteIpAddress
            // X-Forwarded-Proto - Holds original scheme (HTTP or HTTPS) even if call traversed proxies and changed and ends up in HttpContext.Request.Scheme
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Clear();
                options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor;
            });

            //Create backup of token handler before default claim maps are cleared
            var defaultTokenHandler = new JwtSecurityTokenHandler();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            authBuilder.AddJwtBearer(options =>
            {
                options.Authority = Configuration["Auth:Authority"];
                options.Audience  = Configuration["Auth:Audience"];

                if (WebHostEnvironment.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }

                options.IncludeErrorDetails = true;

                X509SecurityKey publicKey = null;
                if (!Configuration["Auth:PublicCertPath"].IsNullOrEmpty())
                {
                    var publicCert = new X509Certificate2(Configuration["Auth:PublicCertPath"]);
                    publicKey      = new X509SecurityKey(publicCert);
                }

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType            = OpenIdConnectConstants.Claims.Subject,
                    RoleClaimType            = OpenIdConnectConstants.Claims.Role,
                    ValidateIssuer           = !string.IsNullOrEmpty(options.Authority),
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = publicKey
                };
            });

            var azureAdSection = Configuration.GetSection("AzureAd");

            if (azureAdSection.GetChildren().Any())
            {
                var options = new AzureAdOptions();
                azureAdSection.Bind(options);

                if (options.Enabled)
                {
                    //TODO: Need to check how this influence to OpennIddict Reference tokens activated by this line below  AddValidation(options => options.UseReferenceTokens())
                    //TechDept: Need to upgrade to Microsoft.Identity.Web
                    //https://docs.microsoft.com/en-us/azure/active-directory/develop/microsoft-identity-web
                    authBuilder.AddOpenIdConnect(options.AuthenticationType, options.AuthenticationCaption,
                                                 openIdConnectOptions =>
                    {
                        openIdConnectOptions.ClientId = options.ApplicationId;

                        openIdConnectOptions.Authority              = $"{options.AzureAdInstance}{options.TenantId}";
                        openIdConnectOptions.UseTokenLifetime       = true;
                        openIdConnectOptions.RequireHttpsMetadata   = false;
                        openIdConnectOptions.SignInScheme           = IdentityConstants.ExternalScheme;
                        openIdConnectOptions.SecurityTokenValidator = defaultTokenHandler;
                        openIdConnectOptions.MetadataAddress        = options.MetadataAddress;
                    });
                }
            }

            services.AddOptions <Core.Security.AuthorizationOptions>().Bind(Configuration.GetSection("Authorization")).ValidateDataAnnotations();
            var authorizationOptions = Configuration.GetSection("Authorization").Get <Core.Security.AuthorizationOptions>();
            var platformOptions      = Configuration.GetSection("VirtoCommerce").Get <PlatformOptions>();

            // Register the OpenIddict services.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict entities.
            services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFrameworkCore()
                .UseDbContext <SecurityDbContext>();
            }).AddServer(options =>
            {
                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.UseMvc();

                // Enable the authorization, logout, token and userinfo endpoints.
                options.EnableTokenEndpoint("/connect/token")
                .EnableUserinfoEndpoint("/api/security/userinfo");

                // Note: the Mvc.Client sample only uses the code flow and the password flow, but you
                // can enable the other flows if you need to support implicit or client credentials.
                options.AllowPasswordFlow()
                .AllowRefreshTokenFlow()
                .AllowClientCredentialsFlow();

                options.SetRefreshTokenLifetime(authorizationOptions?.RefreshTokenLifeTime);
                options.SetAccessTokenLifetime(authorizationOptions?.AccessTokenLifeTime);

                options.AcceptAnonymousClients();

                // Configure Openiddict to issues new refresh token for each token refresh request.
                options.UseRollingTokens();

                // Make the "client_id" parameter mandatory when sending a token request.
                //options.RequireClientIdentification()

                // When request caching is enabled, authorization and logout requests
                // are stored in the distributed cache by OpenIddict and the user agent
                // is redirected to the same page with a single parameter (request_id).
                // This allows flowing large OpenID Connect requests even when using
                // an external authentication provider like Google, Facebook or Twitter.
                options.EnableRequestCaching();

                options.DisableScopeValidation();

                // During development or when you explicitly run the platform in production mode without https, need to disable the HTTPS requirement.
                if (WebHostEnvironment.IsDevelopment() || platformOptions.AllowInsecureHttp || !Configuration.IsHttpsServerUrlSet())
                {
                    options.DisableHttpsRequirement();
                }

                // Note: to use JWT access tokens instead of the default
                // encrypted format, the following lines are required:
                options.UseJsonWebTokens();

                var bytes = File.ReadAllBytes(Configuration["Auth:PrivateKeyPath"]);
                X509Certificate2 privateKey;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    // https://github.com/dotnet/corefx/blob/release/2.2/Documentation/architecture/cross-platform-cryptography.md
                    // macOS cannot load certificate private keys without a keychain object, which requires writing to disk. Keychains are created automatically for PFX loading, and are deleted when no longer in use. Since the X509KeyStorageFlags.EphemeralKeySet option means that the private key should not be written to disk, asserting that flag on macOS results in a PlatformNotSupportedException.
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet);
                }
                else
                {
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
                }
                options.AddSigningCertificate(privateKey);
            });

            services.Configure <IdentityOptions>(Configuration.GetSection("IdentityOptions"));
            services.Configure <PasswordOptionsExtended>(Configuration.GetSection("IdentityOptions:Password"));
            services.Configure <UserOptionsExtended>(Configuration.GetSection("IdentityOptions:User"));
            services.Configure <DataProtectionTokenProviderOptions>(Configuration.GetSection("IdentityOptions:DataProtection"));

            //always  return 401 instead of 302 for unauthorized  requests
            services.ConfigureApplicationCookie(options =>
            {
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
            });

            services.AddAuthorization(options =>
            {
                //We need this policy because it is a single way to implicitly use the two schema (JwtBearer and ApiKey)  authentication for resource based authorization.
                var mutipleSchemaAuthPolicy = new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme)
                                              .RequireAuthenticatedUser()
                                              .Build();
                //The good article is described the meaning DefaultPolicy and FallbackPolicy
                //https://scottsauber.com/2020/01/20/globally-require-authenticated-users-by-default-using-fallback-policies-in-asp-net-core/
                options.DefaultPolicy = mutipleSchemaAuthPolicy;
            });
            // register the AuthorizationPolicyProvider which dynamically registers authorization policies for each permission defined in module manifest
            services.AddSingleton <IAuthorizationPolicyProvider, PermissionAuthorizationPolicyProvider>();
            //Platform authorization handler for policies based on permissions
            services.AddSingleton <IAuthorizationHandler, DefaultPermissionAuthorizationHandler>();

            services.AddOptions <LocalStorageModuleCatalogOptions>().Bind(Configuration.GetSection("VirtoCommerce"))
            .PostConfigure(options =>
            {
                options.DiscoveryPath = Path.GetFullPath(options.DiscoveryPath ?? "modules");
            })
            .ValidateDataAnnotations();
            services.AddModules(mvcBuilder);

            services.AddOptions <ExternalModuleCatalogOptions>().Bind(Configuration.GetSection("ExternalModules")).ValidateDataAnnotations();
            services.AddExternalModules();

            //Assets
            var assetsProvider = Configuration.GetSection("Assets:Provider").Value;

            if (assetsProvider.EqualsInvariant(AzureBlobProvider.ProviderName))
            {
                services.AddOptions <AzureBlobOptions>().Bind(Configuration.GetSection("Assets:AzureBlobStorage")).ValidateDataAnnotations();
                services.AddAzureBlobProvider();
            }
            else
            {
                services.AddOptions <FileSystemBlobOptions>().Bind(Configuration.GetSection("Assets:FileSystem"))
                .PostConfigure(options =>
                {
                    options.RootPath = WebHostEnvironment.MapPath(options.RootPath);
                }).ValidateDataAnnotations();

                services.AddFileSystemBlobProvider();
            }

            //HangFire
            services.AddHangfire(Configuration);

            // Register the Swagger generator
            services.AddSwagger();


            // The following line enables Application Insights telemetry collection.
            // CAUTION: It is important to keep the adding AI telemetry in the end of ConfigureServices method in order to avoid of multiple
            // AI modules initialization https://virtocommerce.atlassian.net/browse/VP-6653 and  https://github.com/microsoft/ApplicationInsights-dotnet/issues/2114 until we don't
            // get rid of calling IServiceCollection.BuildServiceProvider from the platform and modules code, each BuildServiceProvider call leads to the running the
            // extra AI module and causes the hight CPU utilization and telemetry data flood on production env.
            services.AddAppInsightsTelemetry(Configuration);
        }
Example #38
0
 public RequireServer()
 {
     _serverVersion = CoreTestConfiguration.ServerVersion;
 }
 public TestBaseVersionCalculator(bool shouldIncrement, SemanticVersion semanticVersion, ICommit source)
 {
     this.semanticVersion = semanticVersion;
     this.source          = source;
     this.shouldIncrement = shouldIncrement;
 }
Example #40
0
        public string GetPackageFileName(string packageId, SemanticVersion version)
        {
            var fileNameBase = packageId + "." + version;

            return(fileNameBase + Constants.PackageExtension);
        }
Example #41
0
        FakePackage CreatePackage(int i)
        {
            var package = new FakePackage();

            package.Id          = "Package ID: " + i;
            package.Description = "Package description.";
            package.Summary     =
                "Package summary. Package summary. Package summary. " +
                "Package summary. Package summary. Package summary. Package summary.";
            package.DownloadCount            = i;
            package.Rating                   = 4.5;
            package.RatingsCount             = 344;
            package.RequireLicenseAcceptance = true;
            package.LicenseUrl               = new Uri("http://www.google.com/license");
            package.ProjectUrl               = new Uri("http://www.codeplex.com");
            package.ReportAbuseUrl           = new Uri("http://www.google.com");
            package.Version                  = SemanticVersion.Parse("1.0.4.5");
            package.LastUpdated              = new DateTime(2011, 1, 2);
            package.AddAuthor("A User");
            package.AddAuthor("B User");
            package.AddDependency("NuGet.Package." + i, SemanticVersion.Parse("1.0.0.1"), SemanticVersion.Parse("1.2.0.2"));
            package.AddDependency("NuGet.Package." + i + 1, SemanticVersion.Parse("1.2.0.2"), SemanticVersion.Parse("2.2.0.0"));
            return(package);
        }
Example #42
0
 public RequireServer VersionGreaterThanOrEqualTo(string version)
 {
     return(VersionGreaterThanOrEqualTo(SemanticVersion.Parse(version)));
 }
Example #43
0
        public static IList <LibraryDescription> Walk(IList <IDependencyProvider> providers, string name, SemanticVersion version, FrameworkName targetFramework)
        {
            var libraries = new List <LibraryDescription>();

            var sw = Stopwatch.StartNew();

            Logger.TraceInformation($"[{nameof(DependencyWalker)}]: Walking dependency graph for '{name} {targetFramework}'.");

            var context = new WalkContext();

            var walkSw = Stopwatch.StartNew();

            context.Walk(
                providers,
                name,
                version,
                targetFramework);

            walkSw.Stop();
            Logger.TraceInformation($"[{nameof(DependencyWalker)}]: Graph walk took {walkSw.ElapsedMilliseconds}ms.");

            context.Populate(targetFramework, libraries);

            sw.Stop();
            Logger.TraceInformation($"$[{ nameof(DependencyWalker)}]: Resolved dependencies for {name} in { sw.ElapsedMilliseconds}ms");

            return(libraries);
        }
Example #44
0
 public string GetPackageDirectory(string packageId, SemanticVersion version)
 {
     return(packageId);
 }
 static bool MajorMinorPatchEqual(SemanticVersion lastTag, SemanticVersion baseVersion)
 {
     return(lastTag.Major == baseVersion.Major &&
            lastTag.Minor == baseVersion.Minor &&
            lastTag.Patch == baseVersion.Patch);
 }
Example #46
0
 public NuspecTemplateContext(NuspecTemplate current, NuspecTemplateCollection templates, Solution solution, SemanticVersion version)
 {
     Templates = templates;
     Version   = version;
     Solution  = solution;
     Current   = current;
 }
Example #47
0
    public void ValidateInvalidVersionParsing(string versionString)
    {
        SemanticVersion version;

        Assert.IsFalse(SemanticVersion.TryParse(versionString, null, out version), "TryParse Result");
    }
Example #48
0
        protected override async Task Export(Dictionary <string, string> paramDictionary)
        {
            if (string.IsNullOrWhiteSpace(paramDictionary["Project"]))
            {
                throw new CommandException("Please specify the project name using the parameter: --project=XYZ");
            }
            if (string.IsNullOrWhiteSpace(paramDictionary["ReleaseVersion"]))
            {
                throw new CommandException("Please specify the release, or range of releases using the parameter: --releaseVersion=1.0.0 for a single release, or --releaseVersion=1.0.0-1.0.3 for a range of releases");
            }
            var projectName    = paramDictionary["Project"];
            var releaseVersion = paramDictionary["ReleaseVersion"];

            Log.Debug("Finding project: {Project:l}", projectName);
            var project = await Repository.Projects.FindByName(projectName).ConfigureAwait(false);

            if (project == null)
            {
                throw new CouldNotFindException("a project named", projectName);
            }

            SemanticVersion minVersionToExport;
            SemanticVersion maxVersionToExport;

            // I don't think -> works on the command line unless it is quoted --releaseVersion="1.0.0->1.0.1"
            if (releaseVersion.IndexOf("->", StringComparison.Ordinal) > 0)
            {
                var releaseVersions = releaseVersion.Split(new[] { "->" }, StringSplitOptions.RemoveEmptyEntries);
                if (releaseVersions.Count() > 2)
                {
                    throw new CommandException("Incorrect format for exporting multiple releases, please specify the release versions as --releaseVersion=1.0.0-1.0.3");
                }
                minVersionToExport = SemanticVersion.Parse(releaseVersions[0]);
                maxVersionToExport = SemanticVersion.Parse(releaseVersions[1]);
            }
            else if (releaseVersion.IndexOf("-", StringComparison.Ordinal) > 0)
            {
                var releaseVersions = releaseVersion.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                if (releaseVersions.Count() > 2)
                {
                    throw new CommandException("Incorrect format for exporting multiple releases, please specify the release versions as --releaseVersion=1.0.0-1.0.3");
                }

                minVersionToExport = SemanticVersion.Parse(releaseVersions[0]);
                if (!SemanticVersion.TryParse(releaseVersions[1], out maxVersionToExport))
                {
                    minVersionToExport = SemanticVersion.Parse(releaseVersion);
                    maxVersionToExport = minVersionToExport;
                }
            }
            else
            {
                minVersionToExport = SemanticVersion.Parse(releaseVersion);
                maxVersionToExport = minVersionToExport;
            }

            Log.Debug("Finding releases for project...");
            var releasesToExport = new List <ReleaseResource>();
            var releases         = await Repository.Projects.GetReleases(project).ConfigureAwait(false);

            await releases.Paginate(Repository, page =>
            {
                foreach (var release in page.Items)
                {
                    var version = SemanticVersion.Parse(release.Version);
                    if (minVersionToExport <= version && version <= maxVersionToExport)
                    {
                        Log.Debug("Found release {Version:l}", version);
                        releasesToExport.Add(release);

                        if (minVersionToExport == maxVersionToExport)
                        {
                            break;
                        }
                    }
                }

                // Stop paging if the range is a single version, or if there is only a single release worth exporting after this page
                return((minVersionToExport != maxVersionToExport) || releasesToExport.Count != 1);
            })
            .ConfigureAwait(false);

            var metadata = new ExportMetadata
            {
                ExportedAt     = DateTime.Now,
                OctopusVersion = Repository.Client.RootDocument.Version,
                Type           = typeof(ReleaseExporter).GetAttributeValue((ExporterAttribute ea) => ea.Name),
                ContainerType  = typeof(ReleaseExporter).GetAttributeValue((ExporterAttribute ea) => ea.EntityType)
            };

            FileSystemExporter.Export(FilePath, metadata, releasesToExport);
        }
Example #49
0
        public static void SetInfo(string filename, Version version, Version fileVersion, SemanticVersion infoVersion, UpdateMethod updateMethod = UpdateMethod.ILDasm)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                try
                {
                    var data = Win32Resource.ReadVersionResource(filename);

                    var versionInfo = new VERSION_INFO_CHUNK(data);

                    // Update fixed file info
                    var info = CopyFrom <VS_FIXEDFILEINFO>(versionInfo.Value);

                    if (fileVersion != null)
                    {
                        EncodeVersion(ref info.dwFileVersion, fileVersion);
                        EncodeVersion(ref info.dwProductVersion, fileVersion);

                        versionInfo.Value = CopyTo(info);
                    }

                    var trl         = versionInfo.Children.First(c => c.Key == "VarFileInfo").Children.First(c => c.Key == "Translation");
                    var translation = BitConverter.ToUInt16(trl.Value, 0);

                    foreach (var sfi in versionInfo.Children.Where(c => c.Key == "StringFileInfo"))
                    {
                        foreach (var table in sfi.Children)
                        {
                            foreach (var str in table.Children)
                            {
                                switch (str.Key)
                                {
                                case "FileVersion":
                                    if (fileVersion != null)
                                    {
                                        str.ValueText = fileVersion.ToString(3);
                                    }
                                    break;

                                case "ProductVersion":
                                    if (infoVersion != null)
                                    {
                                        str.ValueText = infoVersion.ToString();
                                    }
                                    else if (fileVersion != null)
                                    {
                                        str.ValueText = fileVersion.ToString(3);
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    data = versionInfo.GetData();

                    Win32Resource.WriteVersionResource(filename, data);
                }
                catch (Exception ex)
                {
                    throw new Exception($"Error while updating version information for '{filename}'", ex);
                }
            }

            if (updateMethod == UpdateMethod.ILDasm)
            {
                var isDLL = (Path.GetExtension(filename) ?? "").Equals(".dll", StringComparison.InvariantCultureIgnoreCase);

                var tmpIL = Path.GetTempFileName();

                if (!IL.Disassemble(filename, tmpIL))
                {
                    throw new Exception(string.Format("Failed to disassemble input DLL/EXE {0}.", filename));
                }

                var data = File.ReadAllText(tmpIL);

                data = ReplaceAssemblyVersion(data, version);

                if (fileVersion != null)
                {
                    data = AddOrReplaceAttribute(data, "AssemblyFileVersionAttribute", fileVersion.ToString());
                }

                if (infoVersion != null)
                {
                    data = AddOrReplaceAttribute(data, "AssemblyInformationalVersionAttribute", infoVersion.ToString());
                }

                File.WriteAllText(tmpIL, data);

                var tmpDest = Path.GetTempFileName();

                if (!IL.Assemble(tmpIL, tmpDest, isDLL, Path.ChangeExtension(tmpIL, "res")))
                {
                    throw new Exception(string.Format("Failed to assemble IL code."));
                }

                ProgramHelper.FileCopy(tmpDest, filename);

                File.Delete(tmpDest);
                File.Delete(tmpIL);
            }
            else
            {
                var resolver = new TapMonoResolver();
                var asm      = AssemblyDefinition.ReadAssembly(filename, new ReaderParameters {
                    AssemblyResolver = resolver, InMemory = true, ReadingMode = ReadingMode.Immediate
                });

                if (version != null)
                {
                    asm.Name.Version = version;
                }

                foreach (var attr in asm.CustomAttributes)
                {
                    if (fileVersion != null && attr.AttributeType.FullName == typeof(AssemblyFileVersionAttribute).FullName)
                    {
                        attr.ConstructorArguments[0] = new CustomAttributeArgument(attr.ConstructorArguments[0].Type, fileVersion.ToString());
                    }

                    if (infoVersion != null && attr.AttributeType.FullName == typeof(AssemblyInformationalVersionAttribute).FullName)
                    {
                        attr.ConstructorArguments[0] = new CustomAttributeArgument(attr.ConstructorArguments[0].Type, infoVersion.ToString());
                    }
                }

                using (var stream = File.Open(filename, FileMode.OpenOrCreate))
                    asm.Write(stream);
            }
        }
Example #50
0
 public void VersionSorting()
 {
     SemanticVersion.Parse("1.0.0", null).ShouldBeGreaterThan(SemanticVersion.Parse("1.0.0-beta", null));
     SemanticVersion.Parse("1.0.0-beta.2", null).ShouldBeGreaterThan(SemanticVersion.Parse("1.0.0-beta.1", null));
     SemanticVersion.Parse("1.0.0-beta.1", null).ShouldBeLessThan(SemanticVersion.Parse("1.0.0-beta.2", null));
 }
        public virtual async Task <ActionResult> GetPackage(string id, string version)
        {
            // some security paranoia about URL hacking somehow creating e.g. open redirects
            // validate user input: explicit calls to the same validators used during Package Registrations
            // Ideally shouldn't be necessary?
            if (!PackageIdValidator.IsValidPackageId(id ?? ""))
            {
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The format of the package id is invalid"));
            }

            if (!String.IsNullOrEmpty(version))
            {
                SemanticVersion dummy;
                if (!SemanticVersion.TryParse(version, out dummy))
                {
                    return(new HttpStatusCodeWithBodyResult(HttpStatusCode.BadRequest, "The package version is not a valid semantic version"));
                }
            }

            // Normalize the version
            version = SemanticVersionExtensions.Normalize(version);

            // if the version is null, the user is asking for the latest version. Presumably they don't want includePrerelease release versions.
            // The allow prerelease flag is ignored if both partialId and version are specified.
            // In general we want to try to add download statistics for any package regardless of whether a version was specified.

            // Only allow database requests to take up to 5 seconds.  Any longer and we just lose the data; oh well.
            EntitiesContext.SetCommandTimeout(5);

            Package package = null;

            try
            {
                package = PackageService.FindPackageByIdAndVersion(id, version, allowPrerelease: false);
                if (package == null)
                {
                    return(new HttpStatusCodeWithBodyResult(
                               HttpStatusCode.NotFound, String.Format(CultureInfo.CurrentCulture, Strings.PackageWithIdAndVersionNotFound, id, version)));
                }

                try
                {
                    var stats = new PackageStatistics
                    {
                        IPAddress        = Request.UserHostAddress,
                        UserAgent        = Request.UserAgent,
                        Package          = package,
                        Operation        = Request.Headers["NuGet-Operation"],
                        DependentPackage = Request.Headers["NuGet-DependentPackage"],
                        ProjectGuids     = Request.Headers["NuGet-ProjectGuids"],
                    };

                    PackageService.AddDownloadStatistics(stats);
                }
                catch (ReadOnlyModeException)
                {
                    // *gulp* Swallowed. It's OK not to add statistics and ok to not log errors in read only mode.
                }
                catch (SqlException e)
                {
                    // Log the error and continue
                    QuietLog.LogHandledException(e);
                }
                catch (DataException e)
                {
                    // Log the error and continue
                    QuietLog.LogHandledException(e);
                }
            }
            catch (SqlException e)
            {
                QuietLog.LogHandledException(e);
            }
            catch (DataException e)
            {
                QuietLog.LogHandledException(e);
            }

            // Fall back to constructing the URL based on the package version and ID.
            if (String.IsNullOrEmpty(version) && package == null)
            {
                // Database was unavailable and we don't have a version, return a 503
                return(new HttpStatusCodeWithBodyResult(HttpStatusCode.ServiceUnavailable, Strings.DatabaseUnavailable_TrySpecificVersion));
            }
            return(await PackageFileService.CreateDownloadPackageActionResultAsync(
                       HttpContext.Request.Url,
                       id,
                       String.IsNullOrEmpty(version)?package.NormalizedVersion : version));
        }
        public bool CanDetermineVersionlessPackageIsInstalled(string id, string onDiskVersion, string packageVersion, bool installedUsingMultipleVersion, bool currentlyAllowMultipleVersions, bool exhaustive)
        {
            var mfs = new Mock <MockFileSystem>()
            {
                CallBase = true
            };

            mfs.Setup(m => m.Root).Returns(@"c:\packages");

            var installPathResolver = new DefaultPackagePathResolver(mfs.Object, installedUsingMultipleVersion);
            var currentPathResolver = new DefaultPackagePathResolver(mfs.Object, currentlyAllowMultipleVersions);

            var testPackage = new DataServicePackage()
            {
                Version = packageVersion,
                Id      = id
            };

            var filePackage = new DataServicePackage()
            {
                Version = onDiskVersion,
                Id      = id
            };

            IPackage zipPackage = null;

            if (!string.IsNullOrEmpty(onDiskVersion))
            {
                string baseLocation = installPathResolver.GetInstallPath(filePackage);
                string fileName     = installPathResolver.GetPackageFileName(filePackage.Id, SemanticVersion.Parse(filePackage.Version));
                string filePath     = Path.Combine(baseLocation, fileName);
                zipPackage = PackageUtility.GetZipPackage(filePackage.Id, filePackage.Version);
                mfs.Setup(m => m.FileExists(filePath)).Returns(true);
                mfs.Setup(m => m.OpenFile(filePath)).Returns(zipPackage.GetStream());
                mfs.Object.AddFile(filePath, zipPackage.GetStream());
            }

            var pm     = new PackageManager(new MockPackageRepository(), currentPathResolver, mfs.Object);
            var exists = pm.IsPackageInstalled(testPackage, exhaustive: exhaustive);

            //var test = testPackage.IsPackageInstalled(allowMultipleVersions, pm, mfs.Object);
            return(exists);
        }
Example #53
0
 public GreaterThanOrEqualVersionVertex(SemanticVersion version)
     : base(version)
 {
 }
Example #54
0
 private IPackage FindCandidate(string name, SemanticVersion version)
 {
     return(_repository.FindPackagesById(name).FirstOrDefault(p => p.Version == version)?.Package);
 }
Example #55
0
 bool MajorMatches(SemanticVersion version)
 {
     return(version.Major >= Version.Major);
 }
Example #56
0
 public override void UpdatePackageToSpecificVersion(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPreReleaseVersions, ILogger logger)
 {
     ProjectManager     = projectManager;
     PackageId          = packageId;
     Version            = version;
     UpdateDependencies = updateDependencies;
 }
Example #57
0
 public static void DoUpdateChecks()
 {
     try
     {
         string version = typeof(Game1).Assembly.GetName().Version.ToString(2);
         bool   Connected;
         try
         {
             using (WebClient client = new WebClient())
                 using (Stream stream = client.OpenRead("http://www.google.com"))
                     Connected = true;
         }
         catch
         {
             Connected = false;
         }
         if (Connected)
         {
             Parallel.ForEach(Map, (pair) =>
             {
                 try
                 {
                     WebClient Client           = new WebClient();
                     Uri uri                    = new Uri(pair.Value);
                     SemanticVersion modVersion = (SemanticVersion)pair.Key.Version;
                     try
                     {
                         Client.DownloadStringCompleted += (sender, evt) =>
                         {
                             try
                             {
                                 if (evt.Error != null)
                                 {
                                     HandleError(pair.Key.Name, (WebException)evt.Error);
                                     return;
                                 }
                                 Dictionary <string, UpdateInfo> Data = JsonConvert.DeserializeObject <Dictionary <string, UpdateInfo> >(evt.Result);
                                 UpdateInfo info = null;
                                 if (Data.ContainsKey(version))
                                 {
                                     info = Data[version];
                                 }
                                 else if (Data.ContainsKey("Default"))
                                 {
                                     info = Data["Default"];
                                 }
                                 else
                                 {
                                     ModEntry.Logger.ExitGameImmediately("[UpdateChecker] The `" + pair.Key.Name + "` mod does not support the current version of SDV.");
                                 }
                                 if (info != null)
                                 {
                                     SemanticVersion min = new SemanticVersion(info.Minimum);
                                     SemanticVersion rec = new SemanticVersion(info.Recommended);
                                     SemanticVersion max = new SemanticVersion(info.Latest);
                                     if (min.IsNewerThan(modVersion))
                                     {
                                         ModEntry.Logger.ExitGameImmediately("[UpdateChecker] The `" + pair.Key.Name + "` mod is too old, a newer version is required.");
                                     }
                                     if (rec.IsNewerThan(modVersion))
                                     {
                                         ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod has a new version available, it is recommended you update now.", LogLevel.Alert);
                                     }
                                     if (modVersion.IsBetween(rec, max))
                                     {
                                         ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod has a new version available.", LogLevel.Info);
                                     }
                                 }
                             }
                             catch (WebException err)
                             {
                                 HandleError(pair.Key.Name, err);
                             }
                             catch (Exception err)
                             {
                                 ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod failed to check for updates, unexpected error occured while reading result." + Environment.NewLine + err.ToString(), LogLevel.Error);
                             }
                         };
                         Client.DownloadStringAsync(uri);
                     }
                     catch (WebException err)
                     {
                         HandleError(pair.Key.Name, err);
                     }
                 }
                 catch (Exception err)
                 {
                     ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod failed to check for updates, unexpected error occured." + Environment.NewLine + err.ToString(), LogLevel.Error);
                 }
             });
         }
         else
         {
             ModEntry.Logger.Log("[UpdateChecker] No internet connection, skipping update checks.", LogLevel.Debug);
         }
     }
     catch (Exception err)
     {
         ModEntry.Logger.Log("[UpdateChecker] Unexpected failure, unexpected error occured." + Environment.NewLine + err.ToString(), LogLevel.Error);
     }
 }
Example #58
0
 bool MinorMatches(SemanticVersion version)
 {
     return(version.Major > Version.Major ||
            (version.Major == Version.Major &&
             version.Minor >= Version.Minor));
 }
Example #59
0
        public static int CheckMod(string modsPath, string modFolder, ModUpdateManifest mod)
        {
            if (!shouldUpdate && !mod.ModUpdater.Install)
            {
                if (!loggedNextUpdateCheck)
                {
                    Console.WriteLine("[ModUpdater] Next update check: " + (config.LastUpdateCheck.AddMinutes(config.Interval).ToString("s")));
                    loggedNextUpdateCheck = true;
                }
                return(0);
            }

            string tempFolder     = Path.Combine(modsPath, "ModUpdater", "Temp");
            var    currentVersion = mod.Version;


            if (!Directory.Exists(tempFolder))
            {
                Directory.CreateDirectory(tempFolder);
            }

            var rkey = mod.ModUpdater.User + ">" + mod.ModUpdater.Repository + ">" + mod.ModUpdater.ModFolder;
            IReadOnlyList <RepositoryContent> rContent = null;

            if (repoContents.ContainsKey(rkey))
            {
                rContent = repoContents[rkey];
            }

            Repository repo = null;

            if (rContent == null)
            {
                var repoRequest = github.Repository.Get(mod.ModUpdater.User, mod.ModUpdater.Repository);
                repoRequest.Wait();
                repo = repoRequest.Result;
            }

            Console.WriteLine("[ModUpdater] Checking for updates: " + mod.Name);
            Console.WriteLine("[ModUpdater] Current version: " + currentVersion);


            if (rContent != null || repo is Repository)
            {
                if (rContent == null)
                {
                    var fileRequest = github.Repository.Content.GetAllContents(repo.Id, mod.ModUpdater.Directory);
                    fileRequest.Wait();
                    var files = fileRequest.Result;
                    rContent = files;
                    repoContents.Add(rkey, rContent);
                }

                var   selector = mod.ModUpdater.FileSelector.Replace("{ModFolder}", mod.ModUpdater.ModFolder.Replace("[", @"\[").Replace("]", @"\]"));
                Regex findFile = new Regex(selector, RegexOptions.IgnoreCase | RegexOptions.Singleline);

                var filesFound = rContent.Where(f =>
                {
                    var m = findFile.Match(Path.GetFileNameWithoutExtension(f.Path));
                    return(m.Success && m.Groups.Count == 2);
                });

                if (filesFound.Count() == 0)
                {
                    Console.WriteLine("File not found:" + selector);

                    return(0);
                }

                foreach (RepositoryContent file in filesFound)
                {
                    var    fileName   = Path.GetFileNameWithoutExtension(file.Path);
                    var    match      = findFile.Match(fileName);
                    string newVersion = match.Groups[1].Value;

                    if (SemanticVersion.TryParse(newVersion, out ISemanticVersion version) &&
                        (mod.ModUpdater.Install || (shouldUpdate && SemanticVersion.TryParse(currentVersion, out ISemanticVersion current) && version.IsNewerThan(current))))
                    {
                        if (version.IsPrerelease() && !config.LoadPrereleases)
                        {
                            continue;
                        }

                        var url      = file.DownloadUrl;
                        var tempFile = Path.Combine(tempFolder, Path.GetFileName(file.Path));

                        using (WebClient client = new WebClient())
                            client.DownloadFile(url, tempFile);

                        ModUpdateManifest updateManifest = null;

                        using (ZipArchive zip1 = ZipFile.OpenRead(tempFile))
                        {
                            if (zip1.Entries.FirstOrDefault(entry => entry.Name.Equals("manifest.json", StringComparison.InvariantCultureIgnoreCase)) is ZipArchiveEntry manifestEntry)
                            {
                                using (StreamReader sr = new StreamReader(manifestEntry.Open(), System.Text.Encoding.UTF8))
                                {
                                    if (Newtonsoft.Json.JsonConvert.DeserializeObject <ModUpdateManifest>(sr.ReadToEnd()) is ModUpdateManifest um)
                                    {
                                        updateManifest = um;
                                    }

                                    if (updateManifest is ModUpdateManifest &&
                                        SemanticVersion.TryParse(updateManifest.MinimumApiVersion, out ISemanticVersion updateApiVersion) &&
                                        Constants.ApiVersion.IsOlderThan(updateApiVersion))
                                    {
                                        Console.WriteLine("[ModUpdater] [" + updateManifest.UniqueID + "]" + "Could not update to version" + updateManifest.Version + ". Need at least SMAPI " + updateManifest.MinimumApiVersion);
                                        continue;
                                    }
                                }
                            }
                            else
                            {
                                continue;
                            }

                            foreach (ZipArchiveEntry e in zip1.Entries)
                            {
                                string        filePath      = e.FullName.Replace('/', '\\');
                                List <string> filePathParts = filePath.Split('\\').ToList();
                                filePathParts.RemoveAt(0);
                                Console.WriteLine(modFolder);
                                filePath = Path.Combine(filePathParts.ToArray());
                                var tPath      = Path.Combine(modFolder, filePath);
                                var tDirectory = Path.Combine(modFolder, Path.GetDirectoryName(filePath));
                                if (!Directory.Exists(tDirectory))
                                {
                                    Directory.CreateDirectory(tDirectory);
                                }

                                Console.WriteLine("[ModUpdater] " + " [" + mod.UniqueID + "] " + "Updating file: " + tPath);

                                if (File.Exists(tPath) && updateManifest.ModUpdater.DoNotReplace.Contains(Path.GetFileName(tPath)))
                                {
                                    continue;
                                }

                                foreach (string dFile in updateManifest.ModUpdater.DeleteFiles)
                                {
                                    string dfilePath = Path.Combine(modFolder, Path.Combine(dFile.Replace('/', '\\').Split('\\')));
                                    Console.WriteLine("[ModUpdater] " + " [" + mod.UniqueID + "] " + "Deleting file: " + dFile);

                                    if (File.Exists(dfilePath))
                                    {
                                        File.Delete(dfilePath);
                                    }
                                }

                                foreach (string dFolder in updateManifest.ModUpdater.DeleteFolders)
                                {
                                    string dFolderPath = Path.Combine(modFolder, Path.Combine(dFolder.Replace('/', '\\').Split('\\')));
                                    Console.WriteLine("[ModUpdater] " + " [" + mod.UniqueID + "] " + "Deleting folder: " + dFolder);

                                    if (Directory.Exists(dFolderPath))
                                    {
                                        Directory.Delete(dFolderPath, true);
                                    }
                                }

                                e.ExtractToFile(tPath, true);
                            }
                        }

                        Console.WriteLine("[ModUpdater]  [" + mod.UniqueID + "] " + mod.Name + " was successfully updated to version " + version);

                        if (updateManifest is ModUpdateManifest)
                        {
                            updated.Add(updateManifest);
                        }

                        return(1);
                    }
                }
            }

            return(0);
        }
Example #60
0
 public override bool IsCompatibleWith(SemanticVersion version)
 {
     return(MajorMatches(version) &&
            MinorMatches(version) &&
            BuildMatches(version));
 }