1#!/usr/bin/env python3
2#
3# Copyright 2019, The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""Helper util libraries for debug printing."""
18
19import sys
20
21DEBUG = False
22
23def debug_print(*args, **kwargs):
24  """Prints the args to sys.stderr if the DEBUG is set."""
25  if DEBUG:
26    print(*args, **kwargs, file=sys.stderr)
27
28def error_print(*args, **kwargs):
29  print('[ERROR]:', *args, file=sys.stderr, **kwargs)
30
31def _expand_gen_repr(args):
32  """Like repr but any generator-like object has its iterator consumed
33  and then called repr on."""
34  new_args_list = []
35  for i in args:
36    # detect iterable objects that do not have their own override of __str__
37    if hasattr(i, '__iter__'):
38      to_str = getattr(i, '__str__')
39      if to_str.__objclass__ == object:
40        # the repr for a generator is just type+address, expand it out instead.
41        new_args_list.append([_expand_gen_repr([j])[0] for j in i])
42        continue
43    # normal case: uses the built-in to-string
44    new_args_list.append(i)
45  return new_args_list
46
47def debug_print_gen(*args, **kwargs):
48  """Like _debug_print but will turn any iterable args into a list."""
49  if not DEBUG:
50    return
51
52  new_args_list = _expand_gen_repr(args)
53  debug_print(*new_args_list, **kwargs)
54
55def debug_print_nd(*args, **kwargs):
56  """Like _debug_print but will turn any NamedTuple-type args into a string."""
57  if not DEBUG:
58    return
59
60  new_args_list = []
61  for i in args:
62    if hasattr(i, '_field_types'):
63      new_args_list.append("%s: %s" % (i.__name__, i._field_types))
64    else:
65      new_args_list.append(i)
66
67  debug_print(*new_args_list, **kwargs)
68