ui: remove urllib2 from being imported early
authorKyle Lippincott <spectral@google.com>
Sun, 12 Feb 2017 03:06:38 -0800
changeset 30945 8b83b626fb1e
parent 30944 b7e073ae44c4
child 30946 7103122495e2
ui: remove urllib2 from being imported early Before this change, urllib2 was brought in when constructing the ui object, and that added ~5ms on my Linux workstation to the hg startup time for every command, bringing the time for 'HGRCPATH=/dev/null hg root' from 46ms to 40ms. Now, we construct a single proxy object per initial ui creation (so that if the ui is copied they share the object), but defer the actual instantiation of it and the import of urllib2 until it's needed. # no-check-commit
mercurial/ui.py
--- a/mercurial/ui.py	Mon Feb 06 23:57:32 2017 -0500
+++ b/mercurial/ui.py	Sun Feb 12 03:06:38 2017 -0800
@@ -94,6 +94,24 @@
 # pager =""",
 }
 
+
+class httppasswordmgrdbproxy(object):
+    """Delays loading urllib2 until it's needed."""
+    def __init__(self):
+        self._mgr = None
+
+    def _get_mgr(self):
+        if self._mgr is None:
+            self._mgr = urlreq.httppasswordmgrwithdefaultrealm()
+        return self._mgr
+
+    def add_password(self, *args, **kwargs):
+        return self._get_mgr().add_password(*args, **kwargs)
+
+    def find_user_password(self, *args, **kwargs):
+        return self._get_mgr().find_user_password(*args, **kwargs)
+
+
 class ui(object):
     def __init__(self, src=None):
         """Create a fresh new ui object if no src given
@@ -145,7 +163,7 @@
             # shared read-only environment
             self.environ = encoding.environ
 
-            self.httppasswordmgrdb = urlreq.httppasswordmgrwithdefaultrealm()
+            self.httppasswordmgrdb = httppasswordmgrdbproxy()
 
         allowed = self.configlist('experimental', 'exportableenviron')
         if '*' in allowed:
@@ -172,7 +190,7 @@
         """Clear internal state that shouldn't persist across commands"""
         if self._progbar:
             self._progbar.resetstate()  # reset last-print time of progress bar
-        self.httppasswordmgrdb = urlreq.httppasswordmgrwithdefaultrealm()
+        self.httppasswordmgrdb = httppasswordmgrdbproxy()
 
     def formatter(self, topic, opts):
         return formatter.formatter(self, topic, opts)