Skip to content

Commit 13d528c

Browse files
Lukasz Boldysasottile
authored andcommitted
Preserve line ending when running autoupdate
1 parent 2960549 commit 13d528c

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

pre_commit/commands/autoupdate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _original_lines(
9393
retry: bool = False,
9494
) -> Tuple[List[str], List[int]]:
9595
"""detect `rev:` lines or reformat the file"""
96-
with open(path) as f:
96+
with open(path, newline='') as f:
9797
original = f.read()
9898

9999
lines = original.splitlines(True)
@@ -126,7 +126,7 @@ def _write_new_config(path: str, rev_infos: List[Optional[RevInfo]]) -> None:
126126
comment = match[4]
127127
lines[idx] = f'{match[1]}rev:{match[2]}{new_rev}{comment}{match[5]}'
128128

129-
with open(path, 'w') as f:
129+
with open(path, 'w', newline='') as f:
130130
f.write(''.join(lines))
131131

132132

tests/commands/autoupdate_test.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,45 @@ def test_does_not_reformat(tmpdir, out_of_date, store):
263263
assert cfg.read() == expected
264264

265265

266+
def test_does_not_change_mixed_endlines_read(up_to_date, tmpdir, store):
267+
fmt = (
268+
'repos:\n'
269+
'- repo: {}\n'
270+
' rev: {} # definitely the version I want!\r\n'
271+
' hooks:\r\n'
272+
' - id: foo\n'
273+
' # These args are because reasons!\r\n'
274+
' args: [foo, bar, baz]\r\n'
275+
)
276+
cfg = tmpdir.join(C.CONFIG_FILE)
277+
278+
expected = fmt.format(up_to_date, git.head_rev(up_to_date)).encode()
279+
cfg.write_binary(expected)
280+
281+
assert autoupdate(str(cfg), store, freeze=False, tags_only=False) == 0
282+
assert cfg.read_binary() == expected
283+
284+
285+
def test_does_not_change_mixed_endlines_write(tmpdir, out_of_date, store):
286+
fmt = (
287+
'repos:\n'
288+
'- repo: {}\n'
289+
' rev: {} # definitely the version I want!\r\n'
290+
' hooks:\r\n'
291+
' - id: foo\n'
292+
' # These args are because reasons!\r\n'
293+
' args: [foo, bar, baz]\r\n'
294+
)
295+
cfg = tmpdir.join(C.CONFIG_FILE)
296+
cfg.write_binary(
297+
fmt.format(out_of_date.path, out_of_date.original_rev).encode(),
298+
)
299+
300+
assert autoupdate(str(cfg), store, freeze=False, tags_only=False) == 0
301+
expected = fmt.format(out_of_date.path, out_of_date.head_rev).encode()
302+
assert cfg.read_binary() == expected
303+
304+
266305
def test_loses_formatting_when_not_detectable(out_of_date, store, tmpdir):
267306
"""A best-effort attempt is made at updating rev without rewriting
268307
formatting. When the original formatting cannot be detected, this

0 commit comments

Comments
 (0)