I wrote a CSharpSyntaxRewriter that I use to remove attributes from methods, but I try my best to save anything from the attribute (to the previous method) when I remove all attributes from the method.
This works great for methods with multiple attributes, but not for one.
Here's the minimum playback:
void Main() { var code = @"namespace P { class Program { public void NoAttributes() { } //??? [TestCategory(""Atomic"")] public void OneAtt1() { } [TestCategory(""Atomic"")] public void OneAtt2() { } [TestMethod, TestCategory(""Atomic"")] public void TwoAtts() { } } }"; var tree = CSharpSyntaxTree.ParseText(code); var rewriter = new AttributeRemoverRewriter(); var rewrittenRoot = rewriter.Visit(tree.GetRoot()); Console.WriteLine(rewrittenRoot.GetText().ToString()); } public class AttributeRemoverRewriter : CSharpSyntaxRewriter { public override SyntaxNode VisitAttributeList(AttributeListSyntax attributeList) { var nodesToRemove = attributeList .Attributes .Where(att => (att.Name as IdentifierNameSyntax).Identifier.Text.StartsWith("TestCategory")) .ToArray(); if (nodesToRemove.Length == attributeList.Attributes.Count) {
The full version is here on my gist (before anyone notes any other issues).
Expected Result:
namespace P { class Program { public void NoAttributes() { }
Actual conclusion:
namespace P { class Program { public void NoAttributes() { } public void OneAtt1() { } public void OneAtt2() { } [TestMethod] public void TwoAtts() { } } }
Any ideas on what I need to do to keep spaces (or even comments !!)?
I messed up all the Trivia combinations that I can think of. Changing SyntaxRemoveOptions results in a NullReferenceException inside the Roslyn code base and using the *Trivia extension methods means that attributes that were no longer removed are just spaces.
source share