Brad Bishop | e2b65e9 | 2016-04-01 14:41:06 -0400 | [diff] [blame] | 1 | # Contributors Listed Below - COPYRIGHT 2016 |
| 2 | # [+] International Business Machines Corp. |
| 3 | # |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 14 | # implied. See the License for the specific language governing |
| 15 | # permissions and limitations under the License. |
| 16 | |
| 17 | |
| 18 | def dts_encode(obj, fd, **kw): |
| 19 | ''' A rudimentary python to dts encoder. |
| 20 | ''' |
| 21 | indent = kw.get('indent', 0) |
| 22 | depth = kw.setdefault('depth', 0) |
| 23 | tab = indent * depth * ' ' |
| 24 | kw['depth'] += 1 |
| 25 | newline = '\n' if indent else ' ' |
| 26 | context = kw.get('context') |
| 27 | |
| 28 | if(isinstance(obj, dict)): |
| 29 | nodes = [] |
| 30 | for k, v in obj.iteritems(): |
| 31 | if(isinstance(v, dict)): |
| 32 | nodes.append((k, v)) |
| 33 | continue |
| 34 | if(isinstance(v, basestring) and v.lower() == 'true'): |
| 35 | fd.write('%s%s' % (tab, k)) |
| 36 | elif(isinstance(v, basestring) and v.lower() == 'false'): |
| 37 | continue |
| 38 | else: |
| 39 | fd.write('%s%s = ' % (tab, k)) |
| 40 | dts_encode(v, fd, **kw) |
| 41 | fd.write(";%s" % newline) |
| 42 | |
| 43 | for k, v in nodes: |
| 44 | fd.write('%s%s {%s' % (tab, k, newline)) |
| 45 | dts_encode(v, fd, **kw) |
| 46 | fd.write('%s};%s' % (tab, newline)) |
| 47 | |
| 48 | if(isinstance(obj, int)): |
| 49 | if context == 'int_list': |
| 50 | fd.write("%d" % obj) |
| 51 | else: |
| 52 | fd.write("<%d>" % obj) |
| 53 | |
| 54 | if(isinstance(obj, basestring)): |
| 55 | fd.write("\"%s\"" % obj) |
| 56 | |
| 57 | if(isinstance(obj, list)): |
| 58 | ctx = 'int_list' if all((type(x) is int) for x in iter(obj)) else '' |
| 59 | if ctx is 'int_list': |
| 60 | delim = ' ' |
| 61 | closure = ('<', '>') |
| 62 | else: |
| 63 | delim = ',' |
| 64 | closure = ('', '') |
| 65 | |
| 66 | fd.write(closure[0]) |
| 67 | if obj: |
| 68 | for v in obj[:-1]: |
| 69 | dts_encode(v, fd, context=ctx, **kw) |
| 70 | fd.write(delim) |
| 71 | |
| 72 | dts_encode(obj[-1], fd, context=ctx) |
| 73 | |
| 74 | fd.write(closure[1]) |