[gobject-introspection] scanner: use open() as os.fdopen as context managers



commit ebe658542217c510f186dfc68956d51528d81fd6
Author: Dieter Verfaillie <dieterv optionexplicit be>
Date:   Sun Jul 5 10:54:16 2015 +0200

    scanner: use open() as os.fdopen as context managers
    
    Ensures files are correctly and immediately closed.
    
    https://bugzilla.gnome.org/show_bug.cgi?id=751926

 giscanner/cachestore.py  |    6 ++-
 giscanner/docmain.py     |    5 +--
 giscanner/docwriter.py   |    5 +--
 giscanner/dumper.py      |   75 ++++++++++++++++++++++------------------------
 giscanner/gdumpparser.py |   19 +++++------
 giscanner/scannermain.py |   14 ++++-----
 giscanner/utils.py       |   23 +++++--------
 7 files changed, 68 insertions(+), 79 deletions(-)
---
diff --git a/giscanner/cachestore.py b/giscanner/cachestore.py
index 7b465d8..bc5443d 100644
--- a/giscanner/cachestore.py
+++ b/giscanner/cachestore.py
@@ -64,7 +64,8 @@ class CacheStore(object):
         current_hash = _get_versionhash()
         version = os.path.join(self._directory, _CACHE_VERSION_FILENAME)
         try:
-            cache_hash = open(version).read()
+            with open(version, 'r') as version_file:
+                cache_hash = version_file.read()
         except IOError as e:
             # File does not exist
             if e.errno == errno.ENOENT:
@@ -137,7 +138,8 @@ class CacheStore(object):
 
         tmp_fd, tmp_filename = tempfile.mkstemp(prefix='g-ir-scanner-cache-')
         try:
-            cPickle.dump(data, os.fdopen(tmp_fd, 'w'))
+            with os.fdopen(tmp_fd, 'w') as tmp_file:
+                cPickle.dump(data, tmp_file)
         except IOError as e:
             # No space left on device
             if e.errno == errno.ENOSPC:
diff --git a/giscanner/docmain.py b/giscanner/docmain.py
index fdcda18..b5baf99 100644
--- a/giscanner/docmain.py
+++ b/giscanner/docmain.py
@@ -60,9 +60,8 @@ def doc_main(args):
     if args.write_sections:
         sections_file = generate_sections_file(transformer)
 
-        fp = open(args.output, 'w')
-        write_sections_file(fp, sections_file)
-        fp.close()
+        with open(args.output, 'w') as fp:
+            write_sections_file(fp, sections_file)
     else:
         writer = DocWriter(transformer, args.language)
         writer.write(args.output)
diff --git a/giscanner/docwriter.py b/giscanner/docwriter.py
index d888c81..86e11dd 100644
--- a/giscanner/docwriter.py
+++ b/giscanner/docwriter.py
@@ -953,6 +953,5 @@ class DocWriter(object):
 
         output_file_name = os.path.join(os.path.abspath(output),
                                         page_id + '.page')
-        fp = open(output_file_name, 'w')
-        fp.write(result)
-        fp.close()
+        with open(output_file_name, 'w') as fp:
+            fp.write(result)
diff --git a/giscanner/dumper.py b/giscanner/dumper.py
index 9423177..3a7ced6 100644
--- a/giscanner/dumper.py
+++ b/giscanner/dumper.py
@@ -110,44 +110,42 @@ class DumpCompiler(object):
                                       'gdump.c')
         if not os.path.isfile(gdump_path):
             raise SystemExit("Couldn't find %r" % (gdump_path, ))
-        gdump_file = open(gdump_path)
-        gdump_contents = gdump_file.read()
-        gdump_file.close()
+        with open(gdump_path) as gdump_file:
+            gdump_contents = gdump_file.read()
         tpl_args['gdump_include'] = gdump_contents
         tpl_args['init_sections'] = "\n".join(self._options.init_sections)
 
         c_path = self._generate_tempfile(tmpdir, '.c')
-        f = open(c_path, 'w')
-        f.write(_PROGRAM_TEMPLATE % tpl_args)
-
-        # We need to reference our get_type and error_quark functions
-        # to make sure they are pulled in at the linking stage if the
-        # library is a static library rather than a shared library.
-        if len(self._get_type_functions) > 0:
-            for func in self._get_type_functions:
-                f.write("extern GType " + func + "(void);\n")
-            f.write("GType (*GI_GET_TYPE_FUNCS_[])(void) = {\n")
-            first = True
-            for func in self._get_type_functions:
-                if first:
-                    first = False
-                else:
-                    f.write(",\n")
-                f.write("  " + func)
-            f.write("\n};\n")
-        if len(self._error_quark_functions) > 0:
-            for func in self._error_quark_functions:
-                f.write("extern GQuark " + func + "(void);\n")
-            f.write("GQuark (*GI_ERROR_QUARK_FUNCS_[])(void) = {\n")
-            first = True
-            for func in self._error_quark_functions:
-                if first:
-                    first = False
-                else:
-                    f.write(",\n")
-                f.write("  " + func)
-            f.write("\n};\n")
-        f.close()
+        with open(c_path, 'w') as f:
+            f.write(_PROGRAM_TEMPLATE % tpl_args)
+
+            # We need to reference our get_type and error_quark functions
+            # to make sure they are pulled in at the linking stage if the
+            # library is a static library rather than a shared library.
+            if len(self._get_type_functions) > 0:
+                for func in self._get_type_functions:
+                    f.write("extern GType " + func + "(void);\n")
+                f.write("GType (*GI_GET_TYPE_FUNCS_[])(void) = {\n")
+                first = True
+                for func in self._get_type_functions:
+                    if first:
+                        first = False
+                    else:
+                        f.write(",\n")
+                    f.write("  " + func)
+                f.write("\n};\n")
+            if len(self._error_quark_functions) > 0:
+                for func in self._error_quark_functions:
+                    f.write("extern GQuark " + func + "(void);\n")
+                f.write("GQuark (*GI_ERROR_QUARK_FUNCS_[])(void) = {\n")
+                first = True
+                for func in self._error_quark_functions:
+                    if first:
+                        first = False
+                    else:
+                        f.write(",\n")
+                    f.write("  " + func)
+                f.write("\n};\n")
 
         # Microsoft compilers generate intermediate .obj files
         # during compilation, unlike .o files like GCC and others
@@ -307,11 +305,10 @@ class DumpCompiler(object):
             # Create a temporary script file that
             # runs the command we want
             tf, tf_name = tempfile.mkstemp()
-            f = os.fdopen(tf, 'wb')
-            shellcontents = ' '.join([x.replace('\\', '/') for x in args])
-            fcontents = '#!/bin/sh\nunset PWD\n{}\n'.format(shellcontents)
-            f.write(fcontents)
-            f.close()
+            with os.fdopen(tf, 'wb') as f:
+                shellcontents = ' '.join([x.replace('\\', '/') for x in args])
+                fcontents = '#!/bin/sh\nunset PWD\n{}\n'.format(shellcontents)
+                f.write(fcontents)
             shell = utils.which(shell)
             args = [shell, tf_name.replace('\\', '/')]
         try:
diff --git a/giscanner/gdumpparser.py b/giscanner/gdumpparser.py
index b49ceef..179bbd8 100644
--- a/giscanner/gdumpparser.py
+++ b/giscanner/gdumpparser.py
@@ -145,16 +145,15 @@ class GDumpParser(object):
         """Load the library (or executable), returning an XML
 blob containing data gleaned from GObject's primitive introspection."""
         in_path = os.path.join(self._binary.tmpdir, 'functions.txt')
-        f = open(in_path, 'w')
-        for func in self._get_type_functions:
-            f.write('get-type:')
-            f.write(func)
-            f.write('\n')
-        for func in self._error_quark_functions:
-            f.write('error-quark:')
-            f.write(func)
-            f.write('\n')
-        f.close()
+        with open(in_path, 'w') as f:
+            for func in self._get_type_functions:
+                f.write('get-type:')
+                f.write(func)
+                f.write('\n')
+            for func in self._error_quark_functions:
+                f.write('error-quark:')
+                f.write(func)
+                f.write('\n')
         out_path = os.path.join(self._binary.tmpdir, 'dump.xml')
 
         args = []
diff --git a/giscanner/scannermain.py b/giscanner/scannermain.py
index fdc432d..89ec193 100755
--- a/giscanner/scannermain.py
+++ b/giscanner/scannermain.py
@@ -322,8 +322,8 @@ def extract_filelist(options):
     filenames = []
     if not os.path.exists(options.filelist):
         _error('%s: no such filelist file' % (options.filelist, ))
-    filelist_file = open(options.filelist, "r")
-    lines = filelist_file.readlines()
+    with open(options.filelist, "r") as filelist_file:
+        lines = filelist_file.readlines()
     for line in lines:
         # We don't support real C++ parsing yet, but we should be able
         # to understand C API implemented in C++ files.
@@ -443,14 +443,12 @@ def write_output(data, options):
         output = sys.stdout
     elif options.reparse_validate_gir:
         main_f, main_f_name = tempfile.mkstemp(suffix='.gir')
-        main_f = os.fdopen(main_f, 'w')
-        main_f.write(data)
-        main_f.close()
+        with os.fdopen(main_f, 'w') as main_f:
+            main_f.write(data)
 
         temp_f, temp_f_name = tempfile.mkstemp(suffix='.gir')
-        temp_f = os.fdopen(temp_f, 'w')
-        passthrough_gir(main_f_name, temp_f)
-        temp_f.close()
+        with os.fdopen(temp_f, 'w') as temp_f:
+            passthrough_gir(main_f_name, temp_f)
         if not utils.files_are_identical(main_f_name, temp_f_name):
             _error("Failed to re-parse gir file; scanned=%r passthrough=%r" % (
                 main_f_name, temp_f_name))
diff --git a/giscanner/utils.py b/giscanner/utils.py
index cffbec7..660081e 100644
--- a/giscanner/utils.py
+++ b/giscanner/utils.py
@@ -80,9 +80,8 @@ _libtool_pat = re.compile("dlname='([A-z0-9\.\-\+]+)'\n")
 
 
 def _extract_dlname_field(la_file):
-    f = open(la_file)
-    data = f.read()
-    f.close()
+    with open(la_file) as f:
+        data = f.read()
     m = _libtool_pat.search(data)
     if m:
         return m.groups()[0]
@@ -94,9 +93,8 @@ _libtool_libdir_pat = re.compile("libdir='([^']+)'")
 
 
 def _extract_libdir_field(la_file):
-    f = open(la_file)
-    data = f.read()
-    f.close()
+    with open(la_file) as f:
+        data = f.read()
     m = _libtool_libdir_pat.search(data)
     if m:
         return m.groups()[0]
@@ -166,16 +164,13 @@ def get_libtool_command(options):
 
 
 def files_are_identical(path1, path2):
-    f1 = open(path1)
-    f2 = open(path2)
-    buf1 = f1.read(8192)
-    buf2 = f2.read(8192)
-    while buf1 == buf2 and buf1 != '':
+    with open(path1) as f1, open(path2) as f2:
         buf1 = f1.read(8192)
         buf2 = f2.read(8192)
-    f1.close()
-    f2.close()
-    return buf1 == buf2
+        while buf1 == buf2 and buf1 != '':
+            buf1 = f1.read(8192)
+            buf2 = f2.read(8192)
+        return buf1 == buf2
 
 
 def cflag_real_include_path(cflag):


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]