Refactor file opening

This commit is contained in:
Morgan Courbet 2017-07-09 11:10:10 +02:00
parent d16d04a4d7
commit 8bc4af45ba
No known key found for this signature in database
GPG key ID: 467299D324A21B24

View file

@ -129,30 +129,29 @@ def _check_filenames(filenames):
def _detect_line_ending(filename): def _detect_line_ending(filename):
f = open(filename, 'rb') with open(filename, 'rb') as f:
buf = f.read() buf = f.read()
f.close()
crlf_nb = len(LineEnding.CRLF.regex.findall(buf)) crlf_nb = len(LineEnding.CRLF.regex.findall(buf))
lf_nb = len(LineEnding.LF.regex.findall(buf)) lf_nb = len(LineEnding.LF.regex.findall(buf))
crlf_found = crlf_nb > 0 crlf_found = crlf_nb > 0
lf_found = lf_nb > 0 lf_found = lf_nb > 0
logging.debug('_detect_line_ending: crlf_nb = %d, lf_nb = %d, ' logging.debug('_detect_line_ending: crlf_nb = %d, lf_nb = %d, '
'crlf_found = %s, lf_found = %s', 'crlf_found = %s, lf_found = %s',
crlf_nb, lf_nb, crlf_found, lf_found) crlf_nb, lf_nb, crlf_found, lf_found)
if crlf_nb == lf_nb: if crlf_nb == lf_nb:
return MixedLineDetection.UNKNOWN return MixedLineDetection.UNKNOWN
if crlf_found ^ lf_found: if crlf_found ^ lf_found:
return MixedLineDetection.NOT_MIXED return MixedLineDetection.NOT_MIXED
if crlf_nb > lf_nb: if crlf_nb > lf_nb:
return MixedLineDetection.MIXED_MOSTLY_CRLF return MixedLineDetection.MIXED_MOSTLY_CRLF
else: else:
return MixedLineDetection.MIXED_MOSTLY_LF return MixedLineDetection.MIXED_MOSTLY_LF
def _process_no_fix(filenames): def _process_no_fix(filenames):
@ -222,17 +221,16 @@ def _process_fix_force(filenames, line_ending_enum):
def _convert_line_ending(filename, line_ending): def _convert_line_ending(filename, line_ending):
# read the file # read the file
fin = open(filename, 'rb') with open(filename, 'rb+') as f:
bufin = fin.read() bufin = f.read()
fin.close()
# convert line ending # convert line ending
bufout = ANY_LINE_ENDING_PATTERN.sub(line_ending, bufin) bufout = ANY_LINE_ENDING_PATTERN.sub(line_ending, bufin)
# write the result in the file # write the result in the file
fout = open(filename, 'wb') f.seek(0)
fout.write(bufout) f.write(bufout)
fout.close() f.truncate()
if __name__ == '__main__': if __name__ == '__main__':