[PATCH 2 of 7] make_file: always return a fresh file handle that can be closed

Dan Villiom Podlaski Christiansen danchr at gmail.com
Tue Dec 7 10:26:40 CST 2010


# HG changeset patch
# User Dan Villiom Podlaski Christiansen <danchr at gmail.com>
# Date 1291734496 -3600
# Node ID 255cfd26b031953721ac0d41d25203b304e61c2f
# Parent  e3187906974b4fa1b1ea4fe05a771a5e03e0b2c1
make_file: always return a fresh file handle that can be closed

Currently, cmdutil.make_file() will return a freshly made file handle,
except when given a pattern of '-'. If callers would want to close the
handle, they would have to make sure that it's neither sys.stdin or
sys.stdout. Instead, returning a duplicate of either of the two
ensures that make_file() lives up to its name and creates a new
file handle regardless of the input.

diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py
--- a/mercurial/cmdutil.py
+++ b/mercurial/cmdutil.py
@@ -233,7 +233,8 @@ def make_file(repo, pat, node=None,
     writable = 'w' in mode or 'a' in mode
 
     if not pat or pat == '-':
-        return writable and sys.stdout or sys.stdin
+        fp = writable and sys.stdout or sys.stdin
+        return os.fdopen(os.dup(fp.fileno()), mode)
     if hasattr(pat, 'write') and writable:
         return pat
     if hasattr(pat, 'read') and 'r' in mode:
diff --git a/tests/test-hook.t b/tests/test-hook.t
--- a/tests/test-hook.t
+++ b/tests/test-hook.t
@@ -73,8 +73,8 @@ test generic hooks
   [1]
   $ hg cat b
   pre-cat hook: HG_ARGS=cat b HG_OPTS={'rev': '', 'decode': None, 'exclude': [], 'output': '', 'include': []} HG_PATS=['b'] 
+  b
   post-cat hook: HG_ARGS=cat b HG_OPTS={'rev': '', 'decode': None, 'exclude': [], 'output': '', 'include': []} HG_PATS=['b'] HG_RESULT=0 
-  b
 
   $ cd ../b
   $ hg pull ../a


More information about the Mercurial-devel mailing list