Merge lp:~spud/spud/xmldiff into lp:spud

Proposed by Fraser Waters
Status: Merged
Merged at revision: 457
Proposed branch: lp:~spud/spud/xmldiff
Merge into: lp:spud
Diff against target: 2760 lines (+2526/-13)
17 files modified
Makefile.in (+10/-0)
debian/control (+10/-1)
debian/rules (+4/-1)
diamond/bin/diamond (+24/-3)
diamond/diamond/diffview.py (+558/-0)
diamond/diamond/interface.py (+30/-7)
diamond/gui/gui.glade (+15/-1)
dxdiff/COPYING (+15/-0)
dxdiff/GPL-3 (+676/-0)
dxdiff/dxdiff/bimap.py (+49/-0)
dxdiff/dxdiff/diff.py (+26/-0)
dxdiff/dxdiff/dxdiff (+87/-0)
dxdiff/dxdiff/editscript.py (+79/-0)
dxdiff/dxdiff/fmes.py (+466/-0)
dxdiff/dxdiff/lcs.py (+284/-0)
dxdiff/dxdiff/utils.py (+172/-0)
dxdiff/setup.py (+21/-0)
To merge this branch: bzr merge lp:~spud/spud/xmldiff
Reviewer Review Type Date Requested Status
Patrick Farrell Pending
Review via email: mp+72466@code.launchpad.net

Description of the change

Adds xmldiff tool and diff view to Diamond.

To post a comment you must log in.
lp:~spud/spud/xmldiff updated
454. By Patrick Farrell

Set some executable flags (how did these get lost?)

Revision history for this message
Patrick Farrell (pefarrell) wrote :

[pef@caoimhe:/tmp/xmldiff/diamond]$ python bin/diamond
Traceback (most recent call last):
  File "bin/diamond", line 228, in <module>
    main()
  File "bin/diamond", line 92, in main
    import diamond.interface as interface
  File "/tmp/xmldiff/diamond/bin/../diamond/interface.py", line 50, in <module>
    import diffview
ImportError: No module named diffview

Did you forget to bzr add?

lp:~spud/spud/xmldiff updated
455. By Fraser Waters

Added xmldiff/

456. By Fraser Waters

Added diffview.py

457. By Fraser Waters

Fixing pathing bugs, still more to go.

458. By Fraser Waters

Fixed more pathing bugs.

459. By Fraser Waters

Pathing bugs squashed.

460. By Fraser Waters

Renamed xmldiff to dxdiff (Diamond Xml diff). Added dxdiff to packages.

461. By Fraser Waters

Can no longer diff against save if no save.

462. By Fraser Waters

Added diamond -d [FILE] option.

463. By Fraser Waters

Don't delete text() nodes

464. By Fraser Waters

remove xpath names, fix __floodfill

465. By Fraser Waters

Properly fixed __floodfill

466. By Fraser Waters

Fixed indexing bugs

467. By Fraser Waters

Diff timed, fixed typo in _match

468. By Fraser Waters

dxdiff bug fixed

469. By Fraser Waters

Fixed indent typo, removed debuging code

470. By Fraser Waters

Removed more debug code

471. By Fraser Waters

Changed getopt to gnu_getopt

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
=== modified file 'Makefile.in'
--- Makefile.in 2011-08-04 21:30:53 +0000
+++ Makefile.in 2011-08-24 16:38:18 +0000
@@ -101,11 +101,21 @@
101 cd python; for python in $(shell pyversions -r); do $$python setup.py install --prefix=$(DESTDIR)@prefix@ --install-layout=deb; done; cd ..101 cd python; for python in $(shell pyversions -r); do $$python setup.py install --prefix=$(DESTDIR)@prefix@ --install-layout=deb; done; cd ..
102endif102endif
103103
104install-dxdiff:
105ifeq ($(origin DESTDIR),undefined)
106 cd dxdiff; python setup.py install --prefix=$(DESTDIR)@prefix@; cd ..
107else
108 cd dxdiff; for python in $(shell pyversions -r); do $$python setup.py install --prefix=$(DESTDIR)@prefix@ --install-layout=deb; done; cd ..
109endif
110
104clean:111clean:
105 @cd doc; $(MAKE) clean112 @cd doc; $(MAKE) clean
106 rm -f *.o libspud.a libspud.so *.o *.la *.mod *.lo113 rm -f *.o libspud.a libspud.so *.o *.la *.mod *.lo
107 rm -rf .libs114 rm -rf .libs
108 @cd src/tests; $(MAKE) clean115 @cd src/tests; $(MAKE) clean
116 @cd python; rm -rf build; cd ..
117 @cd dxdiff; rm -rf build; cd ..
118
109119
110distclean: clean120distclean: clean
111 @cd src/tests; $(MAKE) distclean121 @cd src/tests; $(MAKE) distclean
112122
=== modified file 'config.guess' (properties changed: +x to -x)
=== modified file 'config.sub' (properties changed: +x to -x)
=== modified file 'debian/control'
--- debian/control 2011-08-15 20:50:30 +0000
+++ debian/control 2011-08-24 16:38:18 +0000
@@ -9,7 +9,7 @@
99
10Package: diamond10Package: diamond
11Architecture: all11Architecture: all
12Depends: python-gtk2, python-lxml, libxml2-utils, python, spudtools, python-gtksourceview212Depends: python-gtk2, python-lxml, libxml2-utils, python, spudtools, python-gtksourceview2, python-dxdiff
13Recommends: python-psyco13Recommends: python-psyco
14Suggests: 14Suggests:
15Conflicts: python-diamond15Conflicts: python-diamond
@@ -62,3 +62,12 @@
62 file is generated using a spud-compatible RELAX NG schema and a62 file is generated using a spud-compatible RELAX NG schema and a
63 schema-aware editor such as Diamond. This package contains the Python63 schema-aware editor such as Diamond. This package contains the Python
64 bindings for libspud.64 bindings for libspud.
65
66Package: python-dxdiff
67Section: python
68Architecture: any
69XB-Python-Version: ${python:Versions}
70Depends: ${python:Depends}, ${misc:Depends}
71Description: An XML aware diff tool.
72 DXdiff (Diamond Xml diff) is an XML aware diff tool for finding edit scripts
73 between two XML files.
6574
=== modified file 'debian/rules'
--- debian/rules 2011-08-16 22:52:44 +0000
+++ debian/rules 2011-08-24 16:38:18 +0000
@@ -83,6 +83,9 @@
83install-pyspud:83install-pyspud:
84 $(MAKE) install-pyspud DESTDIR=$(CURDIR)/debian/python-spud84 $(MAKE) install-pyspud DESTDIR=$(CURDIR)/debian/python-spud
8585
86install-dxdiff:
87 $(MAKE) install-dxdiff DESTDIR=$(CURDIR)/debian/python-dxdiff
88
86binary-arch: build-libspud install-libspud install-spudtools install-pyspud89binary-arch: build-libspud install-libspud install-spudtools install-pyspud
87 dh_testdir90 dh_testdir
88 dh_testroot91 dh_testroot
@@ -114,7 +117,7 @@
114 dh_md5sums117 dh_md5sums
115 dh_builddeb118 dh_builddeb
116119
117binary-indep: build-diamond install-diamond build-libspud install-libspud install-spudtools120binary-indep: build-diamond install-diamond build-libspud install-libspud install-spudtools install-dxdiff
118 dh_testdir -i121 dh_testdir -i
119 dh_testroot -i122 dh_testroot -i
120 DH_PYCENTRAL=include-links dh_pycentral -i123 DH_PYCENTRAL=include-links dh_pycentral -i
121124
=== modified file 'diamond/bin/diamond'
--- diamond/bin/diamond 2011-07-05 11:42:44 +0000
+++ diamond/bin/diamond 2011-08-24 16:38:18 +0000
@@ -29,6 +29,8 @@
29# do this right at the start, so we can find the diamond modules29# do this right at the start, so we can find the diamond modules
30diamond_path = os.path.join( os.path.realpath(os.path.dirname(__file__)), os.pardir )30diamond_path = os.path.join( os.path.realpath(os.path.dirname(__file__)), os.pardir )
31sys.path.insert(0, diamond_path)31sys.path.insert(0, diamond_path)
32dxdiff_path = os.path.join( os.path.realpath(os.path.dirname(__file__)), os.pardir, os.pardir, "dxdiff" )
33sys.path.insert(0, dxdiff_path)
3234
33import diamond.debug as debug35import diamond.debug as debug
3436
@@ -48,6 +50,7 @@
48 "-f Forks at startup\n" + \50 "-f Forks at startup\n" + \
49 "-s [SCHEMAFILE] Use the supplied schema file *\n" + \51 "-s [SCHEMAFILE] Use the supplied schema file *\n" + \
50 "-t [TRONFILE] Use the supplied schematron file for extended validation\n" + \52 "-t [TRONFILE] Use the supplied schematron file for extended validation\n" + \
53 "-d [FILE] Diff against the supplied file. (FILE must be specified)\n" + \
51 "-v Verbosity switch - if supplied Diamond prints additional\n" + \54 "-v Verbosity switch - if supplied Diamond prints additional\n" + \
52 " debugging information to standard output and standard error\n" + \55 " debugging information to standard output and standard error\n" + \
53 "\n" + \56 "\n" + \
@@ -59,7 +62,7 @@
59def main():62def main():
6063
61 try:64 try:
62 opts, args = getopt.getopt(sys.argv[1:], "hvfs:t:")65 opts, args = getopt.gnu_getopt(sys.argv[1:], "hvfs:t:d:")
63 except:66 except:
64 Help()67 Help()
65 sys.exit(1)68 sys.exit(1)
@@ -99,8 +102,13 @@
99 except IndexError:102 except IndexError:
100 input_filename = None103 input_filename = None
101104
105 if sys.platform == "win32" or sys.platform == "win64":
106 possible_logofiles = [os.path.join(diamond_path, "gui", "diamond.png")]
107 else:
108 possible_logofiles = [os.path.join(diamond_path, "gui", "diamond.svg"), "/usr/share/diamond/gui/diamond.svg"]
109
102 logofile = None110 logofile = None
103 for possible_logofile in [os.path.join(diamond_path, "gui", "diamond.svg"), "/usr/share/diamond/gui/diamond.svg"]:111 for possible_logofile in possible_logofiles:
104 try:112 try:
105 os.stat(possible_logofile)113 os.stat(possible_logofile)
106 logofile = possible_logofile114 logofile = possible_logofile
@@ -209,7 +217,20 @@
209217
210 i.main_window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))218 i.main_window.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH))
211 i.open_file(schemafile = input_schemafile, filename = input_filename)219 i.open_file(schemafile = input_schemafile, filename = input_filename)
212 i.main_window.window.set_cursor(None) 220 i.main_window.window.set_cursor(None)
221
222 # see if the user wants to diff against a file
223 input_difffile = None
224 for opt in opts:
225 if opt[0] == "-d":
226 input_difffile = opt[1]
227
228 if input_difffile:
229 if input_filename:
230 i.on_diff(None, input_difffile)
231 else:
232 debug.dprint("Cannot diff if against nothing.", 0)
233
213234
214 gtk.main()235 gtk.main()
215236
216237
=== added file 'diamond/diamond/diffview.py'
--- diamond/diamond/diffview.py 1970-01-01 00:00:00 +0000
+++ diamond/diamond/diffview.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,558 @@
1#!/usr/bin/env python
2
3# This file is part of Diamond.
4#
5# Diamond is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# Diamond is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17
18import os
19import os.path
20import sys
21import cStringIO as StringIO
22
23import gobject
24import gtk
25
26from lxml import etree
27
28import attributewidget
29import databuttonswidget
30import datawidget
31import mixedtree
32
33#diff_path = os.path.join( os.path.realpath(os.path.dirname(__file__)), os.pardir, os.pardir, "xmldiff")
34#sys.path.insert(0, diff_path)
35
36import dxdiff.diff as xmldiff
37
38class DiffView(gtk.Window):
39
40 def __init__(self, path, tree):
41 gtk.Window.__init__(self)
42 self.__add_controls()
43
44 if path and os.path.isfile(path):
45 filename = path
46 else:
47 dialog = gtk.FileChooserDialog(title = "Diff against",
48 action = gtk.FILE_CHOOSER_ACTION_OPEN,
49 buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
50 if path:
51 dialog.set_current_folder(path)
52
53 response = dialog.run()
54 if response != gtk.RESPONSE_OK:
55 dialog.destroy()
56 self.destroy()
57 return
58
59 filename = dialog.get_filename()
60 dialog.destroy()
61
62 tree1 = etree.parse(filename)
63 tree2 = etree.ElementTree(tree.write_core(None))
64
65 editscript = xmldiff.diff(tree1, tree2)
66 self.__update(tree1, editscript)
67
68 self.show_all()
69
70 def __add_controls(self):
71 self.set_default_size(800, 600)
72 self.set_title("Diff View")
73
74 mainvbox = gtk.VBox()
75
76 menubar = gtk.MenuBar()
77 edititem = gtk.MenuItem("_Edit")
78 menubar.append(edititem)
79
80 agr = gtk.AccelGroup()
81 self.add_accel_group(agr)
82
83 self.popup = editmenu = gtk.Menu()
84 edititem.set_submenu(editmenu)
85 copyitem = gtk.MenuItem("Copy")
86 copyitem.connect("activate", self.on_copy)
87 key, mod = gtk.accelerator_parse("<Control>C")
88 copyitem.add_accelerator("activate", agr, key, mod, gtk.ACCEL_VISIBLE)
89 editmenu.append(copyitem)
90
91 mainvbox.pack_start(menubar, expand = False)
92
93 hpane = gtk.HPaned()
94
95 self.treeview = gtk.TreeView()
96
97 self.treeview.get_selection().set_mode(gtk.SELECTION_SINGLE)
98 self.treeview.get_selection().connect("changed", self.on_select_row)
99
100 # Node column
101 celltext = gtk.CellRendererText()
102 column = gtk.TreeViewColumn("Node", celltext)
103 column.set_cell_data_func(celltext, self.set_celltext)
104
105 self.treeview.append_column(column)
106
107 # 0: The node tag
108 # 1: The attributes dict
109 # 2: The value of the node if any
110 # 3: The old value of the node
111 # 4: "insert", "delete", "update", ""
112 self.treestore = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)
113 self.treeview.set_model(self.treestore)
114 self.treeview.set_enable_search(False)
115 self.treeview.connect("button_press_event", self.on_treeview_button_press)
116 self.treeview.connect("popup_menu", self.on_treeview_popup)
117 hpane.pack1(self.treeview)
118
119 vpane = gtk.VPaned()
120 frame = gtk.Frame()
121 label = gtk.Label()
122 label.set_markup("<b>Attributes</b>")
123 frame.set_label_widget(label)
124 frame.set_shadow_type(gtk.SHADOW_NONE)
125
126 self.attribview = gtk.TreeView()
127
128 celltext = gtk.CellRendererText()
129 keycolumn = gtk.TreeViewColumn("Key", celltext)
130 keycolumn.set_cell_data_func(celltext, self.set_cellkey)
131
132 self.attribview.append_column(keycolumn)
133
134 celltext = gtk.CellRendererText()
135 valuecolumn = gtk.TreeViewColumn("Value", celltext)
136 valuecolumn.set_cell_data_func(celltext, self.set_cellvalue)
137
138 self.attribview.append_column(valuecolumn)
139
140 frame.add(self.attribview)
141 vpane.pack1(frame)
142
143 frame = gtk.Frame()
144 label = gtk.Label()
145 label.set_markup("<b>Data</b>")
146 frame.set_label_widget(label)
147 frame.set_shadow_type(gtk.SHADOW_NONE)
148
149 self.dataview = gtk.TextView()
150 self.dataview.set_cursor_visible(False)
151 self.dataview.set_editable(False)
152 self.__create_tags(self.dataview.get_buffer())
153
154 frame.add(self.dataview)
155 vpane.pack2(frame)
156
157 hpane.pack2(vpane)
158 mainvbox.pack_start(hpane)
159 self.add(mainvbox)
160
161 def on_treeview_button_press(self, treeview, event):
162 pathinfo = treeview.get_path_at_pos(int(event.x), int(event.y))
163 if event.button == 3:
164 if pathinfo is not None:
165 treeview.get_selection().select_path(pathinfo[0])
166 self.show_popup(None, event.button, event.time)
167 return True
168
169 def popup_location(self, widget, user_data):
170 column = self.treeview.get_column(0)
171 path = self.treeview.get_selection().get_selected()[1]
172 area = self.treeview.get_cell_area(path, column)
173 tx, ty = area.x, area.y
174 x, y = self.treeview.tree_to_widget_coords(tx, ty)
175 return (x, y, True)
176
177 def on_treeview_popup(self, treeview):
178 self.show_popup(None, self.popup_location, gtk.get_current_event_time())
179 return
180
181 def show_popup(self, func, button, time):
182 self.popup.popup( None, None, func, button, time)
183 return
184
185 def __update(self, tree, editscript):
186 self.__set_treestore(tree.getroot())
187 self.__parse_editscript(editscript)
188 self.__floodfill(self.treestore.get_iter_root())
189
190 def __set_treestore(self, tree, iter = None):
191
192 attrib = {}
193 for key, value in tree.attrib.iteritems():
194 # (new, old, edit)
195 attrib[key] = (value, value, None)
196
197 child_iter = self.treestore.append(iter, [tree.tag, attrib, tree.text, tree.text, None])
198 for child in tree:
199 self.__set_treestore(child, child_iter)
200
201 def __parse_editscript(self, editscript):
202 for edit in editscript:
203 iter, key = self.__get_iter(edit["location"])
204 if key:
205 attribs = self.treestore.get_value(iter, 1)
206 old = attribs[key][1]
207 if edit["type"] == "delete":
208 attribs[key] = (None, old, "delete")
209 elif edit["type"] == "update":
210 attribs[key] = (edit["value"], old, "update")
211 elif edit["type"] == "move":
212 attribs[key] = (None, old, "delete")
213 self.__insert(self.__get_iter(edit["value"])[0], key + " " + old, 0)
214
215 else:
216
217 if edit["type"] == "insert":
218 self.__insert(iter, edit["value"], int(edit["index"]))
219 elif edit["type"] == "delete":
220 self.treestore.set(iter, 2, None)
221 self.treestore.set(iter, 4, "delete")
222 elif edit["type"] == "update":
223 self.treestore.set(iter, 2, edit["value"])
224 elif edit["type"] == "move":
225 self.__move(iter, edit["value"], int(edit["index"]))
226
227 def __floodfill(self, iter, parentedit = None):
228 """
229 Floodfill the tree with the correct edit types.
230 If something has changed below you, "subupdate"
231 If your value or attrs has changed "update"
232 If insert, all below insert
233 If delete, all below delete
234 """
235 attribs, new, old, edit = self.treestore.get(iter, 1, 2, 3, 4)
236
237 if parentedit == "insert":
238 edit = "insert"
239 elif parentedit == "delete":
240 edit = "delete"
241
242 if edit == "insert" or edit == "delete":
243 for key, (valuenew, valueold, valueedit) in attribs.iteritems():
244 attribs[key] = (valuenew, valueold, edit)
245
246 child = self.treestore.iter_children(iter)
247 while child is not None:
248 self.__floodfill(child, edit)
249 child = self.treestore.iter_next(child)
250
251 self.treestore.set(iter, 4, edit)
252 else:
253 update = False
254 for key in attribs:
255 # edit value
256 if attribs[key][2] is not None:
257 update = True
258 break
259 if new != old:
260 update = True
261
262 if update:
263 self.treestore.set(iter, 4, "update")
264 else:
265 child = self.treestore.iter_children(iter)
266 while child is not None:
267 change = self.__floodfill(child, edit)
268 if change is not None:
269 self.treestore.set(iter, 4, "subupdate")
270 child = self.treestore.iter_next(child)
271
272 return self.treestore.get_value(iter, 4)
273
274 def __insert(self, iter, value, index):
275 if " " in value:
276 key, value = value.split(" ")
277 attrib = self.treestore.get_value(iter, 1)
278 attrib[key] = (value, None, "insert")
279 else:
280 before = self.__iter_nth_child(iter, index - 1)
281 if before:
282 self.treestore.insert_before(iter, before, [value, {}, None, None, "insert"])
283 else:
284 self.treestore.append(iter, [value, {}, None, None, "insert"])
285
286 def __move(self, iter, value, index):
287 """
288 Copy the entire subtree at iter to the path at value[index],
289 mark all of iter as deleted, and all of the copy inserted.
290 """
291 tag, attrib, text = self.treestore.get(iter, 0, 1, 2)
292 self.treestore.set(iter, 2, None)
293 self.treestore.set(iter, 4, "delete")
294
295 destiter = self.__get_iter(value)[0]
296
297 before = self.__iter_nth_child(destiter, index - 1)
298 if before:
299 destiter = self.treestore.insert_before(destiter, before, [tag, attrib, text, None, "insert"])
300 else:
301 destiter = self.treestore.append(destiter, [tag, attrib, text, None, "insert"])
302
303 def move(iterfrom, iterto):
304 for childfrom in self.__iter_children(iterfrom):
305 tag, attrib, text = self.treestore.get(childfrom, 0, 1, 2)
306 self.treestore.set(childfrom, 2, None)
307 self.treestore.set(childfrom, 4, "delete")
308
309 childto = self.treestore.append(iterto, [tag, attrib, text, None, "insert"])
310 move(childfrom, childto)
311
312 move(iter, destiter)
313
314 def __iter_children(self, iter):
315 child = self.treestore.iter_children(iter)
316
317 while child:
318 active = self.treestore.get_value(child, 4) != "delete"
319 if active:
320 yield child
321 child = self.treestore.iter_next(child)
322
323 def __iter_nth_child(self, iter, n):
324
325 for child in self.__iter_children(iter):
326 if n == 0:
327 return child
328 else:
329 n -= 1
330 return None
331
332 def __get_iter(self, path, iter = None):
333 """
334 Convert the given XML path to an iter into the treestore.
335 """
336
337 if iter is None:
338 iter = self.treestore.get_iter_first()
339
340 tag, edit = self.treestore.get(iter, 0, 4)
341 if edit == "delete":
342 return None # don't search deleted paths
343
344 parentiter = self.treestore.iter_parent(iter)
345 if parentiter:
346 siblings = []
347 for siblingiter in self.__iter_children(parentiter):
348 siblingtag = self.treestore.get_value(siblingiter, 0)
349 if siblingtag == tag:
350 siblings.append(self.treestore.get_path(siblingiter))
351
352 if len(siblings) != 1:
353 index = "[" + str(siblings.index(self.treestore.get_path(iter)) + 1) + "]"
354 else:
355 index = ""
356
357 tag = "/" + tag + index
358 else:
359 tag = "/" + tag
360
361 index = path.find("/", 1)
362 if index == -1:
363 index = len(path)
364
365 root = path[:index]
366 path = path[index:]
367
368 #check we match root
369 if root != tag:
370 return None
371
372 if path:
373 # check for text()
374 if path == "/text()":
375 return (iter, None)
376
377 # check attributes
378 if path.startswith("/@"):
379 attrib = self.treestore.get_value(iter, 1)
380 for key in attrib:
381 if path == "/@" + key:
382 return (iter, key)
383 return None
384
385 # check children
386 for iter in self.__iter_children(iter):
387 edit = self.treestore.get_value(iter, 4)
388 if edit != "delete":
389 result = self.__get_iter(path, iter)
390 if result:
391 return result
392
393 return None
394 else:
395 # must be us
396 return (iter, None)
397
398 def on_select_row(self, selection):
399 """
400 Called when a row is selected.
401 """
402 (model, row) = selection.get_selected()
403 if row is None:
404 return
405
406 attrib, new, old, edit = model.get(row, 1, 2, 3, 4)
407
408 databuffer = self.dataview.get_buffer()
409 tag = databuffer.get_tag_table().lookup("tag")
410 if new or old:
411 self.__set_textdiff(self.dataview.get_buffer(), old, new)
412 tag.set_property("background-set", False)
413 tag.set_property("foreground", "black")
414 else:
415 databuffer.set_text("No data")
416 self.__set_cell_property(tag, None)
417 tag.set_property("foreground", "grey")
418
419 bounds = databuffer.get_bounds()
420 databuffer.apply_tag(tag, bounds[0], bounds[1])
421
422 # 0: Key
423 # 1: Value
424 # 2: Old value
425 # 3: "insert", "delete", "update", ""
426
427 attribstore = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)
428
429 for key, (new, old, diff) in attrib.iteritems():
430 attribstore.append(None, [key, new, old, diff])
431
432 self.attribview.set_model(attribstore)
433
434 def __set_textdiff(self, databuffer, old, new):
435 text1 = old.splitlines() if old else []
436 text2 = new.splitlines() if new else []
437
438 from difflib import Differ
439 differ = Differ()
440 result = differ.compare(text1, text2)
441 result = [line + "\n" for line in result if not line.startswith("? ")]
442
443 databuffer.set_text("")
444 for line in result:
445 iter = databuffer.get_end_iter()
446 if line.startswith(" "):
447 databuffer.insert(iter, line)
448 elif line.startswith("+ "):
449 databuffer.insert_with_tags_by_name(iter, line, "add")
450 elif line.startswith("- "):
451 databuffer.insert_with_tags_by_name(iter, line, "rem")
452
453
454 def __create_tags(self, databuffer):
455 databuffer.create_tag("tag")
456 add = databuffer.create_tag("add")
457 rem = databuffer.create_tag("rem")
458
459 add.set_property("background", "lightgreen")
460 rem.set_property("background", "indianred")
461
462 def __set_cell_property(self, cell, edit):
463 if edit is None:
464 cell.set_property("foreground", "black")
465 elif edit == "insert":
466 cell.set_property("foreground", "green")
467 elif edit == "delete":
468 cell.set_property("foreground", "red")
469 elif edit == "update":
470 cell.set_property("foreground", "blue")
471 elif edit == "subupdate":
472 cell.set_property("foreground", "cornflowerblue")
473
474 def set_celltext(self, column, cell, model, iter):
475
476 tag, text, edit = model.get(iter, 0, 2, 4)
477
478 cell.set_property("text", tag)
479 self.__set_cell_property(cell, edit)
480
481 def set_cellkey(self, column, cell, model, iter):
482
483 key, edit = model.get(iter, 0, 3)
484 cell.set_property("text", key)
485 self.__set_cell_property(cell, edit)
486
487 def set_cellvalue(self, column, cell, model, iter):
488
489 new, old, edit = model.get(iter, 1, 2, 3)
490 if edit == "delete":
491 cell.set_property("text", old)
492 else:
493 cell.set_property("text", new)
494 self.__set_cell_property(cell, edit)
495
496 def _get_focus_widget(self, parent):
497 """
498 Gets the widget that is a child of parent with the focus.
499 """
500 focus = parent.get_focus_child()
501 if focus is None or (focus.flags() & gtk.HAS_FOCUS):
502 return focus
503 else:
504 return self._get_focus_widget(focus)
505
506 def _handle_clipboard(self, widget, signal):
507 """
508 This finds the currently focused widget.
509 If no widget is focused or the focused widget doesn't support
510 the given clipboard operation use the treeview (False), otherwise
511 signal the widget to handel the clipboard operation (True).
512 """
513 widget = self._get_focus_widget(self)
514
515 if widget is None or widget is self.treeview:
516 return False
517
518 if gobject.signal_lookup(signal + "-clipboard", widget):
519 widget.emit(signal + "-clipboard")
520 return True
521 else:
522 return False
523
524 def __get_treestore(self, iter):
525
526 tag, attrib, text = self.treestore.get(iter, 0, 1, 2)
527
528 tree = etree.Element(tag)
529
530 for key, (newvalue, oldvalue, edit) in attrib.iteritems():
531 tree.attrib[key] = newvalue
532
533 child_iter = self.treestore.iter_children(iter)
534 while child_iter:
535 child = self.__get_treestore(child_iter)
536 tree.append(child)
537 child_iter = self.treestore.iter_next(child_iter)
538
539 return tree
540
541 def on_copy(self, widget=None):
542 if self._handle_clipboard(widget, "copy"):
543 return
544
545 (model, row) = self.treeview.get_selection().get_selected()
546 if row is None:
547 return
548
549 tree = etree.ElementTree(self.__get_treestore(row))
550
551 ios = StringIO.StringIO()
552 tree.write(ios, pretty_print = True, xml_declaration = False, encoding = "utf-8")
553
554 clipboard = gtk.clipboard_get()
555 clipboard.set_text(ios.getvalue())
556 clipboard.store()
557
558 ios.close()
0559
=== modified file 'diamond/diamond/interface.py'
--- diamond/diamond/interface.py 2011-08-16 15:22:31 +0000
+++ diamond/diamond/interface.py 2011-08-24 16:38:18 +0000
@@ -18,6 +18,7 @@
18import os18import os
19import os.path19import os.path
20import re20import re
21import time
21import sys22import sys
22import tempfile23import tempfile
23import cStringIO as StringIO24import cStringIO as StringIO
@@ -47,6 +48,7 @@
47import descriptionwidget48import descriptionwidget
48import databuttonswidget49import databuttonswidget
49import datawidget50import datawidget
51import diffview
50import sliceview52import sliceview
5153
52from lxml import etree54from lxml import etree
@@ -140,6 +142,8 @@
140 "on_copy": self.on_copy,142 "on_copy": self.on_copy,
141 "on_paste": self.on_paste,143 "on_paste": self.on_paste,
142 "on_slice": self.on_slice,144 "on_slice": self.on_slice,
145 "on_diff": self.on_diff,
146 "on_diffsave": self.on_diffsave,
143 "on_group": self.on_group,147 "on_group": self.on_group,
144 "on_ungroup": self.on_ungroup}148 "on_ungroup": self.on_ungroup}
145149
@@ -601,15 +605,16 @@
601 "You should have received a copy of the GNU General Public License\n"+605 "You should have received a copy of the GNU General Public License\n"+
602 "along with Diamond. If not, see http://www.gnu.org/licenses/.")606 "along with Diamond. If not, see http://www.gnu.org/licenses/.")
603607
604 logo = gtk.gdk.pixbuf_new_from_file(self.logofile)608 if self.logofile is not None:
605609 logo = gtk.gdk.pixbuf_new_from_file(self.logofile)
610 about.set_logo(logo)
611
606 try:612 try:
607 image = about.get_children()[0].get_children()[0].get_children()[0]613 image = about.get_children()[0].get_children()[0].get_children()[0]
608 image.set_tooltip_text("Diamond: it's clearer than GEM")614 image.set_tooltip_text("Diamond: it's clearer than GEM")
609 except:615 except:
610 pass616 pass
611617
612 about.set_logo(logo)
613 about.show()618 about.show()
614619
615 return620 return
@@ -730,13 +735,31 @@
730 msg += "Warning: added xml attributes:\n"735 msg += "Warning: added xml attributes:\n"
731 for ele in added_attrs:736 for ele in added_attrs:
732 msg += ele + "\n"737 msg += ele + "\n"
733 738
734 dialogs.long_message(self.main_window, msg)739 dialogs.long_message(self.main_window, msg)
735 740
736 self.set_saved(False) 741 self.set_saved(False)
737742
738 return743 return
739744
745 def __diff(self, path):
746 self.statusbar.set_statusbar("Calculating diff... (this may take a while)")
747 start = time.clock()
748 diffview.DiffView(path, self.tree)
749 seconds = time.clock() - start
750 self.statusbar.set_statusbar("Diff calculated (took " + str(seconds) + " seconds)")
751
752 def on_diff(self, widget = None, path = None):
753 if path is None:
754 path = os.path.dirname(self.filename) if self.filename else None
755 self.__diff(path)
756
757 def on_diffsave(self, widget = None):
758 if self.filename:
759 self.__diff(self.filename)
760 else:
761 dialogs.error(self.main_window, "No save to diff against.")
762
740 def on_slice(self, widget = None):763 def on_slice(self, widget = None):
741 if not self.selected_node.is_sliceable():764 if not self.selected_node.is_sliceable():
742 self.statusbar.set_statusbar("Cannot slice on this element.")765 self.statusbar.set_statusbar("Cannot slice on this element.")
743766
=== modified file 'diamond/diamond/triangle_reader.py' (properties changed: +x to -x)
=== modified file 'diamond/gui/gui.glade'
--- diamond/gui/gui.glade 2011-07-26 11:06:34 +0000
+++ diamond/gui/gui.glade 2011-08-24 16:38:18 +0000
@@ -131,7 +131,7 @@
131 <signal name="activate" handler="on_paste"/>131 <signal name="activate" handler="on_paste"/>
132 <accelerator key="V" signal="activate" modifiers="GDK_CONTROL_MASK"/>132 <accelerator key="V" signal="activate" modifiers="GDK_CONTROL_MASK"/>
133 </widget>133 </widget>
134 </child>134 </child>
135 <child>135 <child>
136 <widget class="GtkMenuItem" id="menuitemGroup">136 <widget class="GtkMenuItem" id="menuitemGroup">
137 <property name="visible">True</property>137 <property name="visible">True</property>
@@ -221,6 +221,20 @@
221 <widget class="GtkMenu" id="menu4">221 <widget class="GtkMenu" id="menu4">
222 <property name="visible">True</property>222 <property name="visible">True</property>
223 <child>223 <child>
224 <widget class="GtkMenuItem" id="menuitemDiff">
225 <property name="visible">True</property>
226 <property name="label" translatable="yes">Diff</property>
227 <signal name="activate" handler="on_diff"/>
228 </widget>
229 </child>
230 <child>
231 <widget class="GtkMenuItem" id="menuitemDiffSave">
232 <property name="visible">True</property>
233 <property name="label" translatable="yes">Diff against last save</property>
234 <signal name="activate" handler="on_diffsave"/>
235 </widget>
236 </child>
237 <child>
224 <widget class="GtkCheckMenuItem" id="display_properties">238 <widget class="GtkCheckMenuItem" id="display_properties">
225 <property name="visible">True</property>239 <property name="visible">True</property>
226 <property name="tooltip" translatable="yes">Display the option properties on the right hand side of the main window.</property>240 <property name="tooltip" translatable="yes">Display the option properties on the right hand side of the main window.</property>
227241
=== modified file 'diamond/tests/plist/plist.py' (properties changed: +x to -x)
=== modified file 'diamond/tests/read_xml/find_hidden_xmldata.py' (properties changed: +x to -x)
=== modified file 'diamond/tests/schema/test_simple_schema.py' (properties changed: +x to -x)
=== added directory 'dxdiff'
=== added file 'dxdiff/COPYING'
--- dxdiff/COPYING 1970-01-01 00:00:00 +0000
+++ dxdiff/COPYING 2011-08-24 16:38:18 +0000
@@ -0,0 +1,15 @@
1dxdiff is copyright (C) 2011 Imperial College London and others.
2For a full list of contributors see the AUTHORS file.
3
4dxdiff is free software: you can redistribute it and/or modify
5it under the terms of the GNU General Public License as published by
6the Free Software Foundation, either version 3 of the License, or
7(at your option) any later version.
8
9This program is distributed in the hope that it will be useful,
10but WITHOUT ANY WARRANTY; without even the implied warranty of
11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12GNU General Public License for more details.
13
14The complete text of the GNU General Public License can be found
15in the file `GPL-3'.
016
=== added file 'dxdiff/GPL-3'
--- dxdiff/GPL-3 1970-01-01 00:00:00 +0000
+++ dxdiff/GPL-3 2011-08-24 16:38:18 +0000
@@ -0,0 +1,676 @@
1
2 GNU GENERAL PUBLIC LICENSE
3 Version 3, 29 June 2007
4
5 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
6 Everyone is permitted to copy and distribute verbatim copies
7 of this license document, but changing it is not allowed.
8
9 Preamble
10
11 The GNU General Public License is a free, copyleft license for
12software and other kinds of works.
13
14 The licenses for most software and other practical works are designed
15to take away your freedom to share and change the works. By contrast,
16the GNU General Public License is intended to guarantee your freedom to
17share and change all versions of a program--to make sure it remains free
18software for all its users. We, the Free Software Foundation, use the
19GNU General Public License for most of our software; it applies also to
20any other work released this way by its authors. You can apply it to
21your programs, too.
22
23 When we speak of free software, we are referring to freedom, not
24price. Our General Public Licenses are designed to make sure that you
25have the freedom to distribute copies of free software (and charge for
26them if you wish), that you receive source code or can get it if you
27want it, that you can change the software or use pieces of it in new
28free programs, and that you know you can do these things.
29
30 To protect your rights, we need to prevent others from denying you
31these rights or asking you to surrender the rights. Therefore, you have
32certain responsibilities if you distribute copies of the software, or if
33you modify it: responsibilities to respect the freedom of others.
34
35 For example, if you distribute copies of such a program, whether
36gratis or for a fee, you must pass on to the recipients the same
37freedoms that you received. You must make sure that they, too, receive
38or can get the source code. And you must show them these terms so they
39know their rights.
40
41 Developers that use the GNU GPL protect your rights with two steps:
42(1) assert copyright on the software, and (2) offer you this License
43giving you legal permission to copy, distribute and/or modify it.
44
45 For the developers' and authors' protection, the GPL clearly explains
46that there is no warranty for this free software. For both users' and
47authors' sake, the GPL requires that modified versions be marked as
48changed, so that their problems will not be attributed erroneously to
49authors of previous versions.
50
51 Some devices are designed to deny users access to install or run
52modified versions of the software inside them, although the manufacturer
53can do so. This is fundamentally incompatible with the aim of
54protecting users' freedom to change the software. The systematic
55pattern of such abuse occurs in the area of products for individuals to
56use, which is precisely where it is most unacceptable. Therefore, we
57have designed this version of the GPL to prohibit the practice for those
58products. If such problems arise substantially in other domains, we
59stand ready to extend this provision to those domains in future versions
60of the GPL, as needed to protect the freedom of users.
61
62 Finally, every program is threatened constantly by software patents.
63States should not allow patents to restrict development and use of
64software on general-purpose computers, but in those that do, we wish to
65avoid the special danger that patents applied to a free program could
66make it effectively proprietary. To prevent this, the GPL assures that
67patents cannot be used to render the program non-free.
68
69 The precise terms and conditions for copying, distribution and
70modification follow.
71
72 TERMS AND CONDITIONS
73
74 0. Definitions.
75
76 "This License" refers to version 3 of the GNU General Public License.
77
78 "Copyright" also means copyright-like laws that apply to other kinds of
79works, such as semiconductor masks.
80
81 "The Program" refers to any copyrightable work licensed under this
82License. Each licensee is addressed as "you". "Licensees" and
83"recipients" may be individuals or organizations.
84
85 To "modify" a work means to copy from or adapt all or part of the work
86in a fashion requiring copyright permission, other than the making of an
87exact copy. The resulting work is called a "modified version" of the
88earlier work or a work "based on" the earlier work.
89
90 A "covered work" means either the unmodified Program or a work based
91on the Program.
92
93 To "propagate" a work means to do anything with it that, without
94permission, would make you directly or secondarily liable for
95infringement under applicable copyright law, except executing it on a
96computer or modifying a private copy. Propagation includes copying,
97distribution (with or without modification), making available to the
98public, and in some countries other activities as well.
99
100 To "convey" a work means any kind of propagation that enables other
101parties to make or receive copies. Mere interaction with a user through
102a computer network, with no transfer of a copy, is not conveying.
103
104 An interactive user interface displays "Appropriate Legal Notices"
105to the extent that it includes a convenient and prominently visible
106feature that (1) displays an appropriate copyright notice, and (2)
107tells the user that there is no warranty for the work (except to the
108extent that warranties are provided), that licensees may convey the
109work under this License, and how to view a copy of this License. If
110the interface presents a list of user commands or options, such as a
111menu, a prominent item in the list meets this criterion.
112
113 1. Source Code.
114
115 The "source code" for a work means the preferred form of the work
116for making modifications to it. "Object code" means any non-source
117form of a work.
118
119 A "Standard Interface" means an interface that either is an official
120standard defined by a recognized standards body, or, in the case of
121interfaces specified for a particular programming language, one that
122is widely used among developers working in that language.
123
124 The "System Libraries" of an executable work include anything, other
125than the work as a whole, that (a) is included in the normal form of
126packaging a Major Component, but which is not part of that Major
127Component, and (b) serves only to enable use of the work with that
128Major Component, or to implement a Standard Interface for which an
129implementation is available to the public in source code form. A
130"Major Component", in this context, means a major essential component
131(kernel, window system, and so on) of the specific operating system
132(if any) on which the executable work runs, or a compiler used to
133produce the work, or an object code interpreter used to run it.
134
135 The "Corresponding Source" for a work in object code form means all
136the source code needed to generate, install, and (for an executable
137work) run the object code and to modify the work, including scripts to
138control those activities. However, it does not include the work's
139System Libraries, or general-purpose tools or generally available free
140programs which are used unmodified in performing those activities but
141which are not part of the work. For example, Corresponding Source
142includes interface definition files associated with source files for
143the work, and the source code for shared libraries and dynamically
144linked subprograms that the work is specifically designed to require,
145such as by intimate data communication or control flow between those
146subprograms and other parts of the work.
147
148 The Corresponding Source need not include anything that users
149can regenerate automatically from other parts of the Corresponding
150Source.
151
152 The Corresponding Source for a work in source code form is that
153same work.
154
155 2. Basic Permissions.
156
157 All rights granted under this License are granted for the term of
158copyright on the Program, and are irrevocable provided the stated
159conditions are met. This License explicitly affirms your unlimited
160permission to run the unmodified Program. The output from running a
161covered work is covered by this License only if the output, given its
162content, constitutes a covered work. This License acknowledges your
163rights of fair use or other equivalent, as provided by copyright law.
164
165 You may make, run and propagate covered works that you do not
166convey, without conditions so long as your license otherwise remains
167in force. You may convey covered works to others for the sole purpose
168of having them make modifications exclusively for you, or provide you
169with facilities for running those works, provided that you comply with
170the terms of this License in conveying all material for which you do
171not control copyright. Those thus making or running the covered works
172for you must do so exclusively on your behalf, under your direction
173and control, on terms that prohibit them from making any copies of
174your copyrighted material outside their relationship with you.
175
176 Conveying under any other circumstances is permitted solely under
177the conditions stated below. Sublicensing is not allowed; section 10
178makes it unnecessary.
179
180 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
181
182 No covered work shall be deemed part of an effective technological
183measure under any applicable law fulfilling obligations under article
18411 of the WIPO copyright treaty adopted on 20 December 1996, or
185similar laws prohibiting or restricting circumvention of such
186measures.
187
188 When you convey a covered work, you waive any legal power to forbid
189circumvention of technological measures to the extent such circumvention
190is effected by exercising rights under this License with respect to
191the covered work, and you disclaim any intention to limit operation or
192modification of the work as a means of enforcing, against the work's
193users, your or third parties' legal rights to forbid circumvention of
194technological measures.
195
196 4. Conveying Verbatim Copies.
197
198 You may convey verbatim copies of the Program's source code as you
199receive it, in any medium, provided that you conspicuously and
200appropriately publish on each copy an appropriate copyright notice;
201keep intact all notices stating that this License and any
202non-permissive terms added in accord with section 7 apply to the code;
203keep intact all notices of the absence of any warranty; and give all
204recipients a copy of this License along with the Program.
205
206 You may charge any price or no price for each copy that you convey,
207and you may offer support or warranty protection for a fee.
208
209 5. Conveying Modified Source Versions.
210
211 You may convey a work based on the Program, or the modifications to
212produce it from the Program, in the form of source code under the
213terms of section 4, provided that you also meet all of these conditions:
214
215 a) The work must carry prominent notices stating that you modified
216 it, and giving a relevant date.
217
218 b) The work must carry prominent notices stating that it is
219 released under this License and any conditions added under section
220 7. This requirement modifies the requirement in section 4 to
221 "keep intact all notices".
222
223 c) You must license the entire work, as a whole, under this
224 License to anyone who comes into possession of a copy. This
225 License will therefore apply, along with any applicable section 7
226 additional terms, to the whole of the work, and all its parts,
227 regardless of how they are packaged. This License gives no
228 permission to license the work in any other way, but it does not
229 invalidate such permission if you have separately received it.
230
231 d) If the work has interactive user interfaces, each must display
232 Appropriate Legal Notices; however, if the Program has interactive
233 interfaces that do not display Appropriate Legal Notices, your
234 work need not make them do so.
235
236 A compilation of a covered work with other separate and independent
237works, which are not by their nature extensions of the covered work,
238and which are not combined with it such as to form a larger program,
239in or on a volume of a storage or distribution medium, is called an
240"aggregate" if the compilation and its resulting copyright are not
241used to limit the access or legal rights of the compilation's users
242beyond what the individual works permit. Inclusion of a covered work
243in an aggregate does not cause this License to apply to the other
244parts of the aggregate.
245
246 6. Conveying Non-Source Forms.
247
248 You may convey a covered work in object code form under the terms
249of sections 4 and 5, provided that you also convey the
250machine-readable Corresponding Source under the terms of this License,
251in one of these ways:
252
253 a) Convey the object code in, or embodied in, a physical product
254 (including a physical distribution medium), accompanied by the
255 Corresponding Source fixed on a durable physical medium
256 customarily used for software interchange.
257
258 b) Convey the object code in, or embodied in, a physical product
259 (including a physical distribution medium), accompanied by a
260 written offer, valid for at least three years and valid for as
261 long as you offer spare parts or customer support for that product
262 model, to give anyone who possesses the object code either (1) a
263 copy of the Corresponding Source for all the software in the
264 product that is covered by this License, on a durable physical
265 medium customarily used for software interchange, for a price no
266 more than your reasonable cost of physically performing this
267 conveying of source, or (2) access to copy the
268 Corresponding Source from a network server at no charge.
269
270 c) Convey individual copies of the object code with a copy of the
271 written offer to provide the Corresponding Source. This
272 alternative is allowed only occasionally and noncommercially, and
273 only if you received the object code with such an offer, in accord
274 with subsection 6b.
275
276 d) Convey the object code by offering access from a designated
277 place (gratis or for a charge), and offer equivalent access to the
278 Corresponding Source in the same way through the same place at no
279 further charge. You need not require recipients to copy the
280 Corresponding Source along with the object code. If the place to
281 copy the object code is a network server, the Corresponding Source
282 may be on a different server (operated by you or a third party)
283 that supports equivalent copying facilities, provided you maintain
284 clear directions next to the object code saying where to find the
285 Corresponding Source. Regardless of what server hosts the
286 Corresponding Source, you remain obligated to ensure that it is
287 available for as long as needed to satisfy these requirements.
288
289 e) Convey the object code using peer-to-peer transmission, provided
290 you inform other peers where the object code and Corresponding
291 Source of the work are being offered to the general public at no
292 charge under subsection 6d.
293
294 A separable portion of the object code, whose source code is excluded
295from the Corresponding Source as a System Library, need not be
296included in conveying the object code work.
297
298 A "User Product" is either (1) a "consumer product", which means any
299tangible personal property which is normally used for personal, family,
300or household purposes, or (2) anything designed or sold for incorporation
301into a dwelling. In determining whether a product is a consumer product,
302doubtful cases shall be resolved in favor of coverage. For a particular
303product received by a particular user, "normally used" refers to a
304typical or common use of that class of product, regardless of the status
305of the particular user or of the way in which the particular user
306actually uses, or expects or is expected to use, the product. A product
307is a consumer product regardless of whether the product has substantial
308commercial, industrial or non-consumer uses, unless such uses represent
309the only significant mode of use of the product.
310
311 "Installation Information" for a User Product means any methods,
312procedures, authorization keys, or other information required to install
313and execute modified versions of a covered work in that User Product from
314a modified version of its Corresponding Source. The information must
315suffice to ensure that the continued functioning of the modified object
316code is in no case prevented or interfered with solely because
317modification has been made.
318
319 If you convey an object code work under this section in, or with, or
320specifically for use in, a User Product, and the conveying occurs as
321part of a transaction in which the right of possession and use of the
322User Product is transferred to the recipient in perpetuity or for a
323fixed term (regardless of how the transaction is characterized), the
324Corresponding Source conveyed under this section must be accompanied
325by the Installation Information. But this requirement does not apply
326if neither you nor any third party retains the ability to install
327modified object code on the User Product (for example, the work has
328been installed in ROM).
329
330 The requirement to provide Installation Information does not include a
331requirement to continue to provide support service, warranty, or updates
332for a work that has been modified or installed by the recipient, or for
333the User Product in which it has been modified or installed. Access to a
334network may be denied when the modification itself materially and
335adversely affects the operation of the network or violates the rules and
336protocols for communication across the network.
337
338 Corresponding Source conveyed, and Installation Information provided,
339in accord with this section must be in a format that is publicly
340documented (and with an implementation available to the public in
341source code form), and must require no special password or key for
342unpacking, reading or copying.
343
344 7. Additional Terms.
345
346 "Additional permissions" are terms that supplement the terms of this
347License by making exceptions from one or more of its conditions.
348Additional permissions that are applicable to the entire Program shall
349be treated as though they were included in this License, to the extent
350that they are valid under applicable law. If additional permissions
351apply only to part of the Program, that part may be used separately
352under those permissions, but the entire Program remains governed by
353this License without regard to the additional permissions.
354
355 When you convey a copy of a covered work, you may at your option
356remove any additional permissions from that copy, or from any part of
357it. (Additional permissions may be written to require their own
358removal in certain cases when you modify the work.) You may place
359additional permissions on material, added by you to a covered work,
360for which you have or can give appropriate copyright permission.
361
362 Notwithstanding any other provision of this License, for material you
363add to a covered work, you may (if authorized by the copyright holders of
364that material) supplement the terms of this License with terms:
365
366 a) Disclaiming warranty or limiting liability differently from the
367 terms of sections 15 and 16 of this License; or
368
369 b) Requiring preservation of specified reasonable legal notices or
370 author attributions in that material or in the Appropriate Legal
371 Notices displayed by works containing it; or
372
373 c) Prohibiting misrepresentation of the origin of that material, or
374 requiring that modified versions of such material be marked in
375 reasonable ways as different from the original version; or
376
377 d) Limiting the use for publicity purposes of names of licensors or
378 authors of the material; or
379
380 e) Declining to grant rights under trademark law for use of some
381 trade names, trademarks, or service marks; or
382
383 f) Requiring indemnification of licensors and authors of that
384 material by anyone who conveys the material (or modified versions of
385 it) with contractual assumptions of liability to the recipient, for
386 any liability that these contractual assumptions directly impose on
387 those licensors and authors.
388
389 All other non-permissive additional terms are considered "further
390restrictions" within the meaning of section 10. If the Program as you
391received it, or any part of it, contains a notice stating that it is
392governed by this License along with a term that is a further
393restriction, you may remove that term. If a license document contains
394a further restriction but permits relicensing or conveying under this
395License, you may add to a covered work material governed by the terms
396of that license document, provided that the further restriction does
397not survive such relicensing or conveying.
398
399 If you add terms to a covered work in accord with this section, you
400must place, in the relevant source files, a statement of the
401additional terms that apply to those files, or a notice indicating
402where to find the applicable terms.
403
404 Additional terms, permissive or non-permissive, may be stated in the
405form of a separately written license, or stated as exceptions;
406the above requirements apply either way.
407
408 8. Termination.
409
410 You may not propagate or modify a covered work except as expressly
411provided under this License. Any attempt otherwise to propagate or
412modify it is void, and will automatically terminate your rights under
413this License (including any patent licenses granted under the third
414paragraph of section 11).
415
416 However, if you cease all violation of this License, then your
417license from a particular copyright holder is reinstated (a)
418provisionally, unless and until the copyright holder explicitly and
419finally terminates your license, and (b) permanently, if the copyright
420holder fails to notify you of the violation by some reasonable means
421prior to 60 days after the cessation.
422
423 Moreover, your license from a particular copyright holder is
424reinstated permanently if the copyright holder notifies you of the
425violation by some reasonable means, this is the first time you have
426received notice of violation of this License (for any work) from that
427copyright holder, and you cure the violation prior to 30 days after
428your receipt of the notice.
429
430 Termination of your rights under this section does not terminate the
431licenses of parties who have received copies or rights from you under
432this License. If your rights have been terminated and not permanently
433reinstated, you do not qualify to receive new licenses for the same
434material under section 10.
435
436 9. Acceptance Not Required for Having Copies.
437
438 You are not required to accept this License in order to receive or
439run a copy of the Program. Ancillary propagation of a covered work
440occurring solely as a consequence of using peer-to-peer transmission
441to receive a copy likewise does not require acceptance. However,
442nothing other than this License grants you permission to propagate or
443modify any covered work. These actions infringe copyright if you do
444not accept this License. Therefore, by modifying or propagating a
445covered work, you indicate your acceptance of this License to do so.
446
447 10. Automatic Licensing of Downstream Recipients.
448
449 Each time you convey a covered work, the recipient automatically
450receives a license from the original licensors, to run, modify and
451propagate that work, subject to this License. You are not responsible
452for enforcing compliance by third parties with this License.
453
454 An "entity transaction" is a transaction transferring control of an
455organization, or substantially all assets of one, or subdividing an
456organization, or merging organizations. If propagation of a covered
457work results from an entity transaction, each party to that
458transaction who receives a copy of the work also receives whatever
459licenses to the work the party's predecessor in interest had or could
460give under the previous paragraph, plus a right to possession of the
461Corresponding Source of the work from the predecessor in interest, if
462the predecessor has it or can get it with reasonable efforts.
463
464 You may not impose any further restrictions on the exercise of the
465rights granted or affirmed under this License. For example, you may
466not impose a license fee, royalty, or other charge for exercise of
467rights granted under this License, and you may not initiate litigation
468(including a cross-claim or counterclaim in a lawsuit) alleging that
469any patent claim is infringed by making, using, selling, offering for
470sale, or importing the Program or any portion of it.
471
472 11. Patents.
473
474 A "contributor" is a copyright holder who authorizes use under this
475License of the Program or a work on which the Program is based. The
476work thus licensed is called the contributor's "contributor version".
477
478 A contributor's "essential patent claims" are all patent claims
479owned or controlled by the contributor, whether already acquired or
480hereafter acquired, that would be infringed by some manner, permitted
481by this License, of making, using, or selling its contributor version,
482but do not include claims that would be infringed only as a
483consequence of further modification of the contributor version. For
484purposes of this definition, "control" includes the right to grant
485patent sublicenses in a manner consistent with the requirements of
486this License.
487
488 Each contributor grants you a non-exclusive, worldwide, royalty-free
489patent license under the contributor's essential patent claims, to
490make, use, sell, offer for sale, import and otherwise run, modify and
491propagate the contents of its contributor version.
492
493 In the following three paragraphs, a "patent license" is any express
494agreement or commitment, however denominated, not to enforce a patent
495(such as an express permission to practice a patent or covenant not to
496sue for patent infringement). To "grant" such a patent license to a
497party means to make such an agreement or commitment not to enforce a
498patent against the party.
499
500 If you convey a covered work, knowingly relying on a patent license,
501and the Corresponding Source of the work is not available for anyone
502to copy, free of charge and under the terms of this License, through a
503publicly available network server or other readily accessible means,
504then you must either (1) cause the Corresponding Source to be so
505available, or (2) arrange to deprive yourself of the benefit of the
506patent license for this particular work, or (3) arrange, in a manner
507consistent with the requirements of this License, to extend the patent
508license to downstream recipients. "Knowingly relying" means you have
509actual knowledge that, but for the patent license, your conveying the
510covered work in a country, or your recipient's use of the covered work
511in a country, would infringe one or more identifiable patents in that
512country that you have reason to believe are valid.
513
514 If, pursuant to or in connection with a single transaction or
515arrangement, you convey, or propagate by procuring conveyance of, a
516covered work, and grant a patent license to some of the parties
517receiving the covered work authorizing them to use, propagate, modify
518or convey a specific copy of the covered work, then the patent license
519you grant is automatically extended to all recipients of the covered
520work and works based on it.
521
522 A patent license is "discriminatory" if it does not include within
523the scope of its coverage, prohibits the exercise of, or is
524conditioned on the non-exercise of one or more of the rights that are
525specifically granted under this License. You may not convey a covered
526work if you are a party to an arrangement with a third party that is
527in the business of distributing software, under which you make payment
528to the third party based on the extent of your activity of conveying
529the work, and under which the third party grants, to any of the
530parties who would receive the covered work from you, a discriminatory
531patent license (a) in connection with copies of the covered work
532conveyed by you (or copies made from those copies), or (b) primarily
533for and in connection with specific products or compilations that
534contain the covered work, unless you entered into that arrangement,
535or that patent license was granted, prior to 28 March 2007.
536
537 Nothing in this License shall be construed as excluding or limiting
538any implied license or other defenses to infringement that may
539otherwise be available to you under applicable patent law.
540
541 12. No Surrender of Others' Freedom.
542
543 If conditions are imposed on you (whether by court order, agreement or
544otherwise) that contradict the conditions of this License, they do not
545excuse you from the conditions of this License. If you cannot convey a
546covered work so as to satisfy simultaneously your obligations under this
547License and any other pertinent obligations, then as a consequence you may
548not convey it at all. For example, if you agree to terms that obligate you
549to collect a royalty for further conveying from those to whom you convey
550the Program, the only way you could satisfy both those terms and this
551License would be to refrain entirely from conveying the Program.
552
553 13. Use with the GNU Affero General Public License.
554
555 Notwithstanding any other provision of this License, you have
556permission to link or combine any covered work with a work licensed
557under version 3 of the GNU Affero General Public License into a single
558combined work, and to convey the resulting work. The terms of this
559License will continue to apply to the part which is the covered work,
560but the special requirements of the GNU Affero General Public License,
561section 13, concerning interaction through a network will apply to the
562combination as such.
563
564 14. Revised Versions of this License.
565
566 The Free Software Foundation may publish revised and/or new versions of
567the GNU General Public License from time to time. Such new versions will
568be similar in spirit to the present version, but may differ in detail to
569address new problems or concerns.
570
571 Each version is given a distinguishing version number. If the
572Program specifies that a certain numbered version of the GNU General
573Public License "or any later version" applies to it, you have the
574option of following the terms and conditions either of that numbered
575version or of any later version published by the Free Software
576Foundation. If the Program does not specify a version number of the
577GNU General Public License, you may choose any version ever published
578by the Free Software Foundation.
579
580 If the Program specifies that a proxy can decide which future
581versions of the GNU General Public License can be used, that proxy's
582public statement of acceptance of a version permanently authorizes you
583to choose that version for the Program.
584
585 Later license versions may give you additional or different
586permissions. However, no additional obligations are imposed on any
587author or copyright holder as a result of your choosing to follow a
588later version.
589
590 15. Disclaimer of Warranty.
591
592 THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
593APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
594HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
595OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
596THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
597PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
598IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
599ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
600
601 16. Limitation of Liability.
602
603 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
604WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
605THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
606GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
607USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
608DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
609PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
610EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
611SUCH DAMAGES.
612
613 17. Interpretation of Sections 15 and 16.
614
615 If the disclaimer of warranty and limitation of liability provided
616above cannot be given local legal effect according to their terms,
617reviewing courts shall apply local law that most closely approximates
618an absolute waiver of all civil liability in connection with the
619Program, unless a warranty or assumption of liability accompanies a
620copy of the Program in return for a fee.
621
622 END OF TERMS AND CONDITIONS
623
624 How to Apply These Terms to Your New Programs
625
626 If you develop a new program, and you want it to be of the greatest
627possible use to the public, the best way to achieve this is to make it
628free software which everyone can redistribute and change under these terms.
629
630 To do so, attach the following notices to the program. It is safest
631to attach them to the start of each source file to most effectively
632state the exclusion of warranty; and each file should have at least
633the "copyright" line and a pointer to where the full notice is found.
634
635 <one line to give the program's name and a brief idea of what it does.>
636 Copyright (C) <year> <name of author>
637
638 This program is free software: you can redistribute it and/or modify
639 it under the terms of the GNU General Public License as published by
640 the Free Software Foundation, either version 3 of the License, or
641 (at your option) any later version.
642
643 This program is distributed in the hope that it will be useful,
644 but WITHOUT ANY WARRANTY; without even the implied warranty of
645 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
646 GNU General Public License for more details.
647
648 You should have received a copy of the GNU General Public License
649 along with this program. If not, see <http://www.gnu.org/licenses/>.
650
651Also add information on how to contact you by electronic and paper mail.
652
653 If the program does terminal interaction, make it output a short
654notice like this when it starts in an interactive mode:
655
656 <program> Copyright (C) <year> <name of author>
657 This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
658 This is free software, and you are welcome to redistribute it
659 under certain conditions; type `show c' for details.
660
661The hypothetical commands `show w' and `show c' should show the appropriate
662parts of the General Public License. Of course, your program's commands
663might be different; for a GUI interface, you would use an "about box".
664
665 You should also get your employer (if you work as a programmer) or school,
666if any, to sign a "copyright disclaimer" for the program, if necessary.
667For more information on this, and how to apply and follow the GNU GPL, see
668<http://www.gnu.org/licenses/>.
669
670 The GNU General Public License does not permit incorporating your program
671into proprietary programs. If your program is a subroutine library, you
672may consider it more useful to permit linking proprietary applications with
673the library. If this is what you want to do, use the GNU Lesser General
674Public License instead of this License. But first, please read
675<http://www.gnu.org/philosophy/why-not-lgpl.html>.
676
0677
=== added directory 'dxdiff/dxdiff'
=== added file 'dxdiff/dxdiff/__init__.py'
=== added file 'dxdiff/dxdiff/bimap.py'
--- dxdiff/dxdiff/bimap.py 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/bimap.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,49 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17
18
19class Bimap:
20 """
21 Bimap is a simple wrapper class over two dicts,
22 it behaves as a bi-directional map.
23 """
24
25 def __init__(self):
26 self.left = {}
27 self.right = {}
28
29 def __len__(self):
30 return len(self.left)
31
32 def __iter__(self):
33 # we iter over the left dict so that the left item is
34 # on the left side of the tuple returned
35 for item in self.left.iteritems():
36 yield item
37
38 def __contains__(self, item):
39 # check that the left dict contains left and points to right
40 try:
41 left, right = item
42 return self.left[left] == right
43 except KeyError:
44 return False
45
46 def add(self, item):
47 x, y = item
48 self.left[x] = y
49 self.right[y] = x
050
=== added file 'dxdiff/dxdiff/diff.py'
--- dxdiff/dxdiff/diff.py 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/diff.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,26 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17
18import fmes
19
20def diff(xmlold, xmlnew):
21 """
22 Compares two xml trees.
23 Returns an editscript to transform old into new.
24 """
25
26 return fmes.diff(xmlold, xmlnew)
027
=== added file 'dxdiff/dxdiff/dxdiff'
--- dxdiff/dxdiff/dxdiff 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/dxdiff 2011-08-24 16:38:18 +0000
@@ -0,0 +1,87 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17
18from getopt import getopt
19import sys
20import os
21from lxml import etree
22from dxdiff.diff import diff
23
24def __display_help():
25 """
26 Prints usage information to standard output.
27 """
28
29 print "\n".join(["Usage: dxdiff [OPTIONS] ... [FILE1] [FILE2]",
30 "",
31 "An XML aware diff tool. [FILE1] and [FILE2] are the XML files to be compared.",
32 "[FILE1] should be the old file.",
33 "",
34 "Options:",
35 ""
36 "-h Display this message",
37 ""])
38
39def __main():
40 """
41 Main routine to run dxdiff
42 """
43
44 try:
45 opts, args = getopt(sys.argv[1:], "hso:")
46 except:
47 __display_help()
48 sys.exit(1)
49
50 if len(args) != 2:
51 __display_help()
52 sys.exit(1)
53
54 if ("h", "") in opts:
55 __display_help()
56
57 output_file = None
58 for opt in opts:
59 if opt[0] == "-o":
60 output_file = opt[1]
61
62 file1 = args[0]
63 file2 = args[1]
64
65 try:
66 os.stat(file1)
67 except OSError:
68 print "Could not find " + file1 + "!"
69 sys.exit(1)
70
71 try:
72 os.stat(file2)
73 except OSError:
74 print "Could not find " + file2 + "!"
75 sys.exit(1)
76
77 xmlold = etree.parse(file1)
78 xmlnew = etree.parse(file2)
79
80 editscript = diff(xmlold, xmlnew)
81 if ("s", "") not in opts:
82 print editscript
83 if output_file is not None:
84 editscript.write(output_file)
85
86if __name__ == "__main__":
87 __main()
088
=== added file 'dxdiff/dxdiff/editscript.py'
--- dxdiff/dxdiff/editscript.py 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/editscript.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,79 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17
18from lxml import etree
19
20class EditScript:
21
22 def __init__(self):
23 self.script = []
24
25 def __str__(self):
26 return etree.tostring(self.to_xml(), pretty_print = True)
27
28 def __len__(self):
29 return len(self.script)
30
31 def __getitem__(self, key):
32 return self.script[key]
33
34 def __iter__(self):
35 return self.script.__iter__()
36
37 def update(self, path, value, userdata = None):
38 self.script.append({ "type": "update",
39 "location": path,
40 "value": value,
41 "userdata": userdata })
42
43 def insert(self, path, index, tag, value = None, userdata = None):
44 self.script.append({ "type": "insert",
45 "location": path,
46 "index": index,
47 "value": tag + (" " + value if value is not None else ""),
48 "userdata": userdata})
49
50 def delete(self, path, userdata = None):
51 self.script.append({ "type": "delete",
52 "location": path,
53 "userdata": userdata})
54
55 def move(self, path, destination, index, userdata = None):
56 self.script.append({ "type": "move",
57 "location": path,
58 "index": index,
59 "value": destination,
60 "userdata": userdata })
61
62 def to_xml(self):
63 tree = etree.Element("xmldiff")
64
65 for edit in self.script:
66 node = etree.Element(edit["type"], location = edit["location"])
67 if "index" in edit:
68 node.attrib["index"] = edit["index"]
69 if edit["userdata"] is not None:
70 node.attrib["userdata"] = edit["userdata"]
71
72 if "value" in edit:
73 node.text = edit["value"]
74 tree.append(node)
75
76 return etree.ElementTree(tree)
77
78 def write(self, path):
79 self.to_xml().write(path, pretty_print = True, xml_declaration = True, encoding = "utf-8")
080
=== added file 'dxdiff/dxdiff/fmes.py'
--- dxdiff/dxdiff/fmes.py 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/fmes.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,466 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17"""
18Diff xml trees using a modification of FMES [http://infolab.stanford.edu/pub/papers/tdiff3-8.ps]
19"""
20
21from lxml import etree
22from collections import deque
23from bimap import Bimap
24from editscript import EditScript
25
26import lcs
27import utils
28
29class Dom:
30 def __init__(self, tag, value, parent, attribute = False):
31 self.tag = tag
32 self.value = value
33 self.parent = parent
34 self.children = []
35
36 if value is None:
37 self.typetag = "/Element"
38 elif attribute:
39 self.typetag = "/Attribute"
40 else:
41 self.typetag = "/Text"
42
43 if parent:
44 self.depth = parent.depth + 1
45 else:
46 self.depth = 0
47
48 self.inorder = False
49
50 def elements(self):
51 return [child for child in self.children if child.is_element()]
52
53 def attributes(self):
54 return [child for child in self.children if child.is_attribute()]
55
56 def text(self):
57 return [child for child in self.children if child.is_text()]
58
59 def is_element(self):
60 return self.typetag == "/Element"
61
62 def is_text(self):
63 return self.typetag == "/Text"
64
65 def is_attribute(self):
66 return self.typetag == "/Attribute"
67
68 def __repr__(self):
69 return "<" + self.label + ">" + (self.value or "")
70
71 def __str__(self, indent = ""):
72 title = indent + "<" + self.path() + ">" + (self.value or "") + "\n" + indent
73 children = ("\n" + indent).join(child.__str__(indent + " ") for child in self.children)
74 return title + children
75
76 def path(self):
77 """
78 Finds the path of this element.
79 """
80 if self.is_text():
81 return self.parent.path() + "/text()"
82
83 if self.is_attribute():
84 return self.parent.path() + "/@" + self.tag
85
86 if self.parent:
87 siblings = [sibling for sibling in self.parent.elements() if sibling.tag == self.tag]
88 if len(siblings) != 1:
89 index = "[" + str(siblings.index(self) + 1) + "]"
90 else:
91 index = ""
92 return self.parent.path() + "/" + self.tag + index
93 else:
94 return "/" + self.tag
95
96 def find(self, path):
97
98 if self.is_text():
99 if path == "/text()":
100 return self
101 else: return None
102
103 if self.is_attribute():
104 if path == "/@" + self.tag:
105 return self
106 else: return None
107
108 index = path.find("/", 1)
109 if index == -1:
110 index = len(path)
111
112 root = path[:index]
113 path = path[index:]
114
115 if self.parent:
116 siblings = [sibling for sibling in self.parent.elements() if sibling.tag == self.tag]
117 if len(siblings) != 1:
118 index = "[" + str(siblings.index(self) + 1) + "]"
119 else:
120 index = ""
121
122 if root != "/" + self.tag + index:
123 return None
124 else:
125 if root != "/" + self.tag:
126 return None
127
128 if path:
129 for child in self.children:
130 result = child.find(path)
131 if result:
132 return result
133 else:
134 return self
135
136 def _real_index(self, parent, index):
137 if index == 0:
138 return 0
139
140 elements = parent.elements()
141 if len(elements) < index:
142 return len(parent.children)
143 return parent.children.index(elements[index - 1])
144
145 def insert(self, tag, tagtype, value, path, index):
146 parent = self.find(path)
147
148 node = Dom(tag, value, parent, tagtype == "/Attribute")
149 parent.children.insert(self._real_index(parent, index), node)
150 node.label = _strip_indexers(node.path()) + node.typetag
151 return node
152
153 def update(self, path, value):
154 node = self.find(path)
155
156 node.value = value
157 return node
158
159 def move(self, from_path, to_path, index):
160 node = self.find(from_path)
161 node.parent.children.remove(node)
162
163 parent = self.find(to_path)
164 parent.children.insert(self._real_index(parent, index), node)
165 node.parent = parent
166
167 def delete(self, path):
168 node = self.find(path)
169 node.parent.children.remove(node)
170 node.parent = None
171
172def _get_text(tree):
173 """
174 Returns the text and child tails.
175 """
176 return "".join([tree.text or ""] + [child.tail or "" for child in tree]).strip()
177
178def _strip_indexers(path):
179 """
180 Strips out indexers from an path.
181 """
182 while True:
183 lindex = path.find("[")
184 if lindex == -1:
185 break
186 rindex = path.find("]", lindex)
187 path = path[:lindex] + path[rindex + 1:]
188 return path
189
190def dom(root, tree = None, parent = None):
191
192 if tree is None:
193 tree = root.getroot()
194
195 xpath = root.getpath(tree)
196 path = _strip_indexers(xpath)
197
198 node = Dom(tree.tag, None, parent)
199 node.label = path + node.typetag
200 node.xpath = xpath
201
202 text = _get_text(tree)
203 if text:
204 text = Dom(tree.tag, text, node)
205 text.label = path + text.typetag
206 text.xpath = xpath + "/text()"
207 node.children.append(text)
208
209 for key, value in tree.items():
210 attr = Dom(key, value, node, True)
211 attr.label = path + "/@" + key + attr.typetag
212 attr.xpath = path + "/@" + key
213 node.children.append(attr)
214
215 for child in tree:
216 node.children.append(dom(root, child, node))
217
218 return node
219
220def get_leaf_nodes(tree):
221 """
222 Gets all the leaf nodes of an xml tree.
223 """
224 if tree.children:
225 return utils.flatten([get_leaf_nodes(child) for child in tree.children])
226 else:
227 return [tree]
228
229def get_parent_nodes(tree):
230 """
231 Returns all the non leaf nodes of an xml tree.
232 """
233
234 if tree.children:
235 return utils.flatten([get_parent_nodes(child) for child in tree.children]) + [tree]
236 else:
237 return []
238
239def get_depth(tree):
240 """
241 Returns the maximum depth of a tree.
242 """
243 depth = tree.depth
244 for child in tree.children:
245 depth = max(depth, get_depth(child))
246 return depth
247
248def get_depth_nodes(tree, depth):
249 """
250 Gets all the nodes of a certain depth of an xml tree.
251 """
252 if tree.depth == depth:
253 return [tree]
254 else:
255 if tree.children:
256 return utils.flatten([get_depth_nodes(child, depth) for child in tree.children])
257 else:
258 return []
259
260def get_chain(nodes, label):
261 return [node for node in nodes if node.label == label]
262
263def compare_value(value1, value2):
264 if value1 is None and value2 is None:
265 return 0.0
266 if value1 is None or value2 is None:
267 return 1.0
268 return 1.0 - (float(len(lcs.lcs(lcs.path(value1, value2)))) / max(len(value1), len(value2)))
269
270def leaf_equal(f, M, l1, l2):
271 return l1.label == l2.label and compare_value(l1.value, l2.value) <= f
272
273def common(children1, children2, M):
274 return [(x, y) for (x, y) in M if x in children1 and y in children2]
275
276def compare_children(children1, children2, M):
277 return (float(len(common(children1, children2, M))) / max(len(children1), len(children2)))
278
279def node_equal(t, M, n1, n2):
280 return n1.label == n2.label and compare_children(n1.children, n2.children, M) > t
281
282def depth_equal(f, t, M, n1, n2):
283 if n1.children or n2.children:
284 return node_equal(t, M, n1, n2)
285 else:
286 return leaf_equal(f, M, n1, n2)
287
288def _match(nodes1, nodes2, M, equal):
289 nodes = nodes1 + nodes2
290 for label in utils.nub([node.label for node in nodes]):
291
292 s1 = get_chain(nodes1, label)
293 s2 = get_chain(nodes2, label)
294
295 path = lcs.lcs(lcs.path(s1, s2, equal))
296
297 for x, y in path:
298 M.add((s1[x], s2[y]))
299 for x, y in reversed(path):
300 s1.pop(x)
301 s2.pop(y)
302
303 for x in range(len(s1)):
304 for y in range(len(s2)):
305 if equal(s1[x], s2[y]):
306 M.add((s1[x], s2[y]))
307 s2.pop(y)
308 break
309
310def fastmatch(t1, t2):
311 """
312 Calculates a match between t1 and t2.
313 See figure 10 in reference.
314 """
315 M = Bimap()
316
317 depth = max(get_depth(t1), get_depth(t2))
318
319 while 0 <= depth:
320 nodes1 = get_depth_nodes(t1, depth)
321 nodes2 = get_depth_nodes(t2, depth)
322
323 equal = utils.partial(depth_equal, 0.6, 0.5, M)
324
325 _match(nodes1, nodes2, M, equal)
326
327 depth -= 1
328
329 return M
330
331def breadth_iter(tree):
332 Q = deque()
333 Q.append(tree)
334 while Q:
335 t = Q.popleft()
336 if t is not tree:
337 yield t
338 if t.parent is not None or t is tree: #check we haven't deleted it
339 for child in t.children:
340 Q.append(child)
341
342def postorder_iter(tree):
343 S = []
344 O = []
345 S.append(tree)
346 while S:
347 t = S.pop()
348 O.append(t)
349 for child in t.children:
350 S.append(child)
351 while O:
352 t = O.pop()
353 if t is not tree:
354 yield t
355
356def editscript(t1, t2):
357 """
358 Finds an editscript between t1 and t2.
359 See figure 8 in reference.
360 """
361
362 E = EditScript()
363 M = fastmatch(t1, t2)
364
365 M.add((t1, t2))
366 alignchildren(t1, t2, M, E, t1, t2)
367
368 for x in breadth_iter(t2):
369 y = x.parent
370 z = M.right[y]
371
372 if x not in M.right:
373 if x.typetag == "/Text": #Can't insert Text, do an update
374 E.update(z.path(), x.value, x.xpath if hasattr(x, "xpath") else None)
375 w = t1.insert(x.tag, x.typetag, x.value, z.path(), 0)
376 M.add((w, x))
377 else:
378 x.inorder = True
379 k = findpos(M, x)
380 E.insert(z.path(), str(k), x.tag, x.value, x.xpath if hasattr(x, "xpath") else None)
381 w = t1.insert(x.tag, x.typetag, x.value, z.path(), k)
382 M.add((w, x))
383 else: # y is not None:
384 w = M.right[x]
385 v = w.parent
386 if w.value != x.value:
387 E.update(w.path(), x.value, w.xpath if hasattr(w, "xpath") else None)
388 t1.update(w.path(), x.value)
389 if (v, y) not in M:
390 x.inorder = True
391 k = findpos(M, x)
392 E.move(w.path(), z.path(), str(k), w.xpath if hasattr(w, "xpath") else None)
393 t1.move(w.path(), z.path(), k)
394
395 alignchildren(t1, t2, M, E, w, x)
396
397 for w in breadth_iter(t1):
398 if w not in M.left:
399 if w.typetag == "/Text": #Can't delete Text, do an update
400 E.update(w.path(), "", w.xpath if hasattr(w, "xpath") else None)
401 t1.update(w.path(), "")
402 else:
403 E.delete(w.path(), w.xpath if hasattr(w, "xpath") else None)
404 t1.delete(w.path())
405
406 return E
407
408def alignchildren(t1, t2, M, E, w, x):
409 """
410 See figure 9 in reference.
411 """
412
413 for c in w.elements():
414 c.inorder = False
415 for c in x.elements():
416 c.inorder = False
417
418 s1 = [child for child in w.elements() if child in M.left and M.left[child].parent == x]
419 s2 = [child for child in x.elements() if child in M.right and M.right[child].parent == w]
420
421 def equal(a, b):
422 return (a, b) in M
423
424 S = [(s1[x], s2[y]) for x, y in lcs.lcs(lcs.path(s1, s2, equal))]
425 for (a, b) in S:
426 a.inorder = b.inorder = True
427
428 for a in s1:
429 for b in s2:
430 if (a, b) in M and (a, b) not in S:
431 k = findpos(M, b)
432 E.move(a.path(), w.path(), k, a.xpath if hasattr(a, "xpath") else None)
433 t1.move(a.path(), w.path(), str(k))
434 a.inorder = b.inorder = True
435
436def findpos(M, x):
437 """
438 See figure 9 in reference.
439 """
440 if x.is_text() or x.is_attribute():
441 return 0
442
443 y = x.parent
444 children = y.elements()
445
446 #find the rightmost inorder node left of x (v)
447 index = children.index(x)
448 v = None
449 for i in range(index):
450 c = children[i]
451 if c.inorder:
452 v = c
453
454 if v is None:
455 return 1
456
457 u = M.right[v]
458 children = u.parent.elements()
459 index = children.index(u) + 1
460 return index + 1
461
462def diff(tree1, tree2):
463 t1 = dom(tree1)
464 t2 = dom(tree2)
465 E = editscript(t1, t2)
466 return E
0467
=== added file 'dxdiff/dxdiff/lcs.py'
--- dxdiff/dxdiff/lcs.py 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/lcs.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,284 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17"""
18Find the LCS (Longest Common Subsequence). Uses [http://www.xmailserver.org/diff2.pdf]
19"""
20
21from utils import irange
22
23def __path(V, D, k):
24 if D == 0:
25 return [(xy, xy) for xy in irange(V[0][0])]
26
27 tx = V[D][k]
28
29 if k == -D or (k != D and V[D][k - 1] < V[D][k + 1]):
30 x = V[D][k + 1]
31 y = x - (k + 1)
32 k = k + 1
33 y = y + 1
34 else:
35 x = V[D][k - 1]
36 y = x - (k - 1)
37 k = k - 1
38 x = x + 1
39
40 return __path(V, D - 1, k) + [(x + d, y + d) for d in irange(tx - x)]
41
42def __eq(a, b): return a == b
43
44def path(a, b, eq = __eq):
45 """
46 Finds the path through the match grid of sequence a and b,
47 using the function eq to determine equality.
48 Returns path
49 """
50
51 m = len(a)
52 n = len(b)
53 mn = m + n
54
55 if mn == 0: # two empty sequences
56 return [(0, 0)]
57
58 Vd = []
59 V = {1: 0}
60
61 for D in irange(mn):
62 for k in irange(-D, D, 2):
63 if k == -D or (k != D and V[k - 1] < V[k + 1]):
64 x = V[k + 1]
65 else:
66 x = V[k - 1] + 1
67 y = x - k
68
69 while x < m and y < n and eq(a[x], b[y]):
70 x += 1
71 y += 1
72
73 V[k] = x
74
75 if x >= m and y >= n:
76 Vd.append(V.copy())
77 return __path(Vd, D, k)
78
79 Vd.append(V.copy())
80
81 raise Exception("lcs should not reach here")
82
83def lcs(path):
84 """
85 Given an edit script path returns the longest common subseqence.
86 """
87
88 result = []
89
90 for i in range(1, len(path)):
91 x, y = path[i]
92 px, py = path[i - 1]
93 dx, dy = x - px, y - py
94 if dx == 1 and dy == 1:
95 result.append((px, py))
96
97 return result
98
99def ses(path, b):
100 """
101 Returns an edit script for a given match grid path.
102 The edit script transforms sequence A of the match grid
103 into sequence B via deletions ("D", index) and inserations
104 ("I", A index, B value).
105 """
106
107 patch = []
108 for i in range(len(path) - 1):
109 x, y = path[i]
110 nx, ny = path[i + 1]
111 dx, dy = nx - x, ny - y
112 if dx == 1 and dy == 1:
113 pass #match
114 elif dx == 1:
115 patch.append(("D", x))
116 else: #dy == 1:
117 patch.append(("I", x, b[y]))
118
119 return patch
120
121def patch(patch, a):
122 """
123 Given a sequence and a patch from the ses function transforms a into b
124 """
125
126 seq = type(a)
127 result = seq()
128 i = 0
129
130 for op in patch:
131 while i < op[1]:
132 result += seq(a[i])
133 i += 1
134
135 if op[0] == "D":
136 i += 1
137 else:
138 result += seq(op[2])
139
140 while i < len(a):
141 result += seq(a[i])
142 i += 1
143
144 return result
145
146##################
147### Unit Tests ###
148##################
149
150import unittest
151
152class __Test_lcs(unittest.TestCase):
153 def test_zero(self):
154 self.assertEqual(path("", ""), [(0, 0)])
155 self.assertEqual(path("", "a"), [(0, 0), (0, 1)])
156 self.assertEqual(path("a", ""), [(0, 0), (1, 0)])
157
158 def test_single(self):
159 self.assertEqual(path("a", "a"), [(0, 0), (1, 1)])
160 self.assertEqual(path("a", "b"), [(0, 0), (1, 0), (1, 1)])
161
162 def test_short(self):
163 self.assertEqual(path("ab", "ab"), [(0, 0), (1, 1), (2, 2)])
164 self.assertEqual(path("ab", "ac"), [(0, 0), (1, 1), (2, 1), (2, 2)])
165 self.assertEqual(path("abcabba", "cbabac"), [(0, 0), (1, 0), (2, 0), (3, 1), (3, 2), (4, 3), (5, 4), (6, 4), (7, 5), (7, 6)])
166 self.assertEqual(path("hello", "help me"), [(0, 0), (1, 1), (2, 2), (3, 3), (4, 3), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7)])
167
168 def test_long(self):
169 self.assertEqual(path("hello", "night night"),
170 [(0, 0), (0, 1), (0, 2), (0, 3), (1, 4), (2, 4),
171 (3, 4), (4, 4), (5, 4), (5, 5), (5, 6), (5, 7),
172 (5, 8), (5, 9), (5, 10), (5, 11)])
173
174 self.assertEqual(path([
175 "This part of the",
176 "document has stayed the",
177 "same from version to",
178 "version. It shouldn't",
179 "be shown if it doesn't",
180 "change. Otherwise, that",
181 "would not be helping to",
182 "compress the size of the",
183 "changes.",
184 "",
185 "This paragraph contains",
186 "text that is outdated.",
187 "It will be deleted in the",
188 "near future.",
189 "",
190 "It is important to spell",
191 "check this dokument. On",
192 "the other hand, a",
193 "misspelled word isn't",
194 "the end of the world.",
195 "Nothing in the rest of",
196 "this paragraph needs to",
197 "be changed. Things can",
198 "be added after it."
199 ], [
200 "This is an important",
201 "notice! It should",
202 "therefore be located at",
203 "the beginning of this",
204 "document!",
205 "",
206 "This part of the",
207 "document has stayed the",
208 "same from version to",
209 "version. It shouldn't",
210 "be shown if it doesn't",
211 "change. Otherwise, that",
212 "would not be helping to",
213 "compress anything.",
214 "",
215 "It is important to spell",
216 "check this document. On",
217 "the other hand, a",
218 "misspelled word isn't",
219 "the end of the world.",
220 "Nothing in the rest of",
221 "this paragraph needs to",
222 "be changed. Things can",
223 "be added after it.",
224 "",
225 "This paragraph contains",
226 "important new additions",
227 "to this document.",
228 ]), [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4),
229 (0, 5), (0, 6), (1, 7), (2, 8), (3, 9),
230 (4, 10), (5, 11), (6, 12), (7, 13), (8, 13),
231 (9, 13), (9, 14), (10, 15), (11, 15), (12, 15),
232 (13, 15), (14, 15), (15, 15), (16, 16), (17, 16),
233 (17, 17), (18, 18), (19, 19), (20, 20), (21, 21),
234 (22, 22), (23, 23), (24, 24), (24, 25), (24, 26),
235 (24, 27), (24, 28)])
236
237class __Test_diff(unittest.TestCase):
238 def test_zero(self):
239 p = path("", "")
240
241 self.assertEqual(ses(p, ""), [])
242
243 def test_delete(self):
244 p = path("a", "")
245 self.assertEqual(ses(p, ""), [("D", 0)])
246
247 p = path("abcd", "")
248 self.assertEqual(ses(p, ""), [("D", 0), ("D", 1), ("D", 2), ("D", 3)])
249
250 p = path("abcd", "cd")
251 self.assertEqual(ses(p, "cd"), [("D", 0), ("D", 1)])
252
253 p = path("abcd", "ab")
254 self.assertEqual(ses(p, "ab"), [("D", 2), ("D", 3)])
255
256 p = path("abcd", "bc")
257 self.assertEqual(ses(p, "bc"), [("D", 0), ("D", 3)])
258
259 def test_insert(self):
260 p = path("", "a")
261 self.assertEqual(ses(p, "a"), [("I", 0, "a")])
262
263 p = path("", "abcd")
264 self.assertEqual(ses(p, "abcd"), [("I", 0, "a"), ("I", 0, "b"), ("I", 0, "c"), ("I", 0, "d")])
265
266 def test_delins(self):
267 p = path("abcd", "abef")
268 self.assertEqual(ses(p, "abef"), [("D", 2), ("D", 3), ("I", 4, "e"), ("I", 4, "f")])
269
270class __Test_patch(unittest.TestCase):
271 def do_patch(self, a, b):
272 self.assertEqual(patch(ses(path(a, b), b), a), b)
273
274 def test_patch(self):
275 self.do_patch("", "hello")
276 self.do_patch("hello", "")
277 self.do_patch("hello", "hello")
278 self.do_patch("hello", "night night")
279 self.do_patch("hello", "help me")
280 self.do_patch("test bob", "kill bob")
281 self.do_patch("test bill", "test jane")
282
283if __name__ == "__main__":
284 unittest.main()
0285
=== added file 'dxdiff/dxdiff/utils.py'
--- dxdiff/dxdiff/utils.py 1970-01-01 00:00:00 +0000
+++ dxdiff/dxdiff/utils.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,172 @@
1#!/usr/bin/env python
2
3# This file is part of dxdiff.
4#
5# dxdiff is free software: you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation, either version 3 of the License, or
8# (at your option) any later version.
9#
10# dxdiff is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
17
18def flatten(l):
19 """
20 Flattens a list of lists into a list.
21 """
22 return [item for sublist in l for item in sublist]
23
24def nub(l, reverse=False):
25 """
26 Removes duplicates from a list.
27 If reverse is true keeps the last duplicate item
28 as opposed to the first.
29 """
30 if reverse:
31 seen = {}
32 result = []
33 for item in reversed(l):
34 if item in seen: continue
35 seen[item] = 1
36 result.append(item)
37 return reversed(result)
38 else:
39 seen = {}
40 result = []
41 for item in l:
42 if item in seen: continue
43 seen[item] = 1
44 result.append(item)
45 return result
46
47def partial(fn, *cargs, **ckwargs):
48 """
49 Partial function application, taken from PEP 309.
50 """
51 ckwargs = ckwargs.copy()
52 def call_fn(*fargs, **fkwargs):
53 d = ckwargs
54 d.update(fkwargs)
55 return fn(*(cargs + fargs), **d)
56 return call_fn
57
58def irange(*args):
59 """
60 Similar to range but stop is an inclusive upper bound.
61 """
62 if len(args) == 0:
63 raise TypeError("irange expected at least 1 arguments, got 0")
64 elif len(args) == 1:
65 stop = args[0]
66 start = 0
67 step = 1
68 elif len(args) == 2:
69 start, stop = args
70 step = 1
71 elif len(args) == 3:
72 start, stop, step = args
73 else:
74 raise TypeError("irange expected at most 3 arguments, got " + str(len(args)))
75
76 if step == 0:
77 raise ValueError("irange() step argument must not be zero")
78
79 stop = stop + 1 if step > 0 else stop - 1
80 return range(start, stop, step)
81
82##################
83### Unit Tests ###
84##################
85
86import unittest
87
88class __Test_flatten(unittest.TestCase):
89 def test_type(self):
90 self.assertRaises(TypeError, flatten, 1, 2, 3)
91
92 def test_zero(self):
93 self.assertEqual(flatten([]), [])
94 self.assertEqual(flatten([[]]), [])
95 self.assertEqual(flatten([[], []]), [])
96
97 def test_one(self):
98 self.assertEqual(flatten([[1]]), [1])
99 self.assertEqual(flatten([[1, 2], [3, 4]]), [1, 2, 3, 4])
100
101 def test_two(self):
102 self.assertEqual(flatten([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]), [[1, 2], [3, 4], [5, 6], [7, 8]])
103
104class __Test_nub(unittest.TestCase):
105 def test_zero(self):
106 self.assertEqual(nub([]), [])
107
108 def test_nodups(self):
109 self.assertEqual(nub([1, 2, 3, 4]), [1, 2, 3, 4])
110
111 def test_dups(self):
112 self.assertEqual(nub([1, 1, 2, 3, 4, 2]), [1, 2, 3, 4])
113
114class __Test_partial(unittest.TestCase):
115 def printer(*args, **kargs):
116 result = []
117 for arg in args:
118 result.append(str(args))
119 for k, v in kargs.items():
120 result.append(str(k) + ": " + str(v))
121 return ' '.join(result)
122
123 def test_zero(self):
124 self.assertEqual(partial(self.printer)(), self.printer())
125
126 def test_args(self):
127 self.assertEqual(partial(self.printer, 1)(), self.printer(1))
128 self.assertEqual(partial(self.printer)(1), self.printer(1))
129
130 def test_kargs(self):
131 self.assertEqual(partial(self.printer, a = 0)(), self.printer(a = 0))
132 self.assertEqual(partial(self.printer)(a = 0), self.printer(a = 0))
133
134class __Test_irange(unittest.TestCase):
135 def test_type(self):
136 self.assertRaises(TypeError, irange)
137 self.assertRaises(TypeError, irange, 0, 1, 2, 3)
138 self.assertRaises(TypeError, irange, 0, 1, 2, 3, 4)
139
140 def test_zerostep(self):
141 self.assertRaises(ValueError, irange, 0, 0, 0)
142 self.assertRaises(ValueError, irange, 1, 2, 0)
143
144 def test_zero(self):
145 self.assertEqual(irange(0), [0])
146
147 def test_stop(self):
148 self.assertEqual(irange(1), [0, 1])
149 self.assertEqual(irange(2), [0, 1, 2])
150
151 def test_start(self):
152 self.assertEqual(irange(5, 10), [5, 6, 7, 8, 9, 10])
153
154 def test_step(self):
155 self.assertEqual(irange(0, 4, 2), [0, 2, 4])
156 self.assertEqual(irange(0, 3, 2), [0, 2])
157
158 def test_negative(self):
159 self.assertEqual(irange(-10, -5), [-10, -9, -8, -7, -6, -5])
160 self.assertEqual(irange(-5, 5), [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5])
161
162 def test_negstep(self):
163 self.assertEqual(irange(5, 0, -1), [5, 4, 3, 2, 1, 0])
164 self.assertEqual(irange(2, -2, -1), [2, 1, 0, -1, -2])
165
166 def test_norange(self):
167 self.assertEqual(irange(5, 0), [])
168 self.assertEqual(irange(1, -1), [])
169 self.assertEqual(irange(0, 5, -1), [])
170
171if __name__ == "__main__":
172 unittest.main()
0173
=== added file 'dxdiff/setup.py'
--- dxdiff/setup.py 1970-01-01 00:00:00 +0000
+++ dxdiff/setup.py 2011-08-24 16:38:18 +0000
@@ -0,0 +1,21 @@
1from distutils.core import setup
2import os
3import os.path
4import glob
5
6try:
7 destdir = os.environ["DESTDIR"]
8except KeyError:
9 destdir = ""
10
11setup(
12 name='dxdiff',
13 version='1.0',
14 description="An XML aware diff tool.",
15 author = "The ICOM team",
16 author_email = "fraser.waters08@imperial.ac.uk",
17 url = "http://amcg.ese.ic.ac.uk",
18 packages = ['dxdiff'],
19 scripts=["dxdiff/dxdiff"],
20 )
21
022
=== modified file 'examples/show_ballistics' (properties changed: +x to -x)
=== modified file 'install-sh' (properties changed: +x to -x)

Subscribers

People subscribed via source and target branches