ファイル

62 行
2.6 KiB
C#

using System.Text;
namespace UndoTree;
internal static class UndoTreeExport
{
const string Indent = " ";
public static string ToMarkdown(UndoTreeRecord record, string? projectPath)
{
var children = record.Nodes.ToLookup(node => node.Parent);
var ids = record.Nodes.Select(node => node.Id).ToHashSet();
var text = new StringBuilder();
text.Append("# ").Append(Texts.UndoTree).Append(Environment.NewLine);
if (!string.IsNullOrWhiteSpace(projectPath))
text.Append(Environment.NewLine).Append(projectPath).Append(Environment.NewLine);
text.Append(Environment.NewLine);
foreach (var root in record.Nodes.Where(node => node.Parent < 0 || !ids.Contains(node.Parent)))
AppendChain(text, root, children, 0);
return text.ToString();
}
static void AppendChain(StringBuilder text, UndoTreeRecordNode start, ILookup<int, UndoTreeRecordNode> children, int level)
{
for (UndoTreeRecordNode? node = start; node is not null; node = PrimaryOf(node, children))
{
AppendNode(text, node, level);
var primary = PrimaryOf(node, children);
var branches = children[node.Id].Where(child => child.Id != primary?.Id).OrderBy(child => child.Id).ToArray();
if (branches.Length == 0)
continue;
AppendLine(text, level + 1, Texts.SideBranches);
foreach (var branch in branches)
AppendChain(text, branch, children, level + 2);
}
}
static UndoTreeRecordNode? PrimaryOf(UndoTreeRecordNode node, ILookup<int, UndoTreeRecordNode> children)
=> children[node.Id].MaxBy(child => child.Id);
static void AppendNode(StringBuilder text, UndoTreeRecordNode node, int level)
{
var marks = UndoTreeText.Marks(false, node.Saved, node.Tag, string.Empty);
var label = UndoTreeText.SingleLine(node.Parent < 0 && node.Label.Length == 0 ? Texts.InitialState : node.Label);
var time = node.Time == DateTime.MinValue ? string.Empty : $" ({node.Time:T})";
AppendLine(text, level, (marks.Length > 0 ? marks + " " : string.Empty) + label + time);
foreach (var command in node.Commands)
AppendLine(text, level + 1, UndoTreeText.SingleLine(UndoTreeText.WithDetail(UndoTreeText.Join(command.Target, command.Member), command.Detail)));
}
static void AppendLine(StringBuilder text, int level, string content)
{
for (var index = 0; index < level; index++)
text.Append(Indent);
text.Append("- ").Append(content).Append(Environment.NewLine);
}
}