source: products/qPloneSkinDump/tags/0.7.3/utils.py @ 1

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

Building directory structure

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