_utils.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python3
  2. # Copyright 2020 The gRPC Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Utility functions for build file generation scripts."""
  16. import os
  17. import sys
  18. import types
  19. import importlib.util
  20. from typing import Any, Union, Mapping, List
  21. def import_python_module(path: str) -> types.ModuleType:
  22. """Imports the Python file at the given path, returns a module object."""
  23. module_name = os.path.basename(path).replace('.py', '')
  24. spec = importlib.util.spec_from_file_location(module_name, path)
  25. module = importlib.util.module_from_spec(spec)
  26. sys.modules[module_name] = module
  27. spec.loader.exec_module(module)
  28. return module
  29. class Bunch(dict):
  30. """Allows dot-accessible dictionaries."""
  31. def __init__(self, d: Mapping):
  32. dict.__init__(self, d)
  33. self.__dict__.update(d)
  34. def to_bunch(var: Any) -> Any:
  35. """Converts any kind of variable to a Bunch."""
  36. if isinstance(var, list):
  37. return [to_bunch(i) for i in var]
  38. if isinstance(var, dict):
  39. ret = {}
  40. for k, v in var.items():
  41. if isinstance(v, (list, dict)):
  42. v = to_bunch(v)
  43. ret[k] = v
  44. return Bunch(ret)
  45. else:
  46. return var
  47. def merge_json(dst: Union[Mapping, List], add: Union[Mapping, List]) -> None:
  48. """Merges JSON objects recursively."""
  49. if isinstance(dst, dict) and isinstance(add, dict):
  50. for k, v in add.items():
  51. if k in dst:
  52. if k.startswith('#'):
  53. continue
  54. merge_json(dst[k], v)
  55. else:
  56. dst[k] = v
  57. elif isinstance(dst, list) and isinstance(add, list):
  58. dst.extend(add)
  59. else:
  60. raise TypeError(
  61. 'Tried to merge incompatible objects %s %s\n\n%r\n\n%r' %
  62. (type(dst).__name__, type(add).__name__, dst, add))