|
| 1 | +from typing import Any, Iterable, List, Optional, Sized |
| 2 | + |
| 3 | +from graphql import Node |
| 4 | + |
| 5 | + |
| 6 | +def _node_tree_recursive( |
| 7 | + obj: Any, |
| 8 | + *, |
| 9 | + indent: int = 0, |
| 10 | + ignored_keys: List, |
| 11 | +): |
| 12 | + |
| 13 | + assert ignored_keys is not None |
| 14 | + |
| 15 | + results = [] |
| 16 | + |
| 17 | + if hasattr(obj, "__slots__"): |
| 18 | + |
| 19 | + results.append(" " * indent + f"{type(obj).__name__}") |
| 20 | + |
| 21 | + try: |
| 22 | + keys = obj.keys |
| 23 | + except AttributeError: |
| 24 | + # If the object has no keys attribute, print its repr and return. |
| 25 | + results.append(" " * (indent + 1) + repr(obj)) |
| 26 | + else: |
| 27 | + for key in keys: |
| 28 | + if key in ignored_keys: |
| 29 | + continue |
| 30 | + attr_value = getattr(obj, key, None) |
| 31 | + results.append(" " * (indent + 1) + f"{key}:") |
| 32 | + if isinstance(attr_value, Iterable) and not isinstance( |
| 33 | + attr_value, (str, bytes) |
| 34 | + ): |
| 35 | + if isinstance(attr_value, Sized) and len(attr_value) == 0: |
| 36 | + results.append( |
| 37 | + " " * (indent + 2) + f"empty {type(attr_value).__name__}" |
| 38 | + ) |
| 39 | + else: |
| 40 | + for item in attr_value: |
| 41 | + results.append( |
| 42 | + _node_tree_recursive( |
| 43 | + item, |
| 44 | + indent=indent + 2, |
| 45 | + ignored_keys=ignored_keys, |
| 46 | + ) |
| 47 | + ) |
| 48 | + else: |
| 49 | + results.append( |
| 50 | + _node_tree_recursive( |
| 51 | + attr_value, |
| 52 | + indent=indent + 2, |
| 53 | + ignored_keys=ignored_keys, |
| 54 | + ) |
| 55 | + ) |
| 56 | + else: |
| 57 | + results.append(" " * indent + repr(obj)) |
| 58 | + |
| 59 | + return "\n".join(results) |
| 60 | + |
| 61 | + |
| 62 | +def node_tree( |
| 63 | + obj: Node, |
| 64 | + *, |
| 65 | + ignore_loc: bool = True, |
| 66 | + ignore_block: bool = True, |
| 67 | + ignored_keys: Optional[List] = None, |
| 68 | +): |
| 69 | + """Method which returns a tree of Node elements as a String. |
| 70 | +
|
| 71 | + Useful to debug deep DocumentNode instances created by gql or dsl_gql. |
| 72 | +
|
| 73 | + WARNING: the output of this method is not guaranteed and may change without notice. |
| 74 | + """ |
| 75 | + |
| 76 | + assert isinstance(obj, Node) |
| 77 | + |
| 78 | + if ignored_keys is None: |
| 79 | + ignored_keys = [] |
| 80 | + |
| 81 | + if ignore_loc: |
| 82 | + # We are ignoring loc attributes by default |
| 83 | + ignored_keys.append("loc") |
| 84 | + |
| 85 | + if ignore_block: |
| 86 | + # We are ignoring block attributes by default (in StringValueNode) |
| 87 | + ignored_keys.append("block") |
| 88 | + |
| 89 | + return _node_tree_recursive(obj, ignored_keys=ignored_keys) |
0 commit comments