diff --git a/src/betterproto/plugin/models.py b/src/betterproto/plugin/models.py index e330e688..1f6f977d 100644 --- a/src/betterproto/plugin/models.py +++ b/src/betterproto/plugin/models.py @@ -178,6 +178,11 @@ def get_comment( # We don't add this space to the generated file. lines = [line[1:] if line and line[0] == " " else line for line in lines] + # The comment is emitted inside a triple-quoted docstring, so escape + # backslashes and double quotes: otherwise a comment containing """ + # would end the docstring and the rest would become code. + lines = [line.replace("\\", "\\\\").replace('"', '\\"') for line in lines] + # This is a field, message, enum, service, or method if len(lines) == 1 and len(lines[0]) < 79 - indent - 6: return f'{pad}"""{lines[0]}"""' diff --git a/tests/inputs/documentation_escaping/documentation_escaping.proto b/tests/inputs/documentation_escaping/documentation_escaping.proto new file mode 100644 index 00000000..787ebd70 --- /dev/null +++ b/tests/inputs/documentation_escaping/documentation_escaping.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; +package documentation_escaping; + +// Ends a docstring early: """; raise RuntimeError("comment escaped the docstring"); """ +// A "quoted" word, a trailing quote" and a backslash \ in a comment. +message Test { + // Short: """ + uint32 x = 1; +} diff --git a/tests/test_documentation_escaping.py b/tests/test_documentation_escaping.py new file mode 100644 index 00000000..4acbd993 --- /dev/null +++ b/tests/test_documentation_escaping.py @@ -0,0 +1,7 @@ +def test_comment_cannot_close_docstring() -> None: + # Importing the module would raise if a comment had escaped the docstring. + from .output_betterproto.documentation_escaping import Test + + assert Test.__doc__ is not None + assert '"""; raise RuntimeError("comment escaped the docstring"); """' in Test.__doc__ + assert 'A "quoted" word, a trailing quote" and a backslash \\ in a comment.' in Test.__doc__