Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@charettes
Last active July 7, 2017 18:44
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 charettes/0fec639f57ab54a855207832696a19db to your computer and use it in GitHub Desktop.
Save charettes/0fec639f57ab54a855207832696a19db to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
This script assumes you have both flake8 and flake8-commas packages
installed in the Python environment you use to run this script.
"""
import subprocess
import sys
from collections import defaultdict
MISSING_TRAILING_COMMAS = 'missing trailing comma'
def extract_missing_commas(violations):
paths_missing_commas = defaultdict(lambda: defaultdict(list))
for violation in out.strip().split('\n'):
if violation.endswith(MISSING_TRAILING_COMMAS):
path, line, char, _ = violation.split(':')
paths_missing_commas[path][int(line)] = int(char) - 1
return sorted(paths_missing_commas.items())
def add_missing_commas(path, locations):
with open(path, 'r') as file_:
lines = []
for line, content in enumerate(file_, start=1):
char = locations.get(line)
if char:
content = '%s,%s' % (content[0:char], content[char:])
lines.append(content)
with open(path, 'w+') as file_:
file_.writelines(lines)
if __name__ == '__main__':
sys.stdout.write('Running flake8 to detect missing trailing commas... ')
sys.stdout.flush()
process = subprocess.Popen(
'flake8 %s' % ' '.join(sys.argv[1:]),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, err = process.communicate()
sys.stdout.write('done.\n')
violations = out.strip().split('\n')
for path, locations in extract_missing_commas(violations):
sys.stdout.write('Adding missing commas to "%s"... ' % path)
sys.stdout.flush()
add_missing_commas(path, locations)
sys.stdout.write('done.\n')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment