~launchpad-pqm/launchpad/devel

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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# Copyright 2009 Canonical Ltd.  This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

"""Utilities to move zcml to a new location in the tree."""

__metaclass__ = type

__all__ = [
    'handle_zcml',
    ]

import os
import re

from find import find_matches
from lxml import etree
from rename_module import (
    bzr_add, bzr_has_filename, bzr_move_file, bzr_remove_file)


EMPTY_ZCML = """\
<configure
    xmlns="http://namespaces.zope.org/zope"
    xmlns:browser="http://namespaces.zope.org/browser"
    xmlns:i18n="http://namespaces.zope.org/i18n"
    xmlns:xmlrpc="http://namespaces.zope.org/xmlrpc"
    i18n_domain="launchpad"></configure>"""

namespaces = {
    'zope': 'http://namespaces.zope.org/zope',
    'browser': 'http://namespaces.zope.org/browser',
    }


def handle_zcml(
    app_name, old_top, new_top, app_files, app_members, not_moved):
    """Migrate the file if it is ZCML."""
    new_path = os.path.join(new_top, app_name)
    zcml_files = [path for path in app_files if path.endswith('.zcml')]
    for lib_path in zcml_files:
        old_path = os.path.join(old_top, lib_path)
        if not os.path.exists(old_path):
            print "Processing  %s" % old_path
            continue
        migrate_zcml(old_top, old_path, new_path)
        dummy, file_name = os.path.split(old_path)
        rewrite_zcml_class_paths(
            old_top, new_path, file_name, app_members, app_name)
        create_browser_zcml(app_name, new_path, file_name, app_members)
        not_moved.remove(lib_path)
    package_names = consolidate_app_zcml(app_name, new_path)
    register_zcml(package_names, old_top)


def migrate_zcml(old_top, old_path, new_path):
    """Move the ZCML into the new tree and reorganise it."""
    bzr_move_file(old_path, new_path)
    print '%s => %s' % (old_path, new_path)
    # Remove the old registration.
    old_zcml_dir = os.path.join(old_top, 'zcml')
    delete_pattern = r'^.*"%s".*\n' % os.path.basename(old_path)
    for dummy in find_matches(
        old_zcml_dir, 'configure.zcml', delete_pattern, substitution=''):
        print "    Removed old configure include."


def rewrite_zcml_class_paths(old_top, new_path,
                             file_name, app_members, app_name):
    """Rewrite app classes to use relative paths."""
    abs_lib = 'canonical\.launchpad'
    module_name, dummy = os.path.splitext(file_name)
    for package_name in app_members:
        try:
            members = '|'.join(app_members[package_name][module_name])
        except KeyError:
            old_module_path = os.path.join(
                old_top, package_name, '%s.py' % module_name)
            if os.path.isfile(old_module_path):
                print '    ** missing %s.%s' % (package_name, module_name)
            continue
        module_pattern = r'\b%s(\.%s\.)(?:\w*\.)?(%s)\b' % (
            abs_lib, package_name, members)
        substitution = r'lp.%s\1%s.\2' % (app_name, module_name)
        for dummy in find_matches(
            new_path, file_name, module_pattern, substitution=substitution):
            # This function is an iterator, but we do not care about the
            # summary of what is changed.
            pass
    # Update the menu and navigation directives.
    module_pattern = r'module="canonical.launchpad.browser"'
    substitution = r'module="lp.%s.browser.%s"' % (app_name, module_name)
    for dummy in find_matches(
        new_path, file_name, module_pattern, substitution=substitution):
        pass


def create_browser_zcml(app_name, new_path, file_name, app_members):
    """Extract browser ZCML to the browser/ directory."""
    module_name, dummy = os.path.splitext(file_name)
    browser_module_name = '.browser.%s' % module_name
    new_file_path = os.path.join(new_path, file_name)
    source = open(new_file_path)
    try:
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(source, parser)
    finally:
        source.close()
    doc = tree.getroot()
    browser_doc = etree.fromstring(EMPTY_ZCML)
    # Move the facet browser directives first.
    for facet_node in doc.xpath('./zope:facet', namespaces=namespaces):
        facet = facet_node.get('facet')
        browser_facet = etree.Element('facet', facet=facet)
        for node in facet_node.xpath('./browser:*', namespaces=namespaces):
            facet_node.remove(node)
            browser_facet.append(node)
        if len(browser_facet) > 0:
            browser_doc.append(browser_facet)
    # All remaining browser directives can be moved.
    for node in doc.xpath('./browser:*', namespaces=namespaces):
        doc.remove(node)
        browser_doc.append(node)
    # Split the menus directive into two nodes, one for the this app, and
    # one for the old Launchpad app.
    module_class_path = "lp.%s.browser.%s" % (app_name, module_name)
    other_class_path = "canonical.launchpad.browser"
    for node in browser_doc.xpath('./browser:menus', namespaces=namespaces):
        app_menus = []
        other_menus = []
        module_members = app_members['browser'][module_name]
        for menu in node.get('classes').split():
            if menu in module_members:
                app_menus.append(menu)
            else:
                other_menus.append(menu)
        if len(other_menus) > 0:
            browser_doc.append(
                create_menu_node(other_class_path, other_menus))
        if len(app_menus) > 0:
            browser_doc.append(
                create_menu_node(module_class_path, app_menus))
        browser_doc.remove(node)
    # Only save the browser and other doc if information was put into them.
    if len(browser_doc) > 0:
        file_path = os.path.join(new_path, 'browser', file_name)
        write_zcml_file(file_path, browser_doc)
        write_zcml_file(new_file_path, doc)


def create_menu_node(module, menus):
    """Create a browser:menus node for the module and list of menu classes."""
    menus_tag = '{%s}menus' % namespaces['browser']
    classes = ' '.join(menus)
    return etree.Element(
        menus_tag, module=module, classes=classes, nsmap=namespaces)


def write_zcml_file(file_path, doc):
    """Write the zcml file to its location."""
    xml = format_xml(etree.tostring(doc, pretty_print=True))
    browser_file = open(file_path, 'w')
    try:
        browser_file.write(xml)
    finally:
        browser_file.close()


def format_xml(xml):
    """Format the xml for pretty printing."""
    lines = []
    leading_pattern = re.compile(r'^( *)<')
    attribute_pattern = re.compile(r' ([\w:]+=)')
    open_comment_pattern = re.compile(r'(<!--)')
    close_comment_pattern = re.compile(r'(-->)')
    classes_pattern = re.compile(
        r'( +)(classes|attributes)(=")([^"]+)')
    trailing_whitespace_pattern = re.compile(r'\s+$')
    for line in xml.splitlines():
        match = leading_pattern.match(line)
        if match is None:
            leading = ''
        else:
            leading = match.group(1)
            if len(leading) > 8:
                # lxml does not normalise whitespace between closing tags.
                leading = '        '
                line = leading + line.strip()
        line = open_comment_pattern.sub(r'\n%s\1' % leading, line)
        line = close_comment_pattern.sub(r'\1\n%s' % leading, line)
        line = attribute_pattern.sub(r'\n  %s\1' % leading, line)
        classes = classes_pattern.search(line)
        if classes is not None:
            indent = classes.group(1)
            modules = classes.group(4).split()
            module_indent = '\n  %s' % indent
            markup = r'\1\2\3' + module_indent + module_indent.join(modules)
            line = classes_pattern.sub(markup, line)
        lines.append(line)
    xml = '\n'.join(lines)
    xml = trailing_whitespace_pattern.sub('', xml)
    xml = xml.replace('  ', '    ')
    return xml


def consolidate_app_zcml(app_name, dir_path):
    """Consolidate the all the app zcml into configure.zcml."""
    consolidate_zcml(dir_path)
    consolidate_zcml(os.path.join(dir_path, 'browser'))
    # This function should also create the coop/<module>.zcml files and
    # build a list of each one so that they can be registered. The registry
    # doesn't have coop files, so it just returns a list of its own name.
    return [app_name]


def consolidate_zcml(dir_path):
    """Consolidate the directory zcml into configure.zcml."""
    all_lines = []
    if os.path.isdir(os.path.join(dir_path, 'browser')):
        # This configure.zcml must include the browser package.
        all_lines.append('\n    <include package=".browser" />')
    converted_zcml = []
    for file_name in os.listdir(dir_path):
        if not file_name.endswith('.zcml') or file_name == 'configure.zcml':
            # This is not a single zcml file.
            continue
        file_path = os.path.join(dir_path, file_name)
        zcml_file = open(file_path)
        in_root = False
        after_root = False
        try:
            for line in zcml_file:
                if '</configure>' not in line and after_root:
                    all_lines.append(line)
                    continue
                if not in_root and '<configure' in line:
                    in_root = True
                if in_root and '>' in line:
                    after_root = True
        finally:
            zcml_file.close()
        converted_zcml.append(file_path)
    configure_xml = EMPTY_ZCML.replace('><', '>%s<' % ''.join(all_lines))
    configure_path = os.path.join(dir_path, 'configure.zcml')
    if os.path.isfile(configure_path):
        configure_path = configure_path + '.extra'
        print '    ** Warning %s must be reconciled with configure.zcml ' % (
            configure_path)
    parser = etree.XMLParser(remove_blank_text=True)
    doc = etree.fromstring(configure_xml, parser=parser)
    write_zcml_file(configure_path, doc)
    bzr_add([configure_path])
    for file_path in converted_zcml:
        if bzr_has_filename(file_path):
            bzr_remove_file(file_path)
        else:
            os.remove(file_path)


def register_zcml(package_names, old_top):
    """Register the new zcml in Launchpad's config."""
    # Package names could be like: ['answers', 'coop.answersbugs']
    for package_name in package_names:
        include = r'<include package="lp\.%s" />' % package_name
        unregistered = False
        for dummy in find_matches(old_top, 'configure.zcml', include):
            # The module is already registered.
            unregistered = True
        if unregistered:
            continue
        insert_after = r'(<include package="canonical.launchpad.xmlrpc" />)'
        include = r'\1\n\n  <include package="lp.%s" />' % package_name
        for dummy in find_matches(
            old_top, 'configure.zcml', insert_after, substitution=include):
            pass


# Verify the formatter is sane.
if __name__ == '__main__':
    source = open('lib/lp/registry/browser/configure.zcml')
    try:
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(source, parser)
    finally:
        source.close()
    doc = tree.getroot()
    write_zcml_file('./test.xml', doc)