qapi: Factor open_output(), close_output() out of generators

Signed-off-by: Markus Armbruster <armbru@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
diff --git a/scripts/qapi-event.py b/scripts/qapi-event.py
index bc5ca4a..56bc602 100644
--- a/scripts/qapi-event.py
+++ b/scripts/qapi-event.py
@@ -11,8 +11,6 @@
 
 from ordereddict import OrderedDict
 from qapi import *
-import os
-import errno
 
 def _generate_event_api_name(event_name, params):
     api_name = "void qapi_event_send_%s(" % c_name(event_name).lower();
@@ -214,36 +212,9 @@
 ''')
     return ret
 
-
-# Start the real job
-
-c_file = 'qapi-event.c'
-h_file = 'qapi-event.h'
-
 (input_file, output_dir, do_c, do_h, prefix, dummy) = parse_command_line()
 
-c_file = output_dir + prefix + c_file
-h_file = output_dir + prefix + h_file
-
-try:
-    os.makedirs(output_dir)
-except os.error, e:
-    if e.errno != errno.EEXIST:
-        raise
-
-def maybe_open(really, name, opt):
-    if really:
-        return open(name, opt)
-    else:
-        import StringIO
-        return StringIO.StringIO()
-
-fdef = maybe_open(do_c, c_file, 'w')
-fdecl = maybe_open(do_h, h_file, 'w')
-
-fdef.write(mcgen('''
-/* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
-
+c_comment = '''
 /*
  * schema-defined QAPI event functions
  *
@@ -256,19 +227,8 @@
  * See the COPYING.LIB file in the top-level directory.
  *
  */
-
-#include "qemu-common.h"
-#include "%(header)s"
-#include "%(prefix)sqapi-visit.h"
-#include "qapi/qmp-output-visitor.h"
-#include "qapi/qmp-event.h"
-
-''',
-                 prefix=prefix, header=basename(h_file)))
-
-fdecl.write(mcgen('''
-/* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
-
+'''
+h_comment = '''
 /*
  * schema-defined QAPI event functions
  *
@@ -281,16 +241,29 @@
  * See the COPYING.LIB file in the top-level directory.
  *
  */
+'''
 
-#ifndef %(guard)s
-#define %(guard)s
+(fdef, fdecl) = open_output(output_dir, do_c, do_h, prefix,
+                            'qapi-event.c', 'qapi-event.h',
+                            c_comment, h_comment)
 
+fdef.write(mcgen('''
+#include "qemu-common.h"
+#include "%(prefix)sqapi-event.h"
+#include "%(prefix)sqapi-visit.h"
+#include "qapi/qmp-output-visitor.h"
+#include "qapi/qmp-event.h"
+
+''',
+                 prefix=prefix))
+
+fdecl.write(mcgen('''
 #include "qapi/error.h"
 #include "qapi/qmp/qdict.h"
 #include "%(prefix)sqapi-types.h"
 
 ''',
-                  prefix=prefix, guard=guardname(h_file)))
+                  prefix=prefix))
 
 exprs = parse_schema(input_file)
 
@@ -323,12 +296,4 @@
 ret = generate_event_enum_lookup(event_enum_name, event_enum_strings)
 fdef.write(ret)
 
-fdecl.write('''
-#endif
-''')
-
-fdecl.flush()
-fdecl.close()
-
-fdef.flush()
-fdef.close()
+close_output(fdef, fdecl)