home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2826 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  19.0 KB  |  669 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import linecache
  5. import os
  6. import re
  7. import sys
  8. import threading
  9. import time
  10. import token
  11. import tokenize
  12. import types
  13. import gc
  14.  
  15. try:
  16.     import cPickle
  17.     pickle = cPickle
  18. except ImportError:
  19.     import pickle
  20.  
  21.  
  22. def usage(outfile):
  23.     outfile.write("Usage: %s [OPTIONS] <file> [ARGS]\n\nMeta-options:\n--help                Display this help then exit.\n--version             Output version information then exit.\n\nOtherwise, exactly one of the following three options must be given:\n-t, --trace           Print each line to sys.stdout before it is executed.\n-c, --count           Count the number of times each line is executed\n                      and write the counts to <module>.cover for each\n                      module executed, in the module's directory.\n                      See also `--coverdir', `--file', `--no-report' below.\n-l, --listfuncs       Keep track of which functions are executed at least\n                      once and write the results to sys.stdout after the\n                      program exits.\n-T, --trackcalls      Keep track of caller/called pairs and write the\n                      results to sys.stdout after the program exits.\n-r, --report          Generate a report from a counts file; do not execute\n                      any code.  `--file' must specify the results file to\n                      read, which must have been created in a previous run\n                      with `--count --file=FILE'.\n\nModifiers:\n-f, --file=<file>     File to accumulate counts over several runs.\n-R, --no-report       Do not generate the coverage report files.\n                      Useful if you want to accumulate over several runs.\n-C, --coverdir=<dir>  Directory where the report files.  The coverage\n                      report for <package>.<module> is written to file\n                      <dir>/<package>/<module>.cover.\n-m, --missing         Annotate executable lines that were not executed\n                      with '>>>>>> '.\n-s, --summary         Write a brief summary on stdout for each file.\n                      (Can only be used with --count or --report.)\n-g, --timing          Prefix each line with the time since the program started.\n                      Only used while tracing.\n\nFilters, may be repeated multiple times:\n--ignore-module=<mod> Ignore the given module(s) and its submodules\n                      (if it is a package).  Accepts comma separated\n                      list of module names\n--ignore-dir=<dir>    Ignore files in the given directory (multiple\n                      directories can be joined by os.pathsep).\n" % sys.argv[0])
  24.  
  25. PRAGMA_NOCOVER = '#pragma NO COVER'
  26. rx_blank = re.compile('^\\s*(#.*)?$')
  27.  
  28. class Ignore:
  29.     
  30.     def __init__(self, modules = None, dirs = None):
  31.         if not modules:
  32.             pass
  33.         self._mods = []
  34.         if not dirs:
  35.             pass
  36.         self._dirs = []
  37.         self._dirs = map(os.path.normpath, self._dirs)
  38.         self._ignore = {
  39.             '<string>': 1 }
  40.  
  41.     
  42.     def names(self, filename, modulename):
  43.         if self._ignore.has_key(modulename):
  44.             return self._ignore[modulename]
  45.         for mod in self._mods:
  46.             if mod == modulename:
  47.                 self._ignore[modulename] = 1
  48.                 return 1
  49.             n = len(mod)
  50.             if mod == modulename[:n] and modulename[n] == '.':
  51.                 self._ignore[modulename] = 1
  52.                 return 1
  53.         
  54.         if filename is None:
  55.             self._ignore[modulename] = 1
  56.             return 1
  57.         for d in self._dirs:
  58.             if filename.startswith(d + os.sep):
  59.                 self._ignore[modulename] = 1
  60.                 return 1
  61.         
  62.         self._ignore[modulename] = 0
  63.         return 0
  64.  
  65.  
  66.  
  67. def modname(path):
  68.     base = os.path.basename(path)
  69.     (filename, ext) = os.path.splitext(base)
  70.     return filename
  71.  
  72.  
  73. def fullmodname(path):
  74.     comparepath = os.path.normcase(path)
  75.     longest = ''
  76.     for dir in sys.path:
  77.         dir = os.path.normcase(dir)
  78.         if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
  79.             if len(dir) > len(longest):
  80.                 longest = dir
  81.             
  82.         len(dir) > len(longest)
  83.     
  84.     if longest:
  85.         base = path[len(longest) + 1:]
  86.     else:
  87.         base = path
  88.     base = base.replace(os.sep, '.')
  89.     if os.altsep:
  90.         base = base.replace(os.altsep, '.')
  91.     
  92.     (filename, ext) = os.path.splitext(base)
  93.     return filename
  94.  
  95.  
  96. class CoverageResults:
  97.     
  98.     def __init__(self, counts = None, calledfuncs = None, infile = None, callers = None, outfile = None):
  99.         self.counts = counts
  100.         if self.counts is None:
  101.             self.counts = { }
  102.         
  103.         self.counter = self.counts.copy()
  104.         self.calledfuncs = calledfuncs
  105.         if self.calledfuncs is None:
  106.             self.calledfuncs = { }
  107.         
  108.         self.calledfuncs = self.calledfuncs.copy()
  109.         self.callers = callers
  110.         if self.callers is None:
  111.             self.callers = { }
  112.         
  113.         self.callers = self.callers.copy()
  114.         self.infile = infile
  115.         self.outfile = outfile
  116.         if self.infile:
  117.             
  118.             try:
  119.                 (counts, calledfuncs, callers) = pickle.load(open(self.infile, 'rb'))
  120.                 self.update(self.__class__(counts, calledfuncs, callers))
  121.             except (IOError, EOFError, ValueError):
  122.                 err = None
  123.                 print >>sys.stderr, 'Skipping counts file %r: %s' % (self.infile, err)
  124.             except:
  125.                 None<EXCEPTION MATCH>(IOError, EOFError, ValueError)
  126.             
  127.  
  128.         None<EXCEPTION MATCH>(IOError, EOFError, ValueError)
  129.  
  130.     
  131.     def update(self, other):
  132.         counts = self.counts
  133.         calledfuncs = self.calledfuncs
  134.         callers = self.callers
  135.         other_counts = other.counts
  136.         other_calledfuncs = other.calledfuncs
  137.         other_callers = other.callers
  138.         for key in other_counts.keys():
  139.             counts[key] = counts.get(key, 0) + other_counts[key]
  140.         
  141.         for key in other_calledfuncs.keys():
  142.             calledfuncs[key] = 1
  143.         
  144.         for key in other_callers.keys():
  145.             callers[key] = 1
  146.         
  147.  
  148.     
  149.     def write_results(self, show_missing = True, summary = False, coverdir = None):
  150.         if self.calledfuncs:
  151.             print 
  152.             print 'functions called:'
  153.             calls = self.calledfuncs.keys()
  154.             calls.sort()
  155.             for filename, modulename, funcname in calls:
  156.                 print 'filename: %s, modulename: %s, funcname: %s' % (filename, modulename, funcname)
  157.             
  158.         
  159.         if self.callers:
  160.             print 
  161.             print 'calling relationships:'
  162.             calls = self.callers.keys()
  163.             calls.sort()
  164.             lastfile = lastcfile = ''
  165.             for pfile, pmod, pfunc in calls:
  166.                 (cfile, cmod, cfunc) = None
  167.                 if pfile != lastfile:
  168.                     print 
  169.                     print '***', pfile, '***'
  170.                     lastfile = pfile
  171.                     lastcfile = ''
  172.                 
  173.                 if cfile != pfile and lastcfile != cfile:
  174.                     print '  -->', cfile
  175.                     lastcfile = cfile
  176.                 
  177.                 print '    %s.%s -> %s.%s' % (pmod, pfunc, cmod, cfunc)
  178.             
  179.         
  180.         per_file = { }
  181.         for filename, lineno in self.counts.keys():
  182.             lines_hit = per_file[filename] = per_file.get(filename, { })
  183.             lines_hit[lineno] = self.counts[(filename, lineno)]
  184.         
  185.         sums = { }
  186.         for filename, count in per_file.iteritems():
  187.             if filename == '<string>':
  188.                 continue
  189.             
  190.             if filename.startswith('<doctest '):
  191.                 continue
  192.             
  193.             if filename.endswith(('.pyc', '.pyo')):
  194.                 filename = filename[:-1]
  195.             
  196.             if coverdir is None:
  197.                 dir = os.path.dirname(os.path.abspath(filename))
  198.                 modulename = modname(filename)
  199.             else:
  200.                 dir = coverdir
  201.                 if not os.path.exists(dir):
  202.                     os.makedirs(dir)
  203.                 
  204.                 modulename = fullmodname(filename)
  205.             if show_missing:
  206.                 lnotab = find_executable_linenos(filename)
  207.             else:
  208.                 lnotab = { }
  209.             source = linecache.getlines(filename)
  210.             coverpath = os.path.join(dir, modulename + '.cover')
  211.             (n_hits, n_lines) = self.write_results_file(coverpath, source, lnotab, count)
  212.             if summary and n_lines:
  213.                 percent = int(100 * n_hits / n_lines)
  214.                 sums[modulename] = (n_lines, percent, modulename, filename)
  215.                 continue
  216.         
  217.         if summary and sums:
  218.             mods = sums.keys()
  219.             mods.sort()
  220.             print 'lines   cov%   module   (path)'
  221.             for m in mods:
  222.                 (n_lines, percent, modulename, filename) = sums[m]
  223.                 print '%5d   %3d%%   %s   (%s)' % sums[m]
  224.             
  225.         
  226.         if self.outfile:
  227.             
  228.             try:
  229.                 pickle.dump((self.counts, self.calledfuncs, self.callers), open(self.outfile, 'wb'), 1)
  230.             except IOError:
  231.                 err = None
  232.                 print >>sys.stderr, "Can't save counts files because %s" % err
  233.             except:
  234.                 None<EXCEPTION MATCH>IOError
  235.             
  236.  
  237.         None<EXCEPTION MATCH>IOError
  238.  
  239.     
  240.     def write_results_file(self, path, lines, lnotab, lines_hit):
  241.         
  242.         try:
  243.             outfile = open(path, 'w')
  244.         except IOError:
  245.             err = None
  246.             print >>sys.stderr, 'trace: Could not open %r for writing: %s- skipping' % (path, err)
  247.             return (0, 0)
  248.  
  249.         n_lines = 0
  250.         n_hits = 0
  251.         for i, line in enumerate(lines):
  252.             lineno = i + 1
  253.             if lineno in lines_hit:
  254.                 outfile.write('%5d: ' % lines_hit[lineno])
  255.                 n_hits += 1
  256.                 n_lines += 1
  257.             elif rx_blank.match(line):
  258.                 outfile.write('       ')
  259.             elif lineno in lnotab and PRAGMA_NOCOVER not in lines[i]:
  260.                 outfile.write('>>>>>> ')
  261.                 n_lines += 1
  262.             else:
  263.                 outfile.write('       ')
  264.             outfile.write(lines[i].expandtabs(8))
  265.         
  266.         outfile.close()
  267.         return (n_hits, n_lines)
  268.  
  269.  
  270.  
  271. def find_lines_from_code(code, strs):
  272.     linenos = { }
  273.     line_increments = [ ord(c) for c in code.co_lnotab[1::2] ]
  274.     table_length = len(line_increments)
  275.     docstring = False
  276.     lineno = code.co_firstlineno
  277.     for li in line_increments:
  278.         lineno += li
  279.         if lineno not in strs:
  280.             linenos[lineno] = 1
  281.             continue
  282.         []
  283.     
  284.     return linenos
  285.  
  286.  
  287. def find_lines(code, strs):
  288.     linenos = find_lines_from_code(code, strs)
  289.     for c in code.co_consts:
  290.         if isinstance(c, types.CodeType):
  291.             linenos.update(find_lines(c, strs))
  292.             continue
  293.     
  294.     return linenos
  295.  
  296.  
  297. def find_strings(filename):
  298.     d = { }
  299.     prev_ttype = token.INDENT
  300.     f = open(filename)
  301.     for ttype, tstr, start, end, line in tokenize.generate_tokens(f.readline):
  302.         if ttype == token.STRING:
  303.             if prev_ttype == token.INDENT:
  304.                 (sline, scol) = start
  305.                 (eline, ecol) = end
  306.                 for i in range(sline, eline + 1):
  307.                     d[i] = 1
  308.                 
  309.             
  310.         
  311.         prev_ttype = ttype
  312.     
  313.     f.close()
  314.     return d
  315.  
  316.  
  317. def find_executable_linenos(filename):
  318.     
  319.     try:
  320.         prog = open(filename, 'rU').read()
  321.     except IOError:
  322.         err = None
  323.         print >>sys.stderr, 'Not printing coverage data for %r: %s' % (filename, err)
  324.         return { }
  325.  
  326.     code = compile(prog, filename, 'exec')
  327.     strs = find_strings(filename)
  328.     return find_lines(code, strs)
  329.  
  330.  
  331. class Trace:
  332.     
  333.     def __init__(self, count = 1, trace = 1, countfuncs = 0, countcallers = 0, ignoremods = (), ignoredirs = (), infile = None, outfile = None, timing = False):
  334.         self.infile = infile
  335.         self.outfile = outfile
  336.         self.ignore = Ignore(ignoremods, ignoredirs)
  337.         self.counts = { }
  338.         self.blabbed = { }
  339.         self.pathtobasename = { }
  340.         self.donothing = 0
  341.         self.trace = trace
  342.         self._calledfuncs = { }
  343.         self._callers = { }
  344.         self._caller_cache = { }
  345.         self.start_time = None
  346.         if timing:
  347.             self.start_time = time.time()
  348.         
  349.         if countcallers:
  350.             self.globaltrace = self.globaltrace_trackcallers
  351.         elif countfuncs:
  352.             self.globaltrace = self.globaltrace_countfuncs
  353.         elif trace and count:
  354.             self.globaltrace = self.globaltrace_lt
  355.             self.localtrace = self.localtrace_trace_and_count
  356.         elif trace:
  357.             self.globaltrace = self.globaltrace_lt
  358.             self.localtrace = self.localtrace_trace
  359.         elif count:
  360.             self.globaltrace = self.globaltrace_lt
  361.             self.localtrace = self.localtrace_count
  362.         else:
  363.             self.donothing = 1
  364.  
  365.     
  366.     def run(self, cmd):
  367.         import __main__
  368.         dict = __main__.__dict__
  369.         if not self.donothing:
  370.             sys.settrace(self.globaltrace)
  371.             threading.settrace(self.globaltrace)
  372.         
  373.         
  374.         try:
  375.             exec cmd in dict, dict
  376.         finally:
  377.             if not self.donothing:
  378.                 sys.settrace(None)
  379.                 threading.settrace(None)
  380.             
  381.  
  382.  
  383.     
  384.     def runctx(self, cmd, globals = None, locals = None):
  385.         if globals is None:
  386.             globals = { }
  387.         
  388.         if locals is None:
  389.             locals = { }
  390.         
  391.         if not self.donothing:
  392.             sys.settrace(self.globaltrace)
  393.             threading.settrace(self.globaltrace)
  394.         
  395.         
  396.         try:
  397.             exec cmd in globals, locals
  398.         finally:
  399.             if not self.donothing:
  400.                 sys.settrace(None)
  401.                 threading.settrace(None)
  402.             
  403.  
  404.  
  405.     
  406.     def runfunc(self, func, *args, **kw):
  407.         result = None
  408.         if not self.donothing:
  409.             sys.settrace(self.globaltrace)
  410.         
  411.         
  412.         try:
  413.             result = func(*args, **kw)
  414.         finally:
  415.             if not self.donothing:
  416.                 sys.settrace(None)
  417.             
  418.  
  419.         return result
  420.  
  421.     
  422.     def file_module_function_of(self, frame):
  423.         code = frame.f_code
  424.         filename = code.co_filename
  425.         if filename:
  426.             modulename = modname(filename)
  427.         else:
  428.             modulename = None
  429.         funcname = code.co_name
  430.         clsname = None
  431.         return (filename, modulename, funcname)
  432.  
  433.     
  434.     def globaltrace_trackcallers(self, frame, why, arg):
  435.         if why == 'call':
  436.             this_func = self.file_module_function_of(frame)
  437.             parent_func = self.file_module_function_of(frame.f_back)
  438.             self._callers[(parent_func, this_func)] = 1
  439.         
  440.  
  441.     
  442.     def globaltrace_countfuncs(self, frame, why, arg):
  443.         if why == 'call':
  444.             this_func = self.file_module_function_of(frame)
  445.             self._calledfuncs[this_func] = 1
  446.         
  447.  
  448.     
  449.     def globaltrace_lt(self, frame, why, arg):
  450.         if why == 'call':
  451.             code = frame.f_code
  452.             filename = frame.f_globals.get('__file__', None)
  453.             if filename:
  454.                 modulename = modname(filename)
  455.                 if modulename is not None:
  456.                     ignore_it = self.ignore.names(filename, modulename)
  457.                     if not ignore_it:
  458.                         if self.trace:
  459.                             print ' --- modulename: %s, funcname: %s' % (modulename, code.co_name)
  460.                         
  461.                         return self.localtrace
  462.                 
  463.             else:
  464.                 return None
  465.         filename
  466.  
  467.     
  468.     def localtrace_trace_and_count(self, frame, why, arg):
  469.         if why == 'line':
  470.             filename = frame.f_code.co_filename
  471.             lineno = frame.f_lineno
  472.             key = (filename, lineno)
  473.             self.counts[key] = self.counts.get(key, 0) + 1
  474.             if self.start_time:
  475.                 print '%.2f' % (time.time() - self.start_time),
  476.             
  477.             bname = os.path.basename(filename)
  478.             print '%s(%d): %s' % (bname, lineno, linecache.getline(filename, lineno)),
  479.         
  480.         return self.localtrace
  481.  
  482.     
  483.     def localtrace_trace(self, frame, why, arg):
  484.         if why == 'line':
  485.             filename = frame.f_code.co_filename
  486.             lineno = frame.f_lineno
  487.             if self.start_time:
  488.                 print '%.2f' % (time.time() - self.start_time),
  489.             
  490.             bname = os.path.basename(filename)
  491.             print '%s(%d): %s' % (bname, lineno, linecache.getline(filename, lineno)),
  492.         
  493.         return self.localtrace
  494.  
  495.     
  496.     def localtrace_count(self, frame, why, arg):
  497.         if why == 'line':
  498.             filename = frame.f_code.co_filename
  499.             lineno = frame.f_lineno
  500.             key = (filename, lineno)
  501.             self.counts[key] = self.counts.get(key, 0) + 1
  502.         
  503.         return self.localtrace
  504.  
  505.     
  506.     def results(self):
  507.         return CoverageResults(self.counts, infile = self.infile, outfile = self.outfile, calledfuncs = self._calledfuncs, callers = self._callers)
  508.  
  509.  
  510.  
  511. def _err_exit(msg):
  512.     sys.stderr.write('%s: %s\n' % (sys.argv[0], msg))
  513.     sys.exit(1)
  514.  
  515.  
  516. def main(argv = None):
  517.     import getopt
  518.     if argv is None:
  519.         argv = sys.argv
  520.     
  521.     
  522.     try:
  523.         (opts, prog_argv) = getopt.getopt(argv[1:], 'tcrRf:d:msC:lTg', [
  524.             'help',
  525.             'version',
  526.             'trace',
  527.             'count',
  528.             'report',
  529.             'no-report',
  530.             'summary',
  531.             'file=',
  532.             'missing',
  533.             'ignore-module=',
  534.             'ignore-dir=',
  535.             'coverdir=',
  536.             'listfuncs',
  537.             'trackcalls',
  538.             'timing'])
  539.     except getopt.error:
  540.         msg = None
  541.         sys.stderr.write('%s: %s\n' % (sys.argv[0], msg))
  542.         sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0])
  543.         sys.exit(1)
  544.  
  545.     trace = 0
  546.     count = 0
  547.     report = 0
  548.     no_report = 0
  549.     counts_file = None
  550.     missing = 0
  551.     ignore_modules = []
  552.     ignore_dirs = []
  553.     coverdir = None
  554.     summary = 0
  555.     listfuncs = False
  556.     countcallers = False
  557.     timing = False
  558.     for opt, val in opts:
  559.         if opt == '--help':
  560.             usage(sys.stdout)
  561.             sys.exit(0)
  562.         
  563.         if opt == '--version':
  564.             sys.stdout.write('trace 2.0\n')
  565.             sys.exit(0)
  566.         
  567.         if opt == '-T' or opt == '--trackcalls':
  568.             countcallers = True
  569.             continue
  570.         
  571.         if opt == '-l' or opt == '--listfuncs':
  572.             listfuncs = True
  573.             continue
  574.         
  575.         if opt == '-g' or opt == '--timing':
  576.             timing = True
  577.             continue
  578.         
  579.         if opt == '-t' or opt == '--trace':
  580.             trace = 1
  581.             continue
  582.         
  583.         if opt == '-c' or opt == '--count':
  584.             count = 1
  585.             continue
  586.         
  587.         if opt == '-r' or opt == '--report':
  588.             report = 1
  589.             continue
  590.         
  591.         if opt == '-R' or opt == '--no-report':
  592.             no_report = 1
  593.             continue
  594.         
  595.         if opt == '-f' or opt == '--file':
  596.             counts_file = val
  597.             continue
  598.         
  599.         if opt == '-m' or opt == '--missing':
  600.             missing = 1
  601.             continue
  602.         
  603.         if opt == '-C' or opt == '--coverdir':
  604.             coverdir = val
  605.             continue
  606.         
  607.         if opt == '-s' or opt == '--summary':
  608.             summary = 1
  609.             continue
  610.         
  611.         if opt == '--ignore-module':
  612.             for mod in val.split(','):
  613.                 ignore_modules.append(mod.strip())
  614.             
  615.             continue
  616.         
  617.         if opt == '--ignore-dir':
  618.             for s in val.split(os.pathsep):
  619.                 s = os.path.expandvars(s)
  620.                 s = s.replace('$prefix', os.path.join(sys.prefix, 'lib', 'python' + sys.version[:3]))
  621.                 s = s.replace('$exec_prefix', os.path.join(sys.exec_prefix, 'lib', 'python' + sys.version[:3]))
  622.                 s = os.path.normpath(s)
  623.                 ignore_dirs.append(s)
  624.             
  625.             continue
  626.             continue
  627.     
  628.     if listfuncs:
  629.         if count or trace:
  630.             _err_exit('cannot specify both --listfuncs and (--trace or --count)')
  631.         
  632.     if not count and trace and report and listfuncs or countcallers:
  633.         _err_exit('must specify one of --trace, --count, --report, --listfuncs, or --trackcalls')
  634.     
  635.     if report and no_report:
  636.         _err_exit('cannot specify both --report and --no-report')
  637.     
  638.     if report and not counts_file:
  639.         _err_exit('--report requires a --file')
  640.     
  641.     if no_report and len(prog_argv) == 0:
  642.         _err_exit('missing name of file to run')
  643.     
  644.     if report:
  645.         results = CoverageResults(infile = counts_file, outfile = counts_file)
  646.         results.write_results(missing, summary = summary, coverdir = coverdir)
  647.     else:
  648.         sys.argv = prog_argv
  649.         progname = prog_argv[0]
  650.         sys.path[0] = os.path.split(progname)[0]
  651.         t = Trace(count, trace, countfuncs = listfuncs, countcallers = countcallers, ignoremods = ignore_modules, ignoredirs = ignore_dirs, infile = counts_file, outfile = counts_file, timing = timing)
  652.         
  653.         try:
  654.             t.run('execfile(%r)' % (progname,))
  655.         except IOError:
  656.             err = None
  657.             _err_exit('Cannot run file %r because: %s' % (sys.argv[0], err))
  658.         except SystemExit:
  659.             pass
  660.  
  661.         results = t.results()
  662.         if not no_report:
  663.             results.write_results(missing, summary = summary, coverdir = coverdir)
  664.         
  665.  
  666. if __name__ == '__main__':
  667.     main()
  668.  
  669.