[PATCH 6 of 8 v2] blackbox: avoid creating multiple file handles for a single log

timeless timeless at mozdev.org
Mon Feb 8 01:15:08 EST 2016


# HG changeset patch
# User timeless <timeless at mozdev.org>
# Date 1454514091 0
#      Wed Feb 03 15:41:31 2016 +0000
# Node ID c10b56801049483531e531f0f4d2533fb987f8b3
# Parent  99aa1e5f3b7e24afe97954d95a5107858888240e
blackbox: avoid creating multiple file handles for a single log

There are multiple ui objects in Mercurial that can relate to a repository,
before this change, each one would have its own file pointer, which
results in unfortunate logging behavior.

Also, any log rotation results would be bad because only the
active blackboxui object's file pointer would be refreshed.

diff --git a/hgext/blackbox.py b/hgext/blackbox.py
--- a/hgext/blackbox.py
+++ b/hgext/blackbox.py
@@ -42,6 +42,22 @@
 testedwith = 'internal'
 lastblackbox = None
 
+filehandles = {}
+
+def _openlog(vfs):
+    path = vfs.join('blackbox.log')
+    if path in filehandles:
+        return filehandles[path]
+    filehandles[path] = fp = vfs('blackbox.log', 'a')
+    filehandles[fp] = path
+    return fp
+
+def _closelog(fp):
+    path = filehandles[fp]
+    del filehandles[fp]
+    del filehandles[path]
+    fp.close()
+
 def wrapui(ui):
     class blackboxui(ui.__class__):
         @util.propertycache
@@ -64,20 +80,20 @@
                         self.debug("warning: cannot rename '%s' to '%s': %s\n" %
                                    (newpath, oldpath, err.strerror))
 
-            fp = self._bbvfs('blackbox.log', 'a')
+            fp = _openlog(self._bbvfs)
             maxsize = self.configbytes('blackbox', 'maxsize', 1048576)
             if maxsize > 0:
                 st = self._bbvfs.fstat(fp)
                 if st.st_size >= maxsize:
                     path = fp.name
-                    fp.close()
+                    _closelog(fp)
                     maxfiles = self.configint('blackbox', 'maxfiles', 7)
                     for i in xrange(maxfiles - 1, 1, -1):
                         rotate(oldpath='%s.%d' % (path, i - 1),
                                newpath='%s.%d' % (path, i))
                     rotate(oldpath=path,
                            newpath=maxfiles > 0 and path + '.1')
-                    fp = self._bbvfs('blackbox.log', 'a')
+                    fp = _openlog(self._bbvfs)
             return fp
 
         def log(self, event, *msg, **opts):


More information about the Mercurial-devel mailing list