Skip to content

Instantly share code, notes, and snippets.

@ScriptAutomate
Created August 17, 2021 21:54
Show Gist options
  • Save ScriptAutomate/4e53a9b0097d23a0f0013abbe2b082b8 to your computer and use it in GitHub Desktop.
Save ScriptAutomate/4e53a9b0097d23a0f0013abbe2b082b8 to your computer and use it in GitHub Desktop.
Fix smartquotes with pre-commit via local repo call
"""
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