| 36 | |
| 37 | |
| 38 | def combine(files): |
| 39 | impl = getDOMImplementation() |
| 40 | doc = impl.createDocument(None, "svg", None) |
| 41 | defs = doc.createElement("defs") |
| 42 | doc.documentElement.appendChild(defs) |
| 43 | svgs_to_insert = [] |
| 44 | for filename in files: |
| 45 | partial_doc = minidom.parse(filename) |
| 46 | partial_defs = partial_doc.getElementsByTagName("defs") |
| 47 | if partial_defs: |
| 48 | if len(partial_defs) > 1: |
| 49 | raise ValueError( |
| 50 | "Unexpected document structure. Expected only one `<defs>`" |
| 51 | "in '%s'." % filename |
| 52 | ) |
| 53 | svgs_to_insert.extend(partial_defs[0].childNodes) |
| 54 | else: |
| 55 | maybe_svg_el = partial_doc.documentElement |
| 56 | if maybe_svg_el.tagName != "svg": |
| 57 | raise ValueError( |
| 58 | "Unexpected document. Expected '%s' to start with <svg>." |
| 59 | % filename |
| 60 | ) |
| 61 | svg_el = maybe_svg_el |
| 62 | |
| 63 | basename = path.basename(filename) |
| 64 | svg_el.setAttribute("id", path.splitext(basename)[0]) |
| 65 | svgs_to_insert.append(svg_el) |
| 66 | |
| 67 | svg_ids = set() |
| 68 | duplicate_ids = set() |
| 69 | for partial_svg in svgs_to_insert: |
| 70 | svg_id = partial_svg.getAttribute("id") |
| 71 | if not svg_id: |
| 72 | raise ValueError( |
| 73 | "Unexpected document type: expected SVG inside defs contain " |
| 74 | "`id` attribute." |
| 75 | ) |
| 76 | |
| 77 | if svg_id in svg_ids: |
| 78 | duplicate_ids.add(svg_id) |
| 79 | |
| 80 | svg_ids.add(svg_id) |
| 81 | defs.appendChild(partial_svg) |
| 82 | |
| 83 | if duplicate_ids: |
| 84 | raise ValueError( |
| 85 | "Violation: SVG with these ids appeared more than once in `srcs`: " |
| 86 | + ", ".join(duplicate_ids), |
| 87 | ) |
| 88 | |
| 89 | return doc.toxml() |
| 90 | |
| 91 | |
| 92 | if __name__ == "__main__": |