aboutsummaryrefslogtreecommitdiffhomepage
path: root/third_party/java/jarjar/jarjar-gradle/src/main/java/org/anarres/gradle/plugin/jarjar/JarjarTask.java
blob: 9d863caf35b1454715f6b923e520770b7cce1d67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anarres.gradle.plugin.jarjar;

import com.tonicsystems.jarjar.classpath.ClassPath;
import com.tonicsystems.jarjar.transform.JarTransformer;
import com.tonicsystems.jarjar.transform.config.ClassKeepTransitive;
import com.tonicsystems.jarjar.transform.config.ClassDelete;
import com.tonicsystems.jarjar.transform.config.ClassRename;
import com.tonicsystems.jarjar.transform.jar.DefaultJarProcessor;
import groovy.lang.Closure;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import org.apache.oro.text.GlobCompiler;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.Perl5Matcher;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.ConventionTask;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.OutputFiles;
import org.gradle.api.tasks.TaskAction;
import org.gradle.api.tasks.TaskOutputs;

/**
 *
 * @author shevek
 */
public class JarjarTask extends ConventionTask {

    private class FilterSpec implements Spec<File> {

        private final String message;
        private final Iterable<? extends Pattern> patterns;
        private final boolean result;

        public FilterSpec(@Nonnull String message, @Nonnull Iterable<? extends Pattern> patterns, boolean result) {
            this.message = message;
            this.patterns = patterns;
            this.result = result;
        }

        @Override
        public boolean isSatisfiedBy(File t) {
            if (matchesAny(patterns, t.getName())) {
                getLogger().info(message + " " + t);
                return result;
            }
            return !result;
        }

        @Override
        public String toString() {
            return getClass().getSimpleName() + "(patterns=" + patterns + ")";
        }
    }

    private static final Perl5Matcher globMatcher = new Perl5Matcher();

    private static boolean matchesAny(@Nonnull Iterable<? extends Pattern> patterns, @Nonnull String text) {
        for (Pattern pattern : patterns) {
            if (globMatcher.matches(text, pattern)) {
                return true;
            }
        }
        return false;
    }

    @Nonnull
    private static Iterable<Pattern> toPatterns(@Nonnull Iterable<? extends String>... patterns) throws MalformedPatternException {
        GlobCompiler compiler = new GlobCompiler();
        List<Pattern> out = new ArrayList<Pattern>();
        for (Iterable<? extends String> in : patterns)
            for (String pattern : in)
                out.add(compiler.compile(pattern));
        return out;
    }

    private final ConfigurableFileCollection sourceFiles;
    private final Set<String> archiveBypasses = new HashSet<String>();
    private final Set<String> archiveExcludes = new HashSet<String>();
    private File destinationDir;
    private String destinationName;

    private final DefaultJarProcessor processor = new DefaultJarProcessor();

    public JarjarTask() {
        sourceFiles = getProject().files();
    }

    @InputFiles
    public FileCollection getSourceFiles() {
        return sourceFiles;
    }

    /**
     * Returns the directory where the archive is generated into.
     *
     * @return the directory
     */
    public File getDestinationDir() {
        File out = destinationDir;
        if (out == null)
            out = new File(getProject().getBuildDir(), "jarjar");
        return out;
    }

    public void setDestinationDir(File destinationDir) {
        this.destinationDir = destinationDir;
    }

    /**
     * Returns the file name of the generated archive.
     *
     * @return the name
     */
    public String getDestinationName() {
        String out = destinationName;
        if (out == null)
            out = getName() + ".jar";
        return out;
    }

    public void setDestinationName(String destinationName) {
        this.destinationName = destinationName;
    }

    /**
     * The path where the archive is constructed.
     * The path is simply the {@code destinationDir} plus the {@code destinationName}.
     *
     * @return a File object with the path to the archive
     */
    @OutputFile
    public File getDestinationPath() {
        return new File(getDestinationDir(), getDestinationName());
    }

    @OutputFiles
    public FileCollection getBypassedArchives() throws MalformedPatternException {
        return sourceFiles.filter(new FilterSpec("Bypassing archive", toPatterns(archiveBypasses), true));
    }

    /**
     * Processes a FileCollection, which may be simple, a {@link Configuration},
     * or derived from a {@link TaskOutputs}.
     *
     * @param files The input FileCollection to consume.
     */
    public void from(@Nonnull FileCollection files) {
        sourceFiles.from(files);
    }

    /**
     * Processes a Dependency directly, which may be derived from
     * {@link DependencyHandler#create(java.lang.Object)},
     * {@link DependencyHandler#project(java.util.Map)},
     * {@link DependencyHandler#module(java.lang.Object)},
     * {@link DependencyHandler#gradleApi()}, etc.
     *
     * @param dependency The dependency to process.
     */
    public void from(@Nonnull Dependency dependency) {
        Configuration configuration = getProject().getConfigurations().detachedConfiguration(dependency);
        from(configuration);
    }

    /**
     * Processes a dependency specified by name.
     *
     * @param dependencyNotation The dependency, in a notation described in {@link DependencyHandler}.
     * @param configClosure The closure to use to configure the dependency.
     * @see DependencyHandler
     */
    public void from(@Nonnull String dependencyNotation, Closure configClosure) {
        from(getProject().getDependencies().create(dependencyNotation, configClosure));
    }

    /**
     * Processes a dependency specified by name.
     *
     * @param dependencyNotation The dependency, in a notation described in {@link DependencyHandler}.
     */
    public void from(@Nonnull String dependencyNotation) {
        from(getProject().getDependencies().create(dependencyNotation));
    }

    public void archiveBypass(@Nonnull String pattern) throws MalformedPatternException {
        archiveBypasses.add(pattern);
    }

    public void archiveExclude(@Nonnull String pattern) throws MalformedPatternException {
        archiveExcludes.add(pattern);
    }

    public void classRename(@Nonnull String pattern, @Nonnull String replacement) {
        processor.addClassRename(new ClassRename(pattern, replacement));
    }

    public void classDelete(@Nonnull String pattern) {
        processor.addClassDelete(new ClassDelete(pattern));
    }

    public void classClosureRoot(@Nonnull String pattern) {
        processor.addClassKeepTransitive(new ClassKeepTransitive(pattern));
    }

    @TaskAction
    public void run() throws Exception {
        FileCollection inputFiles = sourceFiles.filter(new FilterSpec("Excluding archive", toPatterns(archiveBypasses, archiveExcludes), false));
        final File outputFile = getDestinationPath();
        outputFile.getParentFile().mkdirs();
        getLogger().info("Running jarjar for {}", outputFile);
        getLogger().info("Inputs are {}", inputFiles);

        JarTransformer transformer = new JarTransformer(outputFile, processor);
        transformer.transform(new ClassPath(getProject().getProjectDir(), inputFiles));
    }
}