Skip to content

Commit

Permalink
fix(trees): Fix merging algorithm
Browse files Browse the repository at this point in the history
This commit fixes the merging algorithm by bringing it more in line with what ToChildNodes does. It also fixes an issue where top-level commands were not added to the root node.
  • Loading branch information
VelvetToroyashi committed Mar 17, 2024
1 parent b8b6097 commit 60a89b1
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions Remora.Commands/Trees/CommandTreeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ private IEnumerable<IChildNode> BindDynamicCommands(IReadOnlyList<IChildNode> no
{
if (!values.Any())
{
foreach (var node in nodes)
{
yield return node;
}
yield break;
}

Expand Down Expand Up @@ -163,26 +167,39 @@ private GroupNode MergeRecursively(IReadOnlyList<IChildNode> children, IParentNo
description
);

foreach (var child in children)
var mutableChildren = children.SelectMany(n => n is GroupNode gn ? gn.Children : new[] { n }).ToList();

for (var i = children.Count - 1; i >= 0; i--)
{
var child = children[i];

if (child is not GroupNode cgn)
{
childNodes.Add(child);
mutableChildren.RemoveAt(i);
continue;
}

// Parity with ToChildNodes; if the group's name is empty
// Nest it directly under the parent.
if (string.IsNullOrWhiteSpace(cgn.Key))
// Parity with ToChildNodes; if the group's name is empty, or
// shouldn't be merged, just nest it under the parent.
if (string.IsNullOrWhiteSpace(cgn.Key) || name != child.Key)
{
childNodes.AddRange(cgn.Children);
continue;
mutableChildren.RemoveAt(i);
}
}

// Otherwise, merge, recursively.
if (name == child.Key)
var groups = mutableChildren.GroupBy(g => g.Key);

foreach (var subgroup in groups)
{
if (subgroup.Count() is 1)
{
childNodes.Add(subgroup.Single());
}
else
{
childNodes.Add(MergeRecursively(cgn.Children, group));
childNodes.Add(MergeRecursively(subgroup.ToArray(), group));
}
}

Expand Down

0 comments on commit 60a89b1

Please sign in to comment.