Skip to content

Commit

Permalink
Fix scour-project#296, don't remove elements with referenced children
Browse files Browse the repository at this point in the history
  • Loading branch information
joneuhauser committed Sep 15, 2022
1 parent 0609c59 commit 544027f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
9 changes: 6 additions & 3 deletions scour/scour.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ def removeUnusedDefs(doc, defElem, elemsToRemove=None, referencedIDs=None):
# removeUnusedDefs do not change the XML itself; therefore there is no point in
# recomputing findReferencedElements when we recurse into child nodes.
if referencedIDs is None:
referencedIDs = findReferencedElements(doc.documentElement)
referencedIDs = set(findReferencedElements(doc.documentElement).keys())

keepTags = ['font', 'style', 'metadata', 'script', 'title', 'desc']
for elem in defElem.childNodes:
Expand All @@ -660,10 +660,13 @@ def removeUnusedDefs(doc, defElem, elemsToRemove=None, referencedIDs=None):
# we only inspect the children of a group in a defs if the group
# is not referenced anywhere else
if elem.nodeName == 'g' and elem.namespaceURI == NS['SVG']:
elemsToRemove = removeUnusedDefs(doc, elem, elemsToRemove, referencedIDs=referencedIDs)
removeUnusedDefs(doc, elem, elemsToRemove, referencedIDs=referencedIDs)
# we only remove if it is not one of our tags we always keep (see above)
# also we can't remove an element if a child is referenced
elif elem.nodeName not in keepTags:
elemsToRemove.append(elem)
if (set(findElementsWithId(elem).keys()).intersection(referencedIDs) == set() or
elem.tagName == 'defs'):
elemsToRemove.append(elem)
return elemsToRemove


Expand Down
7 changes: 7 additions & 0 deletions test_scour.py
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,13 @@ def runTest(self):
self.assertEqual(len(doc.getElementsByTagNameNS(SVGNS, 'circle')), 1,
'Unreferenced circle removed from defs with `--keep-unreferenced-defs`')

class KeepUnreferencedElementWithReferencedChild(unittest.TestCase):
def runTest(self):
doc = scourXmlFile('unittests/referenced_child.svg')

self.assertEqual(len(doc.getElementsByTagNameNS(SVGNS, 'rect')), 1,
'Referenced element was deleted')


class DoNotRemoveChainedRefsInDefs(unittest.TestCase):

Expand Down
9 changes: 9 additions & 0 deletions unittests/referenced_child.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 544027f

Please sign in to comment.