Created
August 17, 2021 21:54
-
-
Save ScriptAutomate/4e53a9b0097d23a0f0013abbe2b082b8 to your computer and use it in GitHub Desktop.
Fix smartquotes with pre-commit via local repo call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Code that can be called by pre-commit to fix smart quotes | |
Add into .pre-commit-config.yaml | |
- repo: local | |
hooks: | |
- id: check-smart-quotes | |
description: Checks for and fixes smart quotes. | |
name: Check and fix smartquotes | |
entry: python3 ./tools/fix_smartquotes.py | |
always_run: true | |
language: python | |
exclude_types: | |
- png | |
- gif | |
- jpeg | |
""" | |
from pathlib import Path | |
import sys | |
def fix_smartquotes(s: str) -> str: | |
return ( | |
s.replace("“", '"') | |
.replace("”", '"') | |
.replace("‘", "'") | |
.replace("’", "'") | |
) | |
# non_hidden_files = [x for x in Path().glob('**/*') if x.is_file() and not str(x).startswith('.') and (str(x.name) != 'fix_smartquotes.py')] | |
files_to_test = sys.argv[1:] | |
fixed = 0 | |
for filename in files_to_test: | |
target_file = Path(filename) | |
if str(target_file.name) != 'fix_smartquotes.py': | |
with open(target_file, "r") as target_file_reader: | |
target_file_content = target_file_reader.read() | |
new_target_file_content = fix_smartquotes(target_file_content) | |
if new_target_file_content != target_file_content: | |
print(f"Fixing {target_file}...") | |
with open(target_file, "w") as target_file_writer: | |
target_file_writer.write(new_target_file_content) | |
fixed += 1 | |
print(f"Fixed {fixed} files.") | |
if fixed > 0: | |
exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment