1 # Copyright (C) 2005-2012 Aaron Bentley <abentley@panoramicfeedback.com>
2 # Chris Ball <cjb@laptop.org>
3 # Gianluca Montecchi <gian@grys.it>
4 # W. Trevor King <wking@tremily.us>
6 # This file is part of Bugs Everywhere.
8 # Bugs Everywhere is free software: you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by the Free
10 # Software Foundation, either version 2 of the License, or (at your option) any
13 # Bugs Everywhere is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
18 # You should have received a copy of the GNU General Public License along with
19 # Bugs Everywhere. If not, see <http://www.gnu.org/licenses/>.
21 """Serializing and deserializing dictionaries of parameters.
23 The serialized "mapfiles" should be clear, flat-text strings, and allow
24 easy merging of independent/conflicting changes.
32 if libbe.TESTING == True:
36 class InvalidMapfileContents (Exception):
37 def __init__(self, contents):
38 super(InvalidMapfileContents, self).__init__('Invalid JSON contents')
39 self.contents = contents
43 """Generate a JSON mapfile content string.
49 >>> sys.stdout.write(generate({}))
51 >>> sys.stdout.write(generate({'q':'p'}))
67 >>> generate({'q':u'Fran\u00e7ais'})
68 '{\\n\\n\\n\\n\\n\\n\\n "q": "Fran\\\\u00e7ais"\\n\\n\\n\\n\\n\\n\\n}\\n'
69 >>> generate({'q':u'hello'})
70 '{\\n\\n\\n\\n\\n\\n\\n "q": "hello"\\n\\n\\n\\n\\n\\n\\n}\\n'
71 >>> sys.stdout.write(generate(
72 ... {'p':'really long line\\n'*10, 'q': 'the next entry'}))
80 "p": "really long line\\nreally long line\\nreally long line\\nreally long line\\nreally long line\\nreally long line\\nreally long line\\nreally long line\\nreally long line\\nreally long line\\n",
100 lines = json.dumps(map, sort_keys=True, indent=4).splitlines()
101 # add blank lines for context-less merging
102 return '\n\n\n\n\n\n\n'.join(lines) + '\n'
105 """Parse a JSON mapfile string.
110 >>> parse('{"q": "p"}')['q']
112 >>> contents = generate({'a':'b', 'c':'d', 'e':'f'})
113 >>> dict = parse(contents)
120 >>> contents = generate({'q':u'Fran\u00e7ais'})
121 >>> dict = parse(contents)
124 >>> dict = parse('a!')
125 Traceback (most recent call last):
127 InvalidMapfileContents: Invalid JSON contents
135 return json.loads(contents)
137 raise InvalidMapfileContents(contents)
139 if libbe.TESTING == True:
140 suite = doctest.DocTestSuite()