Added --add-from as a replacement option name for --local
[0publish.git] / merge.py
blobfcc8a94c1b9067e5b417c245c314afd00a224de7
1 from xml.dom import minidom, XMLNS_NAMESPACE, Node
2 from zeroinstall.injector.namespaces import XMLNS_IFACE
3 import xmltools
5 def childNodes(parent, namespaceURI = None, localName = None):
6 for x in parent.childNodes:
7 if x.nodeType != Node.ELEMENT_NODE: continue
8 if namespaceURI is not None and x.namespaceURI != namespaceURI: continue
10 if localName is None or x.localName == localName:
11 yield x
13 class Context:
14 def __init__(self, impl):
15 doc = impl.ownerDocument
16 self.attribs = {}
17 self.requires = []
18 self.commands = {}
20 node = impl
21 while True:
22 for name, value in node.attributes.itemsNS():
23 if name[0] == XMLNS_NAMESPACE:
24 xmltools.register_namespace(value, name[1])
25 elif name not in self.attribs:
26 self.attribs[name] = value
27 if node.nodeName == 'group':
28 # We don't care about <requires> or <command> inside <implementation>;
29 # they'll get copied over anyway
30 for x in childNodes(node, XMLNS_IFACE, 'requires'):
31 self.requires.append(x)
32 for x in childNodes(node, XMLNS_IFACE, 'command'):
33 self.commands[x.getAttribute('name')] = x
34 node = node.parentNode
35 if node.nodeName != 'group':
36 break
38 def find_impls(parent):
39 """Return all <implementation> children, including those inside groups."""
40 for x in childNodes(parent, XMLNS_IFACE):
41 if x.localName == 'implementation':
42 yield x
43 elif x.localName == 'group':
44 for y in find_impls(x):
45 yield y
47 def find_groups(parent):
48 """Return all <group> children, including those inside other groups."""
49 for x in childNodes(parent, XMLNS_IFACE, 'group'):
50 yield x
51 for y in find_groups(x):
52 yield y
54 def nodesEqual(a, b):
55 assert a.nodeType == Node.ELEMENT_NODE
56 assert b.nodeType == Node.ELEMENT_NODE
58 if a.namespaceURI != b.namespaceURI:
59 return False
61 if a.nodeName != b.nodeName:
62 return False
64 a_attrs = set(["%s %s" % (name, value) for name, value in a.attributes.itemsNS()])
65 b_attrs = set(["%s %s" % (name, value) for name, value in b.attributes.itemsNS()])
67 if a_attrs != b_attrs:
68 #print "%s != %s" % (a_attrs, b_attrs)
69 return False
71 a_children = list(childNodes(a))
72 b_children = list(childNodes(b))
74 if len(a_children) != len(b_children):
75 return False
77 for a_child, b_child in zip(a_children, b_children):
78 if not nodesEqual(a_child, b_child):
79 return False
81 return True
83 def score_subset(group, impl):
84 """Returns (is_subset, goodness)"""
85 for key in group.attribs:
86 if key not in impl.attribs.keys():
87 #print "BAD", key
88 return (0,) # Group sets an attribute the impl doesn't want
89 for name, g_command in group.commands.iteritems():
90 if name not in impl.commands:
91 return (0,) # Group sets a command the impl doesn't want
92 for g_req in group.requires:
93 for i_req in impl.requires:
94 if nodesEqual(g_req, i_req): break
95 else:
96 return (0,) # Group adds a requires that the impl doesn't want
97 # Score result so we get groups that have all the same requires/commands first, then ones with all the same attribs
98 return (1, len(group.requires) + len(group.commands), len(group.attribs))
100 # Note: the namespace stuff isn't quite right yet.
101 # Might get conflicts if both documents use the same prefix for different things.
102 def merge(data, local):
103 local_doc = minidom.parse(local)
104 master_doc = minidom.parseString(data)
106 # Merge each implementation in the local feed in turn (normally there will only be one)
107 for impl in find_impls(local_doc.documentElement):
108 # 1. Get the context of the implementation to add. This is:
109 # - The set of its requirements
110 # - The set of its commands
111 # - Its attributes
112 new_impl_context = Context(impl)
114 # 2. For each <group> in the master feed, see if it provides a compatible context:
115 # - A subset of the new implementation's requirements
116 # - A subset of the new implementation's command names
117 # - A subset of the new implementation's attributes (names, not values)
118 # Choose the most compatible <group> (the root counts as a minimally compatible group)
120 best_group = ((1, 0, 0), master_doc.documentElement) # (score, element)
122 for group in find_groups(master_doc.documentElement):
123 group_context = Context(group)
124 score = score_subset(group_context, new_impl_context)
125 if score > best_group[0]:
126 best_group = (score, group)
128 group = best_group[1]
129 group_context = Context(group)
131 new_commands = []
132 for name, new_command in new_impl_context.commands.iteritems():
133 old_command = group_context.commands.get(name, None)
134 if not (old_command and nodesEqual(old_command, new_command)):
135 new_commands.append(master_doc.importNode(new_command, True))
137 # If we have additional requirements, we'll need to create a subgroup and add them
138 if len(new_impl_context.requires) > len(group_context.requires) or new_commands:
139 subgroup = xmltools.create_element(group, 'group')
140 group = subgroup
141 #group_context = Context(group)
142 for x in new_impl_context.requires:
143 for y in group_context.requires:
144 if nodesEqual(x, y): break
145 else:
146 req = master_doc.importNode(x, True)
147 #print "Add", req
148 xmltools.insert_element(req, group)
149 for c in new_commands:
150 xmltools.insert_element(c, group)
152 new_impl = master_doc.importNode(impl, True)
154 # Attributes might have been set on a parent group; move to the impl
155 for name in new_impl_context.attribs:
156 #print "Set", name, value
157 xmltools.add_attribute_ns(new_impl, name[0], name[1], new_impl_context.attribs[name])
159 for name, value in new_impl.attributes.itemsNS():
160 if name[0] == XMLNS_NAMESPACE or \
161 (name in group_context.attribs and group_context.attribs[name] == value):
162 #print "Deleting duplicate attribute", name, value
163 new_impl.removeAttributeNS(name[0], name[1])
165 xmltools.insert_element(new_impl, group)
167 return master_doc.toxml()