Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 52 additions & 58 deletions src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,56 +13,6 @@ namespace Microsoft.OpenApi
/// </summary>
public static class SpecialCharacterStringExtensions
{
// Plain style strings cannot start with indicators.
// http://www.yaml.org/spec/1.2/spec.html#indicator//
private static readonly HashSet<string> _yamlIndicators = new()
{
"-",
"?",
":",
",",
"{",
"}",
"[",
"]",
"&",
"*",
"#",
"?",
"|",
"-",
">",
"!",
"%",
"@",
"`",
"'",
"\""
};

// Plain style strings cannot contain these character combinations.
// http://www.yaml.org/spec/1.2/spec.html#style/flow/plain
private static readonly HashSet<string> _yamlPlainStringForbiddenCombinations = new()
{
": ",
" #",

// These are technically forbidden only inside flow collections, but
// for the sake of simplicity, we will never allow them in our generated plain string.
"[",
"]",
"{",
"}",
","
};

// Plain style strings cannot end with these characters.
// http://www.yaml.org/spec/1.2/spec.html#style/flow/plain
private static readonly HashSet<string> _yamlPlainStringForbiddenTerminals = new()
{
":"
};

// Double-quoted strings are needed for these non-printable control characters.
// http://www.yaml.org/spec/1.2/spec.html#style/flow/double-quoted
private static readonly Dictionary<char, string> _yamlControlCharacterCharReplacements = new()
Expand Down Expand Up @@ -104,12 +54,24 @@ public static class SpecialCharacterStringExtensions
private static readonly Dictionary<string, string> _yamlControlCharacterStringReplacements = _yamlControlCharacterCharReplacements
.ToDictionary(x => x.Key.ToString(), x => x.Value);

// Plain style strings cannot contain these characters.
// These are technically forbidden only inside flow collections, but
// for the sake of simplicity, we will never allow them in our generated plain string.
// http://www.yaml.org/spec/1.2/spec.html#style/flow/plain
private static readonly char[] _yamlPlainStringForbiddenCharacters = ['[', ']', '{', '}', ','];

// Plain style strings cannot start with indicators.
// http://www.yaml.org/spec/1.2/spec.html#indicator//
private const string _yamlIndicators = "-?:,{}[]&*#|>!%@`'\"";

/// <summary>
/// Escapes all special characters and put the string in quotes if necessary to
/// get a YAML-compatible string.
/// </summary>
internal static string GetYamlCompatibleString(this string input)
{
Utils.CheckArgumentNull(input);

switch (input)
{
// If string is an empty string, wrap it in quote to ensure it is not recognized as null.
Expand All @@ -124,7 +86,7 @@ internal static string GetYamlCompatibleString(this string input)
}

// If string includes a control character, wrapping in double quote is required.
if (input.Any(c => _yamlControlCharacterCharReplacements.ContainsKey(c)))
if (ContainsControlCharacter(input))
{
// Replace the backslash first, so that the new backslashes created by other Replaces are not duplicated.
input = input.Replace("\\", "\\\\");
Expand All @@ -147,10 +109,13 @@ internal static string GetYamlCompatibleString(this string input)
// 3) has trailing/leading white spaces,
// wrap the string in single quote.
// http://www.yaml.org/spec/1.2/spec.html#style/flow/plain
if (_yamlPlainStringForbiddenCombinations.Any(fc => input.Contains(fc)) ||
_yamlIndicators.Any(i => input.StartsWith(i, StringComparison.Ordinal)) ||
_yamlPlainStringForbiddenTerminals.Any(i => input.EndsWith(i)) ||
input.Trim() != input)
if (input.IndexOfAny(_yamlPlainStringForbiddenCharacters) >= 0 ||
input.IndexOf(": ", StringComparison.Ordinal) >= 0 ||
input.IndexOf(" #", StringComparison.Ordinal) >= 0 ||
_yamlIndicators.IndexOf(input[0]) >= 0 ||
char.IsWhiteSpace(input[0]) ||
char.IsWhiteSpace(input[input.Length - 1]) ||
input.EndsWith(":"))
{
// Escape single quotes with two single quotes.
input = input.Replace("'", "''");
Expand All @@ -160,10 +125,12 @@ internal static string GetYamlCompatibleString(this string input)

// If string can be mistaken as a number, c-style hexadecimal notation, a boolean, or a timestamp,
// wrap it in quote to indicate that this is indeed a string, not a number, c-style hexadecimal notation, a boolean, or a timestamp
if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out _) ||
// A number, a hexadecimal notation, and a timestamp all contain an ASCII digit.
if (bool.TryParse(input, out _) ||
ContainsAsciiDigit(input) &&
(decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out _) ||
IsHexadecimalNotation(input) ||
bool.TryParse(input, out _) ||
DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out _)))
{
return $"'{input}'";
}
Expand Down Expand Up @@ -197,6 +164,33 @@ internal static string GetJsonCompatibleString(this string value)
return $"\"{value}\"";
}

// The control characters are \0 to \x1f, the keys of _yamlControlCharacterCharReplacements.
private static bool ContainsControlCharacter(string input)
{
foreach (var c in input)
{
if (c < '\x20')
{
return true;
}
}

return false;
}

private static bool ContainsAsciiDigit(string input)
{
foreach (var c in input)
{
if (c is >= '0' and <= '9')
{
return true;
}
}

return false;
}

internal static bool IsHexadecimalNotation(string input)
{
return input.StartsWith("0x", StringComparison.Ordinal) && int.TryParse(input.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _);
Expand Down