Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't write the file unless there are changes #457

Merged
merged 2 commits into from
Dec 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,7 @@ class documentation for more information.
MAX_PYTHON_FILE_DETECTION_BYTES = 1024


def open_with_encoding(filename,
encoding=None, mode='r', limit_byte_check=-1):
def open_with_encoding(filename, mode='r', encoding=None, limit_byte_check=-1):
"""Return opened file with a specific encoding."""
if not encoding:
encoding = detect_encoding(filename, limit_byte_check=limit_byte_check)
Expand All @@ -159,7 +158,7 @@ def detect_encoding(filename, limit_byte_check=-1):
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]

with open_with_encoding(filename, encoding) as test_file:
with open_with_encoding(filename, encoding=encoding) as test_file:
test_file.read(limit_byte_check)

return encoding
Expand Down Expand Up @@ -3431,12 +3430,11 @@ def fix_file(filename, options=None, output=None, apply_config=False):
output.flush()
return diff
elif options.in_place:
fp = open_with_encoding(filename, encoding=encoding, mode='w')
fp.write(fixed_source)
fp.close()
original = "".join(original_source).splitlines()
fixed = fixed_source.splitlines()
if original != fixed:
with open_with_encoding(filename, 'w', encoding=encoding) as fp:
fp.write(fixed_source)
return fixed_source
else:
return ''
Expand Down
12 changes: 12 additions & 0 deletions test/test_autopep8.py
Original file line number Diff line number Diff line change
Expand Up @@ -4956,6 +4956,18 @@ def test_in_place(self):
self.assertEqual(fixed, f.read())
self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK)

def test_in_place_no_modifications_no_writes(self):
with temporary_file_context('import os\n') as filename:
# ensure that noops do not do writes by making writing an error
os.chmod(filename, 0o444)
p = Popen(
list(AUTOPEP8_CMD_TUPLE) + [filename, '--in-place'],
stderr=PIPE,
)
_, err = p.communicate()
self.assertEqual(err, b'')
self.assertEqual(p.returncode, autopep8.EXIT_CODE_OK)

def test_in_place_with_exit_code_option(self):
line = "'abc' \n"
fixed = "'abc'\n"
Expand Down