Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not escape slashes in single quoted strings #6190

Merged
merged 1 commit into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -96,21 +96,27 @@ fun String.decodeAsGraphQLTripleQuoted(): String {
}

/**
* https://spec.graphql.org/draft/#EscapedCharacter
* Escapes a single quoted string.
* The 2 mandatory characters to be escaped are `"` and `\`.
* For better readability, control codes are also escaped.
* Although `/` may be escaped, we leave it as is for better readability.
*
* See https://spec.graphql.org/draft/#sec-String-Value.Escape-Sequences.
* See https://en.wikipedia.org/wiki/List_of_Unicode_characters#Control_codes
*/
fun String.encodeToGraphQLSingleQuoted(): String {
return buildString {
this@encodeToGraphQLSingleQuoted.forEach { c ->
when (c) {
'\"' -> append("\\\"")
'\\' -> append("\\\\")
'/' -> append("\\/")
'\b' -> append("\\b")
'\u000C' -> append("\\t")
'\u000C' -> append("\\f")
'\n' -> append("\\n")
'\r' -> append("\\r")
'\t' -> append("\\t")
// TODO: handle range outside U+0020–U+FFFF
in '\u0000'..'\u001f' -> append("\\u00${c.code.toByte().hexString()}")
in '\u007f'..'\u009f' -> append("\\u00${c.code.toByte().hexString()}")
else -> append(c)
}
}
Expand All @@ -134,3 +140,8 @@ fun String.encodeToGraphQLTripleQuoted(): String {
}
}

private fun Byte.hexString(): String {
val hexArray = "0123456789abcdef"
val value = toInt()
return "${hexArray[value.ushr(4)]}${hexArray[value and 0x0F]}"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.apollographql.apollo.graphql.ast.test

import com.apollographql.apollo.ast.encodeToGraphQLSingleQuoted
import kotlin.test.Test
import kotlin.test.assertEquals

class StringTest {
@Test
fun slashesAreNotEscapedWhenWriting() {
assertEquals("rest/api/3/search", "rest/api/3/search".encodeToGraphQLSingleQuoted())
}

@Test
fun controlCodesAreEscaped() {
assertEquals("\\n\\u0003", "\n\u0003".encodeToGraphQLSingleQuoted())
}
}
Loading