enhance: introduce template engine for commit templates (#704) (#719)

This commit is contained in:
aikawayataro 2024-11-19 11:46:44 +00:00 committed by GitHub
parent 73687689ce
commit 8021cd8566
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 413 additions and 56 deletions

View file

@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using CommunityToolkit.Mvvm.ComponentModel;
@ -9,9 +6,6 @@ namespace SourceGit.Models
{
public partial class CommitTemplate : ObservableObject
{
[GeneratedRegex(@"\$\{files(\:\d+)?\}")]
private static partial Regex REG_COMMIT_TEMPLATE_FILES();
public string Name
{
get => _name;
@ -26,55 +20,8 @@ namespace SourceGit.Models
public string Apply(Branch branch, List<Change> changes)
{
var content = _content
.Replace("${files_num}", $"{changes.Count}")
.Replace("${branch_name}", branch.Name);
var matches = REG_COMMIT_TEMPLATE_FILES().Matches(content);
if (matches.Count == 0)
return content;
var builder = new StringBuilder();
var last = 0;
for (int i = 0; i < matches.Count; i++)
{
var match = matches[i];
if (!match.Success)
continue;
var start = match.Index;
if (start != last)
builder.Append(content.Substring(last, start - last));
var countStr = match.Groups[1].Value;
var paths = new List<string>();
var more = string.Empty;
if (countStr is { Length: <= 1 })
{
foreach (var c in changes)
paths.Add(c.Path);
}
else
{
var count = Math.Min(int.Parse(countStr.Substring(1)), changes.Count);
for (int j = 0; j < count; j++)
paths.Add(changes[j].Path);
if (count < changes.Count)
more = $" and {changes.Count - count} other files";
}
builder.Append(string.Join(", ", paths));
if (!string.IsNullOrEmpty(more))
builder.Append(more);
last = start + match.Length;
}
if (last != content.Length - 1)
builder.Append(content.Substring(last));
return builder.ToString();
var te = new TemplateEngine();
return te.Eval(_content, branch, changes);
}
private string _name = string.Empty;