From cb2dc696713bb2adab293fbec6470064ce23c8ee Mon Sep 17 00:00:00 2001 From: Dilanka Kaushal Hewage <234629294+r3vpwnx@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:42:27 -0500 Subject: [PATCH] Escape .proto comments emitted as docstrings get_comment() copied comment text verbatim into a triple-quoted docstring, so a comment containing """ ended the docstring and the rest of the line became code in the generated module, which ran on import. Escape backslashes and double quotes before emitting the docstring. Fixes #684 --- src/betterproto/plugin/models.py | 5 +++++ .../documentation_escaping/documentation_escaping.proto | 9 +++++++++ tests/test_documentation_escaping.py | 7 +++++++ 3 files changed, 21 insertions(+) create mode 100644 tests/inputs/documentation_escaping/documentation_escaping.proto create mode 100644 tests/test_documentation_escaping.py diff --git a/src/betterproto/plugin/models.py b/src/betterproto/plugin/models.py index e330e6884..1f6f977d0 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 000000000..787ebd703 --- /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 000000000..4acbd9930 --- /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__