Patchwork [1,of,6,v2] procutil: factor out conditional creation of LineBufferedWrapper

login
register
mail settings
Submitter Manuel Jacob
Date July 6, 2020, 12:03 p.m.
Message ID <2178c53039ac0366469d.1594036993@tmp>
Download mbox | patch
Permalink /patch/46630/
State Accepted
Headers show

Comments

Manuel Jacob - July 6, 2020, 12:03 p.m.
# HG changeset patch
# User Manuel Jacob <me@manueljacob.de>
# Date 1593857741 -7200
#      Sat Jul 04 12:15:41 2020 +0200
# Node ID 2178c53039ac0366469dd3f2d5eafecb9c34695f
# Parent  2bfbd7d2c204734616f15237894feb4b9eaa3c1f
# EXP-Topic stdio
procutil: factor out conditional creation of LineBufferedWrapper

At the same time, document the logic and generalize it to work on all Python
versions.
Yuya Nishihara - July 6, 2020, 12:56 p.m.
On Mon, 06 Jul 2020 14:03:13 +0200, Manuel Jacob wrote:
> # HG changeset patch
> # User Manuel Jacob <me@manueljacob.de>
> # Date 1593857741 -7200
> #      Sat Jul 04 12:15:41 2020 +0200
> # Node ID 2178c53039ac0366469dd3f2d5eafecb9c34695f
> # Parent  2bfbd7d2c204734616f15237894feb4b9eaa3c1f
> # EXP-Topic stdio
> procutil: factor out conditional creation of LineBufferedWrapper

Queued, thanks.

Patch

diff --git a/mercurial/utils/procutil.py b/mercurial/utils/procutil.py
--- a/mercurial/utils/procutil.py
+++ b/mercurial/utils/procutil.py
@@ -67,6 +67,18 @@ 
 io.BufferedIOBase.register(LineBufferedWrapper)
 
 
+def make_line_buffered(stream):
+    if pycompat.ispy3 and not isinstance(stream, io.BufferedIOBase):
+        # On Python 3, buffered streams can be expected to subclass
+        # BufferedIOBase. This is definitively the case for the streams
+        # initialized by the interpreter. For unbuffered streams, we don't need
+        # to emulate line buffering.
+        return stream
+    if isinstance(stream, LineBufferedWrapper):
+        return stream
+    return LineBufferedWrapper(stream)
+
+
 # glibc determines buffering on first write to stdout - if we replace a TTY
 # destined stdout with a pipe destined stdout (e.g. pager), we want line
 # buffering (or unbuffered, on Windows)
@@ -77,10 +89,7 @@ 
     elif pycompat.ispy3:
         # On Python 3, buffered binary streams can't be set line-buffered.
         # Therefore we have a wrapper that implements line buffering.
-        if isinstance(stdout, io.BufferedIOBase) and not isinstance(
-            stdout, LineBufferedWrapper
-        ):
-            stdout = LineBufferedWrapper(stdout)
+        stdout = make_line_buffered(stdout)
     else:
         stdout = os.fdopen(stdout.fileno(), 'wb', 1)