| 1 |
|
| 2 |
|
| 3 |
import os |
| 4 |
import pprint |
| 5 |
|
| 6 |
from . import Parser |
| 7 |
from . import Compiler |
| 8 |
from . import Template |
| 9 |
|
| 10 |
|
| 11 |
class Analyzer(Parser.Parser): |
| 12 |
def __init__(self, *args, **kwargs): |
| 13 |
self.calls = {} |
| 14 |
super(Analyzer, self).__init__(*args, **kwargs) |
| 15 |
|
| 16 |
def eatDirective(self): |
| 17 |
directive = self.matchDirective() |
| 18 |
try: |
| 19 |
self.calls[directive] += 1 |
| 20 |
except KeyError: |
| 21 |
self.calls[directive] = 1 |
| 22 |
super(Analyzer, self).eatDirective() |
| 23 |
|
| 24 |
|
| 25 |
class AnalysisCompiler(Compiler.ModuleCompiler): |
| 26 |
parserClass = Analyzer |
| 27 |
|
| 28 |
|
| 29 |
def analyze(source): |
| 30 |
klass = Template.Template.compile(source, compilerClass=AnalysisCompiler) |
| 31 |
return klass._CHEETAH_compilerInstance._parser.calls |
| 32 |
|
| 33 |
|
| 34 |
def main_file(f): |
| 35 |
fd = open(f, 'r') |
| 36 |
try: |
| 37 |
print(u'>>> Analyzing %s' % f) |
| 38 |
calls = analyze(fd.read()) |
| 39 |
return calls |
| 40 |
finally: |
| 41 |
fd.close() |
| 42 |
|
| 43 |
|
| 44 |
def _find_templates(directory, suffix): |
| 45 |
for root, dirs, files in os.walk(directory): |
| 46 |
for f in files: |
| 47 |
if not f.endswith(suffix): |
| 48 |
continue |
| 49 |
yield root + os.path.sep + f |
| 50 |
|
| 51 |
|
| 52 |
def _analyze_templates(iterable): |
| 53 |
for template in iterable: |
| 54 |
yield main_file(template) |
| 55 |
|
| 56 |
|
| 57 |
def main_dir(opts): |
| 58 |
results = _analyze_templates(_find_templates(opts.dir, opts.suffix)) |
| 59 |
totals = {} |
| 60 |
for series in results: |
| 61 |
if not series: |
| 62 |
continue |
| 63 |
for k, v in series.items(): |
| 64 |
try: |
| 65 |
totals[k] += v |
| 66 |
except KeyError: |
| 67 |
totals[k] = v |
| 68 |
return totals |
| 69 |
|
| 70 |
|
| 71 |
def main(): |
| 72 |
from optparse import OptionParser |
| 73 |
op = OptionParser() |
| 74 |
op.add_option('-f', '--file', dest='file', default=None, |
| 75 |
help='Specify a single file to analyze') |
| 76 |
op.add_option('-d', '--dir', dest='dir', default=None, |
| 77 |
help='Specify a directory of templates to analyze') |
| 78 |
op.add_option('--suffix', default='tmpl', dest='suffix', |
| 79 |
help='Specify a custom template file suffix ' |
| 80 |
'for the -d option (default: "tmpl")') |
| 81 |
opts, args = op.parse_args() |
| 82 |
|
| 83 |
if not opts.file and not opts.dir: |
| 84 |
op.print_help() |
| 85 |
return |
| 86 |
|
| 87 |
results = None |
| 88 |
if opts.file: |
| 89 |
results = main_file(opts.file) |
| 90 |
if opts.dir: |
| 91 |
results = main_dir(opts) |
| 92 |
|
| 93 |
pprint.pprint(results) |
| 94 |
|
| 95 |
|
| 96 |
if __name__ == '__main__': |
| 97 |
main() |