source: products/qPloneSkinDump/tags/0.7.1/write_utils.py @ 1552

Last change on this file since 1552 was 1, checked in by myroslav, 18 years ago

Building directory structure

  • Property svn:eol-style set to native
File size: 4.6 KB
Line 
1#
2# Main part of code of this module is taking from RedPICK product
3# was made some correction in ControllerBaseMetadata forming procedure
4#
5
6def writeObjectsMeta( obj_meta, basepath ):
7    "Write pairs list of object's id and his meta_type for given directory."
8    data = ""
9    for id, m_t in obj_meta.items():
10        data += "%s : %s\n" % (id, m_t)
11    filename = "%s/.objects" % basepath
12    filewrite( filename, data )
13
14# just in case of nessecity (not use now)
15def writeProps( obj, basepath, extension = '.properties' ):
16    "Write object properties to a file."
17    ext = getExtForObject( obj )
18    filename = basepath + '/' + obj.getId() + ext + extension
19    writeProps2( filename, obj )
20
21def writeFileContent( obj, basepath, data ):
22    "Write object content to external file."
23    ext = getExtForObject( obj )
24    filename = basepath + '/' + obj.getId() + ext
25    filewrite( filename, data, 'wb' )
26    if 'Controller ' == obj.meta_type[:11]:
27        _writeControllerBaseMetadata( obj, filename + '.metadata' )
28
29def getExtForObject( obj ):
30    "Return the appropriate filename extension according to the object meta_type."
31    dict = {
32        'Controller Page Template' : '.cpt',
33        'Controller Python Script' : '.cpy',
34        'Controller Validator' : '.vpy',
35        'DTML Method' : '.dtml',
36        #'File' : '',
37        #'Folder' : '',
38        #'Image' : '',
39        'Page Template' : '.pt',
40        'Script (Python)' : '.py',
41        'I18NLayer' : '.I18NL',
42    }
43    return dict.get( obj.meta_type, '' )
44
45def writeProps2( filename, obj ):
46    "Write object properties to a file."
47    filewrite( filename, formatProps2( obj ) )
48
49def formatProps2( obj, notuple = 0, suppresstitle = 0, onlynew = None, existing = None ):
50    "Return object properties in a multi-line string."
51    lines = []
52    props = obj.propertyMap()
53    for prop in props:
54        id = prop['id']
55        tp = prop['type']
56        if id.lower() == 'title' and suppresstitle:
57            continue
58        if onlynew and id in existing:
59            continue
60        value = obj.getProperty( id )
61        if notuple:
62            t = type( value )
63            if t == type([]) or t == type(()):
64                # we use comma as field delimiter, so be careful to escape existing ones
65                value = map( lambda x: x.replace( ',', '&COMMA&' ), value )
66                value = ','.join( list( value ) )
67        #if this is a multiline string we must handle it specially
68        #lines.append( '%s:%s=%s' % (id, tp, escape_quote( str( value ) ) ) )
69        lines.append( '%s:%s=%s' % (id, tp, str( value ) ) )
70    lines.sort()
71    return '\n'.join( lines )
72
73#def escape_quote( s ):
74#    "Return string with all single and double quotes escaped, i.e. backslash added before."
75#    return s.replace( '"', r'\"' ).replace( "'", r"\'" )
76
77def _writeControllerBaseMetadata( obj, filename ):
78    "Write controller base metadata to external file."
79    lines = []
80    if hasattr( obj, 'actions' ):
81        for a in obj.actions.actions.values(): 
82            lines.append(replaceActionKey(adjustMetadata(str( a ) ) ) )
83        if lines: lines.insert( 0, '[actions]' )
84    if hasattr( obj, 'validators' ):
85        n = len( lines )
86        for a in obj.validators.validators.values(): append_validator_str( lines, a )
87        if len( lines ) > n: lines.insert( n, '[validators]' )
88    if lines:
89        # brauchts das ?? for a in lines: print a
90        filewritelines( filename, lines )
91
92def append_validator_str( lines, validator ):
93    "Return a FormValidator string representation."
94    #assert 'FormValidator' == validator.__class__, 'expected a FormValidator, not ' + str( validator )
95    # validators.context.button = validate_script1, validate_script3
96    vallist = ','.join( validator.getValidators() )
97    if vallist:
98        lines.append(adjustMetadata( 'validators.%s.%s=%s' \
99            % (validator.getContextType(), validator.getButton(), vallist) ) )
100
101def replaceActionKey(str):
102    return "action.%s" % '.'.join(str.split(".")[1:])
103   
104def adjustMetadata(str):
105    str = str.replace('.None', '.')
106    while str.find('.=')>-1:
107        str = str.replace('.=', '=')
108    return str
109
110def filewrite( filename, data, mode = 'wb' ):
111    f = open( filename, mode )
112    f.write( prepareData(data) )
113    f.close()
114
115def filewritelines( filename, data ):
116    "Write a list of strings to a file, joining list items with '\n'."
117    f = open( filename, 'wb' )
118    f.write( '\n'.join( [prepareData(item) for item in data]) )
119    f.close()
120
121def prepareData(data):
122    """ Encode unicode type string for prevent UnicodeEncodeError
123        while writing none ascii string data to file."""
124    return type(data) == type(u"") and data.encode("utf-8") or data
Note: See TracBrowser for help on using the repository browser.