|
| 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 | + |
| 15 | +import logging |
| 16 | + |
| 17 | +from lib import terminal |
| 18 | + |
| 19 | +_commands = logging.getLogger('commands') |
| 20 | + |
| 21 | + |
| 22 | +def log(command_args): |
| 23 | + """Logs that a command has run. |
| 24 | +
|
| 25 | + Args: |
| 26 | + command_args: A list of the command and its arguments. |
| 27 | + """ |
| 28 | + if _commands.isEnabledFor(logging.DEBUG): |
| 29 | + columns = terminal.columns() |
| 30 | + |
| 31 | + text = ' '.join(command_args) |
| 32 | + |
| 33 | + # When just passing --trace, shorten output to the width of the current |
| 34 | + # window. When running extra verbose don't shorten. |
| 35 | + if not logging.root.isEnabledFor(logging.INFO): |
| 36 | + if len(text) >= columns: |
| 37 | + text = text[0:columns - 5] + ' ...' |
| 38 | + |
| 39 | + _commands.debug('%s', text) |
| 40 | + |
| 41 | + |
| 42 | +def add_arguments(parser): |
| 43 | + """Adds standard arguments to the given ArgumentParser.""" |
| 44 | + parser.add_argument('--trace', action='store_true', |
| 45 | + help='show commands') |
| 46 | + parser.add_argument('--verbose', '-v', action='count', default=0, |
| 47 | + help='run verbosely') |
| 48 | + |
| 49 | + |
| 50 | +def enable_tracing(): |
| 51 | + """Enables tracing of command execution.""" |
| 52 | + _commands.setLevel(logging.DEBUG) |
| 53 | + |
| 54 | + |
| 55 | +def setup(args): |
| 56 | + """Prepares for tracing/verbosity based on the given parsed arguments.""" |
| 57 | + level = logging.WARN |
| 58 | + |
| 59 | + if args.trace: |
| 60 | + enable_tracing() |
| 61 | + |
| 62 | + if args.verbose >= 2: |
| 63 | + level = logging.DEBUG |
| 64 | + elif args.verbose >= 1: |
| 65 | + level = logging.INFO |
| 66 | + |
| 67 | + logging.basicConfig(format='%(message)s', level=level) |
| 68 | + |
| 69 | + |
| 70 | +def parse_args(parser): |
| 71 | + """Shortcut that adds arguments, parses, and runs setup. |
| 72 | +
|
| 73 | + Returns: |
| 74 | + The args result from parser.parse_args(). |
| 75 | + """ |
| 76 | + add_arguments(parser) |
| 77 | + args = parser.parse_args() |
| 78 | + setup(args) |
| 79 | + return args |
0 commit comments