mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-09 21:04:17 +00:00
Refactor file opening
This commit is contained in:
parent
d16d04a4d7
commit
8bc4af45ba
1 changed files with 25 additions and 27 deletions
|
|
@ -129,9 +129,8 @@ 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))
|
||||||
|
|
@ -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__':
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue