Skip to content

Commit

Permalink
Escape braces in ReferenceExpression.AppendFormatted() (#4869)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidebbo authored Aug 12, 2024
1 parent 55eb46f commit fecfe0a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Aspire.Hosting/ApplicationModel/ReferenceExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ public readonly void AppendLiteral(string value)
/// <param name="value">The formatted string to be appended to the interpolated string.</param>
public readonly void AppendFormatted(string? value)
{
_builder.Append(value);
// The value that comes in is a literal string that is not meant to be interpreted.
// But the _builder later gets treated as a format string, so we just need to escape the braces.
_builder.Append(value?.Replace("{", "{{").Replace("}", "}}"));
}

/// <summary>
Expand Down
25 changes: 25 additions & 0 deletions tests/Aspire.Hosting.Tests/ReferenceExpressionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Xunit;

namespace Aspire.Hosting.Tests;
public class ReferenceExpressionTests
{
[Theory]
[InlineData("world", "Hello world", "Hello world")]
[InlineData("{", "Hello {{", "Hello {")]
[InlineData("}", "Hello }}", "Hello }")]
[InlineData("{1}", "Hello {{1}}", "Hello {1}")]
[InlineData("{x}", "Hello {{x}}", "Hello {x}")]
[InlineData("{{x}}", "Hello {{{{x}}}}", "Hello {{x}}")]
public void TestReferenceExpressionCreateInputStringTreatedAsLiteral(string input, string expectedFormat, string expectedExpression)
{
var refExpression = ReferenceExpression.Create($"Hello {input}");
Assert.Equal(expectedFormat, refExpression.Format);

// Generally, the input string should end up unchanged in the expression, since it's a literal
var expr = refExpression.ValueExpression;
Assert.Equal(expectedExpression, expr);
}
}

0 comments on commit fecfe0a

Please sign in to comment.