summaryrefslogtreecommitdiffstats
path: root/func/yaml/dump.py
blob: eb34955b88ed2f491865cd49f93a223ea015a30f (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""

pyyaml legacy

Copyright (c) 2001 Steve Howell and Friends; All Rights Reserved

(see open source license information in docs/ directory)

"""


import types
import string
from types import StringType, UnicodeType, IntType, FloatType
from types import DictType, ListType, TupleType, InstanceType
from klass import hasMethod, isDictionary
import re

"""

  The methods from this module that are exported to the top 

  level yaml package should remain stable.  If you call

  directly into other methods of this module, be aware that 

  they may change or go away in future implementations.

  Contact the authors if there are methods in this file 

  that you wish to remain stable.

"""

def dump(*data):
    return Dumper().dump(*data)

def d(data): return dump(data)

def dumpToFile(file, *data):
    return Dumper().dumpToFile(file, *data)

class Dumper:
    def __init__(self):
        self.currIndent   = "\n"
        self.indent = "    "
        self.keysrt   = None
        self.alphaSort = 1 # legacy -- on by default


    def setIndent(self, indent):
        self.indent = indent
        return self

    def setSort(self, sort_hint):
        self.keysrt = sortMethod(sort_hint)
        return self

    def dump(self, *data):
        self.result = []  
        self.output = self.outputToString
        self.dumpDocuments(data)
        return string.join(self.result,"")

    def outputToString(self, data):
        self.result.append(data)

    def dumpToFile(self, file, *data):
        self.file = file
        self.output = self.outputToFile
        self.dumpDocuments(data)

    def outputToFile(self, data):
        self.file.write(data)

    def dumpDocuments(self, data):
        for obj in data:
            self.anchors  = YamlAnchors(obj)
            self.output("---")
            self.dumpData(obj)
            self.output("\n")       

    def indentDump(self, data):
        oldIndent = self.currIndent
        self.currIndent += self.indent
        self.dumpData(data)
        self.currIndent = oldIndent

    def dumpData(self, data):
        anchor = self.anchors.shouldAnchor(data)
        # Disabling anchors because they are lame for strings that the user might want to view/edit -- mdehaan

        # 

        #if anchor: 

        #    self.output(" &%d" % anchor )

        #else:

        #    anchor = self.anchors.isAlias(data)

        #    if anchor:

        #        self.output(" *%d" % anchor )

        #        return

        if (data is None):
            self.output(' ~')
        elif hasMethod(data, 'to_yaml'):
            self.dumpTransformedObject(data)            
        elif hasMethod(data, 'to_yaml_implicit'):
            self.output(" " + data.to_yaml_implicit())
        elif type(data) is InstanceType:
            self.dumpRawObject(data)
        elif isDictionary(data):
            self.dumpDict(data)
        elif type(data) in [ListType, TupleType]:
            self.dumpList(data)
        else:
            self.dumpScalar(data)

    def dumpTransformedObject(self, data):
        obj_yaml = data.to_yaml()
        if type(obj_yaml) is not TupleType:
            self.raiseToYamlSyntaxError()
        (data, typestring) = obj_yaml
        if typestring:
            self.output(" " + typestring)
        self.dumpData(data)

    def dumpRawObject(self, data):
        self.output(' !!%s.%s' % (data.__module__, data.__class__.__name__))
        self.dumpData(data.__dict__)

    def dumpDict(self, data):
        keys = data.keys()
        if len(keys) == 0:
            self.output(" {}")
            return
        if self.keysrt:
            keys = sort_keys(keys,self.keysrt)
        else:
            if self.alphaSort:
                keys.sort()
        for key in keys:
            self.output(self.currIndent)
            self.dumpKey(key)
            self.output(":")
            self.indentDump(data[key])

    def dumpKey(self, key):
        if type(key) is TupleType:
            self.output("?")
            self.indentDump(key) 
            self.output("\n")
        else:
            self.output(quote(key))

    def dumpList(self, data):
        if len(data) == 0:
            self.output(" []")
            return
        for item in data:
            self.output(self.currIndent)
            self.output("-")
            self.indentDump(item)

    def dumpScalar(self, data):
        if isUnicode(data):
            self.output(' "%s"' % repr(data)[2:-1])
        elif isMulti(data):
            self.dumpMultiLineScalar(data.splitlines())
        else:
            self.output(" ")
            self.output(quote(data))
    
    def dumpMultiLineScalar(self, lines):
        self.output(" |")
        if lines[-1] == "":
            self.output("+")
        for line in lines:
            self.output(self.currIndent)
            self.output(line)

    def raiseToYamlSyntaxError(self):
            raise """

to_yaml should return tuple w/object to dump 

and optional YAML type.  Example:

({'foo': 'bar'}, '!!foobar')

"""

#### ANCHOR-RELATED METHODS


def accumulate(obj,occur):
    typ = type(obj)
    if obj is None or \
       typ is IntType or \
       typ is FloatType or \
       ((typ is StringType or typ is UnicodeType) \
       and len(obj) < 32): return
    obid = id(obj)
    if 0 == occur.get(obid,0):
        occur[obid] = 1
        if typ is ListType:
            for x in obj: 
                accumulate(x,occur)
        if typ is DictType:
            for (x,y) in obj.items():
                accumulate(x,occur)
                accumulate(y,occur)
    else:
        occur[obid] = occur[obid] + 1

class YamlAnchors:
     def __init__(self,data):
         occur = {}
         accumulate(data,occur)
         anchorVisits = {}
         for (obid, occur) in occur.items():
             if occur > 1:
                 anchorVisits[obid] = 0 
         self._anchorVisits = anchorVisits
         self._currentAliasIndex     = 0
     def shouldAnchor(self,obj):
         ret = self._anchorVisits.get(id(obj),None)
         if 0 == ret:
             self._currentAliasIndex = self._currentAliasIndex + 1
             ret = self._currentAliasIndex
             self._anchorVisits[id(obj)] = ret
             return ret
         return 0
     def isAlias(self,obj):
         return self._anchorVisits.get(id(obj),0)

### SORTING METHODS


def sort_keys(keys,fn):
    tmp = []
    for key in keys:
        val = fn(key)
        if val is None: val = '~'
        tmp.append((val,key))
    tmp.sort()
    return [ y for (x,y) in tmp ]

def sortMethod(sort_hint):
    typ = type(sort_hint)
    if DictType == typ:
        return sort_hint.get
    elif ListType == typ or TupleType == typ:
        indexes = {}; idx = 0
        for item in sort_hint:
            indexes[item] = idx
            idx += 1
        return indexes.get
    else:
        return sort_hint

### STRING QUOTING AND SCALAR HANDLING

def isStr(data):
    # XXX 2.1 madness

    if type(data) == type(''):
        return 1
    if type(data) == type(u''):
        return 1
    return 0
    
def doubleUpQuotes(data):
    return data.replace("'", "''")

def quote(data):
    if not isStr(data):
        return str(data)
    single = "'"
    double = '"'
    quote = ''
    if len(data) == 0:
        return "''"
    if hasSpecialChar(data) or data[0] == single:
        data = `data`[1:-1]
        data = string.replace(data, r"\x08", r"\b")
        quote = double 
    elif needsSingleQuote(data):
        quote = single
        data = doubleUpQuotes(data)
    return "%s%s%s" % (quote, data, quote)

def needsSingleQuote(data):
    if re.match(r"^-?\d", data):
        return 1
    if re.match(r"\*\S", data):
        return 1
    if data[0] in ['&', ' ']:
        return 1
    if data[0] == '"':
        return 1
    if data[-1] == ' ':
        return 1
    return (re.search(r'[:]', data) or re.search(r'(\d\.){2}', data))

def hasSpecialChar(data):
    # need test to drive out '#' from this

    return re.search(r'[\t\b\r\f#]', data)

def isMulti(data):
    if not isStr(data):
        return 0
    if hasSpecialChar(data):
        return 0
    return re.search("\n", data)

def isUnicode(data):
    return type(data) == unicode
    
def sloppyIsUnicode(data):
        # XXX - hack to make tests pass for 2.1

        return repr(data)[:2] == "u'" and repr(data) != data

import sys
if sys.hexversion < 0x20200000:
    isUnicode = sloppyIsUnicode