Skip to content

Commit b5e8eb5

Browse files
committed
Code to preserve original linefeeds (issue #121)
1 parent b9b4c9e commit b5e8eb5

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

libmodernize/main.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,35 @@
1717
from libmodernize import __version__
1818
from libmodernize.fixes import lib2to3_fix_names, six_fix_names, opt_in_fix_names
1919

20+
21+
class LFPreservingRefactoringTool(StdoutRefactoringTool):
22+
""" https://github.com/python-modernize/python-modernize/issues/121 """
23+
def write_file(self, new_text, filename, old_text, encoding):
24+
# detect linefeeds
25+
lineends = {'\n':0, '\r\n':0, '\r':0}
26+
lines = []
27+
for line in open(filename, 'rb'):
28+
if line.endswith('\r\n'):
29+
lineends['\r\n'] += 1
30+
elif line.endswith('\n'):
31+
lineends['\n'] += 1
32+
elif line.endswith('\r'):
33+
lineends['\r'] += 1
34+
lines.append(line.rstrip(\r\n))
35+
super(LFPreservingRefactoringTool, self).write_file(
36+
new_text, filename, old_text, encoding)
37+
# detect if line ends are consistent in source file
38+
if sum([bool(lineends[x]) for x in lineends]) == 1:
39+
# detect if line ends are different from system-specific
40+
newline = [x for x in lineends if lineends[x] != 0][0]
41+
if os.linesep != newline:
42+
with open(filename, 'wb') as f:
43+
for line in lines:
44+
f.write(line)
45+
self.log_debug('fixed %s linefeeds back to %s',
46+
filename, newline)
47+
48+
2049
usage = __doc__ + """\
2150
%s
2251
@@ -125,7 +154,7 @@ def main(args=None):
125154
else:
126155
requested = default_fixes
127156
fixer_names = requested.difference(unwanted_fixes)
128-
rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit),
157+
rt = LFPreservingRefactoringTool(sorted(fixer_names), flags, sorted(explicit),
129158
options.nobackups, not options.no_diffs)
130159

131160
# Refactor all files and directories passed as arguments

0 commit comments

Comments
 (0)