-
Notifications
You must be signed in to change notification settings - Fork 89
/
ShadeMojo.java
1424 lines (1242 loc) · 54.3 KB
/
ShadeMojo.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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.apache.maven.plugins.shade.mojo;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.model.Model;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.plugins.shade.ShadeRequest;
import org.apache.maven.plugins.shade.Shader;
import org.apache.maven.plugins.shade.filter.Filter;
import org.apache.maven.plugins.shade.filter.MinijarFilter;
import org.apache.maven.plugins.shade.filter.SimpleFilter;
import org.apache.maven.plugins.shade.pom.PomWriter;
import org.apache.maven.plugins.shade.relocation.Relocator;
import org.apache.maven.plugins.shade.relocation.SimpleRelocator;
import org.apache.maven.plugins.shade.resource.ManifestResourceTransformer;
import org.apache.maven.plugins.shade.resource.ResourceTransformer;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException;
import org.apache.maven.shared.dependency.graph.DependencyNode;
import org.apache.maven.shared.transfer.artifact.DefaultArtifactCoordinate;
import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolver;
import org.apache.maven.shared.transfer.artifact.resolve.ArtifactResolverException;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.WriterFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import static org.apache.maven.plugins.shade.resource.UseDependencyReducedPom.createPomReplaceTransformers;
/**
* Mojo that performs shading delegating to the Shader component.
*
* @author Jason van Zyl
* @author Mauro Talevi
* @author David Blevins
* @author Hiram Chirino
*/
// CHECKSTYLE_OFF: LineLength
@Mojo( name = "shade", defaultPhase = LifecyclePhase.PACKAGE, threadSafe = true, requiresDependencyResolution = ResolutionScope.RUNTIME )
// CHECKSTYLE_ON: LineLength
public class ShadeMojo
extends AbstractMojo
{
/**
* The current Maven session.
*/
@Parameter( defaultValue = "${session}", readonly = true, required = true )
private MavenSession session;
/**
* The current Maven project.
*/
@Parameter( defaultValue = "${project}", readonly = true, required = true )
private MavenProject project;
@Component
private MavenProjectHelper projectHelper;
@Component( hint = "default", role = org.apache.maven.plugins.shade.Shader.class )
private Shader shader;
/**
* The dependency graph builder to use.
*/
@Component
private DependencyGraphBuilder dependencyGraphBuilder;
/**
* ProjectBuilder, needed to create projects from the artifacts.
*/
@Component
private ProjectBuilder projectBuilder;
/**
* Remote repositories which will be searched for source attachments.
*/
@Parameter( readonly = true, required = true, defaultValue = "${project.remoteArtifactRepositories}" )
protected List<ArtifactRepository> remoteArtifactRepositories;
/**
* Local maven repository.
*/
@Parameter( readonly = true, required = true, defaultValue = "${localRepository}" )
protected ArtifactRepository localRepository;
/**
* Artifact resolver, needed to download source jars for inclusion in classpath.
*/
@Component
protected ArtifactResolver artifactResolver;
/**
* Artifacts to include/exclude from the final artifact. Artifacts are denoted by composite identifiers of the
* general form <code>groupId:artifactId:type:classifier</code>. Since version 1.3, the wildcard characters '*' and
* '?' can be used within the sub parts of those composite identifiers to do pattern matching. For convenience, the
* syntax <code>groupId</code> is equivalent to <code>groupId:*:*:*</code>, <code>groupId:artifactId</code> is
* equivalent to <code>groupId:artifactId:*:*</code> and <code>groupId:artifactId:classifier</code> is equivalent to
* <code>groupId:artifactId:*:classifier</code>. For example:
*
* <pre>
* <artifactSet>
* <includes>
* <include>org.apache.maven:*</include>
* </includes>
* <excludes>
* <exclude>*:maven-core</exclude>
* </excludes>
* </artifactSet>
* </pre>
*/
@Parameter
private ArtifactSet artifactSet;
/**
* Packages to be relocated. For example:
*
* <pre>
* <relocations>
* <relocation>
* <pattern>org.apache</pattern>
* <shadedPattern>hidden.org.apache</shadedPattern>
* <includes>
* <include>org.apache.maven.*</include>
* </includes>
* <excludes>
* <exclude>org.apache.maven.Public*</exclude>
* </excludes>
* </relocation>
* </relocations>
* </pre>
*
* <em>Note:</em> Support for includes exists only since version 1.4.
*/
@SuppressWarnings( "MismatchedReadAndWriteOfArray" )
@Parameter
private PackageRelocation[] relocations;
/**
* Resource transformers to be used. Please see the "Examples" section for more information on available
* transformers and their configuration.
*/
@Parameter
private ResourceTransformer[] transformers;
/**
* Archive Filters to be used. Allows you to specify an artifact in the form of a composite identifier as used by
* {@link #artifactSet} and a set of include/exclude file patterns for filtering which contents of the archive are
* added to the shaded jar. From a logical perspective, includes are processed before excludes, thus it's possible
* to use an include to collect a set of files from the archive then use excludes to further reduce the set. By
* default, all files are included and no files are excluded. If multiple filters apply to an artifact, the
* intersection of the matched files will be included in the final JAR. For example:
*
* <pre>
* <filters>
* <filter>
* <artifact>junit:junit</artifact>
* <includes>
* <include>org/junit/**</include>
* </includes>
* <excludes>
* <exclude>org/junit/experimental/**</exclude>
* </excludes>
* </filter>
* </filters>
* </pre>
*/
@SuppressWarnings( "MismatchedReadAndWriteOfArray" )
@Parameter
private ArchiveFilter[] filters;
/**
* The destination directory for the shaded artifact.
*/
@Parameter( defaultValue = "${project.build.directory}" )
private File outputDirectory;
/**
* The name of the shaded artifactId.
* <p/>
* If you like to change the name of the native artifact, you may use the <build><finalName> setting. If this
* is set to something different than <build><finalName>, no file replacement will be performed, even if
* shadedArtifactAttached is being used.
*/
@Parameter
private String finalName;
/**
* The name of the shaded artifactId. So you may want to use a different artifactId and keep the standard version.
* If the original artifactId was "foo" then the final artifact would be something like foo-1.0.jar. So if you
* change the artifactId you might have something like foo-special-1.0.jar.
*/
@Parameter( defaultValue = "${project.artifactId}" )
private String shadedArtifactId;
/**
* If specified, this will include only artifacts which have groupIds which start with this.
*/
@Parameter
private String shadedGroupFilter;
/**
* Defines whether the shaded artifact should be attached as classifier to the original artifact. If false, the
* shaded jar will be the main artifact of the project
*/
@Parameter
private boolean shadedArtifactAttached;
/**
* Flag whether to generate a simplified POM for the shaded artifact. If set to <code>true</code>, dependencies that
* have been included into the uber JAR will be removed from the <code><dependencies></code> section of the
* generated POM. The reduced POM will be named <code>dependency-reduced-pom.xml</code> and is stored into the same
* directory as the shaded artifact. Unless you also specify dependencyReducedPomLocation, the plugin will create a
* temporary file named <code>dependency-reduced-pom.xml</code> in the project basedir.
*/
@Parameter( defaultValue = "true" )
private boolean createDependencyReducedPom;
/**
* Where to put the dependency reduced pom. Note: setting a value for this parameter with a directory other than
* ${basedir} will change the value of ${basedir} for all executions that come after the shade execution. This is
* often not what you want. This is considered an open issue with this plugin.
*
* @since 1.7
*/
@Parameter( defaultValue = "${basedir}/dependency-reduced-pom.xml" )
private File dependencyReducedPomLocation;
/**
* Create a dependency-reduced POM in ${basedir}/drp-UNIQUE.pom. This avoids build collisions of parallel builds
* without moving the dependency-reduced POM to a different directory. The property
* maven.shade.dependency-reduced-pom is set to the generated filename.
*
* @since 1.7.2
*/
@Parameter( defaultValue = "false" )
private boolean generateUniqueDependencyReducedPom;
/**
* Add dependency reduced POM to the JAR instead of the original one provided by the project.
* If {@code createDependencyReducedPom} is {@code false} this parameter will be ignored.
*
* @since 3.3.0
*/
@Parameter( defaultValue = "false" )
private boolean useDependencyReducedPomInJar;
/**
* When true, dependencies are kept in the pom but with scope 'provided'; when false, the dependency is removed.
*/
@Parameter
private boolean keepDependenciesWithProvidedScope;
/**
* When true, transitive deps of removed dependencies are promoted to direct dependencies. This should allow the
* drop in replacement of the removed deps with the new shaded jar and everything should still work.
*/
@Parameter
private boolean promoteTransitiveDependencies;
/**
* The name of the classifier used in case the shaded artifact is attached.
*/
@Parameter( defaultValue = "shaded" )
private String shadedClassifierName;
/**
* When true, it will attempt to create a sources jar as well
*/
@Parameter
private boolean createSourcesJar;
/**
* When true, it will attempt to create a test sources jar.
*/
@Parameter
private boolean createTestSourcesJar;
/**
* When true, it will attempt to shade the contents of Java source files when creating the sources JAR. When false,
* it will just relocate the Java source files to the shaded paths, but will not modify the actual source file
* contents.
* <p>
* <b>Please note:</b> This feature uses a heuristic search & replace approach which covers many, but definitely not
* all possible cases of source code shading and its excludes. There is no full Java parser behind this
* functionality, which would be the only way to get this right for Java language elements. As for matching within
* Java string constants, this is next to impossible to get 100% right, trying to guess if they are used in
* reflection or not.
* <p>
* Please understand that the source shading feature is not meant as a source code generator anyway, merely as a
* tool creating reasonably plausible source code when navigating to a relocated library class from an IDE,
* hopefully displaying source code which makes 95% sense - no more, no less.
*/
@Parameter( property = "shadeSourcesContent", defaultValue = "false" )
private boolean shadeSourcesContent;
/**
* When true, dependencies will be stripped down on the class level to only the transitive hull required for the
* artifact. <em>Note:</em> Usage of this feature requires Java 1.5 or higher.
*
* @since 1.4
*/
@Parameter
private boolean minimizeJar;
/**
* The path to the output file for the shaded artifact. When this parameter is set, the created archive will neither
* replace the project's main artifact nor will it be attached. Hence, this parameter causes the parameters
* {@link #finalName}, {@link #shadedArtifactAttached}, {@link #shadedClassifierName} and
* {@link #createDependencyReducedPom} to be ignored when used.
*
* @since 1.3
*/
@Parameter
private File outputFile;
/**
* You can pass here the roleHint about your own Shader implementation plexus component.
*
* @since 1.6
*/
@Parameter
private String shaderHint;
/**
* When true, the version of each dependency of the reduced pom will be based on the baseVersion of the original
* dependency instead of its resolved version. For example, if the original pom (transitively) depends on
* a:a:2.7-SNAPSHOT, if useBaseVersion is set to false, the reduced pom will depend on a:a:2.7-20130312.222222-12
* whereas if useBaseVersion is set to true, the reduced pom will depend on a:a:2.7-SNAPSHOT
*
* @since 3.0
*/
@Parameter( defaultValue = "false" )
private boolean useBaseVersion;
/**
* When true, creates a shaded test-jar artifact as well.
*/
@Parameter( defaultValue = "false" )
private boolean shadeTestJar;
/**
* All the present Shaders.
*/
@Inject
private Map<String, Shader> shaders;
/**
* When true, skips the execution of this MOJO.
* @since 3.3.0
*/
@Parameter( defaultValue = "false" )
private boolean skip;
/**
* @throws MojoExecutionException in case of an error.
*/
public void execute()
throws MojoExecutionException
{
if ( skip )
{
getLog().info( "Shading has been skipped." );
return;
}
setupHintedShader();
Set<File> artifacts = new LinkedHashSet<>();
Set<String> artifactIds = new LinkedHashSet<>();
Set<File> sourceArtifacts = new LinkedHashSet<>();
Set<File> testArtifacts = new LinkedHashSet<>();
Set<File> testSourceArtifacts = new LinkedHashSet<>();
ArtifactSelector artifactSelector =
new ArtifactSelector( project.getArtifact(), artifactSet, shadedGroupFilter );
if ( artifactSelector.isSelected( project.getArtifact() ) && !"pom".equals( project.getArtifact().getType() ) )
{
if ( invalidMainArtifact() )
{
createErrorOutput();
throw new MojoExecutionException( "Failed to create shaded artifact, "
+ "project main artifact does not exist." );
}
artifacts.add( project.getArtifact().getFile() );
if ( createSourcesJar )
{
File file = shadedSourcesArtifactFile();
if ( file.isFile() )
{
sourceArtifacts.add( file );
}
}
if ( shadeTestJar )
{
File file = shadedTestArtifactFile();
if ( file.isFile() )
{
testArtifacts.add( file );
}
}
if ( createTestSourcesJar )
{
File file = shadedTestSourcesArtifactFile();
if ( file.isFile() )
{
testSourceArtifacts.add( file );
}
}
}
processArtifactSelectors( artifacts, artifactIds, sourceArtifacts, testArtifacts, testSourceArtifacts,
artifactSelector );
File outputJar = ( outputFile != null ) ? outputFile : shadedArtifactFileWithClassifier();
File sourcesJar = shadedSourceArtifactFileWithClassifier();
File testJar = shadedTestArtifactFileWithClassifier();
File testSourcesJar = shadedTestSourceArtifactFileWithClassifier();
// Now add our extra resources
try
{
List<Filter> filters = getFilters();
List<Relocator> relocators = getRelocators();
List<ResourceTransformer> resourceTransformers = getResourceTransformers();
if ( createDependencyReducedPom )
{
createDependencyReducedPom( artifactIds );
if ( useDependencyReducedPomInJar )
{
// In some cases the used implementation of the resourceTransformers is immutable.
resourceTransformers = new ArrayList<>( resourceTransformers );
resourceTransformers.addAll(
createPomReplaceTransformers( project, dependencyReducedPomLocation ) );
}
}
ShadeRequest shadeRequest = shadeRequest( "jar", artifacts, outputJar, filters, relocators,
resourceTransformers );
shader.shade( shadeRequest );
if ( createSourcesJar )
{
ShadeRequest shadeSourcesRequest =
createShadeSourcesRequest( "sources-jar", sourceArtifacts, sourcesJar, filters, relocators,
resourceTransformers );
shader.shade( shadeSourcesRequest );
}
if ( shadeTestJar )
{
ShadeRequest shadeTestRequest =
shadeRequest( "test-jar", testArtifacts, testJar, filters, relocators, resourceTransformers );
shader.shade( shadeTestRequest );
}
if ( createTestSourcesJar )
{
ShadeRequest shadeTestSourcesRequest =
createShadeSourcesRequest( "test-sources-jar", testSourceArtifacts, testSourcesJar, filters,
relocators, resourceTransformers );
shader.shade( shadeTestSourcesRequest );
}
if ( outputFile == null )
{
boolean renamed = false;
// rename the output file if a specific finalName is set
// but don't rename if the finalName is the <build><finalName>
// because this will be handled implicitly later
if ( finalName != null && finalName.length() > 0 //
&& !finalName.equals( project.getBuild().getFinalName() ) )
{
String finalFileName = finalName + "." + project.getArtifact().getArtifactHandler().getExtension();
File finalFile = new File( outputDirectory, finalFileName );
replaceFile( finalFile, outputJar );
outputJar = finalFile;
// Also support the sources JAR
if ( createSourcesJar )
{
finalFileName = finalName + "-sources.jar";
finalFile = new File( outputDirectory, finalFileName );
replaceFile( finalFile, sourcesJar );
sourcesJar = finalFile;
}
// Also support the test JAR
if ( shadeTestJar )
{
finalFileName = finalName + "-tests.jar";
finalFile = new File( outputDirectory, finalFileName );
replaceFile( finalFile, testJar );
testJar = finalFile;
}
if ( createTestSourcesJar )
{
finalFileName = finalName + "-test-sources.jar";
finalFile = new File( outputDirectory, finalFileName );
replaceFile( finalFile, testSourcesJar );
testSourcesJar = finalFile;
}
renamed = true;
}
if ( shadedArtifactAttached )
{
getLog().info( "Attaching shaded artifact." );
projectHelper.attachArtifact( project, project.getArtifact().getType(), shadedClassifierName,
outputJar );
if ( createSourcesJar )
{
projectHelper.attachArtifact( project, "java-source", shadedClassifierName + "-sources",
sourcesJar );
}
if ( shadeTestJar )
{
projectHelper.attachArtifact( project, "test-jar", shadedClassifierName + "-tests",
testJar );
}
if ( createTestSourcesJar )
{
projectHelper.attachArtifact( project, "java-source",
shadedClassifierName + "-test-sources", testSourcesJar );
}
}
else if ( !renamed )
{
getLog().info( "Replacing original artifact with shaded artifact." );
File originalArtifact = project.getArtifact().getFile();
if ( originalArtifact != null )
{
replaceFile( originalArtifact, outputJar );
if ( createSourcesJar )
{
getLog().info( "Replacing original source artifact with shaded source artifact." );
File shadedSources = shadedSourcesArtifactFile();
replaceFile( shadedSources, sourcesJar );
projectHelper.attachArtifact( project, "java-source", "sources", shadedSources );
}
if ( shadeTestJar )
{
getLog().info( "Replacing original test artifact with shaded test artifact." );
File shadedTests = shadedTestArtifactFile();
replaceFile( shadedTests, testJar );
projectHelper.attachArtifact( project, "test-jar", shadedTests );
}
if ( createTestSourcesJar )
{
getLog().info( "Replacing original test source artifact "
+ "with shaded test source artifact." );
File shadedTestSources = shadedTestSourcesArtifactFile();
replaceFile( shadedTestSources, testSourcesJar );
projectHelper.attachArtifact( project, "java-source", "test-sources",
shadedTestSources );
}
}
}
}
}
catch ( Exception e )
{
throw new MojoExecutionException( "Error creating shaded jar: " + e.getMessage(), e );
}
}
private void createErrorOutput()
{
getLog().error( "The project main artifact does not exist. This could have the following" );
getLog().error( "reasons:" );
getLog().error( "- You have invoked the goal directly from the command line. This is not" );
getLog().error( " supported. Please add the goal to the default lifecycle via an" );
getLog().error( " <execution> element in your POM and use \"mvn package\" to have it run." );
getLog().error( "- You have bound the goal to a lifecycle phase before \"package\". Please" );
getLog().error( " remove this binding from your POM such that the goal will be run in" );
getLog().error( " the proper phase." );
getLog().error( "- You removed the configuration of the maven-jar-plugin that produces the main artifact." );
}
private ShadeRequest shadeRequest( String shade, Set<File> artifacts, File outputJar, List<Filter> filters,
List<Relocator> relocators, List<ResourceTransformer> resourceTransformers )
{
ShadeRequest shadeRequest = new ShadeRequest();
shadeRequest.setJars( artifacts );
shadeRequest.setUberJar( outputJar );
shadeRequest.setFilters( filters );
shadeRequest.setRelocators( relocators );
shadeRequest.setResourceTransformers( toResourceTransformers( shade, resourceTransformers ) );
return shadeRequest;
}
private ShadeRequest createShadeSourcesRequest( String shade, Set<File> testArtifacts, File testJar,
List<Filter> filters, List<Relocator> relocators,
List<ResourceTransformer> resourceTransformers )
{
ShadeRequest shadeSourcesRequest =
shadeRequest( shade, testArtifacts, testJar, filters, relocators, resourceTransformers );
shadeSourcesRequest.setShadeSourcesContent( shadeSourcesContent );
return shadeSourcesRequest;
}
private void setupHintedShader()
throws MojoExecutionException
{
if ( shaderHint != null )
{
shader = shaders.get( shaderHint );
if ( shader == null )
{
throw new MojoExecutionException(
"unable to lookup own Shader implementation with hint: '" + shaderHint + "'"
);
}
}
}
private void processArtifactSelectors( Set<File> artifacts, Set<String> artifactIds, Set<File> sourceArtifacts,
Set<File> testArtifacts, Set<File> testSourceArtifacts,
ArtifactSelector artifactSelector )
{
List<String> excludedArtifacts = new ArrayList<>();
List<String> pomArtifacts = new ArrayList<>();
List<String> emptySourceArtifacts = new ArrayList<>();
List<String> emptyTestArtifacts = new ArrayList<>();
List<String> emptyTestSourceArtifacts = new ArrayList<>();
for ( Artifact artifact : project.getArtifacts() )
{
if ( !artifactSelector.isSelected( artifact ) )
{
excludedArtifacts.add( artifact.getId() );
continue;
}
if ( "pom".equals( artifact.getType() ) )
{
pomArtifacts.add( artifact.getId() );
continue;
}
getLog().info( "Including " + artifact.getId() + " in the shaded jar." );
artifacts.add( artifact.getFile() );
artifactIds.add( getId( artifact ) );
if ( createSourcesJar )
{
File file = resolveArtifactForClassifier( artifact, "sources" );
if ( file != null )
{
if ( file.length() > 0 )
{
sourceArtifacts.add( file );
}
else
{
emptySourceArtifacts.add( artifact.getArtifactId() );
}
}
}
if ( shadeTestJar )
{
File file = resolveArtifactForClassifier( artifact, "tests" );
if ( file != null )
{
if ( file.length() > 0 )
{
testArtifacts.add( file );
}
else
{
emptyTestArtifacts.add( artifact.getId() );
}
}
}
if ( createTestSourcesJar )
{
File file = resolveArtifactForClassifier( artifact, "test-sources" );
if ( file != null )
{
testSourceArtifacts.add( file );
}
else
{
emptyTestSourceArtifacts.add( artifact.getId() );
}
}
}
for ( String artifactId : excludedArtifacts )
{
getLog().info( "Excluding " + artifactId + " from the shaded jar." );
}
for ( String artifactId : pomArtifacts )
{
getLog().info( "Skipping pom dependency " + artifactId + " in the shaded jar." );
}
for ( String artifactId : emptySourceArtifacts )
{
getLog().warn( "Skipping empty source jar " + artifactId + "." );
}
for ( String artifactId : emptyTestArtifacts )
{
getLog().warn( "Skipping empty test jar " + artifactId + "." );
}
for ( String artifactId : emptyTestArtifacts )
{
getLog().warn( "Skipping empty test source jar " + artifactId + "." );
}
}
private boolean invalidMainArtifact()
{
return project.getArtifact().getFile() == null || !project.getArtifact().getFile().isFile();
}
private void replaceFile( File oldFile, File newFile )
throws MojoExecutionException
{
getLog().info( "Replacing " + oldFile + " with " + newFile );
File origFile = new File( outputDirectory, "original-" + oldFile.getName() );
if ( oldFile.exists() && !oldFile.renameTo( origFile ) )
{
// try a gc to see if an unclosed stream needs garbage collecting
System.gc();
System.gc();
if ( !oldFile.renameTo( origFile ) )
{
// Still didn't work. We'll do a copy
try
{
copyFiles( oldFile, origFile );
}
catch ( IOException ex )
{
// kind of ignorable here. We're just trying to save the original
getLog().warn( ex );
}
}
}
if ( !newFile.renameTo( oldFile ) )
{
// try a gc to see if an unclosed stream needs garbage collecting
System.gc();
System.gc();
if ( !newFile.renameTo( oldFile ) )
{
// Still didn't work. We'll do a copy
try
{
copyFiles( newFile, oldFile );
}
catch ( IOException ex )
{
throw new MojoExecutionException( "Could not replace original artifact with shaded artifact!", ex );
}
}
}
}
private void copyFiles( File source, File target )
throws IOException
{
try ( InputStream in = new FileInputStream( source );
OutputStream out = new FileOutputStream( target ) )
{
IOUtil.copy( in, out );
}
}
private File resolveArtifactForClassifier( Artifact artifact, String classifier )
{
DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate();
coordinate.setGroupId( artifact.getGroupId() );
coordinate.setArtifactId( artifact.getArtifactId() );
coordinate.setVersion( artifact.getVersion() );
coordinate.setExtension( "jar" );
coordinate.setClassifier( classifier );
Artifact resolvedArtifact;
try
{
resolvedArtifact =
artifactResolver.resolveArtifact( session.getProjectBuildingRequest(), coordinate ).getArtifact();
}
catch ( ArtifactResolverException e )
{
getLog().warn( "Could not get " + classifier + " for " + artifact );
return null;
}
if ( resolvedArtifact.isResolved() )
{
return resolvedArtifact.getFile();
}
return null;
}
private List<Relocator> getRelocators()
{
List<Relocator> relocators = new ArrayList<>();
if ( relocations == null )
{
return relocators;
}
for ( PackageRelocation r : relocations )
{
relocators.add( new SimpleRelocator( r.getPattern(), r.getShadedPattern(), r.getIncludes(), r.getExcludes(),
r.isRawString() ) );
}
return relocators;
}
private List<ResourceTransformer> getResourceTransformers()
{
if ( transformers == null )
{
return Collections.emptyList();
}
return Arrays.asList( transformers );
}
private List<Filter> getFilters()
throws MojoExecutionException
{
List<Filter> filters = new ArrayList<>();
List<SimpleFilter> simpleFilters = new ArrayList<>();
if ( this.filters != null && this.filters.length > 0 )
{
Map<Artifact, ArtifactId> artifacts = new HashMap<>();
artifacts.put( project.getArtifact(), new ArtifactId( project.getArtifact() ) );
for ( Artifact artifact : project.getArtifacts() )
{
artifacts.put( artifact, new ArtifactId( artifact ) );
}
for ( ArchiveFilter filter : this.filters )
{
ArtifactId pattern = new ArtifactId( filter.getArtifact() );
Set<File> jars = new HashSet<>();
for ( Map.Entry<Artifact, ArtifactId> entry : artifacts.entrySet() )
{
if ( entry.getValue().matches( pattern ) )
{
Artifact artifact = entry.getKey();
jars.add( artifact.getFile() );
if ( createSourcesJar )
{
File file = resolveArtifactForClassifier( artifact, "sources" );
if ( file != null )
{
jars.add( file );
}
}
if ( shadeTestJar )
{
File file = resolveArtifactForClassifier( artifact, "tests" );
if ( file != null )
{
jars.add( file );
}
}
}
}
if ( jars.isEmpty() )
{
getLog().info( "No artifact matching filter " + filter.getArtifact() );
continue;
}
simpleFilters.add( new SimpleFilter( jars, filter ) );
}
}
filters.addAll( simpleFilters );
if ( minimizeJar )
{
getLog().info( "Minimizing jar " + project.getArtifact() );
try
{
filters.add( new MinijarFilter( project, getLog(), simpleFilters ) );
}
catch ( IOException e )
{
throw new MojoExecutionException( "Failed to analyze class dependencies", e );
}
}
return filters;
}
private File shadedArtifactFileWithClassifier()
{
Artifact artifact = project.getArtifact();
final String shadedName = shadedArtifactId + "-" + artifact.getVersion() + "-" + shadedClassifierName + "."
+ artifact.getArtifactHandler().getExtension();
return new File( outputDirectory, shadedName );
}