Пример #1
0
    public void GetIdAsVersion_VersionFileNeverCheckedIn_3Ints()
    {
        this.AddCommits();
        var     expectedVersion     = new Version(1, 1, 0);
        var     unstagedVersionData = VersionOptions.FromVersion(expectedVersion);
        string  versionFilePath     = VersionFile.SetVersion(this.RepoPath, unstagedVersionData);
        Version actualVersion       = this.Repo.GetIdAsVersion();

        Assert.Equal(expectedVersion.Major, actualVersion.Major);
        Assert.Equal(expectedVersion.Minor, actualVersion.Minor);
        Assert.Equal(expectedVersion.Build, actualVersion.Build);

        // Height is expressed in the 4th integer since 3 were specified in version.json.
        // height is 0 since the change hasn't been committed.
        Assert.Equal(0, actualVersion.Revision);
    }
    public void SetVersion_WritesSimplestFile(string version, string assemblyVersion, VersionOptions.VersionPrecision precision, int buildNumberOffset, string expectedJson)
    {
        var versionOptions = new VersionOptions
        {
            Version           = SemanticVersion.Parse(version),
            AssemblyVersion   = new VersionOptions.AssemblyVersionOptions(assemblyVersion != null ? new Version(assemblyVersion) : null, precision),
            BuildNumberOffset = buildNumberOffset,
        };
        string pathWritten       = VersionFile.SetVersion(this.RepoPath, versionOptions);
        string actualFileContent = File.ReadAllText(pathWritten);

        this.Logger.WriteLine(actualFileContent);

        string normalizedFileContent = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(actualFileContent));

        Assert.Equal(expectedJson, normalizedFileContent);
    }
Пример #3
0
        private static ExitCodes OnSetVersionCommand(string projectPath, string version)
        {
            if (!SemanticVersion.TryParse(string.IsNullOrEmpty(version) ? DefaultVersionSpec : version, out var semver))
            {
                Console.Error.WriteLine($"\"{version}\" is not a semver-compliant version spec.");
                return(ExitCodes.InvalidVersionSpec);
            }

            var defaultOptions = new VersionOptions
            {
                Version = semver,
            };

            string searchPath      = GetSpecifiedOrCurrentDirectoryPath(projectPath);
            var    repository      = GitExtensions.OpenGitRepo(searchPath);
            var    existingOptions = VersionFile.GetVersion(searchPath, out string actualDirectory);
            string versionJsonPath;

            if (existingOptions != null)
            {
                existingOptions.Version = semver;
                versionJsonPath         = VersionFile.SetVersion(actualDirectory, existingOptions);
            }
            else if (string.IsNullOrEmpty(projectPath))
            {
                if (repository == null)
                {
                    Console.Error.WriteLine("No version file and no git repo found at or above: \"{0}\"", searchPath);
                    return(ExitCodes.NoGitRepo);
                }

                versionJsonPath = VersionFile.SetVersion(repository.Info.WorkingDirectory, defaultOptions);
            }
            else
            {
                versionJsonPath = VersionFile.SetVersion(projectPath, defaultOptions);
            }

            if (repository != null)
            {
                LibGit2Sharp.Commands.Stage(repository, versionJsonPath);
            }

            return(ExitCodes.OK);
        }
    public void SetVersion_WritesSimplestFile(string version, string assemblyVersion, VersionOptions.VersionPrecision?precision, int?versionHeightOffset, bool inherit, string expectedJson)
    {
        var versionOptions = new VersionOptions
        {
            Version             = SemanticVersion.Parse(version),
            AssemblyVersion     = assemblyVersion != null || precision != null ? new VersionOptions.AssemblyVersionOptions(assemblyVersion != null ? new Version(assemblyVersion) : null, precision) : null,
            VersionHeightOffset = versionHeightOffset,
            Inherit             = inherit,
        };
        string pathWritten       = VersionFile.SetVersion(this.RepoPath, versionOptions, includeSchemaProperty: false);
        string actualFileContent = File.ReadAllText(pathWritten);

        this.Logger.WriteLine(actualFileContent);

        string normalizedFileContent = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(actualFileContent));

        Assert.Equal(expectedJson, normalizedFileContent);
    }
    public void SetVersion_GetVersionFromFile(string expectedVersion, string expectedPrerelease)
    {
        string pathWritten = VersionFile.SetVersion(this.RepoPath, new Version(expectedVersion), expectedPrerelease);

        Assert.Equal(Path.Combine(this.RepoPath, VersionFile.FileName), pathWritten);

        string[] actualFileContent = File.ReadAllLines(this.versionTxtPath);
        this.Logger.WriteLine(string.Join(Environment.NewLine, actualFileContent));

        Assert.Equal(2, actualFileContent.Length);
        Assert.Equal(expectedVersion, actualFileContent[0]);
        Assert.Equal(expectedPrerelease ?? string.Empty, actualFileContent[1]);

        SemanticVersion actualVersion = VersionFile.GetVersion(this.RepoPath);

        Assert.Equal(new Version(expectedVersion), actualVersion.Version);
        Assert.Equal(expectedPrerelease ?? string.Empty, actualVersion.UnstableTag);
    }
    public void IsVersionDefined_String_ConsiderAncestorFolders()
    {
        // Construct a repo where versions are defined like this:

        /*   root <- 1.0
         *      a             (inherits 1.0)
         *          b <- 1.1
         *               c    (inherits 1.1)
         */
        VersionFile.SetVersion(this.RepoPath, new Version(1, 0));
        string subDirA   = Path.Combine(this.RepoPath, "a");
        string subDirAB  = Path.Combine(subDirA, "b");
        string subDirABC = Path.Combine(subDirAB, "c");

        Directory.CreateDirectory(subDirABC);
        VersionFile.SetVersion(subDirAB, new Version(1, 1));

        Assert.True(VersionFile.IsVersionDefined(subDirABC));
        Assert.True(VersionFile.IsVersionDefined(subDirAB));
        Assert.True(VersionFile.IsVersionDefined(subDirA));
        Assert.True(VersionFile.IsVersionDefined(this.RepoPath));
    }
    public void SetVersion_PathFilters_InheritOverride()
    {
        this.InitializeSourceControl();

        var rootVersionOptions = new VersionOptions
        {
            Version     = SemanticVersion.Parse("1.2"),
            PathFilters = new []
            {
                new FilterPath("./root-file.txt", ""),
                new FilterPath("/absolute", ""),
            }
        };

        VersionFile.SetVersion(this.RepoPath, rootVersionOptions);

        var versionOptions = new VersionOptions
        {
            Version     = SemanticVersion.Parse("1.2"),
            Inherit     = true,
            PathFilters = new []
            {
                new FilterPath("./project-file.txt", "quux"),
                new FilterPath("/absolute", "quux"),
            }
        };
        var projectDirectory = Path.Combine(this.RepoPath, "quux");

        VersionFile.SetVersion(projectDirectory, versionOptions);

        var expected = versionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        var actualVersionOptions = VersionFile.GetVersion(projectDirectory);
        var actual = actualVersionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        Assert.Equal(expected, actual);
    }
    public void SetVersion_PathFilters_DifferentRelativePaths()
    {
        this.InitializeSourceControl();

        var versionOptions = new VersionOptions
        {
            Version     = SemanticVersion.Parse("1.2"),
            PathFilters = new []
            {
                new FilterPath("./foo", "bar"),
                new FilterPath("/absolute", "bar"),
            }
        };
        var expected = versionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        var projectDirectory = Path.Combine(this.RepoPath, "quux");

        VersionFile.SetVersion(projectDirectory, versionOptions);

        var actualVersionOptions = VersionFile.GetVersion(projectDirectory);
        var actual = actualVersionOptions.PathFilters.Select(x => x.RepoRelativePath).ToList();

        Assert.Equal(expected, actual);
    }
    public void GetVersion_String_FindsNearestFileInAncestorDirectories()
    {
        // Construct a repo where versions are defined like this:

        /*   root <- 1.0
         *      a             (inherits 1.0)
         *          b <- 1.1
         *               c    (inherits 1.1)
         */
        VersionFile.SetVersion(this.RepoPath, new Version(1, 0));
        string subDirA   = Path.Combine(this.RepoPath, "a");
        string subDirAB  = Path.Combine(subDirA, "b");
        string subDirABC = Path.Combine(subDirAB, "c");

        Directory.CreateDirectory(subDirABC);
        VersionFile.SetVersion(subDirAB, new Version(1, 1));
        this.InitializeSourceControl();
        var commit = this.Repo.Head.Commits.First();

        AssertPathHasVersion(commit, subDirABC, new Version(1, 1));
        AssertPathHasVersion(commit, subDirAB, new Version(1, 1));
        AssertPathHasVersion(commit, subDirA, new Version(1, 0));
        AssertPathHasVersion(commit, this.RepoPath, new Version(1, 0));
    }
Пример #10
0
        private static ExitCodes OnInstallCommand(string versionJsonRoot, string version)
        {
            if (!SemanticVersion.TryParse(string.IsNullOrEmpty(version) ? DefaultVersionSpec : version, out var semver))
            {
                Console.Error.WriteLine($"\"{version}\" is not a semver-compliant version spec.");
                return(ExitCodes.InvalidVersionSpec);
            }

            var options = new VersionOptions
            {
                Version = semver,
                PublicReleaseRefSpec = new string[]
                {
                    @"^refs/heads/master$",
                    @"^refs/heads/v\d+(?:\.\d+)?$",
                },
                CloudBuild = new VersionOptions.CloudBuildOptions
                {
                    BuildNumber = new VersionOptions.CloudBuildNumberOptions
                    {
                        Enabled = true,
                    },
                },
            };
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(versionJsonRoot);

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

            var repository = GitExtensions.OpenGitRepo(searchPath);

            if (repository == null)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            if (string.IsNullOrEmpty(versionJsonRoot))
            {
                versionJsonRoot = repository.Info.WorkingDirectory;
            }

            var existingOptions = VersionFile.GetVersion(versionJsonRoot);

            if (existingOptions != null)
            {
                if (!string.IsNullOrEmpty(version))
                {
                    var setVersionExitCode = OnSetVersionCommand(versionJsonRoot, version);
                    if (setVersionExitCode != ExitCodes.OK)
                    {
                        return(setVersionExitCode);
                    }
                }
            }
            else
            {
                string versionJsonPath = VersionFile.SetVersion(versionJsonRoot, options);
                LibGit2Sharp.Commands.Stage(repository, versionJsonPath);
            }

            // Create/update the Directory.Build.props file in the directory of the version.json file to add the NB.GV package.
            string directoryBuildPropsPath = Path.Combine(versionJsonRoot, "Directory.Build.props");

            MSBuild.Project propsFile;
            if (File.Exists(directoryBuildPropsPath))
            {
                propsFile = new MSBuild.Project(directoryBuildPropsPath);
            }
            else
            {
                propsFile = new MSBuild.Project();
            }

            const string PackageReferenceItemType = "PackageReference";
            const string PackageId = "Nerdbank.GitVersioning";

            if (!propsFile.GetItemsByEvaluatedInclude(PackageId).Any(i => i.ItemType == "PackageReference"))
            {
                string packageVersion = GetLatestPackageVersionAsync(PackageId).GetAwaiter().GetResult();
                propsFile.AddItem(
                    PackageReferenceItemType,
                    PackageId,
                    new Dictionary <string, string>
                {
                    { "Version", packageVersion },     // TODO: use the latest version... somehow...
                    { "PrivateAssets", "all" },
                });

                propsFile.Save(directoryBuildPropsPath);
            }

            LibGit2Sharp.Commands.Stage(repository, directoryBuildPropsPath);

            return(ExitCodes.OK);
        }
Пример #11
0
        private static ExitCodes OnInstallCommand(string versionJsonRoot, string version, IReadOnlyList <string> sources)
        {
            if (!SemanticVersion.TryParse(string.IsNullOrEmpty(version) ? DefaultVersionSpec : version, out var semver))
            {
                Console.Error.WriteLine($"\"{version}\" is not a semver-compliant version spec.");
                return(ExitCodes.InvalidVersionSpec);
            }

            var options = new VersionOptions
            {
                Version = semver,
                PublicReleaseRefSpec = new string[]
                {
                    @"^refs/heads/master$",
                    @"^refs/heads/v\d+(?:\.\d+)?$",
                },
                CloudBuild = new VersionOptions.CloudBuildOptions
                {
                    BuildNumber = new VersionOptions.CloudBuildNumberOptions
                    {
                        Enabled = true,
                    },
                },
            };
            string searchPath = GetSpecifiedOrCurrentDirectoryPath(versionJsonRoot);

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

            var repository = GitExtensions.OpenGitRepo(searchPath);

            if (repository == null)
            {
                Console.Error.WriteLine("No git repo found at or above: \"{0}\"", searchPath);
                return(ExitCodes.NoGitRepo);
            }

            if (string.IsNullOrEmpty(versionJsonRoot))
            {
                versionJsonRoot = repository.Info.WorkingDirectory;
            }

            var existingOptions = VersionFile.GetVersion(versionJsonRoot);

            if (existingOptions != null)
            {
                if (!string.IsNullOrEmpty(version))
                {
                    var setVersionExitCode = OnSetVersionCommand(versionJsonRoot, version);
                    if (setVersionExitCode != ExitCodes.OK)
                    {
                        return(setVersionExitCode);
                    }
                }
            }
            else
            {
                string versionJsonPath = VersionFile.SetVersion(versionJsonRoot, options);
                LibGit2Sharp.Commands.Stage(repository, versionJsonPath);
            }

            // Create/update the Directory.Build.props file in the directory of the version.json file to add the NB.GV package.
            string directoryBuildPropsPath = Path.Combine(versionJsonRoot, "Directory.Build.props");

            MSBuild.Project propsFile;
            if (File.Exists(directoryBuildPropsPath))
            {
                propsFile = new MSBuild.Project(directoryBuildPropsPath);
            }
            else
            {
                propsFile = new MSBuild.Project();
            }

            const string PackageReferenceItemType = "PackageReference";

            if (!propsFile.GetItemsByEvaluatedInclude(PackageId).Any(i => i.ItemType == "PackageReference"))
            {
                // Validate given sources
                foreach (var source in sources)
                {
                    if (!Uri.TryCreate(source, UriKind.Absolute, out var _))
                    {
                        Console.Error.WriteLine($"\"{source}\" is not a valid NuGet package source.");
                        return(ExitCodes.InvalidNuGetPackageSource);
                    }
                }

                string packageVersion = GetLatestPackageVersionAsync(PackageId, versionJsonRoot, sources).GetAwaiter().GetResult();
                if (string.IsNullOrEmpty(packageVersion))
                {
                    string verifyPhrase = sources.Any()
                        ? "Please verify the given 'source' option(s)."
                        : "Please verify the package sources in the NuGet.Config files.";
                    Console.Error.WriteLine($"Latest stable version of the {PackageId} package could not be determined. " + verifyPhrase);
                    return(ExitCodes.PackageIdNotFound);
                }

                propsFile.AddItem(
                    PackageReferenceItemType,
                    PackageId,
                    new Dictionary <string, string>
                {
                    { "Version", packageVersion },
                    { "PrivateAssets", "all" },
                });

                propsFile.Save(directoryBuildPropsPath);
            }

            LibGit2Sharp.Commands.Stage(repository, directoryBuildPropsPath);

            return(ExitCodes.OK);
        }