Skip to content

Instantly share code, notes, and snippets.

@dmcardle
Created July 22, 2014 04:01
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 dmcardle/3833ce428aaea897ff39 to your computer and use it in GitHub Desktop.
Save dmcardle/3833ce428aaea897ff39 to your computer and use it in GitHub Desktop.
Enhanced white_spacey.py
'''
Created on Apr 19, 2014
@author: Chris
Edited by Dan on Jul 21, 2014
'''
import os
import re
import codecs
from functools import partial
def get_src_files(root, extensions=['.c', '.cpp', '.h', '.hpp']):
for root, _, files in os.walk(root):
yield from (os.path.join(root, f) for f in files
if any(f.endswith(ext) for ext in extensions))
def read_files(filenames):
for filename in filenames:
try:
with codecs.open(filename, 'r') as f:
yield from f.readlines()
except ValueError:
print("Couldn't read %s" % filename)
pass
def extract_forloops(lines):
yield from (
line.strip() for line in lines
if 'for (' in line
# One of those god forsaken 'enhanced' for loops. Ignore
and ':' not in line
)
class Codebase:
def __init__(self, name, path):
self.name = name
self.path = path
def get_loops(self):
return extract_forloops(read_files(get_src_files(self.path)))
if __name__ == '__main__':
spaced_apart = partial(re.search, '[a-zA-Z]\s\=')
grouped_together = partial(re.search, '[a-zA-Z]\=')
codebases = [
Codebase("Linux kernel", "linux-3.15.6"),
Codebase("Git", "git"),
Codebase("OpenSSL", "openssl-1.0.1h"),
Codebase("Python 3", "Python-3.4.1"),
Codebase("Ruby", "ruby-2.1.2"),
]
for code in codebases:
forloops = code.get_loops()
counts = {'spaced': 0, 'nonspaced':0}
for loop in forloops:
if grouped_together(loop):
counts['nonspaced'] += 1
elif spaced_apart(loop):
counts['spaced'] += 1
print(code.name)
print(counts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment