|
17 | 17 | from libmodernize import __version__
|
18 | 18 | from libmodernize.fixes import lib2to3_fix_names, six_fix_names, opt_in_fix_names
|
19 | 19 |
|
| 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 | + |
20 | 49 | usage = __doc__ + """\
|
21 | 50 | %s
|
22 | 51 |
|
@@ -125,7 +154,7 @@ def main(args=None):
|
125 | 154 | else:
|
126 | 155 | requested = default_fixes
|
127 | 156 | fixer_names = requested.difference(unwanted_fixes)
|
128 |
| - rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit), |
| 157 | + rt = LFPreservingRefactoringTool(sorted(fixer_names), flags, sorted(explicit), |
129 | 158 | options.nobackups, not options.no_diffs)
|
130 | 159 |
|
131 | 160 | # Refactor all files and directories passed as arguments
|
|
0 commit comments