| 1 |
# Copyright 2015 Google Inc. All rights reserved. |
| 2 |
# |
| 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 |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 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. |
| 14 |
|
| 15 |
import numbers |
| 16 |
import re |
| 17 |
|
| 18 |
|
| 19 |
class ConfigError (Exception): |
| 20 |
def __init__(self, msg, note): |
| 21 |
super(ConfigError, self).__init__(msg) |
| 22 |
self.note = note |
| 23 |
|
| 24 |
|
| 25 |
def render_path(path): |
| 26 |
if isinstance(path, basestring): |
| 27 |
return path |
| 28 |
def aux(p): |
| 29 |
if not isinstance(p, basestring): |
| 30 |
return '[%d]' % p |
| 31 |
return ('.%s' if _isidentifier(p) else '["%s"]') % p |
| 32 |
return '$' + ''.join([aux(p) for p in path]) |
| 33 |
|
| 34 |
|
| 35 |
# Utilities |
| 36 |
|
| 37 |
def err(path, msg, note=None): |
| 38 |
raise ConfigError('%s: %s' % (render_path(path), msg), note) |
| 39 |
|
| 40 |
_KEYWORDS = { |
| 41 |
'import', 'importstr', 'importbin', 'function', 'self', 'super', 'assert', 'if', |
| 42 |
'then', 'else', 'for', 'in', 'local', 'tailstrict', 'true', 'false', 'null', 'error', |
| 43 |
} |
| 44 |
|
| 45 |
def _isidentifier(name): |
| 46 |
return name not in _KEYWORDS and re.match("[_A-Za-z_][_a-zA-Z0-9]*$", name) |
| 47 |
|
| 48 |
_TYPE_FROM_STR = { |
| 49 |
'null': type(None), |
| 50 |
'bool': bool, |
| 51 |
'number': numbers.Number, |
| 52 |
'object': dict, |
| 53 |
'array': list, |
| 54 |
'string': basestring, |
| 55 |
} |
| 56 |
|
| 57 |
def _type_err(v): |
| 58 |
if isinstance(v, basestring): |
| 59 |
return '"%s"' % v |
| 60 |
if isinstance(v, numbers.Number): |
| 61 |
return '%s' % v |
| 62 |
if isinstance(v, bool): |
| 63 |
return '%s' % v |
| 64 |
return _type_str(v) |
| 65 |
|
| 66 |
def _type_str(v): |
| 67 |
if v is None: |
| 68 |
return 'null' |
| 69 |
if isinstance(v, basestring): |
| 70 |
return 'string' |
| 71 |
if isinstance(v, dict): |
| 72 |
return 'object' |
| 73 |
if isinstance(v, list): |
| 74 |
return 'array' |
| 75 |
if isinstance(v, numbers.Number): |
| 76 |
return 'number' |
| 77 |
if isinstance(v, bool): |
| 78 |
return 'bool' |
| 79 |
|
| 80 |
class _Empty: |
| 81 |
pass |
| 82 |
|
| 83 |
_NO_DEFAULT = _Empty() |
| 84 |
|
| 85 |
# Return the value obtained by resolving the path from root. If the value does not exist in the |
| 86 |
# last object, create it using the default and return that instead. |
| 87 |
def _resolve_path(root, path, default=_NO_DEFAULT): |
| 88 |
for i, v in enumerate(path): |
| 89 |
if isinstance(root, dict) and i == len(path) - 1: |
| 90 |
if v not in root and default != _NO_DEFAULT: |
| 91 |
root[v] = default |
| 92 |
root = root[v] |
| 93 |
return root |
| 94 |
|
| 95 |
# Validators |
| 96 |
|
| 97 |
def is_string_map(v): |
| 98 |
msg = is_type('object')(v) |
| 99 |
if msg: |
| 100 |
return msg |
| 101 |
for k, v2 in v.iteritems(): |
| 102 |
if not isinstance(v2, basestring): |
| 103 |
return 'Expected field %s type to be string but got %s' % (k, _type_err(v2)) |
| 104 |
|
| 105 |
# Validator generating functions. |
| 106 |
|
| 107 |
# Pretty-print a small set of strings. |
| 108 |
def _set_str(s): |
| 109 |
return '{%s}' % ', '.join(sorted(s)) |
| 110 |
|
| 111 |
def is_any_type(types): |
| 112 |
def check(v): |
| 113 |
if _type_str(v) not in types: |
| 114 |
return 'Expected type to be one of %s but found %s' % (_set_str(types), _type_err(v)) |
| 115 |
return check |
| 116 |
|
| 117 |
def is_type(t): |
| 118 |
def check(v): |
| 119 |
if _type_str(v) != t: |
| 120 |
return 'Expected type %s but found %s' % (t, _type_err(v)) |
| 121 |
return check |
| 122 |
|
| 123 |
def is_value(expected): |
| 124 |
def check(v): |
| 125 |
if v != expected: |
| 126 |
return 'Expected value %s, got %s' % (expected, v) |
| 127 |
return check |
| 128 |
|
| 129 |
def is_any_value(expected): |
| 130 |
def check(v): |
| 131 |
if v not in expected: |
| 132 |
return 'Expected value to be one of %s, got %s' % (_set_str(expected), v) |
| 133 |
return check |
| 134 |
|
| 135 |
|
| 136 |
# User-friendly validation routines: |
| 137 |
|
| 138 |
# You can just give a type name in place of a function. |
| 139 |
def _sanitize_func(func): |
| 140 |
if isinstance(func, basestring): |
| 141 |
return is_type(func) |
| 142 |
return func |
| 143 |
|
| 144 |
# Ensure path validates by func. If not proesent, inserts default. |
| 145 |
def path_val(root, path, func, default=None): |
| 146 |
func = _sanitize_func(func) |
| 147 |
v = _resolve_path(root, path, default) |
| 148 |
msg = func(v) |
| 149 |
if msg is not None: |
| 150 |
err(path, msg) |
| 151 |
return v |
| 152 |
|
| 153 |
# Ensure path is an array and all elements validate by element_func. |
| 154 |
def array(root, path, element_func, default): |
| 155 |
v = path_val(root, path, 'array', default) |
| 156 |
element_func = _sanitize_func(element_func) |
| 157 |
for i, el in enumerate(v): |
| 158 |
path_val(root, path + [i], element_func) |
| 159 |
return v |
| 160 |
|
| 161 |
# Ensure path is an object and only has the given fields. If not present, inserts |
| 162 |
# default. |
| 163 |
def obj_only(root, path, fields, default=None): |
| 164 |
v = path_val(root, path, 'object', default) |
| 165 |
for field in v: |
| 166 |
if field not in fields: |
| 167 |
err(path, 'Unexpected field: %s' % field) |
| 168 |
return v |