Skip to content

Commit ea4470e

Browse files
committed
Omit the XML declaration if the file didn't have it
1 parent 8b3a67d commit ea4470e

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/PackageReferenceCleaner/CleanPackageReferences.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Collections.Immutable;
22
using System.IO;
33
using System.Linq;
4+
using System.Xml;
45
using System.Xml.Linq;
56
using Microsoft.CodeAnalysis;
67
using Microsoft.CodeAnalysis.Diagnostics;
@@ -58,8 +59,21 @@ public override void Initialize(AnalysisContext context)
5859
if (cleaned > 0)
5960
{
6061
ctx.ReportDiagnostic(Diagnostic.Create(SupportedDiagnostics[0], null, cleaned));
61-
doc.Save(projectFile);
62+
// Detect whether the file originally had an XML declaration or not.
63+
var hasDecl = HasXmlDeclaration(projectFile!);
64+
// Save emits the XML declaration, but ToString doesn't.
65+
if (hasDecl)
66+
doc.Save(projectFile);
67+
else
68+
File.WriteAllText(projectFile, doc.ToString().Trim());
6269
}
6370
});
6471
}
72+
73+
static bool HasXmlDeclaration(string projectFile)
74+
{
75+
using var reader = new StreamReader(projectFile);
76+
using var xml = XmlReader.Create(reader);
77+
return xml.Read() && xml.NodeType == XmlNodeType.XmlDeclaration;
78+
}
6579
}

0 commit comments

Comments
 (0)