[PATCH 3 of 5] py3: wrap file object to write patch in native eol preserving byte-ness

Yuya Nishihara yuya at tcha.org
Sat Mar 10 06:28:05 EST 2018


# HG changeset patch
# User Yuya Nishihara <yuya at tcha.org>
# Date 1520343957 21600
#      Tue Mar 06 07:45:57 2018 -0600
# Node ID d472860cb611fb3f268ae48bd2870432387eca5b
# Parent  6c476e5b05b821b9e6b8da9de807ca45940b6fad
py3: wrap file object to write patch in native eol preserving byte-ness

diff --git a/mercurial/patch.py b/mercurial/patch.py
--- a/mercurial/patch.py
+++ b/mercurial/patch.py
@@ -1102,11 +1102,11 @@ all lines of the hunk are removed, then 
 the hunk is left unchanged.
 """)
                 (patchfd, patchfn) = tempfile.mkstemp(prefix="hg-editor-",
-                        suffix=".diff", text=True)
+                                                      suffix=".diff")
                 ncpatchfp = None
                 try:
                     # Write the initial patch
-                    f = os.fdopen(patchfd, r"w")
+                    f = util.nativeeolwriter(os.fdopen(patchfd, r'wb'))
                     chunk.header.write(f)
                     chunk.write(f)
                     f.write('\n'.join(['# ' + i for i in phelp.splitlines()]))
diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -2421,6 +2421,22 @@ bytecount = unitcountfn(
     (1, 1, _('%.0f bytes')),
     )
 
+class transformingwriter(object):
+    """Writable file wrapper to transform data by function"""
+
+    def __init__(self, fp, encode):
+        self._fp = fp
+        self._encode = encode
+
+    def close(self):
+        self._fp.close()
+
+    def flush(self):
+        self._fp.flush()
+
+    def write(self, data):
+        return self._fp.write(self._encode(data))
+
 # Matches a single EOL which can either be a CRLF where repeated CR
 # are removed or a LF. We do not care about old Macintosh files, so a
 # stray CR is an error.
@@ -2432,12 +2448,17 @@ def tolf(s):
 def tocrlf(s):
     return _eolre.sub('\r\n', s)
 
+def _crlfwriter(fp):
+    return transformingwriter(fp, tocrlf)
+
 if pycompat.oslinesep == '\r\n':
     tonativeeol = tocrlf
     fromnativeeol = tolf
+    nativeeolwriter = _crlfwriter
 else:
     tonativeeol = pycompat.identity
     fromnativeeol = pycompat.identity
+    nativeeolwriter = pycompat.identity
 
 def escapestr(s):
     # call underlying function of s.encode('string_escape') directly for


More information about the Mercurial-devel mailing list