changeset 30482:39d13b8c101d

py3: bulk replace sys.stdin/out/err by util's Almost all sys.stdin/out/err in hgext/ and mercurial/ are replaced by util's. There are a few exceptions: - lsprof.py and statprof.py are untouched since they are a kind of vendor code and they never import mercurial modules right now. - ui._readline() needs to replace sys.stdin and stdout to pass them to raw_input(). We'll need another workaround here.
author Yuya Nishihara <yuya@tcha.org>
date Thu, 20 Oct 2016 23:53:36 +0900
parents 277f4fe6d01a
children b02e210a6817
files hgext/chgserver.py hgext/pager.py mercurial/cmdutil.py mercurial/commandserver.py mercurial/dispatch.py mercurial/hgweb/wsgicgi.py mercurial/hook.py mercurial/keepalive.py mercurial/ui.py mercurial/util.py mercurial/wireproto.py
diffstat 11 files changed, 45 insertions(+), 48 deletions(-) [+]
line wrap: on
line diff
--- a/hgext/chgserver.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/hgext/chgserver.py	Thu Oct 20 23:53:36 2016 +0900
@@ -232,7 +232,7 @@
             # these situations and will behave differently (write to stdout).
             if (any(s[1] for s in self._bufferstates)
                 or not util.safehasattr(self.fout, 'fileno')
-                or self.fout.fileno() != sys.stdout.fileno()):
+                or self.fout.fileno() != util.stdout.fileno()):
                 return super(chgui, self).system(cmd, environ, cwd, onerr,
                                                  errprefix)
             # copied from mercurial/util.py:system()
--- a/hgext/pager.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/hgext/pager.py	Thu Oct 20 23:53:36 2016 +0900
@@ -84,19 +84,19 @@
 def _runpager(ui, p):
     pager = subprocess.Popen(p, shell=True, bufsize=-1,
                              close_fds=util.closefds, stdin=subprocess.PIPE,
-                             stdout=sys.stdout, stderr=sys.stderr)
+                             stdout=util.stdout, stderr=util.stderr)
 
     # back up original file objects and descriptors
     olduifout = ui.fout
-    oldstdout = sys.stdout
-    stdoutfd = os.dup(sys.stdout.fileno())
-    stderrfd = os.dup(sys.stderr.fileno())
+    oldstdout = util.stdout
+    stdoutfd = os.dup(util.stdout.fileno())
+    stderrfd = os.dup(util.stderr.fileno())
 
     # create new line-buffered stdout so that output can show up immediately
-    ui.fout = sys.stdout = newstdout = os.fdopen(sys.stdout.fileno(), 'wb', 1)
-    os.dup2(pager.stdin.fileno(), sys.stdout.fileno())
-    if ui._isatty(sys.stderr):
-        os.dup2(pager.stdin.fileno(), sys.stderr.fileno())
+    ui.fout = util.stdout = newstdout = os.fdopen(util.stdout.fileno(), 'wb', 1)
+    os.dup2(pager.stdin.fileno(), util.stdout.fileno())
+    if ui._isatty(util.stderr):
+        os.dup2(pager.stdin.fileno(), util.stderr.fileno())
 
     @atexit.register
     def killpager():
@@ -104,13 +104,13 @@
             signal.signal(signal.SIGINT, signal.SIG_IGN)
         pager.stdin.close()
         ui.fout = olduifout
-        sys.stdout = oldstdout
+        util.stdout = oldstdout
         # close new stdout while it's associated with pager; otherwise stdout
         # fd would be closed when newstdout is deleted
         newstdout.close()
         # restore original fds: stdout is open again
-        os.dup2(stdoutfd, sys.stdout.fileno())
-        os.dup2(stderrfd, sys.stderr.fileno())
+        os.dup2(stdoutfd, util.stdout.fileno())
+        os.dup2(stderrfd, util.stderr.fileno())
         pager.wait()
 
 def uisetup(ui):
--- a/mercurial/cmdutil.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/cmdutil.py	Thu Oct 20 23:53:36 2016 +0900
@@ -888,8 +888,8 @@
                 raise error.Abort(_('invalid value for --daemon-postexec: %s')
                                   % inst)
         util.hidewindow()
-        sys.stdout.flush()
-        sys.stderr.flush()
+        util.stdout.flush()
+        util.stderr.flush()
 
         nullfd = os.open(os.devnull, os.O_RDWR)
         logfilefd = nullfd
--- a/mercurial/commandserver.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/commandserver.py	Thu Oct 20 23:53:36 2016 +0900
@@ -15,7 +15,6 @@
 import signal
 import socket
 import struct
-import sys
 import traceback
 
 from .i18n import _
@@ -304,8 +303,8 @@
     ui.flush()
     newfiles = []
     nullfd = os.open(os.devnull, os.O_RDWR)
-    for f, sysf, mode in [(ui.fin, sys.stdin, 'rb'),
-                          (ui.fout, sys.stdout, 'wb')]:
+    for f, sysf, mode in [(ui.fin, util.stdin, 'rb'),
+                          (ui.fout, util.stdout, 'wb')]:
         if f is sysf:
             newfd = os.dup(f.fileno())
             os.dup2(nullfd, f.fileno())
--- a/mercurial/dispatch.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/dispatch.py	Thu Oct 20 23:53:36 2016 +0900
@@ -97,7 +97,7 @@
     elif req.ui:
         ferr = req.ui.ferr
     else:
-        ferr = sys.stderr
+        ferr = util.stderr
 
     try:
         if not req.ui:
--- a/mercurial/hgweb/wsgicgi.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/hgweb/wsgicgi.py	Thu Oct 20 23:53:36 2016 +0900
@@ -11,7 +11,6 @@
 from __future__ import absolute_import
 
 import os
-import sys
 
 from .. import (
     util,
@@ -22,8 +21,8 @@
 )
 
 def launch(application):
-    util.setbinary(sys.stdin)
-    util.setbinary(sys.stdout)
+    util.setbinary(util.stdin)
+    util.setbinary(util.stdout)
 
     environ = dict(os.environ.iteritems())
     environ.setdefault('PATH_INFO', '')
@@ -33,12 +32,12 @@
         if environ['PATH_INFO'].startswith(scriptname):
             environ['PATH_INFO'] = environ['PATH_INFO'][len(scriptname):]
 
-    stdin = sys.stdin
+    stdin = util.stdin
     if environ.get('HTTP_EXPECT', '').lower() == '100-continue':
-        stdin = common.continuereader(stdin, sys.stdout.write)
+        stdin = common.continuereader(stdin, util.stdout.write)
 
     environ['wsgi.input'] = stdin
-    environ['wsgi.errors'] = sys.stderr
+    environ['wsgi.errors'] = util.stderr
     environ['wsgi.version'] = (1, 0)
     environ['wsgi.multithread'] = False
     environ['wsgi.multiprocess'] = True
@@ -51,7 +50,7 @@
 
     headers_set = []
     headers_sent = []
-    out = sys.stdout
+    out = util.stdout
 
     def write(data):
         if not headers_set:
--- a/mercurial/hook.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/hook.py	Thu Oct 20 23:53:36 2016 +0900
@@ -209,11 +209,11 @@
         for hname, cmd in hooks:
             if oldstdout == -1 and _redirect:
                 try:
-                    stdoutno = sys.stdout.fileno()
-                    stderrno = sys.stderr.fileno()
+                    stdoutno = util.stdout.fileno()
+                    stderrno = util.stderr.fileno()
                     # temporarily redirect stdout to stderr, if possible
                     if stdoutno >= 0 and stderrno >= 0:
-                        sys.stdout.flush()
+                        util.stdout.flush()
                         oldstdout = os.dup(stdoutno)
                         os.dup2(stderrno, stdoutno)
                 except (OSError, AttributeError):
@@ -255,10 +255,10 @@
             # The stderr is fully buffered on Windows when connected to a pipe.
             # A forcible flush is required to make small stderr data in the
             # remote side available to the client immediately.
-            sys.stderr.flush()
+            util.stderr.flush()
     finally:
         if _redirect and oldstdout >= 0:
-            sys.stdout.flush()  # write hook output to stderr fd
+            util.stdout.flush()  # write hook output to stderr fd
             os.dup2(oldstdout, stdoutno)
             os.close(oldstdout)
 
--- a/mercurial/keepalive.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/keepalive.py	Thu Oct 20 23:53:36 2016 +0900
@@ -660,14 +660,14 @@
 def comp(N, url):
     print('  making %i connections to:\n  %s' % (N, url))
 
-    sys.stdout.write('  first using the normal urllib handlers')
+    util.stdout.write('  first using the normal urllib handlers')
     # first use normal opener
     opener = urlreq.buildopener()
     urlreq.installopener(opener)
     t1 = fetch(N, url)
     print('  TIME: %.3f s' % t1)
 
-    sys.stdout.write('  now using the keepalive handler       ')
+    util.stdout.write('  now using the keepalive handler       ')
     # now install the keepalive handler and try again
     opener = urlreq.buildopener(HTTPHandler())
     urlreq.installopener(opener)
@@ -712,11 +712,11 @@
     i = 20
     print("  waiting %i seconds for the server to close the connection" % i)
     while i > 0:
-        sys.stdout.write('\r  %2i' % i)
-        sys.stdout.flush()
+        util.stdout.write('\r  %2i' % i)
+        util.stdout.flush()
         time.sleep(1)
         i -= 1
-    sys.stderr.write('\r')
+    util.stderr.write('\r')
 
     print("  fetching the file a second time")
     fo = urlreq.urlopen(url)
--- a/mercurial/ui.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/ui.py	Thu Oct 20 23:53:36 2016 +0900
@@ -130,9 +130,9 @@
 
             self.httppasswordmgrdb = src.httppasswordmgrdb
         else:
-            self.fout = sys.stdout
-            self.ferr = sys.stderr
-            self.fin = sys.stdin
+            self.fout = util.stdout
+            self.ferr = util.stderr
+            self.fin = util.stdin
 
             # shared read-only environment
             self.environ = os.environ
--- a/mercurial/util.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/util.py	Thu Oct 20 23:53:36 2016 +0900
@@ -986,7 +986,7 @@
     if environ is None:
         environ = {}
     try:
-        sys.stdout.flush()
+        stdout.flush()
     except Exception:
         pass
     def py2shell(val):
@@ -2759,9 +2759,9 @@
         finally:
             elapsed = time.time() - start
             _timenesting[0] -= indent
-            sys.stderr.write('%s%s: %s\n' %
-                             (' ' * _timenesting[0], func.__name__,
-                              timecount(elapsed)))
+            stderr.write('%s%s: %s\n' %
+                         (' ' * _timenesting[0], func.__name__,
+                          timecount(elapsed)))
     return wrapper
 
 _sizeunits = (('m', 2**20), ('k', 2**10), ('g', 2**30),
@@ -2826,7 +2826,7 @@
             else:
                 yield line % (fnmax, fnln, func)
 
-def debugstacktrace(msg='stacktrace', skip=0, f=sys.stderr, otherf=sys.stdout):
+def debugstacktrace(msg='stacktrace', skip=0, f=stderr, otherf=stdout):
     '''Writes a message to f (stderr) with a nicely formatted stacktrace.
     Skips the 'skip' last entries. By default it will flush stdout first.
     It can be used everywhere and intentionally does not require an ui object.
--- a/mercurial/wireproto.py	Thu Oct 20 23:40:24 2016 +0900
+++ b/mercurial/wireproto.py	Thu Oct 20 23:53:36 2016 +0900
@@ -10,7 +10,6 @@
 import hashlib
 import itertools
 import os
-import sys
 import tempfile
 
 from .i18n import _
@@ -575,8 +574,8 @@
             opts[k] = others[k]
             del others[k]
     if others:
-        sys.stderr.write("warning: %s ignored unexpected arguments %s\n"
-                         % (cmd, ",".join(others)))
+        util.stderr.write("warning: %s ignored unexpected arguments %s\n"
+                          % (cmd, ",".join(others)))
     return opts
 
 def bundle1allowed(repo, action):
@@ -907,11 +906,11 @@
             try:
                 raise
             except error.Abort:
-                # The old code we moved used sys.stderr directly.
+                # The old code we moved used util.stderr directly.
                 # We did not change it to minimise code change.
                 # This need to be moved to something proper.
                 # Feel free to do it.
-                sys.stderr.write("abort: %s\n" % exc)
+                util.stderr.write("abort: %s\n" % exc)
                 return pushres(0)
             except error.PushRaced:
                 return pusherr(str(exc))