source: products/qPloneSkinDump/tags/0.7.1/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: 8.9 KB
Line 
1import os, re, string
2from App.config import getConfiguration
3from Products.CMFCore.utils import getToolByName
4
5from config import *
6from write_utils import writeProps, writeFileContent, writeObjectsMeta
7
8CSS_PATTERN = re.compile("^.+\.css$")
9JS_PATTERN = re.compile("^.+\.js$")
10_write_custom_meta_type_list = [
11    'Controller Page Template',
12    'Controller Python Script',
13    'Controller Validator',
14    'DTML Method',
15    'File',
16    'Image',
17    'Page Template',
18    'Script (Python)' ]
19ospJoin = os.path.join
20
21def getProductsFSPath():
22    """ Return Plone instance Product's file system directory path."""
23    cfg = getConfiguration()
24    return ospJoin(cfg.instancehome,'Products')
25
26def getFSSkinPath(fs_product_name, fs_skin_directory, skin_obj, subdir):
27    """ Return file system skin path for subdir."""
28    skinpath = "%s/%s/skins/%s" % (getProductsFSPath() \
29                                  ,fs_product_name \
30                                  ,fs_skin_directory)
31    # If in skin's subfolder - get its path
32    skinp, subp = [obj.getPhysicalPath() for obj in [skin_obj, subdir]]
33    if len(subp) != len(skinp):
34        # adapt skinpath for creating directory
35        skinpath += '/' + '/'.join( subp[len(skinp):] )
36    return skinpath
37
38def get_id(obj):
39    """ Get real object's id."""
40    id = callable(obj.id) and obj.id() or obj.id
41    assert obj.getId() == id, "expected identical ids: '%s' != '%s'" % (obj.getId(), id)
42    return id
43
44def getData(obj, meta_type):
45    """ Return object's data."""
46    return meta_type in ['Image', 'File'] and obj.manage_FTPget() or obj.document_src()
47
48def dumpSkin(context, \
49             skin_name='custom', \
50             subdir=None, \
51             fs_skin_directory='custom', \
52             fs_product_name='QSkinTemplate', \
53             erase_from_skin=0):
54    """Dump custom information to file."""
55    # In case of recursable call go into subdir in skin folder.
56    skin_obj = getToolByName( context, 'portal_skins' )[skin_name]
57    subdir = subdir or skin_obj
58    skinpath = getFSSkinPath(fs_product_name, fs_skin_directory, skin_obj, subdir)
59    # Create directory in FS if not yet exist
60    if not os.path.exists( skinpath ):
61        os.makedirs( skinpath )
62    # Loop of copying content from ZMIskin-folder to FSskin-folder
63    deletelist = []
64    obj_meta = {}
65    for o in subdir.objectValues():
66        meta_type = o.meta_type
67        id = get_id(o)
68        if meta_type == 'Folder':
69            # very plone specific
70            if id in ['stylesheet_properties', 'base_properties'] \
71               or id.startswith('base_properties'):
72                writeProps( o, skinpath, extension = '.props' )
73            else:
74                dumpSkin( context, skin_name, subdir = o,\
75                          fs_skin_directory=fs_skin_directory,\
76                          fs_product_name=fs_product_name,\
77                          erase_from_skin = erase_from_skin )
78            deletelist.append( o.getId() )
79        elif meta_type in _write_custom_meta_type_list:
80            #writeProps( o, skinpath )      # write object's properties
81            # extract content from object(depend on metatype) and write it to the file
82            if id.find('.') < 0 : obj_meta[id] = meta_type
83            writeFileContent( o, skinpath, getData(o, meta_type) )
84            deletelist.append( o.getId() )
85        else:
86            print 'method ignoring ', meta_type
87    # write '.objects' file to directory if present objects with id without extension
88    if obj_meta :
89        writeObjectsMeta(obj_meta, skinpath)
90    # delete objects from the skin, if request
91    if erase_from_skin:
92        subdir.manage_delObjects( ids = deletelist )
93
94def fillinFileTemplate(f_path_read, f_path_write=None, dict={}):
95    """ Fillin file template with data from dictionary."""
96    if not f_path_write:
97        f_path_write = f_path_read
98    f_tmpl = open(f_path_read, 'r')
99    tmpl = f_tmpl.read()
100    f_tmpl.close()
101    f_tmpl = open(f_path_write, 'w')
102    f_tmpl.write(tmpl % dict)
103    f_tmpl.close()
104
105def getResourcesList(directory, resources_list, pattern=CSS_PATTERN):
106    """ Get resources list from 'directory' skin folder."""
107    for o in directory.objectValues():
108        meta_type = o.meta_type
109        id = get_id(o)
110        if meta_type == 'Folder':
111            # very plone specific
112            if id not in ['stylesheet_properties', 'base_properties'] \
113               and not id.startswith('base_properties'):
114                css_list = getResourcesList(o, resources_list, pattern)
115        elif pattern.match(id):
116            resources_list.append( id )
117    return resources_list
118 
119def getResourceProperties(context, regestry_id, prop_list, dflt=''):
120    """ Return list of dictionaries with all dumped resources properties."""
121    properties=[]
122    resource = getToolByName(context, regestry_id, None)
123    if resource:
124        for res in resource.getResources():
125            props = {}
126            for prop in prop_list:
127                accessor = getattr(res, 'get%s' % prop.capitalize(), None)
128                if accessor:
129                    props[prop] = accessor() or dflt
130            properties.append(props)
131    return properties
132
133def getResourceListRegdata(context, subdir, rsrc_pattern, rsrc_name, rsrc_reg_props):
134    rsrc_list = getResourcesList(subdir, resources_list=[], pattern=rsrc_pattern)#---CSS--#000000#aabbcc
135    result_rsrc_list = []
136    [result_rsrc_list.append(item) for item in rsrc_list if item not in result_rsrc_list]
137    skin_css_regdata = getResourceProperties(context, rsrc_name, rsrc_reg_props)   # Get Data from CSS Regestry
138    return result_rsrc_list, skin_css_regdata
139
140def copyDir(srcDirectory, dstDirectory, productName):
141    """Recursive copying from ZMIskin-folder to FS one""" 
142    for item in os.listdir(srcDirectory):
143        src_path = ospJoin(srcDirectory, item)
144        dst_path = ospJoin(dstDirectory, item)
145        if os.path.isfile(src_path):
146            if os.path.exists(dst_path):
147                continue
148            f_sorce = open(src_path,'r')
149            data = f_sorce.read()
150            f_sorce.close()
151            f_dst = open(dst_path,'w')
152            f_dst.write(data)
153            f_dst.close()
154        elif os.path.isdir(src_path):
155            if not os.path.exists(dst_path):
156                os.mkdir(dst_path)
157            copyDir(src_path, dst_path, productName)
158
159def makeNewProduct(context, productName, productSkinName, \
160                   zmi_skin_name, zmi_base_skin_name, subdir,\
161                   doesCustomizeSlots, left_slots, right_slots, slot_forming, main_column, \
162                   doesExportObjects, import_policy, dump_CSS, dump_JS):
163    """Create new skin-product's directory and
164       copy skin-product template with little modification""" 
165    products_path = getProductsFSPath()
166    productPath = ospJoin(products_path, productName)
167    if not ( productName in os.listdir(products_path) ):
168        os.mkdir(productPath)
169    # Form CSS and JS importing list and regestry data (looking in subdir too) for Plone 2.1.0+
170    subdir = subdir or getToolByName( context, 'portal_skins' )[zmi_skin_name]
171    result_css_list = skin_css_regdata = result_js_list = skin_js_regdata = []
172    if dump_CSS:
173        result_css_list, skin_css_regdata = getResourceListRegdata(context, subdir,
174                                            CSS_PATTERN, 'portal_css', CSS_REG_PROPS)
175    if dump_JS:
176        result_js_list, skin_js_regdata = getResourceListRegdata(context, subdir,
177                                            JS_PATTERN, 'portal_javascripts', JS_REG_PROPS)
178    # Get Slots customization information
179    if not doesCustomizeSlots:
180        left_slots = right_slots = None
181        slot_forming = main_column = None
182    # Copy skin_template to SKIN_PRODUCT directory
183    templatePath = ospJoin(products_path, PROJECTNAME, TEMPLATE_PATH)
184    copyDir(templatePath, productPath, productName)
185    # Form data dictionary and form Skin Product's files
186    conf_dict = {"IMPORT_POLICY" : import_policy \
187                ,"GENERATOR_PRODUCT" : PROJECTNAME \
188                ,"SKIN_PRODUCT_NAME" : productName \
189                ,"SKIN_NAME" : productSkinName \
190                ,"BASE_SKIN_NAME" : zmi_base_skin_name \
191                ,"DUMP_CSS": not not dump_CSS \
192                ,"DUMP_JS": not not dump_JS \
193                ,"CSS_LIST" : str(result_css_list) \
194                ,"JS_LIST" : str(result_js_list) \
195                ,"SKIN_CSS_REGDATA" : str(skin_css_regdata) \
196                ,"SKIN_JS_REGDATA" : str(skin_js_regdata) \
197                ,"LEFT_SLOTS" : str(left_slots) \
198                ,"RIGHT_SLOTS" : str(right_slots) \
199                ,"SLOT_FORMING" : slot_forming \
200                ,"MAIN_COLUMN" : main_column \
201                }
202    sp_updated_files = ['config.py' \
203                       ,'README.txt' \
204                       ,ospJoin('Extensions', 'utils.py')\
205                       ,ospJoin('Extensions', 'Install.py')]
206    for fp in sp_updated_files:
207        fillinFileTemplate(ospJoin(productPath, fp), dict=conf_dict)
Note: See TracBrowser for help on using the repository browser.