Public
Snippet $444 authored by Jérome Perrin

Script used to rewrite business template xml for new workflow history format

Edited
rewrite_workflow_history_log.py
Raw
#!/usr/bin/env python
import sys
from lxml import etree
from lxml.builder import E

def reindent(elements):
  """Reindent the workflow item list that is now in a _log
  """
  for e in elements:
    if e.text and '\n' in e.text:
      e.text = e.text + '      '
    if e.tail and '\n' in e.tail:
      if e.tag == 'item':
        if e.tail == '\n            ':
          e.tail =   '\n                  '
        else:
          assert e.tail == '\n          '
          e.tail =         '\n                '
      else:
        e.tail = e.tail + '      '
    # this is not about reindenting, but also make sure that <string></string>
    # does not become <string/> in this process.
    if e.tag == 'string' and not e.text:
      e.text = ''
    reindent(e)
  return elements

for filename in sys.argv[1:]:
  with open(filename) as f:
    tree = etree.parse(f)
    root = tree.getroot()

    class_name_elements = tree.xpath(
        '//record/pickle/global[@name="WorkflowHistoryList" and @module="Products.ERP5Type.patches.WorkflowTool"]'
    )
    if not class_name_elements:
      continue

    for class_name_element in class_name_elements:
      class_name_element.attrib['module'] = 'Products.ERP5Type.Workflow'
      old_pickle, = class_name_element.xpath('../../pickle[2]')

      record = old_pickle.getparent()
      record.remove(old_pickle)

      pickle = E.pickle(
        '\n      ',
        E.dictionary(
          '\n        ',
          E.item(
            '\n            ',
            E.key(' ', E.string('_log'), ' '),
            '\n            ',
            E.value(
              '\n              ',
              # We save **all** the list in the same bucket
              # while not strictly correct, business template histories
              # should not be long. Most have only one element.
              *reindent(old_pickle.xpath('./tuple//list'))),
              '\n        '
          ),
          '\n      '
        ),
        '\n    '
      )
      pickle.tail = '\n  '
      record.append(pickle)

  with open(filename, 'w') as f:
    f.write(
        '<?xml version="1.0"?>\n'
        + etree.tostring(root, pretty_print=True, encoding="utf-8"))
  print (filename)
  #  print etree.tostring(root, pretty_print=True, encoding="utf-8")
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!