Skip to content

Commit

Permalink
Escape literals in public constant string (#288)
Browse files Browse the repository at this point in the history
  • Loading branch information
sungam3r committed Mar 1, 2023
1 parent e0ca30b commit 38edd64
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/PublicApiGenerator/ApiGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -565,13 +565,7 @@ private static CodeExpression CreateInitialiserExpression(CustomAttributeArgumen
}

if (value is string s)
{
// CodeDOM outputs a verbatim string. Any string with \n is treated as such, so normalize
// it to make it easier for comparisons
s = Regex.Replace(s, @"\n", "\\n");
s = Regex.Replace(s, @"\r\n|\r\\n", "\\r\\n");
value = s;
}
value = NormalizeString(s);

return new CodePrimitiveExpression(value);
}
Expand Down Expand Up @@ -824,8 +818,22 @@ private static void AddFieldToTypeDeclaration(CodeTypeDeclaration typeDeclaratio
};

if (memberInfo.HasConstant)
field.InitExpression = new CodePrimitiveExpression(memberInfo.Constant);
{
var value = memberInfo.Constant;
if (value is string s)
value = NormalizeString(s);
field.InitExpression = new CodePrimitiveExpression(value);
}

typeDeclaration.Members.Add(field);
}

private static string NormalizeString(string s)
{
// CodeDOM outputs a verbatim string. Any string with \n is treated as such, so normalize
// it to make it easier for comparisons
s = Regex.Replace(s, @"\n", "\\n");
s = Regex.Replace(s, @"\r\n|\r\\n", "\\r\\n");
return s;
}
}
34 changes: 34 additions & 0 deletions src/PublicApiGeneratorTests/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using PublicApiGeneratorTests.Examples;

namespace PublicApiGeneratorTests
{
public class Constants : ApiGeneratorTestsBase
{
// https://github.com/PublicApiGenerator/PublicApiGenerator/issues/82
[Fact]
public void Should_escape_literals_in_public_constant_string()
{
AssertPublicApi<MyConstants>(
@"namespace PublicApiGeneratorTests.Examples
{
public class MyConstants
{
public const string MULTILINE1 = ""This\\r\\nIs\\r\\nMultiline\\r\\n"";
public const string MULTILINE2 = ""This\\nIs\\nMultiline\\n"";
public const string SINGLELINE = ""ABC"";
public MyConstants() { }
}
}");
}
}

namespace Examples
{
public class MyConstants
{
public const string SINGLELINE = "ABC";
public const string MULTILINE1 = "This\r\nIs\r\nMultiline\r\n";
public const string MULTILINE2 = "This\nIs\nMultiline\n";
}
}
}

0 comments on commit 38edd64

Please sign in to comment.