From 759fd91388235d7f23f2621d7b8e962cded51781 Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Mon, 15 May 2023 17:19:17 -0700 Subject: [PATCH] Internal change PiperOrigin-RevId: 532274191 --- src/google/protobuf/text_format.cc | 34 +++++++++++++++++++++++++++--- src/google/protobuf/text_format.h | 7 ++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/google/protobuf/text_format.cc b/src/google/protobuf/text_format.cc index ea3ed1a4f5..f064b0f479 100644 --- a/src/google/protobuf/text_format.cc +++ b/src/google/protobuf/text_format.cc @@ -2527,6 +2527,10 @@ void TextFormat::Printer::PrintField(const Message& message, PrintFieldName(message, field_index, count, reflection, field, generator); if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + if (TryRedactFieldValue(message, field, generator, + /*insert_value_separator=*/true)) { + return; + } const FastFieldValuePrinter* printer = GetFieldPrinter(field); const Message& sub_message = field->is_repeated() @@ -2607,9 +2611,8 @@ void TextFormat::Printer::PrintFieldValue(const Message& message, << "Index must be -1 for non-repeated fields"; const FastFieldValuePrinter* printer = GetFieldPrinter(field); - if (redact_debug_string_ && field->options().debug_redact()) { - IncrementRedactedFieldCounter(); - generator->PrintString("[REDACTED]"); + if (TryRedactFieldValue(message, field, generator, + /*insert_value_separator=*/false)) { return; } @@ -2829,6 +2832,31 @@ void TextFormat::Printer::PrintUnknownFields( } } +bool TextFormat::Printer::TryRedactFieldValue( + const Message& message, const FieldDescriptor* field, + BaseTextGenerator* generator, bool insert_value_separator) const { + auto do_redact = [&](absl::string_view replacement) { + IncrementRedactedFieldCounter(); + if (insert_value_separator) { + generator->PrintMaybeWithMarker(MarkerToken(), ": "); + } + generator->PrintString(replacement); + if (insert_value_separator) { + if (single_line_mode_) { + generator->PrintLiteral(" "); + } else { + generator->PrintLiteral("\n"); + } + } + }; + + if (redact_debug_string_ && field->options().debug_redact()) { + do_redact("[REDACTED]"); + return true; + } + return false; +} + } // namespace protobuf } // namespace google diff --git a/src/google/protobuf/text_format.h b/src/google/protobuf/text_format.h index e14e788593..71488247a3 100644 --- a/src/google/protobuf/text_format.h +++ b/src/google/protobuf/text_format.h @@ -492,6 +492,13 @@ class PROTOBUF_EXPORT TextFormat { bool PrintAny(const Message& message, BaseTextGenerator* generator) const; + // Try to redact a field value based on the annotations associated with + // the field. This function returns true if it redacts the field value. + bool TryRedactFieldValue(const Message& message, + const FieldDescriptor* field, + BaseTextGenerator* generator, + bool insert_value_separator) const; + const FastFieldValuePrinter* GetFieldPrinter( const FieldDescriptor* field) const { auto it = custom_printers_.find(field);