Skip to content

Instantly share code, notes, and snippets.

@mvaled
Created September 11, 2012 19:32
Show Gist options
  • Save mvaled/3701401 to your computer and use it in GitHub Desktop.
Save mvaled/3701401 to your computer and use it in GitHub Desktop.
Normalizes files titles in a Plone instance
import transaction, pdb
from zope.interface import implementedBy
from zope.component import getUtility, queryUtility, queryAdapter
from Zope2 import debug
from Acquisition import aq_inner, aq_parent, aq_chain
from zope.app.component.hooks import setSite, getSiteManager
from Testing.makerequest import makerequest
from AccessControl.SecurityManagement import newSecurityManager, getSecurityManager
try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
app = makerequest(app)
site = app[site_id]
setSite(site)
user = app.acl_users.getUser('admin').__of__(site.acl_users)
newSecurityManager(None, user)
def normalize_title(old_title):
new_title = old_title.replace('_', ' ')
index = new_title.rfind('.')
if index != -1:
new_title = new_title[:index]
return new_title
def rename_files(app, portal_name, portal_type='File', partition=None):
import sys
catalog = getattr(app, portal_name).portal_catalog
if partition:
files = catalog.unrestrictedSearchResults(portal_type=portal_type)[partition]
else:
files = catalog.unrestrictedSearchResults(portal_type=portal_type)
i = 0
flush = getattr(sys.stdout, 'flush', None)
try:
print 'Going to process %d file(s)' % len(files)
for brain in files:
obj = brain._unrestrictedGetObject()
title = obj.Title()
brain_id = obj.getId()
changed = False
if not title:
title = brain_id
changed = True
if title.find('.') != -1 or title.find('_') != -1 or changed:
obj.setTitle(normalize_title(title))
i += 1
transaction.begin()
transaction.savepoint(optimistic=True)
try:
obj.reindexObject()
if i % 500 == 0:
print '.',
if flush:
flush()
transaction.commit()
except:
print 'Error when normalizing title: %r, from %r ' % (title, obj.id)
import traceback
traceback.print_last()
transaction.abort()
except:
import traceback
traceback.print_last()
print 'Aborting...'
app._p_jar.sync()
# If this script lives in your source tree, then we need to use this trick so that
# five.grok, which scans all modules, does not try to execute the script while
# modules are being loaded on the start-up
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment