Skip to content

Instantly share code, notes, and snippets.

@dmilanp
Last active May 16, 2016 11:52
Show Gist options
  • Save dmilanp/ec755d20a47662b39f2a340ff1aa85ad to your computer and use it in GitHub Desktop.
Save dmilanp/ec755d20a47662b39f2a340ff1aa85ad to your computer and use it in GitHub Desktop.
import argparse
import os
# disect.py usage
parser = argparse.ArgumentParser(description='Disect a go package contained to throw light on its functionality.')
parser.add_argument('package_directory', type=str,
help='the directory of a go package')
args = parser.parse_args()
root = args.package_directory
def get_lines(dir):
files_with_lines = {}
for path, subdirs, files in os.walk(dir):
for name in files:
file_name = os.path.join(path, name)
files_with_lines[file_name] = []
_, file_extension = os.path.splitext(file_name)
if file_extension == '.go':
try:
for line in open(file_name):
files_with_lines[file_name].append(line)
except IOError:
pass
return files_with_lines
def filter_values_from_dict(dict):
# should_not_have = ['for', 'if', 'else', 'switch', 'assert', 'return', ':=', '}']
should_not_have = ['\t']
should_have = ['var', 'type', 'func', 'package']
def guarantee_has_none(item, restrictions):
# Restrictions are all elements that item should not have
for restriction in restrictions:
if restriction in item:
return None
return item
def guarantee_has_at_least_one(item, restrictions):
# Restrictions are elements which at least one should have
for restriction in restrictions:
if restriction in item:
return item
return None
for dir, lines in files_with_lines.iteritems():
guarantee_none = map(lambda x: guarantee_has_none(x, should_not_have), lines)
guarantee_none_filtered = filter(None, guarantee_none)
guarantee_one = map(lambda x: guarantee_has_at_least_one(x, should_have), guarantee_none_filtered)
guarantee_one_filtered = filter(None, guarantee_one)
files_with_lines[dir] = sorted(guarantee_one_filtered, reverse=True)
return files_with_lines
files_with_lines = get_lines(root)
filtered_files = filter_values_from_dict(files_with_lines)
order = ['package', 'type', 'var', 'func']
for dir, lines in filtered_files.iteritems():
if lines:
print "\n\n\nFile: {}\n".format(dir)
for elem in order:
exist = False
for l in lines:
if elem in l.split(' ')[0]:
exist = True
print "\t{}".format(l.rstrip('\n'))
if exist:
print ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment