public
Created

Normalizes files titles in a Plone instance

  • Download Gist
renames_files.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.