Skip to content
Open
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
5 changes: 5 additions & 0 deletions src/betterproto/plugin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}"""'
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
}
7 changes: 7 additions & 0 deletions tests/test_documentation_escaping.py
Original file line number Diff line number Diff line change
@@ -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__
Loading