public void SemVerStableNonPublicVersion()
    {
        var workingCopyVersion = new VersionOptions
        {
            Version = SemanticVersion.Parse("2.3"),
        };

        this.WriteVersionFile(workingCopyVersion);
        this.InitializeSourceControl();
        var oracle = VersionOracle.Create(this.RepoPath);

        oracle.PublicRelease = false;
        Assert.Matches(@"^2.3.1-[^g]{10}$", oracle.SemVer1);
        Assert.Matches(@"^2.3.1-[^g]{10}$", oracle.SemVer2);
        Assert.Matches(@"^2.3.1-g[a-f0-9]{10}$", oracle.NuGetPackageVersion);
        Assert.Matches(@"^2.3.1-g[a-f0-9]{10}$", oracle.ChocolateyPackageVersion);
    }
    public void CanSetSemVer2ForNuGetPackageVersionNonPublicRelease()
    {
        VersionOptions workingCopyVersion = new VersionOptions
        {
            Version             = SemanticVersion.Parse("7.8.9-foo.25"),
            NuGetPackageVersion = new VersionOptions.NuGetPackageVersionOptions
            {
                SemVer = 2,
            }
        };

        this.WriteVersionFile(workingCopyVersion);
        this.InitializeSourceControl();
        var oracle = VersionOracle.Create(this.RepoPath);

        oracle.PublicRelease = false;
        Assert.Equal($"7.8.9-foo.25.g{this.CommitIdShort}", oracle.NuGetPackageVersion);
    }
    public void MajorMinorPrereleaseBuildMetadata()
    {
        VersionOptions workingCopyVersion = new VersionOptions
        {
            Version = SemanticVersion.Parse("7.8-beta.3+metadata.4"),
        };

        this.WriteVersionFile(workingCopyVersion);
        this.InitializeSourceControl();
        var oracle = VersionOracle.Create(this.RepoPath);

        Assert.Equal("7.8", oracle.MajorMinorVersion.ToString());
        Assert.Equal(oracle.VersionHeight, oracle.BuildNumber);

        Assert.Equal("-beta.3", oracle.PrereleaseVersion);
        ////Assert.Equal("+metadata.4", oracle.BuildMetadataFragment);

        Assert.Equal(1, oracle.VersionHeight);
        Assert.Equal(0, oracle.VersionHeightOffset);
    }
    public void HeightInPrerelease()
    {
        VersionOptions workingCopyVersion = new VersionOptions
        {
            Version           = SemanticVersion.Parse("7.8.9-beta.{height}.foo"),
            BuildNumberOffset = 2,
        };

        this.WriteVersionFile(workingCopyVersion);
        this.InitializeSourceControl();
        var oracle = VersionOracle.Create(this.RepoPath);

        Assert.Equal("7.8", oracle.MajorMinorVersion.ToString());
        Assert.Equal(9, oracle.BuildNumber);
        Assert.Equal(oracle.VersionHeight + oracle.VersionHeightOffset, oracle.Version.Revision);

        Assert.Equal("-beta." + (oracle.VersionHeight + oracle.VersionHeightOffset) + ".foo", oracle.PrereleaseVersion);

        Assert.Equal(1, oracle.VersionHeight);
        Assert.Equal(2, oracle.VersionHeightOffset);
    }
    public void Worktree_Support()
    {
        var workingCopyVersion = new VersionOptions
        {
            Version = SemanticVersion.Parse("2.3"),
        };

        this.WriteVersionFile(workingCopyVersion);
        this.InitializeSourceControl();
        var oracleOriginal = VersionOracle.Create(this.RepoPath);

        this.AddCommits();

        string workTreePath = this.CreateDirectoryForNewRepo();

        Directory.Delete(workTreePath);
        this.Repo.Worktrees.Add("HEAD~1", "myworktree", workTreePath, isLocked: false);
        var oracleWorkTree = VersionOracle.Create(workTreePath);

        Assert.Equal(oracleOriginal.Version, oracleWorkTree.Version);
    }
    public void CanUseGitProjectRelativePathWithGitRepoRoot()
    {
        VersionOptions rootVersion = new VersionOptions
        {
            Version = SemanticVersion.Parse("1.1"),
        };

        VersionOptions projectVersion = new VersionOptions
        {
            Version = SemanticVersion.Parse("2.2"),
        };

        string childProjectRelativeDir = "ChildProject1";
        string childProjectAbsoluteDir = Path.Combine(this.RepoPath, childProjectRelativeDir);

        this.WriteVersionFile(rootVersion);
        this.WriteVersionFile(projectVersion, childProjectRelativeDir);

        this.InitializeSourceControl();

        // Check Root Version. Root version will be used
        var oracle = VersionOracle.Create(this.RepoPath, this.RepoPath, null, null);

        Assert.Equal("1.1", oracle.MajorMinorVersion.ToString());

        // Check ChildProject with projectRelativeDir, with version file. Child project version will be used.
        oracle = VersionOracle.Create(childProjectAbsoluteDir, this.RepoPath, null, null, childProjectRelativeDir);
        Assert.Equal("2.2", oracle.MajorMinorVersion.ToString());

        // Check ChildProject withOUT projectRelativeDir, with Version file. Child project version will be used.
        oracle = VersionOracle.Create(childProjectAbsoluteDir, this.RepoPath);
        Assert.Equal("2.2", oracle.MajorMinorVersion.ToString());

        // Check ChildProject withOUT Version file. Root version will be used.
        oracle = VersionOracle.Create(Path.Combine(this.RepoPath, "otherChildProject"), this.RepoPath, null, null, "otherChildProject");
        Assert.Equal("1.1", oracle.MajorMinorVersion.ToString());
    }
        public static VersionOracle GitVersioningGetVersion(this ICakeContext context, string projectDirectory = ".")
        {
            var fullProjectDirectory = (new DirectoryInfo(projectDirectory)).FullName;

            string directoryName = Path.GetDirectoryName(Assembly.GetAssembly(typeof(GitVersioningAliases)).Location);

            if (string.IsNullOrWhiteSpace(directoryName))
            {
                throw new InvalidOperationException("Could not locate the Cake.GitVersioning library");
            }

            // Even after adding the folder containing the native libgit2 DLL to the PATH, DllNotFoundException is still thrown
            // Workaround this by copying the contents of the found folder to the current directory
            GitExtensions.HelpFindLibGit2NativeBinaries(directoryName, out var attemptedDirectory);

            // The HelpFindLibGit2NativeBinaries method throws if the directory does not exist
            var directoryInfo = new DirectoryInfo(attemptedDirectory);

            // There should only be a single file in the directory, but we do not know its extension
            // So, we will just get a list of all files rather than trying to determine the correct name and extension
            // If there are other files there for some reason, it should not matter as long as we don't overwrite anything in the current directory
            var fileInfos = directoryInfo.GetFiles();

            foreach (var fileInfo in fileInfos)
            {
                // Copy the file to the Cake.GitVersioning DLL directory, without overwriting anything
                string destFileName = Path.Combine(directoryName, fileInfo.Name);

                if (!File.Exists(destFileName))
                {
                    File.Copy(fileInfo.FullName, destFileName);
                }
            }

            return(VersionOracle.Create(fullProjectDirectory, null, CloudBuild.Active));
        }
        public void GetVersionWithNbgvBenchmark()
        {
            var oracleA = VersionOracle.Create(RepositoryPath);

            this.Version = oracleA.Version.ToString();
        }
        protected override bool ExecuteInner()
        {
            try
            {
                if (!string.IsNullOrEmpty(this.ProjectPathRelativeToGitRepoRoot))
                {
                    Requires.Argument(!Path.IsPathRooted(this.ProjectPathRelativeToGitRepoRoot), nameof(this.ProjectPathRelativeToGitRepoRoot), "Path must be relative.");
                    Requires.Argument(!(
                                          this.ProjectPathRelativeToGitRepoRoot.Contains(".." + Path.DirectorySeparatorChar) ||
                                          this.ProjectPathRelativeToGitRepoRoot.Contains(".." + Path.AltDirectorySeparatorChar)),
                                      nameof(this.ProjectPathRelativeToGitRepoRoot),
                                      "Path must not use ..\\");
                }

                var cloudBuild = CloudBuild.Active;
                var overrideBuildNumberOffset = (this.OverrideBuildNumberOffset == int.MaxValue) ? (int?)null : this.OverrideBuildNumberOffset;
                var oracle = VersionOracle.Create(this.ProjectDirectory, this.GitRepoRoot, cloudBuild, overrideBuildNumberOffset, this.ProjectPathRelativeToGitRepoRoot);
                if (!string.IsNullOrEmpty(this.DefaultPublicRelease))
                {
                    oracle.PublicRelease = string.Equals(this.DefaultPublicRelease, "true", StringComparison.OrdinalIgnoreCase);
                }

                if (this.BuildMetadata != null)
                {
                    oracle.BuildMetadata.AddRange(this.BuildMetadata.Split(';'));
                }

                if (IsMisconfiguredPrereleaseAndSemVer1(oracle))
                {
                    this.Log.LogWarning("The 'nugetPackageVersion' is explicitly set to 'semVer': 1 but the prerelease version '{0}' is not SemVer1 compliant. Change the 'nugetPackageVersion'.'semVer' value to 2 or change the 'version' member to follow SemVer1 rules (e.g.: '{1}').", oracle.PrereleaseVersion, GetSemVer1WithoutPaddingOrBuildMetadata(oracle));
                }

                this.PublicRelease                = oracle.PublicRelease;
                this.BuildingRef                  = oracle.BuildingRef;
                this.Version                      = oracle.Version.ToString();
                this.AssemblyVersion              = oracle.AssemblyVersion.ToString();
                this.AssemblyFileVersion          = oracle.AssemblyFileVersion.ToString();
                this.AssemblyInformationalVersion = oracle.AssemblyInformationalVersion;
                this.SimpleVersion                = oracle.SimpleVersion.ToString();
                this.MajorMinorVersion            = oracle.MajorMinorVersion.ToString();
                this.BuildNumber                  = oracle.BuildNumber;
                this.PrereleaseVersion            = oracle.PrereleaseVersion;
                this.GitCommitId                  = oracle.GitCommitId;
                this.GitCommitIdShort             = oracle.GitCommitIdShort;
                this.GitCommitDateTicks           = oracle.GitCommitDate != null?oracle.GitCommitDate.Value.UtcTicks.ToString(CultureInfo.InvariantCulture) : null;

                this.GitVersionHeight         = oracle.VersionHeight;
                this.BuildMetadataFragment    = oracle.BuildMetadataFragment;
                this.CloudBuildNumber         = oracle.CloudBuildNumberEnabled ? oracle.CloudBuildNumber : null;
                this.NuGetPackageVersion      = oracle.NuGetPackageVersion;
                this.ChocolateyPackageVersion = oracle.ChocolateyPackageVersion;
                this.NpmPackageVersion        = oracle.NpmPackageVersion;

                IEnumerable <ITaskItem> cloudBuildVersionVars = null;
                if (oracle.CloudBuildVersionVarsEnabled)
                {
                    cloudBuildVersionVars = oracle.CloudBuildVersionVars
                                            .Select(item => new TaskItem(item.Key, new Dictionary <string, string> {
                        { "Value", item.Value }
                    }));
                }

                if (oracle.CloudBuildAllVarsEnabled)
                {
                    var allVariables = oracle.CloudBuildAllVars
                                       .Select(item => new TaskItem(item.Key, new Dictionary <string, string> {
                        { "Value", item.Value }
                    }));

                    if (cloudBuildVersionVars != null)
                    {
                        cloudBuildVersionVars = cloudBuildVersionVars
                                                .Union(allVariables);
                    }
                    else
                    {
                        cloudBuildVersionVars = allVariables;
                    }
                }

                if (cloudBuildVersionVars != null)
                {
                    this.CloudBuildVersionVars = cloudBuildVersionVars.ToArray();
                }

                var outputProperties = new Dictionary <string, PropertySet>(StringComparer.OrdinalIgnoreCase)
                {
                    { "BuildVersion", this.Version },
                    { "AssemblyInformationalVersion", this.AssemblyInformationalVersion },
                    { "AssemblyFileVersion", this.AssemblyFileVersion },
                    { "FileVersion", this.AssemblyFileVersion },
                    { "BuildVersionSimple", this.SimpleVersion },
                    { "PrereleaseVersion", this.PrereleaseVersion },
                    { "MajorMinorVersion", this.MajorMinorVersion },
                    { "AssemblyVersion", this.AssemblyVersion },
                    { "GitCommitId", this.GitCommitId },
                    { "GitCommitIdShort", this.GitCommitIdShort },
                    { "GitCommitDateTicks", this.GitCommitDateTicks },
                    { "GitVersionHeight", this.GitVersionHeight.ToString(CultureInfo.InvariantCulture) },
                    { "BuildNumber", this.BuildNumber.ToString(CultureInfo.InvariantCulture) },
                    { "BuildVersionNumberComponent", this.BuildNumber.ToString(CultureInfo.InvariantCulture) },
                    { "PublicRelease", this.PublicRelease.ToString(CultureInfo.InvariantCulture) },
                    { "BuildingRef", this.BuildingRef },
                    { "CloudBuildNumber", new PropertySet(this.CloudBuildNumber)
                      {
                          HonorPresetValue = true
                      } },
                    { "SemVerBuildSuffix", this.BuildMetadataFragment },
                    { "NuGetPackageVersion", this.NuGetPackageVersion },
                    { "ChocolateyPackageVersion", this.ChocolateyPackageVersion },
                    { "Version", this.NuGetPackageVersion },
                    { "PackageVersion", this.NuGetPackageVersion },
                    { "NPMPackageVersion", this.NpmPackageVersion.ToString(CultureInfo.InvariantCulture) },
                    { "BuildVersion3Components", $"{this.MajorMinorVersion}.{this.BuildNumber}" },
                };
                this.OutputProperties = outputProperties.Select(kv =>
                {
                    var item = new TaskItem(kv.Key);
                    item.SetMetadata("Value", kv.Value.Value);
                    item.SetMetadata("HonorPresetValue", kv.Value.HonorPresetValue ? "true" : "false");
                    return(item);
                }).ToArray();

                return(!this.Log.HasLoggedErrors);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                this.Log.LogErrorFromException(ex);
                return(false);
            }
        }
Exemplo n.º 10
0
        private static ExitCodes OnCloudCommand(string projectPath, string version, string cisystem, bool cloudBuildAllVars, bool cloudBuildCommonVars, IReadOnlyList <string> cloudVariables)
        {
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(projectPath);

            if (!Directory.Exists(searchPath))
            {
                Console.Error.WriteLine("\"{0}\" is not an existing directory.", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            ICloudBuild activeCloudBuild = CloudBuild.Active;

            if (!string.IsNullOrEmpty(cisystem))
            {
                int matchingIndex = Array.FindIndex(CloudProviderNames, m => string.Equals(m, cisystem, StringComparison.OrdinalIgnoreCase));
                if (matchingIndex == -1)
                {
                    Console.Error.WriteLine("No cloud provider found by the name: \"{0}\"", cisystem);
                    return(ExitCodes.NoCloudBuildProviderMatch);
                }

                activeCloudBuild = CloudBuild.SupportedCloudBuilds[matchingIndex];
            }

            var oracle    = VersionOracle.Create(searchPath, cloudBuild: activeCloudBuild);
            var variables = new Dictionary <string, string>();

            if (cloudBuildAllVars)
            {
                foreach (var pair in oracle.CloudBuildAllVars)
                {
                    variables.Add(pair.Key, pair.Value);
                }
            }

            if (cloudBuildCommonVars)
            {
                foreach (var pair in oracle.CloudBuildVersionVars)
                {
                    variables.Add(pair.Key, pair.Value);
                }
            }

            foreach (string def in cloudVariables)
            {
                string[] split = def.Split(new char[] { '=' }, 2);
                if (split.Length < 2)
                {
                    Console.Error.WriteLine($"\"{def}\" is not in the NAME=VALUE syntax required for cloud variables.");
                    return(ExitCodes.BadCloudVariable);
                }

                if (variables.ContainsKey(split[0]))
                {
                    Console.Error.WriteLine($"Cloud build variable \"{split[0]}\" specified more than once.");
                    return(ExitCodes.DuplicateCloudVariable);
                }

                variables[split[0]] = split[1];
            }

            if (activeCloudBuild != null)
            {
                if (string.IsNullOrEmpty(version))
                {
                    version = oracle.CloudBuildNumber;
                }

                activeCloudBuild.SetCloudBuildNumber(version, Console.Out, Console.Error);

                foreach (var pair in variables)
                {
                    activeCloudBuild.SetCloudBuildVariable(pair.Key, pair.Value, Console.Out, Console.Error);
                }

                return(ExitCodes.OK);
            }
            else
            {
                Console.Error.WriteLine("No cloud build detected.");
                return(ExitCodes.NoCloudBuildEnvDetected);
            }
        }
        protected override bool ExecuteInner()
        {
            try
            {
                if (!string.IsNullOrEmpty(this.ProjectPathRelativeToGitRepoRoot))
                {
                    Requires.Argument(!Path.IsPathRooted(this.ProjectPathRelativeToGitRepoRoot), nameof(this.ProjectPathRelativeToGitRepoRoot), "Path must be relative.");
                    Requires.Argument(!(
                                          this.ProjectPathRelativeToGitRepoRoot.Contains(".." + Path.DirectorySeparatorChar) ||
                                          this.ProjectPathRelativeToGitRepoRoot.Contains(".." + Path.AltDirectorySeparatorChar)),
                                      nameof(this.ProjectPathRelativeToGitRepoRoot),
                                      "Path must not use ..\\");
                }

                var cloudBuild = CloudBuild.Active;
                var overrideBuildNumberOffset = (this.OverrideBuildNumberOffset == int.MaxValue) ? (int?)null : this.OverrideBuildNumberOffset;
                var oracle = VersionOracle.Create(Directory.GetCurrentDirectory(), this.GitRepoRoot, cloudBuild, overrideBuildNumberOffset, this.ProjectPathRelativeToGitRepoRoot);
                if (!string.IsNullOrEmpty(this.DefaultPublicRelease))
                {
                    oracle.PublicRelease = string.Equals(this.DefaultPublicRelease, "true", StringComparison.OrdinalIgnoreCase);
                }

                if (this.BuildMetadata != null)
                {
                    oracle.BuildMetadata.AddRange(this.BuildMetadata);
                }

                this.PublicRelease                = oracle.PublicRelease;
                this.Version                      = oracle.Version.ToString();
                this.AssemblyVersion              = oracle.AssemblyVersion.ToString();
                this.AssemblyFileVersion          = oracle.AssemblyFileVersion.ToString();
                this.AssemblyInformationalVersion = oracle.AssemblyInformationalVersion;
                this.SimpleVersion                = oracle.SimpleVersion.ToString();
                this.MajorMinorVersion            = oracle.MajorMinorVersion.ToString();
                this.BuildNumber                  = oracle.BuildNumber;
                this.PrereleaseVersion            = oracle.PrereleaseVersion;
                this.GitCommitId                  = oracle.GitCommitId;
                this.GitCommitIdShort             = oracle.GitCommitIdShort;
                this.GitVersionHeight             = oracle.VersionHeight;
                this.BuildMetadataFragment        = oracle.BuildMetadataFragment;
                this.CloudBuildNumber             = oracle.CloudBuildNumberEnabled ? oracle.CloudBuildNumber : null;
                this.NuGetPackageVersion          = oracle.NuGetPackageVersion;
                this.NpmPackageVersion            = oracle.NpmPackageVersion;

                IEnumerable <ITaskItem> cloudBuildVersionVars = null;
                if (oracle.CloudBuildVersionVarsEnabled)
                {
                    cloudBuildVersionVars = oracle.CloudBuildVersionVars
                                            .Select(item => new TaskItem(item.Key, new Dictionary <string, string> {
                        { "Value", item.Value }
                    }));
                }

                if (oracle.CloudBuildAllVarsEnabled)
                {
                    var allVariables = oracle.CloudBuildAllVars
                                       .Select(item => new TaskItem(item.Key, new Dictionary <string, string> {
                        { "Value", item.Value }
                    }));

                    if (cloudBuildVersionVars != null)
                    {
                        cloudBuildVersionVars = cloudBuildVersionVars
                                                .Union(allVariables);
                    }
                    else
                    {
                        cloudBuildVersionVars = allVariables;
                    }
                }

                if (cloudBuildVersionVars != null)
                {
                    this.CloudBuildVersionVars = cloudBuildVersionVars.ToArray();
                }

                return(!this.Log.HasLoggedErrors);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                this.Log.LogErrorFromException(ex);
                return(false);
            }
        }
        public void GetversionLibGit2()
        {
            var oracleA = VersionOracle.Create(RepositoryPath, Path.GetDirectoryName(VersionPath));

            this.Version = oracleA.Version.ToString();
        }