Skip to content

Commit

Permalink
Add --check, --no-error-on-fix flags
Browse files Browse the repository at this point in the history
Fix pre-commit versions
  • Loading branch information
ovsds committed Jan 9, 2024
1 parent f007cca commit 9a9f017
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ repos:
hooks:
- id: autopep8
- repo: https://github.com/PyCQA/isort
rev: '5.10.1'
rev: '5.13.2'
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: '22.1.0'
rev: '22.3.0'
hooks:
- id: black
language_version: python3 # Should be a command that runs python3.6+
Expand Down
30 changes: 22 additions & 8 deletions sort_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def _fix_src(contents_text: str, fname: str) -> str:
return "".join(chunks)


def fix_file(filename: str) -> int:
def fix_file(filename: str, write: bool = True, error_on_fix: bool = True) -> int:
with open(filename, "rb") as f:
contents_bytes = f.read()

Expand All @@ -172,23 +172,37 @@ def fix_file(filename: str) -> int:
return 1

new_content = _fix_src(contents_text, filename)
if new_content != contents_text:
print(f"Rewriting {filename}")
with open(filename, "wb") as f:
f.write(new_content.encode())
return 1
else:
if new_content == contents_text:
return 0

result = 1 if error_on_fix else 0

if not write:
print(f"Found unsorted {filename}")
return result

print(f"Rewriting {filename}")
with open(filename, "wb") as f:
f.write(new_content.encode())

return result


def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
# add --check flag
parser.add_argument("--check", action="store_true")
parser.add_argument("--no-error-on-fix", action="store_true")
parser.add_argument("filenames", nargs="*")
args = parser.parse_args(argv)

retv = 0
for filename in args.filenames:
retv |= fix_file(filename)
retv |= fix_file(
filename,
write=not args.check,
error_on_fix=not args.no_error_on_fix,
)
return retv


Expand Down

0 comments on commit 9a9f017

Please sign in to comment.