diff options
| author | Ned Batchelder <ned@nedbatchelder.com> | 2009-12-03 08:54:27 -0500 | 
|---|---|---|
| committer | Ned Batchelder <ned@nedbatchelder.com> | 2009-12-03 08:54:27 -0500 | 
| commit | 3b6e8394c3e50cb733caafb275d2ae85c0397565 (patch) | |
| tree | dd960443f9ef3772020d74c102d785968bb44dce /coverage/cmdline.py | |
| parent | 3416380e8e46d839c3111d9f82a5f7d93a218821 (diff) | |
| parent | 9e4908f37c370250ebc7836e744a59170720a9e3 (diff) | |
| download | python-coveragepy-git-3b6e8394c3e50cb733caafb275d2ae85c0397565.tar.gz | |
Merged default onto config.
--HG--
branch : config
Diffstat (limited to 'coverage/cmdline.py')
| -rw-r--r-- | coverage/cmdline.py | 102 | 
1 files changed, 58 insertions, 44 deletions
| diff --git a/coverage/cmdline.py b/coverage/cmdline.py index 938099e2..fe8da549 100644 --- a/coverage/cmdline.py +++ b/coverage/cmdline.py @@ -1,6 +1,6 @@  """Command-line support for Coverage.""" -import optparse, sys +import optparse, re, sys  from coverage.execfile import run_python_file  from coverage.misc import CoverageException @@ -8,10 +8,15 @@ from coverage.misc import CoverageException  class Opts(object):      """A namespace class for individual options we'll build parsers from.""" -     + +    append = optparse.Option( +        '-a', '--append', action='store_false', dest="erase_first", +        help="Append coverage data to .coverage, otherwise it is started " +                "clean with each run." +        )      branch = optparse.Option(          '', '--branch', action='store_true', -        help="Measure branch execution. HIGHLY EXPERIMENTAL!" +        help="Measure branch coverage in addition to statement coverage."          )      directory = optparse.Option(          '-d', '--directory', action='store', @@ -63,18 +68,18 @@ class Opts(object):          help="Use a simpler but slower trace method.  Try this if you get "                  "seemingly impossible results!"          ) -    append = optparse.Option( -        '-a', '--append', action='store_false', dest="erase_first", -        help="Append coverage data to .coverage, otherwise it is started " -                "clean with each run." +    version = optparse.Option( +        '', '--version', action='store_true', +        help="Display version information and exit."          ) -     + +  class CoverageOptionParser(optparse.OptionParser, object):      """Base OptionParser for coverage. -     +      Problems don't exit the program.      Defaults are initialized for all options. -     +      """      def __init__(self, *args, **kwargs): @@ -93,6 +98,7 @@ class CoverageOptionParser(optparse.OptionParser, object):              show_missing=None,              timid=None,              erase_first=None, +            version=None,              )          self.disable_interspersed_args() @@ -101,12 +107,12 @@ class CoverageOptionParser(optparse.OptionParser, object):      class OptionParserError(Exception):          """Used to stop the optparse error handler ending the process."""          pass -     +      def parse_args(self, args=None, options=None):          """Call optparse.parse_args, but return a triple: -         +          (ok, options, args) -         +          """          try:              options, args = \ @@ -114,7 +120,7 @@ class CoverageOptionParser(optparse.OptionParser, object):          except self.OptionParserError:              return False, None, None          return True, options, args -         +      def error(self, msg):          """Override optparse.error so sys.exit doesn't get called."""          self.help_fn(msg) @@ -126,7 +132,7 @@ class ClassicOptionParser(CoverageOptionParser):      def __init__(self):          super(ClassicOptionParser, self).__init__() -         +          self.add_action('-a', '--annotate', 'annotate')          self.add_action('-b', '--html', 'html')          self.add_action('-c', '--combine', 'combine') @@ -143,6 +149,7 @@ class ClassicOptionParser(CoverageOptionParser):              Opts.old_omit,              Opts.parallel_mode,              Opts.timid, +            Opts.version,          ])      def add_action(self, dash, dashdash, action_code): @@ -151,7 +158,7 @@ class ClassicOptionParser(CoverageOptionParser):              callback=self._append_action              )          option.action_code = action_code -         +      def _append_action(self, option, opt_unused, value_unused, parser):          """Callback for an option that adds to the `actions` list."""          parser.values.actions.append(option.action_code) @@ -159,19 +166,19 @@ class ClassicOptionParser(CoverageOptionParser):  class CmdOptionParser(CoverageOptionParser):      """Parse one of the new-style commands for coverage.py.""" -     +      def __init__(self, action, options=None, defaults=None, usage=None,                  cmd=None, description=None                  ):          """Create an OptionParser for a coverage command. -         +          `action` is the slug to put into `options.actions`.          `options` is a list of Option's for the command.          `defaults` is a dict of default value for options.          `usage` is the usage string to display in help.          `cmd` is the command name, if different than `action`.          `description` is the description of the command, for the help text. -         +          """          if usage:              usage = "%prog " + usage @@ -222,20 +229,20 @@ CMDS = {              "Each file gets its own page, with the source decorated to show "              "executed, excluded, and missed lines."          ), -     +      'combine': CmdOptionParser("combine", [Opts.help],          usage = " ",          description = "Combine data from multiple coverage files collected " -            "with 'run -p'.  The combined results are stored into a single " -            "file representing the union of the coverage." +            "with 'run -p'.  The combined results are written to a single " +            "file representing the union of the data."          ),      'debug': CmdOptionParser("debug", [Opts.help],          usage = "<topic>", -        description = "Display information the internals of coverage.py, " +        description = "Display information on the internals of coverage.py, "              "for diagnosing problems. " -            "Topics are 'data' to show a summary of the data collected in " -            ".coverage, or 'sys' to show installation information." +            "Topics are 'data' to show a summary of the collected data, " +            "or 'sys' to show installation information."          ),      'erase': CmdOptionParser("erase", [Opts.help], @@ -251,7 +258,7 @@ CMDS = {              Opts.help,              ],          usage = "[options] [modules]", -        description = "Report coverage stats on modules." +        description = "Report coverage statistics on modules."          ),      'run': CmdOptionParser("execute", @@ -263,12 +270,12 @@ CMDS = {              Opts.timid,              Opts.help,              ], -        defaults = {'erase_first':True}, +        defaults = {'erase_first': True},          cmd = "run",          usage = "[options] <pyfile> [program options]", -        description = "Run a python program, measuring code execution." +        description = "Run a Python program, measuring code execution."          ), -     +      'xml': CmdOptionParser("xml",          [              Opts.ignore_errors, @@ -286,9 +293,10 @@ CMDS = {  OK, ERR = 0, 1 +  class CoverageScript(object):      """The command-line interface to Coverage.""" -     +      def __init__(self, _covpkg=None, _run_python_file=None, _help_fn=None):          # _covpkg is for dependency injection, so we can test this code.          if _covpkg: @@ -296,13 +304,13 @@ class CoverageScript(object):          else:              import coverage              self.covpkg = coverage -         +          # _run_python_file is for dependency injection also.          self.run_python_file = _run_python_file or run_python_file -         +          # _help_fn is for dependency injection.          self.help_fn = _help_fn or self.help -         +          self.coverage = None      def help(self, error=None, topic=None, parser=None): @@ -315,7 +323,6 @@ class CoverageScript(object):              print(parser.format_help().strip())          else:              # Parse out the topic we want from HELP_TOPICS -            import re              topic_list = re.split("(?m)^=+ (\w+) =+$", HELP_TOPICS)              topics = dict(zip(topic_list[1::2], topic_list[2::2]))              help_msg = topics.get(topic, '').strip() @@ -326,14 +333,14 @@ class CoverageScript(object):      def command_line(self, argv):          """The bulk of the command line interface to Coverage. -         +          `argv` is the argument list to process.          Returns 0 if all is well, 1 if something went wrong.          """          # Collect the command-line options. -         +          if not argv:              self.help_fn(topic='minimum_help')              return OK @@ -363,6 +370,10 @@ class CoverageScript(object):                  self.help_fn(parser=parser)              return OK +        if options.version: +            self.help_fn(topic='version') +            return OK +          if "help" in options.actions:              if args:                  for a in args: @@ -399,11 +410,11 @@ class CoverageScript(object):          if not args_allowed and args:              self.help_fn("Unexpected arguments: %s" % " ".join(args))              return ERR -         +          if 'execute' in options.actions and not args:              self.help_fn("Nothing to do.")              return ERR -             +          # Do something.          self.coverage = self.covpkg.coverage(              data_suffix = bool(options.parallel_mode), @@ -472,7 +483,7 @@ class CoverageScript(object):          if options.omit:              omit = options.omit.split(',')          report_args['omit_prefixes'] = omit -         +          if 'report' in options.actions:              self.coverage.report(                  show_missing=options.show_missing, **report_args) @@ -494,7 +505,7 @@ class CoverageScript(object):  HELP_TOPICS = r"""  == classic ==================================================================== -Coverage version %(__version__)s +Coverage.py version %(__version__)s  Measure, collect, and report on code coverage in Python programs.  Usage: @@ -540,14 +551,14 @@ Coverage data is saved in the file .coverage by default.  Set the  COVERAGE_FILE environment variable to save it somewhere else.  == help ======================================================================= -Coverage version %(__version__)s +Coverage.py, version %(__version__)s  Measure, collect, and report on code coverage in Python programs.  usage: coverage <command> [options] [args]  Commands:      annotate    Annotate source files with execution information. -    combine     Combine a number of data files.  +    combine     Combine a number of data files.      erase       Erase previously collected coverage data.      help        Get help on using coverage.py.      html        Create an HTML report. @@ -562,14 +573,17 @@ For more information, see %(__url__)s  == minimum_help ===============================================================  Code coverage for Python.  Use 'coverage help' for help. +== version ==================================================================== +Coverage.py, version %(__version__)s.  %(__url__)s +  """  def main():      """The main entrypoint to Coverage. -     +      This is installed as the script entrypoint. -     +      """      try:          status = CoverageScript().command_line(sys.argv[1:]) | 
