command_trace.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # Copyright 2019 Google
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from lib import terminal
  16. _commands = logging.getLogger('commands')
  17. def log(command_args):
  18. """Logs that a command has run.
  19. Args:
  20. command_args: A list of the command and its arguments.
  21. """
  22. if _commands.isEnabledFor(logging.DEBUG):
  23. columns = terminal.columns()
  24. text = ' '.join(command_args)
  25. # When just passing --trace, shorten output to the width of the current
  26. # window. When running extra verbose don't shorten.
  27. if not logging.root.isEnabledFor(logging.INFO):
  28. if len(text) >= columns:
  29. text = text[0:columns - 5] + ' ...'
  30. _commands.debug('%s', text)
  31. def add_arguments(parser):
  32. """Adds standard arguments to the given ArgumentParser."""
  33. parser.add_argument('--trace', action='store_true',
  34. help='show commands')
  35. parser.add_argument('--verbose', '-v', action='count', default=0,
  36. help='run verbosely')
  37. def enable_tracing():
  38. """Enables tracing of command execution."""
  39. _commands.setLevel(logging.DEBUG)
  40. def setup(args):
  41. """Prepares for tracing/verbosity based on the given parsed arguments."""
  42. level = logging.WARN
  43. if args.trace:
  44. enable_tracing()
  45. if args.verbose >= 2:
  46. level = logging.DEBUG
  47. elif args.verbose >= 1:
  48. level = logging.INFO
  49. logging.basicConfig(format='%(message)s', level=level)
  50. def parse_args(parser):
  51. """Shortcut that adds arguments, parses, and runs setup.
  52. Returns:
  53. The args result from parser.parse_args().
  54. """
  55. add_arguments(parser)
  56. args = parser.parse_args()
  57. setup(args)
  58. return args