source: products/qPloneSkinDump/branches/multipleslots/write_utils.py @ 1591

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

Building directory structure

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