Jan Tattermusch | 7897ae9 | 2017-06-07 22:57:36 +0200 | [diff] [blame] | 1 | # Copyright 2015 gRPC authors. |
Craig Tiller | c2c7921 | 2015-02-16 12:00:01 -0800 | [diff] [blame] | 2 | # |
Jan Tattermusch | 7897ae9 | 2017-06-07 22:57:36 +0200 | [diff] [blame] | 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 |
Craig Tiller | c2c7921 | 2015-02-16 12:00:01 -0800 | [diff] [blame] | 6 | # |
Jan Tattermusch | 7897ae9 | 2017-06-07 22:57:36 +0200 | [diff] [blame] | 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
Craig Tiller | c2c7921 | 2015-02-16 12:00:01 -0800 | [diff] [blame] | 8 | # |
Jan Tattermusch | 7897ae9 | 2017-06-07 22:57:36 +0200 | [diff] [blame] | 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. |
Nicolas Noble | ddef246 | 2015-01-06 18:08:25 -0800 | [diff] [blame] | 14 | """Allows dot-accessible dictionaries.""" |
| 15 | |
| 16 | |
| 17 | class Bunch(dict): |
| 18 | |
ncteisen | 26d70b1 | 2017-12-11 16:40:56 -0800 | [diff] [blame] | 19 | def __init__(self, d): |
| 20 | dict.__init__(self, d) |
| 21 | self.__dict__.update(d) |
Nicolas Noble | ddef246 | 2015-01-06 18:08:25 -0800 | [diff] [blame] | 22 | |
| 23 | |
| 24 | # Converts any kind of variable to a Bunch |
| 25 | def to_bunch(var): |
ncteisen | 26d70b1 | 2017-12-11 16:40:56 -0800 | [diff] [blame] | 26 | if isinstance(var, list): |
| 27 | return [to_bunch(i) for i in var] |
| 28 | if isinstance(var, dict): |
| 29 | ret = {} |
| 30 | for k, v in var.items(): |
| 31 | if isinstance(v, (list, dict)): |
| 32 | v = to_bunch(v) |
| 33 | ret[k] = v |
| 34 | return Bunch(ret) |
| 35 | else: |
| 36 | return var |
Nicolas Noble | ddef246 | 2015-01-06 18:08:25 -0800 | [diff] [blame] | 37 | |
| 38 | |
| 39 | # Merges JSON 'add' into JSON 'dst' |
| 40 | def merge_json(dst, add): |
ncteisen | 26d70b1 | 2017-12-11 16:40:56 -0800 | [diff] [blame] | 41 | if isinstance(dst, dict) and isinstance(add, dict): |
| 42 | for k, v in add.items(): |
| 43 | if k in dst: |
| 44 | if k == '#': continue |
| 45 | merge_json(dst[k], v) |
| 46 | else: |
| 47 | dst[k] = v |
| 48 | elif isinstance(dst, list) and isinstance(add, list): |
| 49 | dst.extend(add) |
| 50 | else: |
Mehrdad Afshari | 87cd994 | 2018-01-02 14:40:00 -0800 | [diff] [blame] | 51 | raise Exception( |
| 52 | 'Tried to merge incompatible objects %s %s\n\n%r\n\n%r' % |
| 53 | (type(dst).__name__, type(add).__name__, dst, add)) |