Skip to content

Instantly share code, notes, and snippets.

@MarkusH
Forked from pydanny/hackychecktitlecase.py
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkusH/838f07e540faaf9ec528 to your computer and use it in GitHub Desktop.
Save MarkusH/838f07e540faaf9ec528 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
From @pydanny at https://gist.github.com/pydanny/ddf965bbec415084fb6d
Git Integration
===============
1. Move .git/hooks/pre-commit.sample to .git/hooks/pre-commit
2. Add::
./hackychecktitlecase.py
exit $?
after the leading comments to prevent commits of "invalid" headlines.
"""
import glob
import re
import sys
from collections import defaultdict
try:
from titlecase import titlecase
except ImportError:
print("Please install titlecase")
regex = re.compile(r'\\(section|subsection|subsubsection)', re.IGNORECASE)
EXEMPTS = ()
def exempter(line):
for exempt in EXEMPTS:
if line.startswith(exempt):
return True
return line in EXEMPTS
def clean_line(line):
line = line.replace('\\section{', '')
line = line.replace('\\subsection{', '')
line = line.replace('\\subsubsection{', '')
line = line.replace('\\section*{', '')
line = line.replace('\\subsection*{', '')
line = line.replace('\\subsubsection*{', '')
line = line.replace('}', '')
line = line.replace('[', '')
line = line.replace(']', ' ')
line = line.strip()
return line
def main():
fixes = defaultdict(list)
for file in glob.glob("content/*.tex"):
with open(file) as f:
lines = f.readlines()
for lineno, line in enumerate(lines, 1):
match = re.match(regex, line)
if match is None:
continue
line = clean_line(line)
if exempter(line):
continue
new_line = titlecase(line)
if new_line != line:
fixes[file].append((lineno, line, new_line))
if fixes:
print('There are titlecase errors')
print('=' * 79)
for file, changes in fixes.items():
print(file)
for lineno, line, new_line in changes:
print('-' * 79)
print('#: %d' % lineno)
print('-: %s' % line)
print('+: %s' % new_line)
print('=' * 79)
return 1
print('No titlecase errors :)')
return 0
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment