Include the field tags in the generated .pb.h file.
[apps/agl-service-can-low-level.git] / generator / nanopb_generator.py
1 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
2 nanopb_version = "nanopb-0.2.2-dev"
3
4 try:
5     import google.protobuf.descriptor_pb2 as descriptor
6     import google.protobuf.text_format as text_format
7 except:
8     print
9     print "*************************************************************"
10     print "*** Could not import the Google protobuf Python libraries ***"
11     print "*** Try installing package 'python-protobuf' or similar.  ***"
12     print "*************************************************************"
13     print
14     raise
15
16 try:
17     import nanopb_pb2
18 except:
19     print
20     print "***************************************************************"
21     print "*** Could not import the precompiled nanopb_pb2.py.         ***"
22     print "*** Run 'make' in the 'generator' folder to update the file.***"
23     print "***************************************************************"
24     print
25     raise
26
27
28
29
30
31
32 # ---------------------------------------------------------------------------
33 #                     Generation of single fields
34 # ---------------------------------------------------------------------------
35
36 import time
37 import os.path
38
39 # Values are tuple (c type, pb type)
40 FieldD = descriptor.FieldDescriptorProto
41 datatypes = {
42     FieldD.TYPE_BOOL:       ('bool',     'BOOL'),
43     FieldD.TYPE_DOUBLE:     ('double',   'DOUBLE'),
44     FieldD.TYPE_FIXED32:    ('uint32_t', 'FIXED32'),
45     FieldD.TYPE_FIXED64:    ('uint64_t', 'FIXED64'),
46     FieldD.TYPE_FLOAT:      ('float',    'FLOAT'),
47     FieldD.TYPE_INT32:      ('int32_t',  'INT32'),
48     FieldD.TYPE_INT64:      ('int64_t',  'INT64'),
49     FieldD.TYPE_SFIXED32:   ('int32_t',  'SFIXED32'),
50     FieldD.TYPE_SFIXED64:   ('int64_t',  'SFIXED64'),
51     FieldD.TYPE_SINT32:     ('int32_t',  'SINT32'),
52     FieldD.TYPE_SINT64:     ('int64_t',  'SINT64'),
53     FieldD.TYPE_UINT32:     ('uint32_t', 'UINT32'),
54     FieldD.TYPE_UINT64:     ('uint64_t', 'UINT64')
55 }
56
57 class Names:
58     '''Keeps a set of nested names and formats them to C identifier.'''
59     def __init__(self, parts = ()):
60         if isinstance(parts, Names):
61             parts = parts.parts
62         self.parts = tuple(parts)
63     
64     def __str__(self):
65         return '_'.join(self.parts)
66
67     def __add__(self, other):
68         if isinstance(other, (str, unicode)):
69             return Names(self.parts + (other,))
70         elif isinstance(other, tuple):
71             return Names(self.parts + other)
72         else:
73             raise ValueError("Name parts should be of type str")
74     
75     def __eq__(self, other):
76         return isinstance(other, Names) and self.parts == other.parts
77     
78 def names_from_type_name(type_name):
79     '''Parse Names() from FieldDescriptorProto type_name'''
80     if type_name[0] != '.':
81         raise NotImplementedError("Lookup of non-absolute type names is not supported")
82     return Names(type_name[1:].split('.'))
83
84 class Enum:
85     def __init__(self, names, desc, enum_options):
86         '''desc is EnumDescriptorProto'''
87         
88         self.options = enum_options
89         self.names = names + desc.name
90         
91         if enum_options.long_names:
92             self.values = [(self.names + x.name, x.number) for x in desc.value]            
93         else:
94             self.values = [(names + x.name, x.number) for x in desc.value] 
95         
96         self.value_longnames = [self.names + x.name for x in desc.value]
97     
98     def __str__(self):
99         result = 'typedef enum _%s {\n' % self.names
100         result += ',\n'.join(["    %s = %d" % x for x in self.values])
101         result += '\n} %s;' % self.names
102         return result
103
104 class Field:
105     def __init__(self, struct_name, desc, field_options):
106         '''desc is FieldDescriptorProto'''
107         self.tag = desc.number
108         self.struct_name = struct_name
109         self.name = desc.name
110         self.default = None
111         self.max_size = None
112         self.max_count = None
113         self.array_decl = ""
114         
115         # Parse field options
116         if field_options.HasField("max_size"):
117             self.max_size = field_options.max_size
118         
119         if field_options.HasField("max_count"):
120             self.max_count = field_options.max_count
121         
122         if desc.HasField('default_value'):
123             self.default = desc.default_value
124            
125         # Check field rules, i.e. required/optional/repeated.
126         can_be_static = True
127         if desc.label == FieldD.LABEL_REQUIRED:
128             self.rules = 'REQUIRED'
129         elif desc.label == FieldD.LABEL_OPTIONAL:
130             self.rules = 'OPTIONAL'
131         elif desc.label == FieldD.LABEL_REPEATED:
132             self.rules = 'REPEATED'
133             if self.max_count is None:
134                 can_be_static = False
135             else:
136                 self.array_decl = '[%d]' % self.max_count
137         else:
138             raise NotImplementedError(desc.label)
139         
140         # Decide the C data type to use in the struct.
141         if datatypes.has_key(desc.type):
142             self.ctype, self.pbtype = datatypes[desc.type]
143         elif desc.type == FieldD.TYPE_ENUM:
144             self.pbtype = 'ENUM'
145             self.ctype = names_from_type_name(desc.type_name)
146             if self.default is not None:
147                 self.default = self.ctype + self.default
148         elif desc.type == FieldD.TYPE_STRING:
149             self.pbtype = 'STRING'
150             if self.max_size is None:
151                 can_be_static = False
152             else:
153                 self.ctype = 'char'
154                 self.array_decl += '[%d]' % self.max_size
155         elif desc.type == FieldD.TYPE_BYTES:
156             self.pbtype = 'BYTES'
157             if self.max_size is None:
158                 can_be_static = False
159             else:
160                 self.ctype = self.struct_name + self.name + 't'
161         elif desc.type == FieldD.TYPE_MESSAGE:
162             self.pbtype = 'MESSAGE'
163             self.ctype = self.submsgname = names_from_type_name(desc.type_name)
164         else:
165             raise NotImplementedError(desc.type)
166         
167         if field_options.type == nanopb_pb2.FT_DEFAULT:
168             if can_be_static:
169                 field_options.type = nanopb_pb2.FT_STATIC
170             else:
171                 field_options.type = nanopb_pb2.FT_CALLBACK
172         
173         if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
174             raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
175         
176         if field_options.type == nanopb_pb2.FT_STATIC:
177             self.allocation = 'STATIC'
178         elif field_options.type == nanopb_pb2.FT_CALLBACK:
179             self.allocation = 'CALLBACK'
180             self.ctype = 'pb_callback_t'
181             self.array_decl = ''
182         else:
183             raise NotImplementedError(field_options.type)
184     
185     def __cmp__(self, other):
186         return cmp(self.tag, other.tag)
187     
188     def __str__(self):
189         if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
190             result = '    bool has_' + self.name + ';\n'
191         elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
192             result = '    size_t ' + self.name + '_count;\n'
193         else:
194             result = ''
195         result += '    %s %s%s;' % (self.ctype, self.name, self.array_decl)
196         return result
197     
198     def types(self):
199         '''Return definitions for any special types this field might need.'''
200         if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
201             result = 'typedef struct {\n'
202             result += '    size_t size;\n'
203             result += '    uint8_t bytes[%d];\n' % self.max_size
204             result += '} %s;\n' % self.ctype
205         else:
206             result = None
207         return result
208     
209     def default_decl(self, declaration_only = False):
210         '''Return definition for this field's default value.'''
211         if self.default is None:
212             return None
213
214         ctype, default = self.ctype, self.default
215         array_decl = ''
216         
217         if self.pbtype == 'STRING':
218             if self.allocation != 'STATIC':
219                 return None # Not implemented
220         
221             array_decl = '[%d]' % self.max_size
222             default = str(self.default).encode('string_escape')
223             default = default.replace('"', '\\"')
224             default = '"' + default + '"'
225         elif self.pbtype == 'BYTES':
226             if self.allocation != 'STATIC':
227                 return None # Not implemented
228
229             data = self.default.decode('string_escape')
230             data = ['0x%02x' % ord(c) for c in data]
231             default = '{%d, {%s}}' % (len(data), ','.join(data))
232         
233         if declaration_only:
234             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
235         else:
236             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
237     
238     def tags(self):
239         '''Return the #define for the tag number of this field.'''
240         identifier = '%s_%s_tag' % (self.struct_name, self.name)
241         return '#define %-40s %d\n' % (identifier, self.tag)
242     
243     def pb_field_t(self, prev_field_name):
244         '''Return the pb_field_t initializer to use in the constant array.
245         prev_field_name is the name of the previous field or None.
246         '''
247         result  = '    PB_FIELD(%3d, ' % self.tag
248         result += '%-8s, ' % self.pbtype
249         result += '%s, ' % self.rules
250         result += '%s, ' % self.allocation
251         result += '%s, ' % self.struct_name
252         result += '%s, ' % self.name
253         result += '%s, ' % (prev_field_name or self.name)
254         
255         if self.pbtype == 'MESSAGE':
256             result += '&%s_fields)' % self.submsgname
257         elif self.default is None:
258             result += '0)'
259         elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
260             result += '0)' # Arbitrary size default values not implemented
261         else:
262             result += '&%s_default)' % (self.struct_name + self.name)
263         
264         return result
265     
266     def largest_field_value(self):
267         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
268         Returns numeric value or a C-expression for assert.'''
269         if self.pbtype == 'MESSAGE':
270             if self.rules == 'REPEATED' and self.allocation == 'STATIC':
271                 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
272             else:
273                 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
274
275         return max(self.tag, self.max_size, self.max_count)        
276
277
278
279
280
281
282 # ---------------------------------------------------------------------------
283 #                   Generation of messages (structures)
284 # ---------------------------------------------------------------------------
285
286
287 class Message:
288     def __init__(self, names, desc, message_options):
289         self.name = names
290         self.fields = []
291         
292         for f in desc.field:
293             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
294             if field_options.type != nanopb_pb2.FT_IGNORE:
295                 self.fields.append(Field(self.name, f, field_options))
296         
297         self.packed = message_options.packed_struct
298         self.ordered_fields = self.fields[:]
299         self.ordered_fields.sort()
300
301     def get_dependencies(self):
302         '''Get list of type names that this structure refers to.'''
303         return [str(field.ctype) for field in self.fields]
304     
305     def __str__(self):
306         result = 'typedef struct _%s {\n' % self.name
307
308         if not self.ordered_fields:
309             # Empty structs are not allowed in C standard.
310             # Therefore add a dummy field if an empty message occurs.
311             result += '    uint8_t dummy_field;'
312
313         result += '\n'.join([str(f) for f in self.ordered_fields])
314         result += '\n}'
315         
316         if self.packed:
317             result += ' pb_packed'
318         
319         result += ' %s;' % self.name
320         
321         if self.packed:
322             result = 'PB_PACKED_STRUCT_START\n' + result
323             result += '\nPB_PACKED_STRUCT_END'
324         
325         return result
326     
327     def types(self):
328         result = ""
329         for field in self.fields:
330             types = field.types()
331             if types is not None:
332                 result += types + '\n'
333         return result
334     
335     def default_decl(self, declaration_only = False):
336         result = ""
337         for field in self.fields:
338             default = field.default_decl(declaration_only)
339             if default is not None:
340                 result += default + '\n'
341         return result
342
343     def fields_declaration(self):
344         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
345         return result
346
347     def fields_definition(self):
348         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
349         
350         prev = None
351         for field in self.ordered_fields:
352             result += field.pb_field_t(prev)
353             result += ',\n'
354             prev = field.name
355         
356         result += '    PB_LAST_FIELD\n};'
357         return result
358
359
360
361
362
363
364 # ---------------------------------------------------------------------------
365 #                    Processing of entire .proto files
366 # ---------------------------------------------------------------------------
367
368
369 def iterate_messages(desc, names = Names()):
370     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
371     if hasattr(desc, 'message_type'):
372         submsgs = desc.message_type
373     else:
374         submsgs = desc.nested_type
375     
376     for submsg in submsgs:
377         sub_names = names + submsg.name
378         yield sub_names, submsg
379         
380         for x in iterate_messages(submsg, sub_names):
381             yield x
382
383 def parse_file(fdesc, file_options):
384     '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
385     
386     enums = []
387     messages = []
388     
389     if fdesc.package:
390         base_name = Names(fdesc.package.split('.'))
391     else:
392         base_name = Names()
393     
394     for enum in fdesc.enum_type:
395         enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
396         enums.append(Enum(base_name, enum, enum_options))
397     
398     for names, message in iterate_messages(fdesc, base_name):
399         message_options = get_nanopb_suboptions(message, file_options, names)
400         messages.append(Message(names, message, message_options))
401         for enum in message.enum_type:
402             enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
403             enums.append(Enum(names, enum, enum_options))
404     
405     # Fix field default values where enum short names are used.
406     for enum in enums:
407         if not enum.options.long_names:
408             for message in messages:
409                 for field in message.fields:
410                     if field.default in enum.value_longnames:
411                         idx = enum.value_longnames.index(field.default)
412                         field.default = enum.values[idx][0]
413     
414     return enums, messages
415
416 def toposort2(data):
417     '''Topological sort.
418     From http://code.activestate.com/recipes/577413-topological-sort/
419     This function is under the MIT license.
420     '''
421     for k, v in data.items():
422         v.discard(k) # Ignore self dependencies
423     extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
424     data.update(dict([(item, set()) for item in extra_items_in_deps]))
425     while True:
426         ordered = set(item for item,dep in data.items() if not dep)
427         if not ordered:
428             break
429         for item in sorted(ordered):
430             yield item
431         data = dict([(item, (dep - ordered)) for item,dep in data.items()
432                 if item not in ordered])
433     assert not data, "A cyclic dependency exists amongst %r" % data
434
435 def sort_dependencies(messages):
436     '''Sort a list of Messages based on dependencies.'''
437     dependencies = {}
438     message_by_name = {}
439     for message in messages:
440         dependencies[str(message.name)] = set(message.get_dependencies())
441         message_by_name[str(message.name)] = message
442     
443     for msgname in toposort2(dependencies):
444         if msgname in message_by_name:
445             yield message_by_name[msgname]
446
447 def make_identifier(headername):
448     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
449     result = ""
450     for c in headername.upper():
451         if c.isalnum():
452             result += c
453         else:
454             result += '_'
455     return result
456
457 def generate_header(dependencies, headername, enums, messages, options):
458     '''Generate content for a header file.
459     Generates strings, which should be concatenated and stored to file.
460     '''
461     
462     yield '/* Automatically generated nanopb header */\n'
463     yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
464     
465     symbol = make_identifier(headername)
466     yield '#ifndef _PB_%s_\n' % symbol
467     yield '#define _PB_%s_\n' % symbol
468     try:
469         yield options.libformat % ('pb.h')
470     except TypeError:
471         # no %s specified - use whatever was passed in as options.libformat
472         yield options.libformat
473     yield '\n'
474     
475     for dependency in dependencies:
476         noext = os.path.splitext(dependency)[0]
477         yield options.genformat % (noext + '.' + options.extension + '.h')
478         yield '\n'
479
480     yield '#ifdef __cplusplus\n'
481     yield 'extern "C" {\n'
482     yield '#endif\n\n'
483     
484     yield '/* Enum definitions */\n'
485     for enum in enums:
486         yield str(enum) + '\n\n'
487     
488     yield '/* Struct definitions */\n'
489     for msg in sort_dependencies(messages):
490         yield msg.types()
491         yield str(msg) + '\n\n'
492         
493     yield '/* Default values for struct fields */\n'
494     for msg in messages:
495         yield msg.default_decl(True)
496     yield '\n'
497     
498     yield '/* Field tags (for use in manual encoding/decoding) */\n'
499     for msg in sort_dependencies(messages):
500         for field in msg.fields:
501             yield field.tags()
502     yield '\n'
503     
504     yield '/* Struct field encoding specification for nanopb */\n'
505     for msg in messages:
506         yield msg.fields_declaration() + '\n'
507     
508     yield '\n#ifdef __cplusplus\n'
509     yield '} /* extern "C" */\n'
510     yield '#endif\n'
511     
512     # End of header
513     yield '\n#endif\n'
514
515 def generate_source(headername, enums, messages):
516     '''Generate content for a source file.'''
517     
518     yield '/* Automatically generated nanopb constant definitions */\n'
519     yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
520     yield options.genformat % (headername)
521     yield '\n'
522     
523     for msg in messages:
524         yield msg.default_decl(False)
525     
526     yield '\n\n'
527     
528     for msg in messages:
529         yield msg.fields_definition() + '\n\n'
530         
531     if messages:
532         count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
533         largest_msg = max(messages, key = count_required_fields)
534         largest_count = count_required_fields(largest_msg)
535         if largest_count > 64:
536             yield '\n/* Check that missing required fields will be properly detected */\n'
537             yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
538             yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
539             yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
540             yield '#endif\n'
541     
542     # Add checks for numeric limits
543     worst = 0
544     worst_field = ''
545     checks = []
546     checks_msgnames = []
547     for msg in messages:
548         checks_msgnames.append(msg.name)
549         for field in msg.fields:
550             status = field.largest_field_value()
551             if isinstance(status, (str, unicode)):
552                 checks.append(status)
553             elif status > worst:
554                 worst = status
555                 worst_field = str(field.struct_name) + '.' + str(field.name)
556
557     if worst > 255 or checks:
558         yield '\n/* Check that field information fits in pb_field_t */\n'
559         
560         if worst < 65536:
561             yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
562             if worst > 255:
563                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
564             else:
565                 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
566                 msgs = '_'.join(str(n) for n in checks_msgnames)
567                 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
568             yield '#endif\n\n'
569         
570         if worst > 65535 or checks:
571             yield '#if !defined(PB_FIELD_32BIT)\n'
572             if worst > 65535:
573                 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
574             else:
575                 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
576                 msgs = '_'.join(str(n) for n in checks_msgnames)
577                 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
578             yield '#endif\n'
579     
580     # Add check for sizeof(double)
581     has_double = False
582     for msg in messages:
583         for field in msg.fields:
584             if field.ctype == 'double':
585                 has_double = True
586     
587     if has_double:
588         yield '\n'
589         yield '/* On some platforms (such as AVR), double is really float.\n'
590         yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
591         yield ' * To get rid of this error, remove any double fields from your .proto.\n'
592         yield ' */\n'
593         yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
594     
595     yield '\n'
596
597 # ---------------------------------------------------------------------------
598 #                    Options parsing for the .proto files
599 # ---------------------------------------------------------------------------
600
601 from fnmatch import fnmatch
602
603 def read_options_file(infile):
604     '''Parse a separate options file to list:
605         [(namemask, options), ...]
606     '''
607     results = []
608     for line in infile:
609         line = line.strip()
610         if not line or line.startswith('//') or line.startswith('#'):
611             continue
612         
613         parts = line.split(None, 1)
614         opts = nanopb_pb2.NanoPBOptions()
615         text_format.Merge(parts[1], opts)
616         results.append((parts[0], opts))
617
618     return results
619
620 class Globals:
621     '''Ugly global variables, should find a good way to pass these.'''
622     verbose_options = False
623     separate_options = []
624
625 def get_nanopb_suboptions(subdesc, options, name):
626     '''Get copy of options, and merge information from subdesc.'''
627     new_options = nanopb_pb2.NanoPBOptions()
628     new_options.CopyFrom(options)
629     
630     # Handle options defined in a separate file
631     dotname = '.'.join(name.parts)
632     for namemask, options in Globals.separate_options:
633         if fnmatch(dotname, namemask):
634             new_options.MergeFrom(options)
635     
636     # Handle options defined in .proto
637     if isinstance(subdesc.options, descriptor.FieldOptions):
638         ext_type = nanopb_pb2.nanopb
639     elif isinstance(subdesc.options, descriptor.FileOptions):
640         ext_type = nanopb_pb2.nanopb_fileopt
641     elif isinstance(subdesc.options, descriptor.MessageOptions):
642         ext_type = nanopb_pb2.nanopb_msgopt
643     elif isinstance(subdesc.options, descriptor.EnumOptions):
644         ext_type = nanopb_pb2.nanopb_enumopt
645     else:
646         raise Exception("Unknown options type")
647     
648     if subdesc.options.HasExtension(ext_type):
649         ext = subdesc.options.Extensions[ext_type]
650         new_options.MergeFrom(ext)
651     
652     if Globals.verbose_options:
653         print "Options for " + dotname + ":"
654         print text_format.MessageToString(new_options)
655     
656     return new_options
657
658
659 # ---------------------------------------------------------------------------
660 #                         Command line interface
661 # ---------------------------------------------------------------------------
662
663 import sys
664 import os.path    
665 from optparse import OptionParser
666
667 optparser = OptionParser(
668     usage = "Usage: nanopb_generator.py [options] file.pb ...",
669     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
670              "Output will be written to file.pb.h and file.pb.c.")
671 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
672     help="Exclude file from generated #include list.")
673 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
674     help="Set extension to use instead of 'pb' for generated files. [default: %default]")
675 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
676     help="Set name of a separate generator options file.")
677 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
678     metavar="FORMAT", default='#include "%s"\n',
679     help="Set format string to use for including other .pb.h files. [default: %default]")
680 optparser.add_option("-L", "--library-include-format", dest="libformat",
681     metavar="FORMAT", default='#include <%s>\n',
682     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
683 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
684     help="Don't print anything except errors.")
685 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
686     help="Print more information.")
687 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
688     help="Set generator option (max_size, max_count etc.).")
689
690 def process(filenames, options):
691     '''Process the files given on the command line.'''
692     
693     if not filenames:
694         optparser.print_help()
695         return False
696     
697     if options.quiet:
698         options.verbose = False
699
700     Globals.verbose_options = options.verbose
701     
702     toplevel_options = nanopb_pb2.NanoPBOptions()
703     for s in options.settings:
704         text_format.Merge(s, toplevel_options)
705     
706     for filename in filenames:
707         data = open(filename, 'rb').read()
708         fdesc = descriptor.FileDescriptorSet.FromString(data)
709         
710         # Check if any separate options are specified
711         try:
712             optfilename = options.options_file % os.path.splitext(filename)[0]
713         except TypeError:
714             # No %s specified, use the filename as-is
715             optfilename = options.options_file
716         
717         if options.verbose:
718             print 'Reading options from ' + optfilename
719         
720         if os.path.isfile(optfilename):
721             Globals.separate_options = read_options_file(open(optfilename, "rU"))
722         else:
723             Globals.separate_options = []
724         
725         # Parse the file
726         file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options, Names([filename]))
727         enums, messages = parse_file(fdesc.file[0], file_options)
728         
729         noext = os.path.splitext(filename)[0]
730         headername = noext + '.' + options.extension + '.h'
731         sourcename = noext + '.' + options.extension + '.c'
732         headerbasename = os.path.basename(headername)
733         
734         if not options.quiet:
735             print "Writing to " + headername + " and " + sourcename
736         
737         # List of .proto files that should not be included in the C header file
738         # even if they are mentioned in the source .proto.
739         excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
740         dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
741         
742         header = open(headername, 'w')
743         for part in generate_header(dependencies, headerbasename, enums, messages, options):
744             header.write(part)
745
746         source = open(sourcename, 'w')
747         for part in generate_source(headerbasename, enums, messages):
748             source.write(part)
749
750     return True
751
752 if __name__ == '__main__':
753     options, filenames = optparser.parse_args()
754     status = process(filenames, options)
755     
756     if not status:
757         sys.exit(1)
758