ovsdbmonitor: add .desktop file
[openvswitch] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import os
5 import re
6 import sys
7
8 import ovs.json
9 import ovs.db.error
10 import ovs.db.schema
11
12 argv0 = sys.argv[0]
13
14 def parseSchema(filename):
15     return ovs.db.schema.IdlSchema.from_json(ovs.json.from_file(filename))
16
17 def annotateSchema(schemaFile, annotationFile):
18     schemaJson = ovs.json.from_file(schemaFile)
19     execfile(annotationFile, globals(), {"s": schemaJson})
20     ovs.json.to_stream(schemaJson, sys.stdout)
21
22 def constify(cType, const):
23     if (const and cType.endswith('*') and not cType.endswith('**')):
24         return 'const %s' % cType
25     else:
26         return cType
27
28 def cMembers(prefix, columnName, column, const):
29     type = column.type
30     if type.n_min == 1 and type.n_max == 1:
31         singleton = True
32         pointer = ''
33     else:
34         singleton = False
35         if type.is_optional_pointer():
36             pointer = ''
37         else:
38             pointer = '*'
39
40     if type.value:
41         key = {'name': "key_%s" % columnName,
42                'type': constify(type.key.toCType(prefix) + pointer, const),
43                'comment': ''}
44         value = {'name': "value_%s" % columnName,
45                  'type': constify(type.value.toCType(prefix) + pointer, const),
46                  'comment': ''}
47         members = [key, value]
48     else:
49         m = {'name': columnName,
50              'type': constify(type.key.toCType(prefix) + pointer, const),
51              'comment': type.cDeclComment()}
52         members = [m]
53
54     if not singleton and not type.is_optional_pointer():
55         members.append({'name': 'n_%s' % columnName,
56                         'type': 'size_t ',
57                         'comment': ''})
58     return members
59
60 def printCIDLHeader(schemaFile):
61     schema = parseSchema(schemaFile)
62     prefix = schema.idlPrefix
63     print '''\
64 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
65
66 #ifndef %(prefix)sIDL_HEADER
67 #define %(prefix)sIDL_HEADER 1
68
69 #include <stdbool.h>
70 #include <stddef.h>
71 #include <stdint.h>
72 #include "ovsdb-data.h"
73 #include "ovsdb-idl-provider.h"
74 #include "uuid.h"''' % {'prefix': prefix.upper()}
75
76     for tableName, table in sorted(schema.tables.iteritems()):
77         structName = "%s%s" % (prefix, tableName.lower())
78
79         print "\f"
80         print "/* %s table. */" % tableName
81         print "struct %s {" % structName
82         print "\tstruct ovsdb_idl_row header_;"
83         for columnName, column in sorted(table.columns.iteritems()):
84             print "\n\t/* %s column. */" % columnName
85             for member in cMembers(prefix, columnName, column, False):
86                 print "\t%(type)s%(name)s;%(comment)s" % member
87         print "};"
88
89         # Column indexes.
90         printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
91                    for columnName in sorted(table.columns)]
92                   + ["%s_N_COLUMNS" % structName.upper()])
93
94         print
95         for columnName in table.columns:
96             print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
97                 's': structName,
98                 'S': structName.upper(),
99                 'c': columnName,
100                 'C': columnName.upper()}
101
102         print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
103
104         print '''
105 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
106 const struct %(s)s *%(s)s_next(const struct %(s)s *);
107 #define %(S)s_FOR_EACH(ROW, IDL) \\
108         for ((ROW) = %(s)s_first(IDL); \\
109              (ROW); \\
110              (ROW) = %(s)s_next(ROW))
111 #define %(S)s_FOR_EACH_SAFE(ROW, NEXT, IDL) \\
112         for ((ROW) = %(s)s_first(IDL); \\
113              (ROW) ? ((NEXT) = %(s)s_next(ROW), 1) : 0; \\
114              (ROW) = (NEXT))
115
116 void %(s)s_delete(const struct %(s)s *);
117 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
118 ''' % {'s': structName, 'S': structName.upper()}
119
120         for columnName, column in sorted(table.columns.iteritems()):
121             print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
122
123         print """
124 /* Functions for fetching columns as \"struct ovsdb_datum\"s.  (This is
125    rarely useful.  More often, it is easier to access columns by using
126    the members of %(s)s directly.) */""" % {'s': structName}
127         for columnName, column in sorted(table.columns.iteritems()):
128             if column.type.value:
129                 valueParam = ', enum ovsdb_atomic_type value_type'
130             else:
131                 valueParam = ''
132             print 'const struct ovsdb_datum *%(s)s_get_%(c)s(const struct %(s)s *, enum ovsdb_atomic_type key_type%(v)s);' % {
133                 's': structName, 'c': columnName, 'v': valueParam}
134
135         print
136         for columnName, column in sorted(table.columns.iteritems()):
137
138             print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
139             args = ['%(type)s%(name)s' % member for member
140                     in cMembers(prefix, columnName, column, True)]
141             print '%s);' % ', '.join(args)
142
143     # Table indexes.
144     printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
145     print
146     for tableName in schema.tables:
147         print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
148             'p': prefix,
149             'P': prefix.upper(),
150             't': tableName.lower(),
151             'T': tableName.upper()}
152     print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
153
154     print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
155     print "\nvoid %sinit(void);" % prefix
156     print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
157
158 def printEnum(members):
159     if len(members) == 0:
160         return
161
162     print "\nenum {";
163     for member in members[:-1]:
164         print "    %s," % member
165     print "    %s" % members[-1]
166     print "};"
167
168 def printCIDLSource(schemaFile):
169     schema = parseSchema(schemaFile)
170     prefix = schema.idlPrefix
171     print '''\
172 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
173
174 #include <config.h>
175 #include %s
176 #include <assert.h>
177 #include <limits.h>
178 #include "ovsdb-data.h"
179 #include "ovsdb-error.h"
180
181 #ifdef __CHECKER__
182 /* Sparse dislikes sizeof(bool) ("warning: expression using sizeof bool"). */
183 enum { sizeof_bool = 1 };
184 #else
185 enum { sizeof_bool = sizeof(bool) };
186 #endif
187
188 static bool inited;
189 ''' % schema.idlHeader
190
191     # Cast functions.
192     for tableName, table in sorted(schema.tables.iteritems()):
193         structName = "%s%s" % (prefix, tableName.lower())
194         print '''
195 static struct %(s)s *
196 %(s)s_cast(const struct ovsdb_idl_row *row)
197 {
198     return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
199 }\
200 ''' % {'s': structName}
201
202
203     for tableName, table in sorted(schema.tables.iteritems()):
204         structName = "%s%s" % (prefix, tableName.lower())
205         print "\f"
206         print "/* %s table. */" % (tableName)
207
208         # Parse functions.
209         for columnName, column in sorted(table.columns.iteritems()):
210             print '''
211 static void
212 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
213 {
214     struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
215                                                 'c': columnName}
216
217             type = column.type
218             if type.value:
219                 keyVar = "row->key_%s" % columnName
220                 valueVar = "row->value_%s" % columnName
221             else:
222                 keyVar = "row->%s" % columnName
223                 valueVar = None
224
225             if (type.n_min == 1 and type.n_max == 1) or type.is_optional_pointer():
226                 print
227                 print "    assert(inited);"
228                 print "    if (datum->n >= 1) {"
229                 if not type.key.ref_table:
230                     print "        %s = datum->keys[0].%s;" % (keyVar, type.key.type.to_string())
231                 else:
232                     print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.key.ref_table.name.lower(), prefix, prefix.upper(), type.key.ref_table.name.upper())
233
234                 if valueVar:
235                     if type.value.ref_table:
236                         print "        %s = datum->values[0].%s;" % (valueVar, type.value.type.to_string())
237                     else:
238                         print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.value.ref_table.name.lower(), prefix, prefix.upper(), type.value.ref_table.name.upper())
239                 print "    } else {"
240                 print "        %s" % type.key.initCDefault(keyVar, type.n_min == 0)
241                 if valueVar:
242                     print "        %s" % type.value.initCDefault(valueVar, type.n_min == 0)
243                 print "    }"
244             else:
245                 if type.n_max != sys.maxint:
246                     print "    size_t n = MIN(%d, datum->n);" % type.n_max
247                     nMax = "n"
248                 else:
249                     nMax = "datum->n"
250                 print "    size_t i;"
251                 print
252                 print "    assert(inited);"
253                 print "    %s = NULL;" % keyVar
254                 if valueVar:
255                     print "    %s = NULL;" % valueVar
256                 print "    row->n_%s = 0;" % columnName
257                 print "    for (i = 0; i < %s; i++) {" % nMax
258                 refs = []
259                 if type.key.ref_table:
260                     print "        struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid));" % (prefix, type.key.ref_table.name.lower(), prefix, type.key.ref_table.name.lower(), prefix, prefix.upper(), type.key.ref_table.name.upper())
261                     keySrc = "keyRow"
262                     refs.append('keyRow')
263                 else:
264                     keySrc = "datum->keys[i].%s" % type.key.type.to_string()
265                 if type.value and type.value.ref_table:
266                     print "        struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid));" % (prefix, type.value.ref_table.name.lower(), prefix, type.value.ref_table.name.lower(), prefix, prefix.upper(), type.value.ref_table.name.upper())
267                     valueSrc = "valueRow"
268                     refs.append('valueRow')
269                 elif valueVar:
270                     valueSrc = "datum->values[i].%s" % type.value.type.to_string()
271                 if refs:
272                     print "        if (%s) {" % ' && '.join(refs)
273                     indent = "            "
274                 else:
275                     indent = "        "
276                 print "%sif (!row->n_%s) {" % (indent, columnName)
277
278                 # Special case for boolean types.  This is only here because
279                 # sparse does not like the "normal" case ("warning: expression
280                 # using sizeof bool").
281                 if type.key.type == ovs.db.types.BooleanType:
282                     sizeof = "sizeof_bool"
283                 else:
284                     sizeof = "sizeof *%s" % keyVar
285                 print "%s    %s = xmalloc(%s * %s);" % (indent, keyVar, nMax,
286                                                         sizeof)
287                 if valueVar:
288                     # Special case for boolean types (see above).
289                     if type.value.type == ovs.db.types.BooleanType:
290                         sizeof = " * sizeof_bool"
291                     else:
292                         sizeof = "sizeof *%s" % valueVar
293                     print "%s    %s = xmalloc(%s * %s);" % (indent, valueVar,
294                                                             nMax, sizeof)
295                 print "%s}" % indent
296                 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
297                 if valueVar:
298                     print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
299                 print "%srow->n_%s++;" % (indent, columnName)
300                 if refs:
301                     print "        }"
302                 print "    }"
303             print "}"
304
305         # Unparse functions.
306         for columnName, column in sorted(table.columns.iteritems()):
307             type = column.type
308             if (type.key.type == ovs.db.types.BooleanType and not type.value
309                 and type.n_min == 0 and type.n_max == 1):
310                 print '''
311 static void
312 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
313 {
314     /* Nothing to do. */
315 }''' % {'s': structName, 'c': columnName}
316             elif (type.n_min != 1 or type.n_max != 1) and not type.is_optional_pointer():
317                 print '''
318 static void
319 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
320 {
321     struct %(s)s *row = %(s)s_cast(row_);
322
323     assert(inited);''' % {'s': structName, 'c': columnName}
324                 if type.value:
325                     keyVar = "row->key_%s" % columnName
326                     valueVar = "row->value_%s" % columnName
327                 else:
328                     keyVar = "row->%s" % columnName
329                     valueVar = None
330                 print "    free(%s);" % keyVar
331                 if valueVar:
332                     print "    free(%s);" % valueVar
333                 print '}'
334             else:
335                 print '''
336 static void
337 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
338 {
339     /* Nothing to do. */
340 }''' % {'s': structName, 'c': columnName}
341
342         # First, next functions.
343         print '''
344 const struct %(s)s *
345 %(s)s_first(const struct ovsdb_idl *idl)
346 {
347     return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
348 }
349
350 const struct %(s)s *
351 %(s)s_next(const struct %(s)s *row)
352 {
353     return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
354 }''' % {'s': structName,
355         'p': prefix,
356         'P': prefix.upper(),
357         'T': tableName.upper()}
358
359         print '''
360 void
361 %(s)s_delete(const struct %(s)s *row)
362 {
363     ovsdb_idl_txn_delete(&row->header_);
364 }
365
366 struct %(s)s *
367 %(s)s_insert(struct ovsdb_idl_txn *txn)
368 {
369     return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s], NULL));
370 }
371 ''' % {'s': structName,
372        'p': prefix,
373        'P': prefix.upper(),
374        'T': tableName.upper()}
375
376         # Verify functions.
377         for columnName, column in sorted(table.columns.iteritems()):
378             print '''
379 void
380 %(s)s_verify_%(c)s(const struct %(s)s *row)
381 {
382     assert(inited);
383     ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
384 }''' % {'s': structName,
385         'S': structName.upper(),
386         'c': columnName,
387         'C': columnName.upper()}
388
389         # Get functions.
390         for columnName, column in sorted(table.columns.iteritems()):
391             if column.type.value:
392                 valueParam = ',\n\tenum ovsdb_atomic_type value_type OVS_UNUSED'
393                 valueType = '\n    assert(value_type == %s);' % column.type.value.toAtomicType()
394                 valueComment = "\n * 'value_type' must be %s." % column.type.value.toAtomicType()
395             else:
396                 valueParam = ''
397                 valueType = ''
398                 valueComment = ''
399             print """
400 /* Returns the %(c)s column's value in 'row' as a struct ovsdb_datum.
401  * This is useful occasionally: for example, ovsdb_datum_find_key() is an
402  * easier and more efficient way to search for a given key than implementing
403  * the same operation on the "cooked" form in 'row'.
404  *
405  * 'key_type' must be %(kt)s.%(vc)s
406  * (This helps to avoid silent bugs if someone changes %(c)s's
407  * type without updating the caller.)
408  *
409  * The caller must not modify or free the returned value.
410  *
411  * Various kinds of changes can invalidate the returned value: modifying
412  * 'column' within 'row', deleting 'row', or completing an ongoing transaction.
413  * If the returned value is needed for a long time, it is best to make a copy
414  * of it with ovsdb_datum_clone(). */
415 const struct ovsdb_datum *
416 %(s)s_get_%(c)s(const struct %(s)s *row,
417 \tenum ovsdb_atomic_type key_type OVS_UNUSED%(v)s)
418 {
419     assert(key_type == %(kt)s);%(vt)s
420     return ovsdb_idl_read(&row->header_, &%(s)s_col_%(c)s);
421 }""" % {'s': structName, 'c': columnName,
422        'kt': column.type.key.toAtomicType(),
423        'v': valueParam, 'vt': valueType, 'vc': valueComment}
424
425         # Set functions.
426         for columnName, column in sorted(table.columns.iteritems()):
427             type = column.type
428             print '\nvoid'
429             members = cMembers(prefix, columnName, column, True)
430             keyVar = members[0]['name']
431             nVar = None
432             valueVar = None
433             if type.value:
434                 valueVar = members[1]['name']
435                 if len(members) > 2:
436                     nVar = members[2]['name']
437             else:
438                 if len(members) > 1:
439                     nVar = members[1]['name']
440             print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
441                 {'s': structName, 'c': columnName,
442                  'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
443             print "{"
444             print "    struct ovsdb_datum datum;"
445             if type.n_min == 1 and type.n_max == 1:
446                 print
447                 print "    assert(inited);"
448                 print "    datum.n = 1;"
449                 print "    datum.keys = xmalloc(sizeof *datum.keys);"
450                 print "    " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
451                 if type.value:
452                     print "    datum.values = xmalloc(sizeof *datum.values);"
453                     print "    "+ type.value.copyCValue("datum.values[0].%s" % type.value.type.to_string(), valueVar)
454                 else:
455                     print "    datum.values = NULL;"
456             elif type.is_optional_pointer():
457                 print
458                 print "    assert(inited);"
459                 print "    if (%s) {" % keyVar
460                 print "        datum.n = 1;"
461                 print "        datum.keys = xmalloc(sizeof *datum.keys);"
462                 print "        " + type.key.copyCValue("datum.keys[0].%s" % type.key.type.to_string(), keyVar)
463                 print "    } else {"
464                 print "        datum.n = 0;"
465                 print "        datum.keys = NULL;"
466                 print "    }"
467                 print "    datum.values = NULL;"
468             else:
469                 print "    size_t i;"
470                 print
471                 print "    assert(inited);"
472                 print "    datum.n = %s;" % nVar
473                 print "    datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
474                 if type.value:
475                     print "    datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
476                 else:
477                     print "    datum.values = NULL;"
478                 print "    for (i = 0; i < %s; i++) {" % nVar
479                 print "        " + type.key.copyCValue("datum.keys[i].%s" % type.key.type.to_string(), "%s[i]" % keyVar)
480                 if type.value:
481                     print "        " + type.value.copyCValue("datum.values[i].%s" % type.value.type.to_string(), "%s[i]" % valueVar)
482                 print "    }"
483                 if type.value:
484                     valueType = type.value.toAtomicType()
485                 else:
486                     valueType = "OVSDB_TYPE_VOID"
487                 print "    ovsdb_datum_sort_unique(&datum, %s, %s);" % (
488                     type.key.toAtomicType(), valueType)
489             print "    ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
490                 % {'s': structName,
491                    'S': structName.upper(),
492                    'C': columnName.upper()}
493             print "}"
494
495         # Table columns.
496         print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
497             structName, structName.upper())
498         print """
499 static void\n%s_columns_init(void)
500 {
501     struct ovsdb_idl_column *c;\
502 """ % structName
503         for columnName, column in sorted(table.columns.iteritems()):
504             cs = "%s_col_%s" % (structName, columnName)
505             d = {'cs': cs, 'c': columnName, 's': structName}
506             print
507             print "    /* Initialize %(cs)s. */" % d
508             print "    c = &%(cs)s;" % d
509             print "    c->name = \"%(c)s\";" % d
510             print column.type.cInitType("    ", "c->type")
511             print "    c->parse = %(s)s_parse_%(c)s;" % d
512             print "    c->unparse = %(s)s_unparse_%(c)s;" % d
513         print "}"
514
515     # Table classes.
516     print "\f"
517     print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
518     for tableName, table in sorted(schema.tables.iteritems()):
519         structName = "%s%s" % (prefix, tableName.lower())
520         if table.is_root:
521             is_root = "true"
522         else:
523             is_root = "false"
524         print "    {\"%s\", %s," % (tableName, is_root)
525         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
526             structName, structName)
527         print "     sizeof(struct %s)}," % structName
528     print "};"
529
530     # IDL class.
531     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
532     print "    \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
533         schema.name, prefix, prefix)
534     print "};"
535
536     # global init function
537     print """
538 void
539 %sinit(void)
540 {
541     if (inited) {
542         return;
543     }
544     inited = true;
545 """ % prefix
546     for tableName, table in sorted(schema.tables.iteritems()):
547         structName = "%s%s" % (prefix, tableName.lower())
548         print "    %s_columns_init();" % structName
549     print "}"
550
551
552 def ovsdb_escape(string):
553     def escape(match):
554         c = match.group(0)
555         if c == '\0':
556             raise ovs.db.error.Error("strings may not contain null bytes")
557         elif c == '\\':
558             return '\\\\'
559         elif c == '\n':
560             return '\\n'
561         elif c == '\r':
562             return '\\r'
563         elif c == '\t':
564             return '\\t'
565         elif c == '\b':
566             return '\\b'
567         elif c == '\a':
568             return '\\a'
569         else:
570             return '\\x%02x' % ord(c)
571     return re.sub(r'["\\\000-\037]', escape, string)
572
573 def usage():
574     print """\
575 %(argv0)s: ovsdb schema compiler
576 usage: %(argv0)s [OPTIONS] COMMAND ARG...
577
578 The following commands are supported:
579   annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
580   c-idl-header IDL            print C header file for IDL
581   c-idl-source IDL            print C source file for IDL implementation
582   nroff IDL                   print schema documentation in nroff format
583
584 The following options are also available:
585   -h, --help                  display this help message
586   -V, --version               display version information\
587 """ % {'argv0': argv0}
588     sys.exit(0)
589
590 if __name__ == "__main__":
591     try:
592         try:
593             options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
594                                               ['directory',
595                                                'help',
596                                                'version'])
597         except getopt.GetoptError, geo:
598             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
599             sys.exit(1)
600
601         for key, value in options:
602             if key in ['-h', '--help']:
603                 usage()
604             elif key in ['-V', '--version']:
605                 print "ovsdb-idlc (Open vSwitch) @VERSION@"
606             elif key in ['-C', '--directory']:
607                 os.chdir(value)
608             else:
609                 sys.exit(0)
610
611         optKeys = [key for key, value in options]
612
613         if not args:
614             sys.stderr.write("%s: missing command argument "
615                              "(use --help for help)\n" % argv0)
616             sys.exit(1)
617
618         commands = {"annotate": (annotateSchema, 2),
619                     "c-idl-header": (printCIDLHeader, 1),
620                     "c-idl-source": (printCIDLSource, 1)}
621
622         if not args[0] in commands:
623             sys.stderr.write("%s: unknown command \"%s\" "
624                              "(use --help for help)\n" % (argv0, args[0]))
625             sys.exit(1)
626
627         func, n_args = commands[args[0]]
628         if len(args) - 1 != n_args:
629             sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
630                              "provided\n"
631                              % (argv0, args[0], n_args, len(args) - 1))
632             sys.exit(1)
633
634         func(*args[1:])
635     except ovs.db.error.Error, e:
636         sys.stderr.write("%s: %s\n" % (argv0, e))
637         sys.exit(1)
638
639 # Local variables:
640 # mode: python
641 # End: