Skip to content

Commit 398aa31

Browse files
authored
[release/dev17.13] Preserve encoding during DocumentState updates (#77362)
Backport of #77354 to release/dev17.13 /cc @sharwell ## Customer Impact ## Regression - [ ] Yes - [ ] No [If yes, specify when the regression was introduced. Provide the PR or commit if known.] ## Testing [How was the fix verified? How was the issue missed previously? What tests were added?] ## Risk [High/Medium/Low. Justify the indication by mentioning how risks were measured and addressed.]
2 parents 44ee46a + 76bb718 commit 398aa31

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/Workspaces/Core/Portable/Workspace/Solution/DocumentState.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,20 @@ internal DocumentState UpdateTree(SyntaxNode newRoot, PreservationMode mode)
497497

498498
// use the encoding that we get from the new root
499499
var encoding = newRoot.SyntaxTree.Encoding;
500+
if (encoding is null)
501+
{
502+
// The new tree doesn't specify an encoding. For these cases, continue to use the previous encoding of the
503+
// document.
504+
if (TryGetSyntaxTree(out var priorTree))
505+
{
506+
// this is most likely available since UpdateTree is normally called after modifying the existing tree.
507+
encoding = priorTree.Encoding;
508+
}
509+
else if (TryGetText(out var priorText))
510+
{
511+
encoding = priorText.Encoding;
512+
}
513+
}
500514

501515
var syntaxTreeFactory = LanguageServices.GetRequiredService<ISyntaxTreeFactoryService>();
502516

src/Workspaces/MSBuildTest/VisualStudioMSBuildWorkspaceTests.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2893,13 +2893,14 @@ class C { }";
28932893
Assert.Equal(encoding.EncodingName, text.Encoding.EncodingName);
28942894
Assert.Equal(fileContent, text.ToString());
28952895

2896-
// update root blindly again, after observing encoding, see that encoding is overridden to null
2896+
// update root blindly again, after observing encoding, see that encoding is preserved
2897+
// 🐉 Tools rely on encoding preservation; see https://github.com/dotnet/sdk/issues/46780
28972898
var doc3 = document.WithSyntaxRoot(gen.CompilationUnit()); // empty CU
28982899
var doc3text = await doc3.GetTextAsync();
2899-
Assert.Null(doc3text.Encoding);
2900+
Assert.Same(text.Encoding, doc3text.Encoding);
29002901
var doc3tree = await doc3.GetSyntaxTreeAsync();
2901-
Assert.Null(doc3tree.Encoding);
2902-
Assert.Null(doc3tree.GetText().Encoding);
2902+
Assert.Same(text.Encoding, doc3tree.Encoding);
2903+
Assert.Same(text.Encoding, doc3tree.GetText().Encoding);
29032904

29042905
// change doc to have no encoding, still succeeds at writing to disk with old encoding
29052906
var root = await document.GetSyntaxRootAsync();

0 commit comments

Comments
 (0)