summaryrefslogtreecommitdiffstats
path: root/tools/json_schema_compiler/json_schema.py
blob: 240a1685f70db8a7319f0e2520e8ff40f66a8b39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import copy
import json

def StripJSONComments(stream):
  """Strips //-style comments from a stream of JSON. Allows un-escaped //
  inside string values.
  """
  # Previously we used json_minify to strip comments, but it seems to be pretty
  # slow and does more than we need. This implementation does a lot less work -
  # it just strips comments from the beginning of the '//' delimiter until end
  # of line, but only if we're not inside a string. For example:
  #
  #  {"url": "http://www.example.com"}
  #
  # will work properly, as will:
  #
  #  {
  #    "url": "http://www.example.com" // some comment
  #  }
  result = ""
  last_char = None
  inside_string = False
  inside_comment = False
  buf = ""
  for char in stream:
    if inside_comment:
      if char == '\n':
        inside_comment = False
      else:
        continue
    else:
      if char == '/' and not inside_string:
        if last_char == '/':
          inside_comment = True
        last_char = char
        continue
      else:
        if last_char == '/' and not inside_string:
          result += '/'
        if char == '"':
          inside_string = not inside_string
    last_char = char
    result += char

  return result

def DeleteNocompileNodes(item):
  def HasNocompile(thing):
    return type(thing) == dict and thing.get('nocompile', False)

  if type(item) == dict:
    toDelete = []
    for key, value in item.items():
      if HasNocompile(value):
        toDelete.append(key)
      else:
        DeleteNocompileNodes(value)
    for key in toDelete:
      del item[key]
  elif type(item) == list:
    item[:] = [DeleteNocompileNodes(thing)
        for thing in item if not HasNocompile(thing)]

  return item

def Load(filename):
  with open(filename, 'r') as handle:
    return DeleteNocompileNodes(json.loads(StripJSONComments(handle.read())))


# A dictionary mapping |filename| to the object resulting from loading the JSON
# at |filename|.
_cache = {}

def CachedLoad(filename):
  """Equivalent to Load(filename), but caches results for subsequent calls"""
  if filename not in _cache:
    _cache[filename] = Load(filename)
  # Return a copy of the object so that any changes a caller makes won't affect
  # the next caller.
  return copy.deepcopy(_cache[filename])