/
BundleTaskExtension.java
656 lines (606 loc) · 21.2 KB
/
BundleTaskExtension.java
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package aQute.bnd.gradle;
import static aQute.bnd.gradle.BndUtils.builtBy;
import static aQute.bnd.gradle.BndUtils.isGradleCompatible;
import static aQute.bnd.gradle.BndUtils.jarLibraryElements;
import static aQute.bnd.gradle.BndUtils.logReport;
import static aQute.bnd.gradle.BndUtils.sourceSets;
import static aQute.bnd.gradle.BndUtils.unwrap;
import static aQute.bnd.gradle.BndUtils.unwrapFile;
import static aQute.bnd.gradle.BndUtils.unwrapFileOptional;
import static aQute.bnd.gradle.BndUtils.unwrapOptional;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toList;
import static org.gradle.api.tasks.PathSensitivity.RELATIVE;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.jar.Manifest;
import java.util.zip.ZipFile;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.java.archives.internal.DefaultManifest;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.MapProperty;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.Classpath;
import org.gradle.api.tasks.ClasspathNormalizer;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskInputFilePropertyBuilder;
import org.gradle.work.NormalizeLineEndings;
import aQute.bnd.exceptions.Exceptions;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.Processor;
import aQute.bnd.stream.MapStream;
import aQute.bnd.unmodifiable.Maps;
import aQute.bnd.version.MavenVersion;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
/**
* BundleTaskExtension for Gradle.
* <p>
* Adds {@code bundle} extension to bundle builder tasks.
* <p>
* Properties:
* <ul>
* <li>bndfile - This is the name of the bnd file to use to make the bundle. The
* bndfile does not need to exist. It will override headers in the jar task's
* manifest.</li>
* <li>bnd - This is a string holding a bnd file to use to make the bundle. It
* will override headers in the jar task's manifest. This properties is ignored
* if bndfile is specified and the specified file exists.</li>
* <li>sourceSet - This is the SourceSet to use for the bnd builder. It defaults
* to "project.sourceSets.main".</li>
* <li>classpath - This is the FileCollection to use for the buildpath for the
* bnd builder. It defaults to "project.sourceSets.main.compileClasspath".</li>
* <li>properties - Properties that are available for evaluation of the bnd
* instructions. The default is the properties of the task and project
* objects.</li>
* </ul>
*/
public class BundleTaskExtension {
/**
* Name of the extension.
*/
public static final String NAME = "bundle";
private final RegularFileProperty bndfile;
private final ConfigurableFileCollection classpath;
private final Provider<String> bnd;
private final MapProperty<String, Object> properties;
private final Optional<EffectiveManifest> effectiveManifest;
/**
* The bndfile property.
* <p>
* A bnd file containing bnd instructions for this project.
*
* @return The property for the bndfile.
*/
@InputFile
@PathSensitive(RELATIVE)
@NormalizeLineEndings
@org.gradle.api.tasks.Optional
public RegularFileProperty getBndfile() {
return bndfile;
}
/**
* The classpath property.
* <p>
* The default value is sourceSets.main.compileClasspath.
*
* @return The property for the classpath.
*/
@InputFiles
@Classpath
public ConfigurableFileCollection getClasspath() {
return classpath;
}
/**
* The bnd property.
* <p>
* If the bndfile property points an existing file, this property is
* ignored. Otherwise, the bnd instructions in this property will be used.
*
* @return The property for the bnd instructions.
*/
@Input
@org.gradle.api.tasks.Optional
public Provider<String> getBnd() {
return bnd;
}
/**
* Properties that are available for evaluation of the bnd instructions.
* <p>
* If this property is not set, the properties of the following are
* available:
* <dl>
* <dt>{@code task}</dt>
* <dd>The Task object of this extension.</dd>
* <dt>{@code project}</dt>
* <dd>The Project object for the task of this extension.</dd>
* </dl>
* If the {@code task} property is not set, the properties of the Task
* object of this extension will automatically be available.
* <p>
* The following properties are set by the builder and are also available:
* <dl>
* <dt>{@code project.dir}</dt>
* <dd>The project directory.</dd>
* <dt>{@code project.output}</dt>
* <dd>The build directory.</dd>
* <dt>{@code project.buildpath}</dt>
* <dd>The project buildpath.</dd>
* <dt>{@code project.sourcepath<}</dt>
* <dd>The project sourcepath.</dd>
* </dl>
* <p>
* Note: The defaults for this property use the Project object which makes
* the task ineligible for the Gradle configuration cache. If you want to
* use this task with the Gradle configuration cache, you must set this
* property to ensure it does not use the Project object. Of course, this
* then means you cannot use <code>${project.xxx}</code> style expressions
* in the bnd instructions unless you set those values in this property.
*
* @return Properties available for evaluation of the bnd instructions.
*/
@Input
public MapProperty<String, Object> getProperties() {
return properties;
}
private final ConfigurableFileCollection allSource;
private final org.gradle.api.tasks.bundling.Jar task;
private final ProjectLayout layout;
private final File buildFile;
private final ListProperty<CharSequence> instructions;
/**
* Create a BundleTaskExtension for the specified Jar task.
* <p>
* This also sets the default values for the added properties and adds the
* bnd file to the task inputs.
*
* @param task The Jar task for this extension.
*/
public BundleTaskExtension(org.gradle.api.tasks.bundling.Jar task) {
this.task = task;
Project project = task.getProject();
layout = project.getLayout();
ObjectFactory objects = project.getObjects();
buildFile = project.getBuildFile();
bndfile = objects.fileProperty();
instructions = objects.listProperty(CharSequence.class)
.empty();
bnd = instructions.map(list -> Strings.join("\n", list));
classpath = objects.fileCollection();
allSource = objects.fileCollection();
SourceSet mainSourceSet = sourceSets(project).getByName(SourceSet.MAIN_SOURCE_SET_NAME);
setSourceSet(mainSourceSet);
classpath(mainSourceSet.getCompileClasspath());
properties = objects.mapProperty(String.class, Object.class)
.convention(Maps.of("project", "__convention__"));
// Wrap manifest
org.gradle.api.java.archives.Manifest delegate = task.getManifest();
if (delegate != null) {
EffectiveManifest em = new EffectiveManifest(delegate);
effectiveManifest = Optional.of(em);
org.gradle.api.java.archives.Manifest manifest = (org.gradle.api.java.archives.Manifest) Proxy
.newProxyInstance(em.classLoader(), em.interfaces(), em);
task.setManifest(manifest);
} else {
effectiveManifest = Optional.empty();
}
// need to programmatically add to inputs since @InputFiles in a
// extension is not processed
task.getInputs()
.files(getClasspath())
.withNormalizer(ClasspathNormalizer.class)
.withPropertyName("classpath");
TaskInputFilePropertyBuilder bndfileInput = task.getInputs()
.file(getBndfile())
.optional()
.withPathSensitivity(RELATIVE)
.withPropertyName("bndfile");
if (isGradleCompatible("7.2")) {
bndfileInput.normalizeLineEndings();
}
task.getInputs()
.property("bnd", getBnd());
task.getInputs()
.property("properties", getProperties());
}
/**
* Set the bnd property from a multi-line string.
*
* @param line bnd instructions.
*/
public void setBnd(CharSequence line) {
instructions.empty();
bnd(line);
}
/**
* Add instructions to the bnd property from a list of multi-line strings.
*
* @param lines bnd instructions.
*/
public void bnd(CharSequence... lines) {
instructions.addAll(lines);
}
/**
* Set the bnd property from a multi-line string using a {@link Provider}.
*
* @param lines A provider of bnd instructions.
*/
public void setBnd(Provider<? extends CharSequence> lines) {
instructions.empty();
bnd(lines);
}
/**
* Add a multi-line string of instructions to the bnd property using a
* {@link Provider}.
*
* @param lines A provider bnd instructions.
*/
public void bnd(Provider<? extends CharSequence> lines) {
instructions.add(lines);
}
/**
* Set the bnd property from a map.
*
* @param map A map of bnd instructions.
*/
public void setBnd(Map<String, ?> map) {
instructions.empty();
bnd(map);
}
/**
* Add instructions to the bnd property from a map.
*
* @param map A map of bnd instructions.
*/
public void bnd(Map<String, ?> map) {
map.forEach((key, value) -> instructions.add(key + "=" + value));
}
/**
* Add files to the classpath.
*
* @param paths The arguments will be handled using
* ConfigurableFileCollection.from().
* @return The property for the classpath.
*/
public ConfigurableFileCollection classpath(Object... paths) {
return builtBy(getClasspath().from(paths), paths);
}
/**
* Set the classpath property.
*
* @param path The argument will be handled using
* ConfigurableFileCollection.from().
*/
public void setClasspath(Object path) {
getClasspath().setFrom(Collections.emptyList());
getClasspath().setBuiltBy(Collections.emptyList());
classpath(path);
}
/**
* Set the sourceSet.
*
* @param sourceSet A sourceSet to use to find source code.
*/
public void setSourceSet(SourceSet sourceSet) {
getAllSource().setFrom(sourceSet.getAllSource()
.getSourceDirectories());
jarLibraryElements(getTask(), sourceSet.getCompileClasspathConfigurationName());
}
ConfigurableFileCollection getAllSource() {
return allSource;
}
File getBuildFile() {
return buildFile;
}
ProjectLayout getLayout() {
return layout;
}
org.gradle.api.tasks.bundling.Jar getTask() {
return task;
}
/**
* Return the Action to build the bundle for the task.
*
* @return The Action to build the bundle for the task.
*/
public Action<Task> buildAction() {
return new BuildAction();
}
private class BuildAction implements Action<Task> {
@Override
public void execute(Task t) {
try {
File projectDir = unwrapFile(getLayout().getProjectDirectory());
File buildDir = unwrapFile(getLayout().getBuildDirectory());
File buildFile = getBuildFile();
FileCollection sourcepath = getAllSource().filter(file -> file.exists());
// create Builder
Properties gradleProperties = new BeanProperties();
gradleProperties.putAll(unwrap(getProperties()));
gradleProperties.computeIfPresent("project",
(k, v) -> "__convention__".equals(v) ? getTask().getProject() : v);
gradleProperties.putIfAbsent("task", getTask());
try (Builder builder = new Builder(new Processor(gradleProperties, false))) {
// load bnd properties
File temporaryBndFile = File.createTempFile("bnd", ".bnd", getTask().getTemporaryDir());
try (Writer writer = IO.writer(temporaryBndFile)) {
// write any task manifest entries into the tmp bnd
// file
Optional<UTF8Properties> properties = Optional.ofNullable(getTask().getManifest())
.map(manifest -> MapStream.ofNullable(manifest.getEffectiveManifest()
.getAttributes())
.filterKey(key -> !Objects.equals(key, "Manifest-Version"))
.mapValue(Object::toString)
.collect(MapStream.toMap((k1, k2) -> {
throw new IllegalStateException("Duplicate key " + k1);
}, UTF8Properties::new)));
if (properties.isPresent()) {
properties.get()
.replaceHere(projectDir)
.store(writer, null);
}
// if the bnd file exists, add its contents to the
// tmp bnd file
Optional<File> bndfile = unwrapFileOptional(getBndfile()).filter(File::isFile);
if (bndfile.isPresent()) {
builder.loadProperties(bndfile.get())
.store(writer, null);
} else {
String bnd = unwrap(getBnd());
if (!bnd.isEmpty()) {
UTF8Properties props = new UTF8Properties();
props.load(bnd, buildFile, builder);
props.replaceHere(projectDir)
.store(writer, null);
}
}
}
// this will cause project.dir property to be set
builder.setProperties(temporaryBndFile, projectDir);
builder.setProperty("project.output", buildDir.getCanonicalPath());
// If no bundle to be built, we have nothing to do
if (builder.is(Constants.NOBUNDLES)) {
return;
}
// Reject sub-bundle projects
if (!Objects.equals(builder.getSubBuilders(), singletonList(builder))) {
throw new GradleException("Sub-bundles are not supported by this task");
}
File archiveFile = unwrapFile(getTask().getArchiveFile());
String archiveFileName = unwrap(getTask().getArchiveFileName());
String archiveBaseName = unwrap(getTask().getArchiveBaseName());
String archiveClassifier = unwrap(getTask().getArchiveClassifier());
String archiveVersion = unwrapOptional(getTask().getArchiveVersion()).orElse(null);
// Include entire contents of Jar task generated jar
// (except the manifest)
File archiveCopyFile = new File(getTask().getTemporaryDir(), archiveFileName);
IO.copy(archiveFile, archiveCopyFile);
Jar bundleJar = new Jar(archiveFileName, archiveCopyFile);
String reproducible = builder.getProperty(Constants.REPRODUCIBLE);
if (Objects.isNull(reproducible)) {
if (!getTask().isPreserveFileTimestamps()) {
builder.setProperty(Constants.REPRODUCIBLE, Boolean.TRUE.toString());
}
}
String compression = builder.getProperty(Constants.COMPRESSION);
if (Objects.isNull(compression)) {
switch (getTask().getEntryCompression()) {
case STORED :
builder.setProperty(Constants.COMPRESSION, Jar.Compression.STORE.name());
break;
case DEFLATED :
// default
break;
}
}
bundleJar.updateModified(archiveFile.lastModified(), "time of Jar task generated jar");
bundleJar.setManifest(new Manifest());
builder.setJar(bundleJar);
// set builder classpath
FileCollection buildpath = getClasspath().filter(file -> {
if (!file.exists()) {
return false;
}
if (file.isDirectory()) {
return true;
}
try (ZipFile zip = new ZipFile(file)) {
// make sure it is a valid zip file and not a pom
zip.entries();
} catch (IOException e) {
return false;
}
return true;
});
builder.setProperty("project.buildpath", buildpath.getAsPath());
builder.setClasspath(buildpath.getFiles()
.toArray(new File[0]));
getTask().getLogger()
.debug("builder classpath: {}", builder.getClasspath()
.stream()
.map(Jar::getSource)
.collect(toList()));
// set builder sourcepath
builder.setProperty("project.sourcepath", sourcepath.getAsPath());
builder.setSourcepath(sourcepath.getFiles()
.toArray(new File[0]));
getTask().getLogger()
.debug("builder sourcepath: {}", builder.getSourcePath());
// set bundle symbolic name from tasks's archiveBaseName
// property if necessary
String bundleSymbolicName = builder.getProperty(Constants.BUNDLE_SYMBOLICNAME);
if (isEmpty(bundleSymbolicName)) {
bundleSymbolicName = archiveClassifier.isEmpty() ? archiveBaseName
: archiveBaseName + "-" + archiveClassifier;
builder.setProperty(Constants.BUNDLE_SYMBOLICNAME, bundleSymbolicName);
}
// set bundle version from task's archiveVersion if
// necessary
String bundleVersion = builder.getProperty(Constants.BUNDLE_VERSION);
if (isEmpty(bundleVersion)) {
builder.setProperty(Constants.BUNDLE_VERSION, MavenVersion.parseMavenString(archiveVersion)
.getOSGiVersion()
.toString());
}
getTask().getLogger()
.debug("builder properties: {}", builder.getProperties());
// Build bundle
Jar builtJar = builder.build();
if (!builder.isOk()) {
// if we already have an error; fail now
logReport(builder, getTask().getLogger());
failTask("Bundle " + archiveFileName + " has errors", archiveFile);
}
// Write out the bundle
builtJar.write(archiveFile);
long now = System.currentTimeMillis();
archiveFile.setLastModified(now);
// Set effective manifest to generated manifest
Manifest manifest = builtJar.getManifest();
effectiveManifest.ifPresent(em -> em.setEffectiveManifest(manifest));
logReport(builder, getTask().getLogger());
if (!builder.isOk()) {
failTask("Bundle " + archiveFileName + " has errors", archiveFile);
}
}
} catch (Exception e) {
throw Exceptions.duck(e);
}
}
private void failTask(String msg, File archiveFile) {
IO.delete(archiveFile);
throw new GradleException(msg);
}
private boolean isEmpty(String header) {
return Objects.isNull(header) || header.trim()
.isEmpty() || Constants.EMPTY_HEADER.equals(header);
}
}
static final class EffectiveManifest implements InvocationHandler {
final org.gradle.api.java.archives.Manifest delegate;
final Class<?> delegateClass;
Manifest effectiveManifest;
EffectiveManifest(org.gradle.api.java.archives.Manifest delegate) {
this.delegate = delegate;
this.delegateClass = delegate.getClass();
this.effectiveManifest = null;
}
void setEffectiveManifest(Manifest effectiveManifest) {
this.effectiveManifest = effectiveManifest;
}
ClassLoader classLoader() {
return delegateClass.getClassLoader();
}
Class<?>[] interfaces() {
return collectInterfaces(delegateClass, new LinkedHashSet<>()).toArray(new Class<?>[0]);
}
private static Set<Class<?>> collectInterfaces(Class<?> c, Set<Class<?>> found) {
while (c != null) {
for (Class<?> i : c.getInterfaces()) {
if (found.add(i)) {
collectInterfaces(i, found);
}
}
c = c.getSuperclass();
}
return found;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
Class<?> returnType = method.getReturnType();
Manifest effectiveManifest = this.effectiveManifest;
if ((effectiveManifest != null) && name.equals("getEffectiveManifest") && (parameterTypes.length == 0)) {
org.gradle.api.java.archives.Manifest result = new DefaultManifest(null);
result.attributes(new AttributesMap(effectiveManifest.getMainAttributes()));
effectiveManifest.getEntries()
.forEach((section, attrs) -> result.attributes(new AttributesMap(attrs), section));
return result;
}
Method delegateMethod;
try {
delegateMethod = delegateClass.getMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
throw new UnsupportedOperationException(e);
}
try {
Object result = delegateMethod.invoke(delegate, args);
if (returnType.equals(org.gradle.api.java.archives.Manifest.class)
&& !(name.equals("getEffectiveManifest") && (parameterTypes.length == 0))) {
return proxy;
}
return result;
} catch (InvocationTargetException e) {
Throwable t = e;
for (Throwable cause; (t instanceof InvocationTargetException) && ((cause = t.getCause()) != null);) {
t = cause;
}
throw t;
}
}
}
static final class AttributesMap extends AbstractMap<String, Object> {
final java.util.jar.Attributes source;
AttributesMap(java.util.jar.Attributes source) {
this.source = requireNonNull(source);
}
@Override
public Set<Entry<String, Object>> entrySet() {
Set<Entry<Object, Object>> entrySet = source.entrySet();
return new AbstractSet<Entry<String, Object>>() {
@Override
public Iterator<Entry<String, Object>> iterator() {
Iterator<Entry<Object, Object>> iterator = entrySet.iterator();
return new Iterator<Entry<String, Object>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Entry<String, Object> next() {
Entry<Object, Object> next = iterator.next();
return new AbstractMap.SimpleImmutableEntry<>(next.getKey()
.toString(), next.getValue());
}
};
}
@Override
public int size() {
return entrySet.size();
}
};
}
}
}