Skip to content

Commit 8021cd8

Browse files
authored
enhance: introduce template engine for commit templates (#704) (#719)
1 parent 7368768 commit 8021cd8

File tree

2 files changed

+413
-56
lines changed

2 files changed

+413
-56
lines changed

src/Models/CommitTemplate.cs

Lines changed: 3 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,11 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Text;
4-
using System.Text.RegularExpressions;
1+
using System.Collections.Generic;
52

63
using CommunityToolkit.Mvvm.ComponentModel;
74

85
namespace SourceGit.Models
96
{
107
public partial class CommitTemplate : ObservableObject
118
{
12-
[GeneratedRegex(@"\$\{files(\:\d+)?\}")]
13-
private static partial Regex REG_COMMIT_TEMPLATE_FILES();
14-
159
public string Name
1610
{
1711
get => _name;
@@ -26,55 +20,8 @@ public string Content
2620

2721
public string Apply(Branch branch, List<Change> changes)
2822
{
29-
var content = _content
30-
.Replace("${files_num}", $"{changes.Count}")
31-
.Replace("${branch_name}", branch.Name);
32-
33-
var matches = REG_COMMIT_TEMPLATE_FILES().Matches(content);
34-
if (matches.Count == 0)
35-
return content;
36-
37-
var builder = new StringBuilder();
38-
var last = 0;
39-
for (int i = 0; i < matches.Count; i++)
40-
{
41-
var match = matches[i];
42-
if (!match.Success)
43-
continue;
44-
45-
var start = match.Index;
46-
if (start != last)
47-
builder.Append(content.Substring(last, start - last));
48-
49-
var countStr = match.Groups[1].Value;
50-
var paths = new List<string>();
51-
var more = string.Empty;
52-
if (countStr is { Length: <= 1 })
53-
{
54-
foreach (var c in changes)
55-
paths.Add(c.Path);
56-
}
57-
else
58-
{
59-
var count = Math.Min(int.Parse(countStr.Substring(1)), changes.Count);
60-
for (int j = 0; j < count; j++)
61-
paths.Add(changes[j].Path);
62-
63-
if (count < changes.Count)
64-
more = $" and {changes.Count - count} other files";
65-
}
66-
67-
builder.Append(string.Join(", ", paths));
68-
if (!string.IsNullOrEmpty(more))
69-
builder.Append(more);
70-
71-
last = start + match.Length;
72-
}
73-
74-
if (last != content.Length - 1)
75-
builder.Append(content.Substring(last));
76-
77-
return builder.ToString();
23+
var te = new TemplateEngine();
24+
return te.Eval(_content, branch, changes);
7825
}
7926

8027
private string _name = string.Empty;

0 commit comments

Comments
 (0)