From 2c48e7eb24990d85dc3fa35a7f262c76a97fa9ce Mon Sep 17 00:00:00 2001 From: Adam Ralph Date: Tue, 13 Aug 2019 19:01:17 +0100 Subject: [PATCH] switch from LibGit2Sharp to Git --- .github/workflows/ci.yml | 2 +- MinVer.Lib/Commit.cs | 15 +++++ MinVer.Lib/DictionaryExtensions.cs | 18 +++++ MinVer.Lib/Git.cs | 42 ++++++++++++ MinVer.Lib/GitCommand.cs | 57 ++++++++++++++++ MinVer.Lib/MinVer.Lib.csproj | 1 - ...{RepositoryExtensions.cs => Repository.cs} | 65 +++++++++++++------ MinVer.Lib/RepositoryEx.cs | 28 -------- MinVer.Lib/Tag.cs | 15 +++++ MinVer.Lib/Versioner.cs | 18 ++--- MinVer/Logger.cs | 15 ++++- MinVerTests/Versioning.cs | 17 ----- README.md | 15 ++--- minver-cli/Logger.cs | 15 ++++- minver-cli/Program.cs | 16 ++--- targets/Program.cs | 8 +-- 16 files changed, 240 insertions(+), 107 deletions(-) create mode 100644 MinVer.Lib/Commit.cs create mode 100644 MinVer.Lib/DictionaryExtensions.cs create mode 100644 MinVer.Lib/Git.cs create mode 100644 MinVer.Lib/GitCommand.cs rename MinVer.Lib/{RepositoryExtensions.cs => Repository.cs} (73%) delete mode 100644 MinVer.Lib/RepositoryEx.cs create mode 100644 MinVer.Lib/Tag.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d286458..46ae1cdd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ jobs: strategy: fail-fast: false matrix: - runs-on: [macOS-10.14, ubuntu-18.04, windows-2019] + runs-on: [macOS-10.14, ubuntu-16.04, ubuntu-18.04, windows-2016, windows-2019] name: ${{ matrix.runs-on }} runs-on: ${{ matrix.runs-on }} steps: diff --git a/MinVer.Lib/Commit.cs b/MinVer.Lib/Commit.cs new file mode 100644 index 00000000..737729d6 --- /dev/null +++ b/MinVer.Lib/Commit.cs @@ -0,0 +1,15 @@ +namespace MinVer.Lib +{ + using System.Collections.Generic; + + internal class Commit + { + public Commit(string sha) => this.Sha = sha; + + public string Sha { get; } + + public string ShortSha => this.Sha.Substring(0, 7); + + public List Parents { get; } = new List(); + } +} diff --git a/MinVer.Lib/DictionaryExtensions.cs b/MinVer.Lib/DictionaryExtensions.cs new file mode 100644 index 00000000..ce72188d --- /dev/null +++ b/MinVer.Lib/DictionaryExtensions.cs @@ -0,0 +1,18 @@ +namespace MinVer.Lib +{ + using System; + using System.Collections.Generic; + + internal static class DictionaryExtensions + { + public static TValue GetOrAdd(this Dictionary dictionary, TKey key, Func valueFactory) + { + if (!dictionary.TryGetValue(key, out var value)) + { + dictionary.Add(key, value = valueFactory()); + } + + return value; + } + } +} diff --git a/MinVer.Lib/Git.cs b/MinVer.Lib/Git.cs new file mode 100644 index 00000000..9a1ca025 --- /dev/null +++ b/MinVer.Lib/Git.cs @@ -0,0 +1,42 @@ +namespace MinVer.Lib +{ + using System; + using System.Collections.Generic; + using System.Linq; + + internal static class Git + { + public static bool IsWorkingDirectory(string directory, ILogger log) => GitCommand.TryRun("status --short", directory, log, out _); + + public static Commit GetHeadOrDefault(string directory, ILogger log) + { + if (!GitCommand.TryRun("log --pretty=format:\"%H %P\"", directory, log, out var output)) + { + return null; + } + + var commits = new Dictionary(); + + foreach (var shas in output + .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries))) + { + commits.GetOrAdd(shas[0], () => new Commit(shas[0])) + .Parents.AddRange(shas.Skip(1).Select(parentSha => commits.GetOrAdd(parentSha, () => new Commit(parentSha)))); + } + + return commits.Values.FirstOrDefault(); + } + + public static IEnumerable GetTagsOrEmpty(string directory, ILogger log) => + GitCommand.TryRun("show-ref --tags --dereference", directory, log, out var output) + ? output + .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Split(new[] { ' ' }, 2)) + .Select(tokens => new Tag(tokens[1].Substring(10).RemoveFromEnd("^{}"), tokens[0])) + : Enumerable.Empty(); + + private static string RemoveFromEnd(this string text, string value) => + text.EndsWith(value) ? text.Substring(0, text.Length - value.Length) : text; + } +} diff --git a/MinVer.Lib/GitCommand.cs b/MinVer.Lib/GitCommand.cs new file mode 100644 index 00000000..b1384b60 --- /dev/null +++ b/MinVer.Lib/GitCommand.cs @@ -0,0 +1,57 @@ +namespace MinVer.Lib +{ + using System; + using System.ComponentModel; + using System.Diagnostics; + using System.Threading.Tasks; + + internal static class GitCommand + { + public static bool TryRun(string args, string workingDirectory, ILogger log, out string output) + { + using (var process = new Process()) + { + process.StartInfo = new ProcessStartInfo + { + FileName = "git", + Arguments = args, + WorkingDirectory = workingDirectory, + UseShellExecute = false, + RedirectStandardError = true, + RedirectStandardOutput = true, + }; + + var tcs = new TaskCompletionSource(); + process.Exited += (s, e) => tcs.SetResult(default); + process.EnableRaisingEvents = true; + + log.Trace($"Running Git: {process.StartInfo.FileName} {process.StartInfo.Arguments}"); + + try + { + process.Start(); + } + catch (Win32Exception ex) + { + throw new Exception("Failed to run Git. Git may not be installed on the system.", ex); + } + + var runProcess = tcs.Task; + var readOutput = process.StandardOutput.ReadToEndAsync(); + var readError = process.StandardError.ReadToEndAsync(); + + Task.WaitAll(runProcess, readOutput, readError); + + var exitCode = process.ExitCode; + output = readOutput.Result; + var error = readError.Result; + + log.Trace($"Git exit code: {exitCode}"); + log.Trace($"Git stdout:{Environment.NewLine}{output}"); + log.Trace($"Git stderr:{Environment.NewLine}{error}"); + + return exitCode == 0; + } + } + } +} diff --git a/MinVer.Lib/MinVer.Lib.csproj b/MinVer.Lib/MinVer.Lib.csproj index 92039ccb..3acc29e5 100644 --- a/MinVer.Lib/MinVer.Lib.csproj +++ b/MinVer.Lib/MinVer.Lib.csproj @@ -6,7 +6,6 @@ - diff --git a/MinVer.Lib/RepositoryExtensions.cs b/MinVer.Lib/Repository.cs similarity index 73% rename from MinVer.Lib/RepositoryExtensions.cs rename to MinVer.Lib/Repository.cs index 163ed37b..8fbd6940 100644 --- a/MinVer.Lib/RepositoryExtensions.cs +++ b/MinVer.Lib/Repository.cs @@ -2,13 +2,38 @@ namespace MinVer.Lib { using System.Collections.Generic; using System.Linq; - using LibGit2Sharp; - internal static class RepositoryExtensions + internal class Repository { - public static Version GetVersion(this Repository repo, string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log) + private readonly Commit head; + private readonly IEnumerable tags; + + private Repository(Commit head, IEnumerable tags) + { + this.head = head; + this.tags = tags; + } + + public static bool TryCreateRepo(string workDir, out Repository repository, ILogger log) + { + repository = null; + + if (!Git.IsWorkingDirectory(workDir, log)) + { + return false; + } + + var head = Git.GetHeadOrDefault(workDir, log); + var tags = head != null ? Git.GetTagsOrEmpty(workDir, log) : Enumerable.Empty(); + + repository = new Repository(head, tags); + + return true; + } + + public Version GetVersion(string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log) { - var commit = repo.Commits.FirstOrDefault(); + var commit = this.head; if (commit == null) { @@ -19,10 +44,10 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version return version; } - var tagsAndVersions = repo.Tags - .Select(tag => (tag, Version.ParseOrDefault(tag.FriendlyName, tagPrefix))) + var tagsAndVersions = this.tags + .Select(tag => (tag, Version.ParseOrDefault(tag.Name, tagPrefix))) .OrderBy(tagAndVersion => tagAndVersion.Item2) - .ThenBy(tagsAndVersion => tagsAndVersion.tag.FriendlyName) + .ThenBy(tagsAndVersion => tagsAndVersion.tag.Name) .ToList(); var commitsChecked = new HashSet(); @@ -34,7 +59,7 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version if (log.IsTraceEnabled) { - log.Trace($"Starting at commit {commit.ShortSha()} (height {height})..."); + log.Trace($"Starting at commit {commit.ShortSha} (height {height})..."); } while (true) @@ -45,12 +70,12 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version { ++count; - var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Target.Sha == commit.Sha).ToList(); + var commitTagsAndVersions = tagsAndVersions.Where(tagAndVersion => tagAndVersion.tag.Sha == commit.Sha).ToList(); var foundVersion = false; foreach (var (tag, commitVersion) in commitTagsAndVersions) { - var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.FriendlyName, Version = commitVersion, }; + var candidate = new Candidate { Commit = commit, Height = height, Tag = tag.Name, Version = commitVersion, }; foundVersion = foundVersion || candidate.Version != null; @@ -77,11 +102,11 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version firstParent = parent; break; case 1: - log.Trace($"History diverges from {commit.ShortSha()} (height {height}) to:"); - log.Trace($"- {firstParent.ShortSha()} (height {height + 1})"); + log.Trace($"History diverges from {commit.ShortSha} (height {height}) to:"); + log.Trace($"- {firstParent.ShortSha} (height {height + 1})"); goto default; default: - log.Trace($"- {parent.ShortSha()} (height {height + 1})"); + log.Trace($"- {parent.ShortSha} (height {height + 1})"); break; } @@ -90,7 +115,7 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version } } - foreach (var parent in commit.Parents.Reverse()) + foreach (var parent in ((IEnumerable)commit.Parents).Reverse()) { commitsToCheck.Push((parent, height + 1, commit)); } @@ -112,7 +137,7 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version { if (log.IsTraceEnabled) { - log.Trace($"History converges from {previousCommit.ShortSha()} (height {height - 1}) back to previously seen commit {commit.ShortSha()} (height {height}). Abandoning path."); + log.Trace($"History converges from {previousCommit.ShortSha} (height {height - 1}) back to previously seen commit {commit.ShortSha} (height {height}). Abandoning path."); } } @@ -134,17 +159,17 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version { if (parentCount > 1) { - log.Trace($"Following path from {child.ShortSha()} (height {height - 1}) through first parent {commit.ShortSha()} (height {height})..."); + log.Trace($"Following path from {child.ShortSha} (height {height - 1}) through first parent {commit.ShortSha} (height {height})..."); } else if (height <= oldHeight) { if (commitsToCheck.Any() && commitsToCheck.Peek().Item2 == height) { - log.Trace($"Backtracking to {child.ShortSha()} (height {height - 1}) and following path through next parent {commit.ShortSha()} (height {height})..."); + log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through next parent {commit.ShortSha} (height {height})..."); } else { - log.Trace($"Backtracking to {child.ShortSha()} (height {height - 1}) and following path through last parent {commit.ShortSha()} (height {height})..."); + log.Trace($"Backtracking to {child.ShortSha} (height {height - 1}) and following path through last parent {commit.ShortSha} (height {height})..."); } } } @@ -178,8 +203,6 @@ public static Version GetVersion(this Repository repo, string tagPrefix, Version return selectedCandidate.Version.WithHeight(selectedCandidate.Height, autoIncrement, defaultPreReleasePhase); } - private static string ShortSha(this Commit commit) => commit.Sha.Substring(0, 7); - private class Candidate { public Commit Commit { get; set; } @@ -193,7 +216,7 @@ private class Candidate public override string ToString() => this.ToString(0, 0, 0); public string ToString(int tagWidth, int versionWidth, int heightWidth) => - $"{{ {nameof(this.Commit)}: {this.Commit.ShortSha()}, {nameof(this.Tag)}: {$"{(this.Tag == null ? "null" : $"'{this.Tag}'")},".PadRight(tagWidth + 3)} {nameof(this.Version)}: {$"{this.Version?.ToString() ?? "null"},".PadRight(versionWidth + 1)} {nameof(this.Height)}: {this.Height.ToString().PadLeft(heightWidth)} }}"; + $"{{ {nameof(this.Commit)}: {this.Commit.ShortSha}, {nameof(this.Tag)}: {$"{(this.Tag == null ? "null" : $"'{this.Tag}'")},".PadRight(tagWidth + 3)} {nameof(this.Version)}: {$"{this.Version?.ToString() ?? "null"},".PadRight(versionWidth + 1)} {nameof(this.Height)}: {this.Height.ToString().PadLeft(heightWidth)} }}"; } } } diff --git a/MinVer.Lib/RepositoryEx.cs b/MinVer.Lib/RepositoryEx.cs deleted file mode 100644 index 1ae98985..00000000 --- a/MinVer.Lib/RepositoryEx.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace MinVer.Lib -{ - using System.IO; - using LibGit2Sharp; - - internal static class RepositoryEx - { - public static bool TryCreateRepo(string repoOrWorkDir, out Repository repository) - { - repository = null; - - while (repoOrWorkDir != null) - { - try - { - repository = new Repository(repoOrWorkDir); - return true; - } - catch (RepositoryNotFoundException) - { - repoOrWorkDir = Directory.GetParent(repoOrWorkDir)?.FullName; - } - } - - return false; - } - } -} diff --git a/MinVer.Lib/Tag.cs b/MinVer.Lib/Tag.cs new file mode 100644 index 00000000..f1d4de3c --- /dev/null +++ b/MinVer.Lib/Tag.cs @@ -0,0 +1,15 @@ +namespace MinVer.Lib +{ + internal class Tag + { + public Tag(string name, string sha) + { + this.Name = name; + this.Sha = sha; + } + + public string Name { get; } + + public string Sha { get; } + } +} diff --git a/MinVer.Lib/Versioner.cs b/MinVer.Lib/Versioner.cs index 9ddbf6a4..a8aa1532 100644 --- a/MinVer.Lib/Versioner.cs +++ b/MinVer.Lib/Versioner.cs @@ -2,7 +2,7 @@ namespace MinVer.Lib { public static class Versioner { - public static Version GetVersion(string repoOrWorkDir, string tagPrefix, MajorMinor minMajorMinor, string buildMeta, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log) + public static Version GetVersion(string workDir, string tagPrefix, MajorMinor minMajorMinor, string buildMeta, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log) { log = log ?? new NullLogger(); @@ -10,7 +10,7 @@ public static Version GetVersion(string repoOrWorkDir, string tagPrefix, MajorMi ? "alpha" : defaultPreReleasePhase; - var version = GetVersion(repoOrWorkDir, tagPrefix, autoIncrement, defaultPreReleasePhase, log).AddBuildMetadata(buildMeta); + var version = GetVersion(workDir, tagPrefix, autoIncrement, defaultPreReleasePhase, log).AddBuildMetadata(buildMeta); var calculatedVersion = version.Satisfying(minMajorMinor, defaultPreReleasePhase); @@ -31,23 +31,19 @@ public static Version GetVersion(string repoOrWorkDir, string tagPrefix, MajorMi return calculatedVersion; } - private static Version GetVersion(string repoOrWorkDir, string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log) + private static Version GetVersion(string workDir, string tagPrefix, VersionPart autoIncrement, string defaultPreReleasePhase, ILogger log) { -#pragma warning disable IDE0068 // Use recommended dispose pattern - if (!RepositoryEx.TryCreateRepo(repoOrWorkDir, out var repo)) -#pragma warning restore IDE0068 // Use recommended dispose pattern + if (!Repository.TryCreateRepo(workDir, out var repo, log)) + { var version = new Version(defaultPreReleasePhase); - log.Warn(1001, $"'{repoOrWorkDir}' is not a valid repository or working directory. Using default version {version}."); + log.Warn(1001, $"'{workDir}' is not a valid working directory. Using default version {version}."); return version; } - using (repo) - { - return repo.GetVersion(tagPrefix, autoIncrement, defaultPreReleasePhase, log); - } + return repo.GetVersion(tagPrefix, autoIncrement, defaultPreReleasePhase, log); } } } diff --git a/MinVer/Logger.cs b/MinVer/Logger.cs index 7263ad9f..972a5b3b 100644 --- a/MinVer/Logger.cs +++ b/MinVer/Logger.cs @@ -45,8 +45,8 @@ public void Warn(int code, string message) } } - public static void ErrorRepoOrWorkDirDoesNotExist(string repoOrWorkDir) => - Error(1002, $"Repository or working directory '{repoOrWorkDir}' does not exist."); + public static void ErrorWorkDirDoesNotExist(string workDir) => + Error(1002, $"Working directory '{workDir}' does not exist."); public static void ErrorInvalidAutoIncrement(string autoIncrement) => Error(1006, $"Invalid auto increment '{autoIncrement}'. Valid values are {VersionPartEx.ValidValues}"); @@ -64,6 +64,15 @@ public static void ErrorInvalidVersionOverride(string versionOverride) => private static void Error(int code, string message) => Message($"error MINVER{code:D4} : {message}"); - private static void Message(string message) => Console.Error.WriteLine($"MinVer: {message}"); + private static void Message(string message) + { + if (message.Contains('\r') || message.Contains('\n')) + { + var lines = message.Replace("\r\n", "\n").Split('\r', '\n'); + message = string.Join($"{Environment.NewLine}MinVer: ", lines); + } + + Console.Error.WriteLine($"MinVer: {message}"); + } } } diff --git a/MinVerTests/Versioning.cs b/MinVerTests/Versioning.cs index 0786c8e9..4ac2b790 100644 --- a/MinVerTests/Versioning.cs +++ b/MinVerTests/Versioning.cs @@ -2,7 +2,6 @@ namespace MinVerTests { using System; using System.Collections.Generic; - using System.IO; using System.Threading.Tasks; using MinVer.Lib; using MinVerTests.Infra; @@ -139,21 +138,5 @@ public static void NoRepo(string path, Version version) "Then the version is 0.0.0-alpha.0" .x(() => Assert.Equal("0.0.0-alpha.0", version.ToString())); } - - [Scenario] - public static void WorkingDir(string path, Version version) - { - $"Given a repository with a commit in '{path = GetScenarioDirectory("versioning-working-dir")}'" - .x(() => EnsureEmptyRepositoryAndCommit(path)); - - "And another commit" - .x(() => Commit(path)); - - "When the version is determined from the working dir" - .x(() => version = Versioner.GetVersion(Path.Combine(path, ".git"), default, default, default, default, default, new TestLogger())); - - "Then the version is 0.0.0-alpha.0.1" - .x(() => Assert.Equal("0.0.0-alpha.0.1", version.ToString())); - } } } diff --git a/README.md b/README.md index 0a040ef5..ec7aaefa 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Also available as a [command line tool](#can-i-use-minver-to-version-software-wh ## Prerequisites - [.NET Core SDK 2.1.300 or a later 2.x version.](https://www.microsoft.com/net/download) +- [Git](https://git-scm.com/) ## Quick start @@ -101,7 +102,7 @@ _(With TL;DR answers inline.)_ - [Can I use MinVer to version software which is not built using a .NET SDK style project?](#can-i-use-minver-to-version-software-which-is-not-built-using-a-net-sdk-style-project) _(yes)_ - [What if the history diverges, and more than one tag is found?](#what-if-the-history-diverges-and-more-than-one-tag-is-found) _(nothing bad)_ - [What if the history diverges, and then converges again, before the latest tag (or root commit) is found?](#what-if-the-history-diverges-and-then-converges-again-before-the-latest-tag-or-root-commit-is-found) _(nothing bad)_ -- [Why does MinVer fail with `LibGit2Sharp.NotFoundException`?](#why-does-minver-fail-with-libgit2sharpnotfoundexception) _(easy to fix)_ +- [Why is the default version sometimes used on Travis CI when a version tag exists in the history?](#why-is-the-default-version-sometimes-used-on-travis-ci-when-a-version-tag-exists-in-the-history) _(shallow clones)_ ### Why not use GitVersion, Nerdbank.GitVersioning, or some other tool? @@ -255,7 +256,7 @@ Yes! You can do this by using a specific tag prefix for each project. For exampl Yes! [`MinVerVerbosity`](#options) can be set to `quiet`, `minimal` (default), `normal`, `detailed`, or `diagnostic`. These verbosity levels match those in MSBuild and therefore `dotnet build`, `dotnet pack`, etc. The default is `minimal`, which matches the default in MSBuild. At the `quiet` and `minimal` levels, you will see only warnings and errors. At the `normal` level you will see which commit is being used to calculate the version, and the calculated version. At the `detailed` level you will see how many commits were examined, which version tags were found but ignored, which version was calculated, etc. At the `diagnostic` level you will see how MinVer walks the commit history, in excruciating detail. -In a future version of MinVer, the verbosity level may be inherited from MSBuild, in which case `MinVerVerbosity` will be deprecated. Currently this is not possible due to technical restrictions related to [libgit2](https://github.com/libgit2/libgit2). +In a future version of MinVer, the verbosity level may be inherited from MSBuild, in which case `MinVerVerbosity` will be deprecated. ### Can I use MinVer to version software which is not built using a .NET SDK style project? @@ -271,15 +272,9 @@ The tag with the higher version is used. MinVer will use the height on the first path followed where the history diverges. The paths are followed in the same order that the parents of the commit are stored in git. The first parent is the commit on the branch that was the current branch when the merge was performed. The remaining parents are stored in the order that their branches were specified in the merge command. -### Why does MinVer fail with `LibGit2Sharp.NotFoundException`? +### Why is the default version sometimes used on Travis CI when a version tag exists in the history? -You may see an exception of this form: - -> Unhandled Exception: LibGit2Sharp.NotFoundException: object not found - no match for id (...) - -This is because you are using a [shallow clone](https://www.git-scm.com/docs/git-clone#git-clone---depthltdepthgt). MinVer uses [libgit2](https://github.com/libgit2/libgit2) to interrogate the repo and [libgit2 does not support shallow clones](https://github.com/libgit2/libgit2/issues/3058). To resolve this problem, use a regular (deep) clone. - -**Important:** By default, [Travis CI](https://travis-ci.org/) uses shallow clones with a depth of 50 commits. To build on Travis CI, [remove the `--depth` flag](https://docs.travis-ci.com/user/customizing-the-build#git-clone-depth). +By default, [Travis CI](https://travis-ci.org/) uses [shallow clones](https://www.git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt) with a depth of 50 commits. In that case, if the latest version tag in the history is at a height of more than 50 commits, it will not be found. To build on Travis CI, [ensure the `--depth` flag is set appropriately](https://docs.travis-ci.com/user/customizing-the-build#git-clone-depth). --- diff --git a/minver-cli/Logger.cs b/minver-cli/Logger.cs index 7a751dd4..0c639af4 100644 --- a/minver-cli/Logger.cs +++ b/minver-cli/Logger.cs @@ -45,8 +45,8 @@ public void Warn(int code, string message) } } - public static void ErrorRepoOrWorkDirDoesNotExist(string repoOrWorkDir) => - Error($"Repository or working directory '{repoOrWorkDir}' does not exist."); + public static void ErrorWorkDirDoesNotExist(string workDir) => + Error($"Working directory '{workDir}' does not exist."); public static void ErrorInvalidAutoIncrement(string autoIncrement) => Error($"Invalid auto increment '{autoIncrement}'. Valid values are {VersionPartEx.ValidValues}"); @@ -59,6 +59,15 @@ public static void ErrorInvalidVerbosity(string verbosity) => private static void Error(string message) => Message($"error : {message}"); - private static void Message(string message) => Console.Error.WriteLine($"MinVer: {message}"); + private static void Message(string message) + { + if (message.Contains('\r') || message.Contains('\n')) + { + var lines = message.Replace("\r\n", "\n").Split('\r', '\n'); + message = string.Join($"{Environment.NewLine}MinVer: ", lines); + } + + Console.Error.WriteLine($"MinVer: {message}"); + } } } diff --git a/minver-cli/Program.cs b/minver-cli/Program.cs index ea45f82a..56ed80a2 100644 --- a/minver-cli/Program.cs +++ b/minver-cli/Program.cs @@ -21,7 +21,7 @@ private static int Main(string[] args) var buildMetaOption = app.Option("-b|--build-metadata ", "", CommandOptionType.SingleValue); var defaultPreReleasePhaseOption = app.Option("-d|--default-pre-release-phase ", "alpha (default), preview, etc.", CommandOptionType.SingleValue); var minMajorMinorOption = app.Option("-m|--minimum-major-minor ", MajorMinor.ValidValues, CommandOptionType.SingleValue); - var repoOrWorkDirOption = app.Option("-r|--repo ", "Repository or working directory.", CommandOptionType.SingleValue); + var workDirOption = app.Option("-r|--repo ", "Working directory.", CommandOptionType.SingleValue); var tagPrefixOption = app.Option("-t|--tag-prefix ", "", CommandOptionType.SingleValue); var verbosityOption = app.Option("-v|--verbosity ", VerbosityMap.ValidValue, CommandOptionType.SingleValue); #if MINVER @@ -30,7 +30,7 @@ private static int Main(string[] args) app.OnExecute(() => { - if (!TryParse(repoOrWorkDirOption.Value(), minMajorMinorOption.Value(), verbosityOption.Value(), autoIncrementOption.Value(), out var repoOrWorkDir, out var minMajorMinor, out var verbosity, out var autoIncrement)) + if (!TryParse(workDirOption.Value(), minMajorMinorOption.Value(), verbosityOption.Value(), autoIncrementOption.Value(), out var workDir, out var minMajorMinor, out var verbosity, out var autoIncrement)) { return 2; } @@ -56,10 +56,10 @@ private static int Main(string[] args) } else { - version = Versioner.GetVersion(repoOrWorkDir, tagPrefixOption.Value(), minMajorMinor, buildMetaOption.Value(), autoIncrement, defaultPreReleasePhaseOption.Value(), log); + version = Versioner.GetVersion(workDir, tagPrefixOption.Value(), minMajorMinor, buildMetaOption.Value(), autoIncrement, defaultPreReleasePhaseOption.Value(), log); } #else - var version = Versioner.GetVersion(repoOrWorkDir, tagPrefixOption.Value(), minMajorMinor, buildMetaOption.Value(), autoIncrement, defaultPreReleasePhaseOption.Value(), log); + var version = Versioner.GetVersion(workDir, tagPrefixOption.Value(), minMajorMinor, buildMetaOption.Value(), autoIncrement, defaultPreReleasePhaseOption.Value(), log); #endif Console.Out.WriteLine(version); @@ -70,16 +70,16 @@ private static int Main(string[] args) return app.Execute(args); } - private static bool TryParse(string repoOrWorkDirOption, string minMajorMinorOption, string verbosityOption, string autoIncrementOption, out string repoOrWorkDir, out MajorMinor minMajorMinor, out Verbosity verbosity, out VersionPart autoIncrement) + private static bool TryParse(string workDirOption, string minMajorMinorOption, string verbosityOption, string autoIncrementOption, out string workDir, out MajorMinor minMajorMinor, out Verbosity verbosity, out VersionPart autoIncrement) { - repoOrWorkDir = "."; + workDir = "."; minMajorMinor = null; verbosity = default; autoIncrement = default; - if (!string.IsNullOrEmpty(repoOrWorkDirOption) && !Directory.Exists(repoOrWorkDir = repoOrWorkDirOption)) + if (!string.IsNullOrEmpty(workDirOption) && !Directory.Exists(workDir = workDirOption)) { - Logger.ErrorRepoOrWorkDirDoesNotExist(repoOrWorkDirOption); + Logger.ErrorWorkDirDoesNotExist(workDirOption); return false; } diff --git a/targets/Program.cs b/targets/Program.cs index 0bed9cf1..df662edb 100644 --- a/targets/Program.cs +++ b/targets/Program.cs @@ -64,7 +64,7 @@ public static async Task Main(string[] args) var output = Path.Combine(testPackageBaseOutput, $"{buildNumber}-test-package-no-repo"); // act - await CleanAndPack(testProject, output, "normal"); + await CleanAndPack(testProject, output, "diagnostic"); // assert AssertPackageFileNameContains("0.0.0-alpha.0.nupkg", output); @@ -81,7 +81,7 @@ public static async Task Main(string[] args) var output = Path.Combine(testPackageBaseOutput, $"{buildNumber}-test-package-no-commits"); // act - await CleanAndPack(testProject, output, "normal"); + await CleanAndPack(testProject, output, "diagnostic"); // assert AssertPackageFileNameContains("0.0.0-alpha.0.nupkg", output); @@ -99,7 +99,7 @@ public static async Task Main(string[] args) var output = Path.Combine(testPackageBaseOutput, $"{buildNumber}-test-package-commit"); // act - await CleanAndPack(testProject, output, "normal"); + await CleanAndPack(testProject, output, "diagnostic"); // assert AssertPackageFileNameContains("0.0.0-alpha.0.nupkg", output); @@ -116,7 +116,7 @@ public static async Task Main(string[] args) var output = Path.Combine(testPackageBaseOutput, $"{buildNumber}-test-package-non-version-tag"); // act - await CleanAndPack(testProject, output, default); + await CleanAndPack(testProject, output, "diagnostic"); // assert AssertPackageFileNameContains("0.0.0-alpha.0.nupkg", output);