using System.Text; using System.Text.RegularExpressions; namespace Chronos.Tools.Commands; /// /// Builds release notes from Conventional Commits. Reads git log --format=%h%x09%s lines from stdin /// (or --in file) and writes Markdown grouped by type. /// internal sealed partial class ChangelogCommand : ICommand { private static readonly (string Type, string Heading)[] Sections = [ ("feat", "Added"), ("fix", "Fixed"), ("perf", "Performance"), ("security", "Security"), ("i18n", "Localization"), ("docs", "Documentation"), ]; public string Name => "changelog"; public string Summary => "Release notes from Conventional Commits on stdin (--title, --out file)"; public async Task RunAsync(string[] args) { var a = new Args(args); IReadOnlyList input = a.Get("in") is { } file ? await File.ReadAllLinesAsync(file) : ReadStdin(); var markdown = Render(input, a.Get("title")); if (a.Get("out") is { } outFile) { Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outFile))!); await File.WriteAllTextAsync(outFile, markdown, new UTF8Encoding(false)); } else { Console.Write(markdown); } return 0; } internal static string Render(IEnumerable lines, string? title) { var groups = new Dictionary>(StringComparer.Ordinal); var breaking = new List(); foreach (var line in lines) { var tab = line.IndexOf('\t'); var hash = tab > 0 ? line[..tab] : string.Empty; var subject = tab > 0 ? line[(tab + 1)..] : line; var m = Conventional().Match(subject); if (!m.Success) continue; var type = m.Groups["type"].Value.ToLowerInvariant(); var scope = m.Groups["scope"].Success ? $"**{m.Groups["scope"].Value}**: " : string.Empty; var entry = $"- {scope}{m.Groups["desc"].Value.Trim()}{(hash.Length > 0 ? $" ({hash})" : string.Empty)}"; if (m.Groups["bang"].Success) breaking.Add(entry); if (!groups.TryGetValue(type, out var list)) groups[type] = list = []; list.Add(entry); } var sb = new StringBuilder(); if (title is not null) sb.Append("# ").AppendLine(title).AppendLine(); // The title alone says nothing about the release: the fallback depends on the entries written, not on the text. var written = false; if (breaking.Count > 0) { sb.AppendLine("### Breaking changes"); foreach (var e in breaking) sb.AppendLine(e); sb.AppendLine(); written = true; } foreach (var (type, heading) in Sections) { if (!groups.TryGetValue(type, out var entries)) continue; sb.Append("### ").AppendLine(heading); foreach (var e in entries) sb.AppendLine(e); sb.AppendLine(); written = true; } if (!written) sb.AppendLine("Maintenance release."); return sb.ToString(); } private static List ReadStdin() { var lines = new List(); if (!Console.IsInputRedirected) return lines; while (Console.In.ReadLine() is { } line) lines.Add(line); return lines; } [GeneratedRegex(@"^(?[a-zA-Z]+)(?:\((?[^)]+)\))?(?!)?:\s*(?.+)$")] private static partial Regex Conventional(); }