Skip to content
Merged
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 @@
/// </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 @@
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 @@
}

// 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 @@
// 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 ||

Check warning on line 113 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'string.Contains' instead of 'string.IndexOf' to improve readability

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxx&open=AaII18Lx7keIBf9Hesxx&pullRequest=3189
input.IndexOf(" #", StringComparison.Ordinal) >= 0 ||

Check warning on line 114 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'string.Contains' instead of 'string.IndexOf' to improve readability

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxy&open=AaII18Lx7keIBf9Hesxy&pullRequest=3189
_yamlIndicators.IndexOf(input[0]) >= 0 ||

Check warning on line 115 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'string.Contains' instead of 'string.IndexOf' to improve readability

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxz&open=AaII18Lx7keIBf9Hesxz&pullRequest=3189
char.IsWhiteSpace(input[0]) ||
char.IsWhiteSpace(input[input.Length - 1]) ||
input.EndsWith(":"))

Check warning on line 118 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

"EndsWith" overloads that take a "char" should be used

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxt&open=AaII18Lx7keIBf9Hesxt&pullRequest=3189

Check warning on line 118 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use 'string.EndsWith(char)' instead of 'string.EndsWith(string)' when you have a string with a single char

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxw&open=AaII18Lx7keIBf9Hesxw&pullRequest=3189
{
// Escape single quotes with two single quotes.
input = input.Replace("'", "''");
Expand All @@ -160,10 +125,12 @@

// 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 @@
return $"\"{value}\"";
}

// The control characters are \0 to \x1f, the keys of _yamlControlCharacterCharReplacements.
private static bool ContainsControlCharacter(string input)
{
foreach (var c in input)

Check warning on line 170 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Loops should be simplified using the "Any" LINQ method

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxu&open=AaII18Lx7keIBf9Hesxu&pullRequest=3189
{
if (c < '\x20')
{
return true;
}
}

return false;
}

private static bool ContainsAsciiDigit(string input)
{
foreach (var c in input)

Check warning on line 183 in src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Loops should be simplified using the "Any" LINQ method

See more on https://sonarcloud.io/project/issues?id=microsoft_OpenAPI.NET&issues=AaII18Lx7keIBf9Hesxv&open=AaII18Lx7keIBf9Hesxv&pullRequest=3189
{
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
Loading