Add option to discard deprecated fields (#997)
diff --git a/generator/nanopb_generator.py b/generator/nanopb_generator.py
index 24ca154..8394b66 100755
--- a/generator/nanopb_generator.py
+++ b/generator/nanopb_generator.py
@@ -1342,9 +1342,13 @@
 
         for index, f in enumerate(desc.field):
             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
+
             if field_options.type == nanopb_pb2.FT_IGNORE:
                 continue
 
+            if field_options.discard_deprecated and f.options.deprecated:
+                continue
+
             if field_options.descriptorsize > self.descriptorsize:
                 self.descriptorsize = field_options.descriptorsize
 
@@ -1920,6 +1924,9 @@
             if message_options.skip_message:
                 continue
 
+            if message_options.discard_deprecated and message.options.deprecated:
+                continue
+
             # Apply any configured typename mangling options
             message = copy.deepcopy(message)
             for field in message.field:
diff --git a/generator/proto/nanopb.proto b/generator/proto/nanopb.proto
index 18164e6..1a1cc98 100644
--- a/generator/proto/nanopb.proto
+++ b/generator/proto/nanopb.proto
@@ -178,6 +178,9 @@
   // Discard unused types that are automatically generated by protoc if they are not actually
   // needed. Currently this applies to map< > types when the field is ignored by options.
   optional bool discard_unused_automatic_types = 33 [default = true];
+
+  // Discard messages and fields marked with [deprecated = true] in the proto file.
+  optional bool discard_deprecated = 35 [default = false];
 }
 
 // Extensions to protoc 'Descriptor' type in order to define options
diff --git a/tests/options/options.proto b/tests/options/options.proto
index d5d3704..4355ced 100644
--- a/tests/options/options.proto
+++ b/tests/options/options.proto
@@ -125,3 +125,20 @@
     required Enum1 normal = 1;
     required Enum1 overridden = 2 [(nanopb).type_override = TYPE_UINT32];
 }
+
+// Deprecated field
+message DeprecatedFieldMessage
+{
+    option (nanopb_msgopt).discard_deprecated = true;
+    required int32 normal = 1;
+    required int32 discarded_deprecatedfield = 2 [deprecated = true];
+    required int32 kept_deprecatedfield = 3 [deprecated = true, (nanopb).discard_deprecated = false];
+}
+
+// Deprecated message
+message DeprecatedMessage
+{
+    option (nanopb_msgopt).discard_deprecated = true;
+    option deprecated = true;
+    required int32 deprecatedmessagefield = 1;
+}
diff --git a/tests/options/options_h.expected b/tests/options/options_h.expected
index 9cad227..062b643 100644
--- a/tests/options/options_h.expected
+++ b/tests/options/options_h.expected
@@ -21,4 +21,7 @@
 uint32_t overridden
 #define TypeOverrideMessage_init_default[ ]*\{_Enum1_MIN, 0\}
 #define TypeOverrideMessage_init_zero[ ]*\{_Enum1_MIN, 0\}
+! discarded_deprecatedfield
+kept_deprecatedfield
+! deprecatedmessagefield