Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #296, don't remove elements with referenced children #302

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.