Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / tools / json_schema_compiler / json_schema.py
blobbb4e9c4bc5d6f0c9e556ef40cb06cefa23232ad8
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 import copy
7 import json_parse
10 def DeleteNodes(item, delete_key=None, matcher=None):
11 """Deletes certain nodes in item, recursively. If |delete_key| is set, all
12 dicts with |delete_key| as an attribute are deleted. If a callback is passed
13 as |matcher|, |DeleteNodes| will delete all dicts for which matcher(dict)
14 returns True.
15 """
16 assert (delete_key is not None) != (matcher is not None)
18 def ShouldDelete(thing):
19 return json_parse.IsDict(thing) and (
20 delete_key is not None and delete_key in thing or
21 matcher is not None and matcher(thing))
23 if json_parse.IsDict(item):
24 toDelete = []
25 for key, value in item.items():
26 if ShouldDelete(value):
27 toDelete.append(key)
28 else:
29 DeleteNodes(value, delete_key, matcher)
30 for key in toDelete:
31 del item[key]
32 elif type(item) == list:
33 item[:] = [DeleteNodes(thing, delete_key, matcher)
34 for thing in item if not ShouldDelete(thing)]
36 return item
39 def Load(filename):
40 with open(filename, 'r') as handle:
41 schemas = json_parse.Parse(handle.read())
42 return schemas
45 # A dictionary mapping |filename| to the object resulting from loading the JSON
46 # at |filename|.
47 _cache = {}
50 def CachedLoad(filename):
51 """Equivalent to Load(filename), but caches results for subsequent calls"""
52 if filename not in _cache:
53 _cache[filename] = Load(filename)
54 # Return a copy of the object so that any changes a caller makes won't affect
55 # the next caller.
56 return copy.deepcopy(_cache[filename])