Skip to content

Instantly share code, notes, and snippets.

@simahawk
Forked from silviot/export_skin_folder.py
Created November 24, 2015 08:30
Show Gist options
  • Save simahawk/f8c3c8b8d0d2bc0f3998 to your computer and use it in GitHub Desktop.
Save simahawk/f8c3c8b8d0d2bc0f3998 to your computer and use it in GitHub Desktop.
"""
Use with
bin/instance run export_skin_folder.py
This script will extract the portal_skins folder
named in SKINFODLER_NAME to the DEST directory
"""
import os
import sys
PLONE_PORTAL = 'Plone'
SKINFODLER_NAME = 'custom'
DEST = '/tmp/mydump'
_write_custom_meta_type_list = [
'Controller Page Template',
'Controller Python Script',
'Controller Validator',
'DTML Method',
'File',
'Image',
'Page Template',
'Script (Python)' ]
_acceptable_meta_types = _write_custom_meta_type_list + ['Folder',]
def main():
# sys.argv looks like
#['/path/to/bin/interpreter', '-c', 'export_skin_folder.py']
# when you call this script as bin/instance run export_skin_folder.py
folder = app[PLONE_PORTAL].portal_skins[SKINFODLER_NAME]
export(folder, DEST)
def export(folder, destination):
# Adapted from qPloneSkinDump
skinpath = os.path.join(destination, folder.id)
# Create directory in FS if not yet exist
if not os.path.exists(skinpath):
os.makedirs(skinpath)
# Loop of copying content from ZMIskin-folder to FSskin-folder
obj_meta = {}
for o in folder.objectValues():
meta_type = o.meta_type
id = get_id(o)
if meta_type in _acceptable_meta_types:
# Adding to .objects all acceptable meta_types.
# Fixing bug of id-meta_type confusing.
obj_meta[id] = meta_type
if meta_type == 'Folder':
export(o, skinpath)
elif meta_type in _write_custom_meta_type_list:
#writeProps(o, skinpath) # write object's properties
# extract content from object(depend on metatype) and write it to the file
writeFileContent(o, skinpath, getData(o, meta_type))
else:
print 'method ignoring ', meta_type
# write '.objects' file to directory if present objects with id without extension
if obj_meta:
writeObjectsMeta(obj_meta, skinpath)
def writeFileContent(obj, basepath, data):
"Write object content to external file."
ext = getExtForObject(obj)
filename = basepath + '/' + obj.getId() + ext
filewrite(filename, data, 'wb')
if 'Controller ' == obj.meta_type[:11]:
_writeControllerBaseMetadata(obj, filename + '.metadata')
def _writeControllerBaseMetadata(obj, filename):
"Write controller base metadata to external file."
lines = []
if hasattr(obj, 'actions'):
for a in obj.actions.actions.values():
lines.append(replaceActionKey(adjustMetadata(str(a))))
if lines: lines.insert(0, '[actions]')
if hasattr(obj, 'validators'):
n = len(lines)
for a in obj.validators.validators.values(): append_validator_str(lines, a)
if len(lines) > n: lines.insert(n, '[validators]')
if lines:
# brauchts das ?? for a in lines: print a
filewritelines(filename, lines)
def replaceActionKey(str):
return "action.%s" % '.'.join(str.split(".")[1:])
def filewritelines(filename, data):
"Write a list of strings to a file, joining list items with '\n'."
f = open(filename, 'wb')
try:
f.write('\n'.join([prepareData(item) for item in data]))
except:
exc_type, exc_value, trace = sys.exc_info()
raise Exception("There is %s (%s) exception while dumping %s file." % (exc_value, exc_type, filename))
f.close()
def adjustMetadata(str):
str = str.replace('.None', '.')
while str.find('.=') > -1:
str = str.replace('.=', '=')
return str
def get_id(obj):
""" Get real object's id."""
id = callable(obj.id) and obj.id() or obj.id
assert obj.getId() == id, "expected identical ids: '%s' != '%s'" % (obj.getId(), id)
return id
def getData(obj, meta_type):
""" Return object's data."""
try:
return meta_type in ['Image', 'File'] and obj.manage_FTPget() or obj.document_src()
except AttributeError: # UGLY, very ugly
return obj.data.data
def writeObjectsMeta(obj_meta, basepath):
"Write pairs list of object's id and his meta_type for given directory."
data = ""
for id, m_t in obj_meta.items():
data += "%s : %s\n" % (id, m_t)
filename = "%s/.objects" % basepath
filewrite(filename, data)
def filewrite(filename, data, mode='wb'):
f = open(filename, mode)
f.write(prepareData(data))
f.close()
def prepareData(data):
""" Encode unicode type string for prevent UnicodeEncodeError
while writing none ascii string data to file."""
return type(data) == type(u"") and data.encode("utf-8") or data
def getExtForObject(obj):
"Return the appropriate filename extension according to the object meta_type."
dict = {
'Controller Page Template': '.cpt',
'Controller Python Script': '.cpy',
'Controller Validator': '.vpy',
'DTML Method': '.dtml',
'Page Template': '.pt',
'Script (Python)': '.py',
'I18NLayer': '.I18NL',
}
return dict.get(obj.meta_type, '')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment