• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1package org.jetbrains
2
3import com.github.jengelman.gradle.plugins.shadow.relocation.RelocateClassContext
4import com.github.jengelman.gradle.plugins.shadow.relocation.Relocator
5import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
6import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
7import groovy.xml.XmlUtil
8import org.gradle.api.file.FileTreeElement
9import shadow.org.apache.tools.zip.ZipEntry
10import shadow.org.apache.tools.zip.ZipOutputStream
11
12public class PluginXmlTransformer implements Transformer {
13    private Map<String, Node> transformedPluginXmlFiles = new HashMap<>();
14
15    @Override
16    boolean canTransformResource(FileTreeElement fileTreeElement) {
17        return fileTreeElement.relativePath.segments.contains("META-INF") && fileTreeElement.name.endsWith(".xml")
18    }
19
20    @Override
21    void transform(TransformerContext context) {
22        def path = context.path
23        def inputStream = context.is
24        System.out.println(path)
25        Node node = new XmlParser().parse(inputStream)
26        relocateXml(node, context)
27        transformedPluginXmlFiles.put(path, node)
28    }
29
30    @Override
31    boolean hasTransformedResource() {
32        return !transformedPluginXmlFiles.isEmpty()
33    }
34
35    @Override
36    void modifyOutputStream(ZipOutputStream zipOutputStream) {
37        for (Map.Entry<String, Node> entry : transformedPluginXmlFiles.entrySet()) {
38            zipOutputStream.putNextEntry(new ZipEntry(entry.key))
39            XmlUtil.serialize(entry.value, zipOutputStream)
40        }
41    }
42
43    private static void relocateXml(Node node, TransformerContext context) {
44        Map attributes = node.attributes()
45        RelocateClassContext relocateClassContext = new RelocateClassContext()
46        relocateClassContext.stats = context.stats
47        for (Map.Entry entry : attributes.entrySet()) {
48            relocateClassContext.setClassName((String) entry.getValue())
49            entry.setValue(relocateClassName(relocateClassContext, context))
50        }
51        List<String> localText = node.localText()
52        if (localText.size() == 1) {
53            relocateClassContext.setClassName(localText[0])
54            node.setValue(relocateClassName(relocateClassContext, context))
55        }
56        node.children().each {
57            if (it instanceof Node) {
58                relocateXml((Node) it, context)
59            }
60        }
61    }
62
63    private static String relocateClassName(RelocateClassContext relocateContext, TransformerContext context) {
64        for (Relocator relocator : context.relocators) {
65            if (relocator.canRelocateClass(relocateContext)) {
66                return relocator.relocateClass(relocateContext)
67            }
68        }
69        return relocateContext.className
70    }
71}