|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Text.RegularExpressions; |
| 4 | +using Nuke.Common; |
| 5 | + |
| 6 | +partial class BuildTask |
| 7 | +{ |
| 8 | + const string VersionPrefixPattern = @"<VersionPrefix>\s*([^<]+?)\s*</VersionPrefix>"; |
| 9 | + |
| 10 | + Target ShowVersion => _ => _ |
| 11 | + .Executes(() => |
| 12 | + { |
| 13 | + Console.WriteLine($"Current VersionPrefix: {ReadCurrentVersionPrefix()}"); |
| 14 | + }); |
| 15 | + |
| 16 | + Target UpdateVersion => _ => _ |
| 17 | + .Executes(() => |
| 18 | + { |
| 19 | + var current = ReadCurrentVersionPrefix(); |
| 20 | + |
| 21 | + if (!string.IsNullOrWhiteSpace(VersionPrefix)) |
| 22 | + { |
| 23 | + if (!Regex.IsMatch(VersionPrefix, @"^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$")) |
| 24 | + throw new ArgumentException($"Invalid VersionPrefix: '{VersionPrefix}'. Expected semver format like 1.2.3 or 1.2.3-rc.1."); |
| 25 | + WriteVersionPrefix(current, VersionPrefix); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + var next = PatchIncrement(current); |
| 30 | + WriteVersionPrefix(current, next); |
| 31 | + }); |
| 32 | + |
| 33 | + string ReadCurrentVersionPrefix() |
| 34 | + { |
| 35 | + var content = File.ReadAllText(DirectoryBuildPropsFile); |
| 36 | + var match = Regex.Match(content, VersionPrefixPattern, RegexOptions.Singleline); |
| 37 | + if (!match.Success) |
| 38 | + throw new InvalidOperationException($"<VersionPrefix> not found in {DirectoryBuildPropsFile}"); |
| 39 | + return match.Groups[1].Value.Trim(); |
| 40 | + } |
| 41 | + |
| 42 | + static string PatchIncrement(string current) |
| 43 | + { |
| 44 | + var baseVersion = current.Split('-')[0]; |
| 45 | + var parts = baseVersion.Split('.'); |
| 46 | + if (parts.Length < 3 || !int.TryParse(parts[0], out var major) || !int.TryParse(parts[1], out var minor) || !int.TryParse(parts[2], out var patch)) |
| 47 | + throw new InvalidOperationException($"Cannot parse current version '{current}' as X.Y.Z."); |
| 48 | + |
| 49 | + return $"{major}.{minor}.{patch + 1}"; |
| 50 | + } |
| 51 | + |
| 52 | + void WriteVersionPrefix(string current, string next) |
| 53 | + { |
| 54 | + if (string.Equals(current, next, StringComparison.OrdinalIgnoreCase)) |
| 55 | + { |
| 56 | + Console.WriteLine($"VersionPrefix is already {next}."); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + var content = File.ReadAllText(DirectoryBuildPropsFile); |
| 61 | + var updated = Regex.Replace( |
| 62 | + content, |
| 63 | + VersionPrefixPattern, |
| 64 | + $"<VersionPrefix>{next}</VersionPrefix>", |
| 65 | + RegexOptions.Singleline); |
| 66 | + |
| 67 | + File.WriteAllText(DirectoryBuildPropsFile, updated); |
| 68 | + Console.WriteLine($"Updated VersionPrefix: {current} -> {next}"); |
| 69 | + } |
| 70 | +} |
0 commit comments