Patchwork [3,of,9,V2] py3: proxy posixfile objects to re-add a useful 'name' attribute on Windows

login
register
mail settings
Submitter Matt Harbison
Date Sept. 25, 2018, 2:25 a.m.
Message ID <788eb3e31f3a6f5edca3.1537842336@Envy>
Download mbox | patch
Permalink /patch/35004/
State Accepted
Headers show

Comments

Matt Harbison - Sept. 25, 2018, 2:25 a.m.
# HG changeset patch
# User Matt Harbison <matt_harbison@yahoo.com>
# Date 1537574587 14400
#      Fri Sep 21 20:03:07 2018 -0400
# Node ID 788eb3e31f3a6f5edca3125cc08dc74e75cb936e
# Parent  bf1934083fa5c3a97492ea112ddb23e8ccf78294
py3: proxy posixfile objects to re-add a useful 'name' attribute on Windows

This file object is used in the vfs layer, so there are many errors like this:

    ...
      File "mercurial\localrepo.py", line 2569, in savecommitmessage
        return self.pathto(fp.name[len(self.root) + 1:])
    TypeError: 'int' object is not subscriptable

It looks like the 'name' value is actually the fileno() value, and the
documentation says the name parameter to PyFile_FromFd() is ignored. [1]  I
tried just assigning the attribute after osutil.posixfile() returns, but that
crashes saying that it's read-only.

[1] https://docs.python.org/3.6/c-api/file.html

Patch

diff --git a/mercurial/windows.py b/mercurial/windows.py
--- a/mercurial/windows.py
+++ b/mercurial/windows.py
@@ -123,11 +123,36 @@  class mixedfilemodewrapper(object):
         object.__setattr__(self, r'_lastop', self.OPREAD)
         return self._fp.readlines(*args, **kwargs)
 
+class fdproxy(object):
+    """Wraps osutil.posixfile() to override the name attribute to reflect the
+    underlying file name.
+    """
+    def __init__(self, name, fp):
+        self.name = name
+        self._fp = fp
+
+    def __enter__(self):
+        return self._fp.__enter__()
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        self._fp.__exit__(exc_type, exc_value, traceback)
+
+    def __iter__(self):
+        return iter(self._fp)
+
+    def __getattr__(self, name):
+        return getattr(self._fp, name)
+
 def posixfile(name, mode='r', buffering=-1):
     '''Open a file with even more POSIX-like semantics'''
     try:
         fp = osutil.posixfile(name, mode, buffering) # may raise WindowsError
 
+        # PyFile_FromFd() ignores the name, and seems to report fp.name as the
+        # underlying file descriptor.
+        if pycompat.ispy3:
+            fp = fdproxy(name, fp)
+
         # The position when opening in append mode is implementation defined, so
         # make it consistent with other platforms, which position at EOF.
         if 'a' in mode: