-
Notifications
You must be signed in to change notification settings - Fork 265
/
PomHelper.java
1756 lines (1642 loc) · 69.9 KB
/
PomHelper.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.codehaus.mojo.versions.api;
/*
* 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 javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Profile;
import org.apache.maven.model.ReportPlugin;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.UrlModelSource;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
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.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader;
import org.codehaus.mojo.versions.utils.RegexUtils;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.ReaderFactory;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import static java.util.Collections.singletonMap;
import static java.util.stream.IntStream.range;
/**
* Helper class for modifying pom files.
*
* @author Stephen Connolly
* @since 1.0-alpha-3
*/
public class PomHelper
{
public static final String APACHE_MAVEN_PLUGINS_GROUPID = "org.apache.maven.plugins";
/**
* Gets the raw model before any interpolation what-so-ever.
*
* @param project The project to get the raw model for.
* @return The raw model.
* @throws IOException if the file is not found or if the file does not parse.
*/
public static Model getRawModel( MavenProject project )
throws IOException
{
return getRawModel( project.getFile() );
}
/**
* Gets the raw model before any interpolation what-so-ever.
*
* @param moduleProjectFile The project file to get the raw model for.
* @return The raw model.
* @throws IOException if the file is not found or if the file does not parse.
*/
public static Model getRawModel( File moduleProjectFile )
throws IOException
{
try ( Reader reader = new BufferedReader( new InputStreamReader( Files.newInputStream( moduleProjectFile
.toPath() ) ) ) )
{
return getRawModel( reader );
}
}
/**
* Gets the current raw model before any interpolation what-so-ever.
*
* @param modifiedPomXMLEventReader The {@link ModifiedPomXMLEventReader} to get the raw model for.
* @return The raw model.
* @throws IOException if the file is not found or if the file does not parse.
*/
public static Model getRawModel( ModifiedPomXMLEventReader modifiedPomXMLEventReader )
throws IOException
{
try ( Reader reader = new StringReader( modifiedPomXMLEventReader.asStringBuilder().toString() ) )
{
return getRawModel( reader );
}
}
/**
* Gets the current raw model before any interpolation what-so-ever.
*
* @param reader The {@link Reader} to get the raw model for.
* @return The raw model.
* @throws IOException if the file is not found or if the file does not parse.
*/
public static Model getRawModel( Reader reader )
throws IOException
{
try
{
return new MavenXpp3Reader().read( reader );
}
catch ( XmlPullParserException e )
{
throw new IOException( e.getMessage(), e );
}
}
/**
* Searches the pom re-defining the specified property to the specified version.
*
* @param pom The pom to modify.
* @param profileId The profile in which to modify the property.
* @param property The property to modify.
* @param value The new value of the property.
* @return <code>true</code> if a replacement was made.
* @throws XMLStreamException if somethinh went wrong.
*/
public static boolean setPropertyVersion( final ModifiedPomXMLEventReader pom, final String profileId,
final String property, final String value )
throws XMLStreamException
{
Stack<String> stack = new Stack<>();
String path = "";
final Pattern propertyRegex;
final Pattern matchScopeRegex;
final Pattern projectProfileId;
boolean inMatchScope = false;
boolean madeReplacement = false;
if ( profileId == null )
{
propertyRegex = Pattern.compile( "/project/properties/" + RegexUtils.quote( property ) );
matchScopeRegex = Pattern.compile( "/project/properties" );
projectProfileId = null;
}
else
{
propertyRegex = Pattern.compile( "/project/profiles/profile/properties/" + RegexUtils.quote( property ) );
matchScopeRegex = Pattern.compile( "/project/profiles/profile" );
projectProfileId = Pattern.compile( "/project/profiles/profile/id" );
}
pom.rewind();
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
stack.push( path );
path = path + "/" + event.asStartElement().getName().getLocalPart();
if ( propertyRegex.matcher( path ).matches() )
{
pom.mark( 0 );
}
else if ( matchScopeRegex.matcher( path ).matches() )
{
// we're in a new match scope
// reset any previous partial matches
inMatchScope = profileId == null;
pom.clearMark( 0 );
pom.clearMark( 1 );
}
else if ( profileId != null && projectProfileId.matcher( path ).matches() )
{
String candidateId = pom.getElementText();
path = stack.pop(); // since getElementText will be after the end element
inMatchScope = profileId.trim().equals( candidateId.trim() );
}
}
if ( event.isEndElement() )
{
if ( propertyRegex.matcher( path ).matches() )
{
pom.mark( 1 );
}
else if ( matchScopeRegex.matcher( path ).matches() )
{
if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) )
{
pom.replaceBetween( 0, 1, value );
madeReplacement = true;
}
pom.clearMark( 0 );
pom.clearMark( 1 );
inMatchScope = false;
}
path = stack.pop();
}
}
return madeReplacement;
}
/**
* Searches the pom re-defining the project version to the specified version.
*
* @param pom The pom to modify.
* @param value The new value of the property.
* @return <code>true</code> if a replacement was made.
* @throws XMLStreamException if somethinh went wrong.
*/
public static boolean setProjectVersion( final ModifiedPomXMLEventReader pom, final String value )
throws XMLStreamException
{
return setElementValue( pom, "/project", "version", value, false );
}
/**
* Sets the value of the given element given its parent element path.
* Will only consider the first found occurrence of the parent element.
* If the element is not found in the parent element, the method will create the element.
*
* @param pom pom to modify
* @param parentPath path of the parent element
* @param elementName name of the element to set or create
* @param value the new value of the element
* @return {@code true} if the element was created or replaced
* @throws XMLStreamException if something went wrong
*/
public static boolean setElementValue( ModifiedPomXMLEventReader pom, String parentPath,
String elementName, String value )
throws XMLStreamException
{
pom.rewind();
return setElementValue( pom, parentPath, elementName, value, true );
}
/**
* Sets the value of the given element given its parent element path.
* Will only consider the first found occurrence of the parent element.
* If the element is not found in the parent element, the method will create the element
* if {@code shouldCreate} is {@code true}.
*
* @param pom pom to modify
* @param parentPath path of the parent element
* @param elementName name of the element to set or create
* @param value the new value of the element
* @param shouldCreate should the element be created if it's not found in the first encountered parent element
* matching the parentPath
* @return {@code true} if the element was created or replaced
* @throws XMLStreamException if something went wrong
*/
public static boolean setElementValue( ModifiedPomXMLEventReader pom, String parentPath,
String elementName, String value, boolean shouldCreate )
throws XMLStreamException
{
class ElementValueInternal
{
private final String parentName;
private final String superParentPath;
private static final int MARK_CHILD_BEGIN = 0;
private static final int MARK_OPTION = 1;
private static final int PARENT_BEGIN = 2;
ElementValueInternal()
{
int lastDelimeterIndex = parentPath.lastIndexOf( '/' );
parentName = parentPath.substring( lastDelimeterIndex + 1 );
superParentPath = parentPath.substring( 0, lastDelimeterIndex );
}
boolean process( String currentPath ) throws XMLStreamException
{
boolean replacementMade = false;
while ( !replacementMade && pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
String currentElementName = event.asStartElement().getName().getLocalPart();
// here, we will only mark the beginning of the child or the parent element
if ( currentPath.equals( parentPath ) && elementName.equals( currentElementName ) )
{
pom.mark( MARK_CHILD_BEGIN );
}
else if ( currentPath.equals( superParentPath ) && currentElementName.equals( parentName ) )
{
pom.mark( PARENT_BEGIN );
}
// process child element
replacementMade = process( currentPath + "/" + currentElementName );
}
else if ( event.isEndElement() )
{
// here we're doing the replacement
if ( currentPath.equals( parentPath + "/" + elementName ) )
{
// end of the child
replaceValueInChild();
replacementMade = true;
}
else if ( shouldCreate && currentPath.equals( parentPath ) )
{
// end of the parent
replaceValueInParent();
replacementMade = true;
}
else
{
return false;
}
}
}
return replacementMade;
}
private void replaceValueInChild()
{
pom.mark( MARK_OPTION );
if ( pom.getBetween( MARK_CHILD_BEGIN, MARK_OPTION ).length() > 0 )
{
pom.replaceBetween( 0, 1, value );
}
else
{
pom.replace( String.format( "<%1$s>%2$s</%1$s>", elementName, value ) );
}
}
private void replaceValueInParent()
{
pom.mark( MARK_OPTION );
if ( pom.hasMark( PARENT_BEGIN ) )
{
if ( pom.getBetween( PARENT_BEGIN, MARK_OPTION ).length() > 0 )
{
pom.replace( String.format( "<%2$s>%3$s</%2$s></%1$s>",
parentName, elementName, value ) );
}
else
{
pom.replace( String.format( "<%1$s><%2$s>%3$s</%2$s></%1$s>",
parentName, elementName, value ) );
}
}
else
{
pom.replace( String.format( "<%1$s><%2$s>%3$s</%2$s></%1$s>",
parentName, elementName, value ) );
}
}
}
try
{
pom.rewind();
return new ElementValueInternal().process( "" );
}
finally
{
range( 0, 3 ).forEach( pom::clearMark );
}
}
/**
* Retrieves the project version from the pom.
*
* @param pom The pom.
* @return the project version or <code>null</code> if the project version is not defined (i.e. inherited from
* parent version).
* @throws XMLStreamException if something went wrong.
*/
public static String getProjectVersion( final ModifiedPomXMLEventReader pom )
throws XMLStreamException
{
Stack<String> stack = new Stack<>();
String path = "";
final Pattern matchScopeRegex = Pattern.compile( "/project/version" );
pom.rewind();
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
stack.push( path );
path = path + "/" + event.asStartElement().getName().getLocalPart();
if ( matchScopeRegex.matcher( path ).matches() )
{
pom.mark( 0 );
}
}
if ( event.isEndElement() )
{
if ( matchScopeRegex.matcher( path ).matches() )
{
pom.mark( 1 );
if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) )
{
return pom.getBetween( 0, 1 ).trim();
}
pom.clearMark( 0 );
pom.clearMark( 1 );
}
path = stack.pop();
}
}
return null;
}
/**
* Searches the pom re-defining the project version to the specified version.
*
* @param pom The pom to modify.
* @param value The new value of the property.
* @return <code>true</code> if a replacement was made.
* @throws XMLStreamException if somethinh went wrong.
*/
public static boolean setProjectParentVersion( final ModifiedPomXMLEventReader pom, final String value )
throws XMLStreamException
{
Stack<String> stack = new Stack<>();
String path = "";
final Pattern matchScopeRegex;
boolean madeReplacement = false;
matchScopeRegex = Pattern.compile( "/project/parent/version" );
pom.rewind();
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
stack.push( path );
path = path + "/" + event.asStartElement().getName().getLocalPart();
if ( matchScopeRegex.matcher( path ).matches() )
{
pom.mark( 0 );
}
}
if ( event.isEndElement() )
{
if ( matchScopeRegex.matcher( path ).matches() )
{
pom.mark( 1 );
if ( pom.hasMark( 0 ) && pom.hasMark( 1 ) )
{
pom.replaceBetween( 0, 1, value );
madeReplacement = true;
}
pom.clearMark( 0 );
pom.clearMark( 1 );
}
path = stack.pop();
}
}
return madeReplacement;
}
/**
* Searches the pom re-defining the specified dependency to the specified version.
*
* @param pom The pom to modify.
* @param groupId The groupId of the dependency.
* @param artifactId The artifactId of the dependency.
* @param oldVersion The old version of the dependency.
* @param newVersion The new version of the dependency.
* @param model The model to get the project properties from.
* @return <code>true</code> if a replacement was made.
* @throws XMLStreamException if something went wrong.
*/
@SuppressWarnings( "checkstyle:MethodLength" )
public static boolean setDependencyVersion( final ModifiedPomXMLEventReader pom, final String groupId,
final String artifactId, final String oldVersion,
final String newVersion, final Model model )
throws XMLStreamException
{
Stack<String> stack = new Stack<>();
String path = "";
Set<String> implicitPaths =
new HashSet<>( Arrays.asList( "/project/parent/groupId", "/project/parent/artifactId",
"/project/parent/version", "/project/groupId",
"/project/artifactId", "/project/version" ) );
Map<String, String> implicitProperties = new HashMap<>();
for ( Map.Entry<Object, Object> entry : model.getProperties().entrySet() )
{
implicitProperties.put( (String) entry.getKey(), (String) entry.getValue() );
}
pom.rewind();
while ( pom.hasNext() )
{
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
stack.push( path );
final String elementName = event.asStartElement().getName().getLocalPart();
path = path + "/" + elementName;
if ( implicitPaths.contains( path ) )
{
final String elementText = pom.getElementText().trim();
implicitProperties.put( path.substring( 1 ).replace( '/', '.' ), elementText );
path = stack.pop();
}
}
if ( event.isEndElement() )
{
path = stack.pop();
}
}
}
boolean modified = true;
while ( modified )
{
modified = false;
for ( Map.Entry<String, String> entry : implicitProperties.entrySet() )
{
if ( entry.getKey().contains( ".parent" ) )
{
String child = entry.getKey().replace( ".parent", "" );
if ( !implicitProperties.containsKey( child ) )
{
implicitProperties.put( child, entry.getValue() );
modified = true;
break;
}
}
}
}
stack = new Stack<>();
path = "";
boolean inMatchScope = false;
boolean madeReplacement = false;
boolean haveGroupId = false;
boolean haveArtifactId = false;
boolean haveOldVersion = false;
final Pattern matchScopeRegex = Pattern.compile(
"/project" + "(/profiles/profile)?"
+ "((/dependencyManagement)|(/build(/pluginManagement)?/plugins/plugin))?"
+ "/dependencies/dependency" );
final Pattern matchTargetRegex = Pattern.compile(
"/project" + "(/profiles/profile)?"
+ "((/dependencyManagement)|(/build(/pluginManagement)?/plugins/plugin))?"
+ "/dependencies/dependency"
+ "((/groupId)|(/artifactId)|(/version))" );
pom.rewind();
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
stack.push( path );
final String elementName = event.asStartElement().getName().getLocalPart();
path = path + "/" + elementName;
if ( matchScopeRegex.matcher( path ).matches() )
{
// we're in a new match scope
// reset any previous partial matches
inMatchScope = true;
pom.clearMark( 0 );
pom.clearMark( 1 );
haveGroupId = false;
haveArtifactId = false;
haveOldVersion = false;
}
else if ( inMatchScope && matchTargetRegex.matcher( path ).matches() )
{
if ( "groupId".equals( elementName ) )
{
haveGroupId = groupId.equals( evaluate( pom.getElementText().trim(), implicitProperties ) );
path = stack.pop();
}
else if ( "artifactId".equals( elementName ) )
{
haveArtifactId =
artifactId.equals( evaluate( pom.getElementText().trim(), implicitProperties ) );
path = stack.pop();
}
else if ( "version".equals( elementName ) )
{
pom.mark( 0 );
}
}
}
if ( event.isEndElement() )
{
if ( matchTargetRegex.matcher( path ).matches()
&& "version".equals( event.asEndElement().getName().getLocalPart() ) )
{
pom.mark( 1 );
String compressedPomVersion = StringUtils.deleteWhitespace( pom.getBetween( 0, 1 ).trim() );
String compressedOldVersion = StringUtils.deleteWhitespace( oldVersion );
try
{
haveOldVersion = isVersionOverlap( compressedOldVersion, compressedPomVersion );
}
catch ( InvalidVersionSpecificationException e )
{
// fall back to string comparison
haveOldVersion = compressedOldVersion.equals( compressedPomVersion );
}
}
else if ( matchScopeRegex.matcher( path ).matches() )
{
if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) && haveGroupId && haveArtifactId
&& haveOldVersion )
{
pom.replaceBetween( 0, 1, newVersion );
madeReplacement = true;
}
pom.clearMark( 0 );
pom.clearMark( 1 );
haveArtifactId = false;
haveGroupId = false;
haveOldVersion = false;
inMatchScope = false;
}
path = stack.pop();
}
}
return madeReplacement;
}
/**
* A lightweight expression evaluation function.
*
* @param expr The expression to evaluate.
* @param properties The properties to substitute.
* @return The evaluated expression.
*/
public static String evaluate( String expr, Map<String, String> properties )
{
if ( expr == null )
{
return null;
}
String expression = stripTokens( expr );
if ( expression.equals( expr ) )
{
int index = expr.indexOf( "${" );
if ( index >= 0 )
{
int lastIndex = expr.indexOf( "}", index );
if ( lastIndex >= 0 )
{
String retVal = expr.substring( 0, index );
if ( index > 0 && expr.charAt( index - 1 ) == '$' )
{
retVal += expr.substring( index + 1, lastIndex + 1 );
}
else
{
retVal += evaluate( expr.substring( index, lastIndex + 1 ), properties );
}
retVal += evaluate( expr.substring( lastIndex + 1 ), properties );
return retVal;
}
}
// Was not an expression
if ( expression.contains( "$$" ) )
{
return expression.replaceAll( "\\$\\$", "\\$" );
}
else
{
return expression;
}
}
String value = properties.get( expression );
if ( value != null )
{
int exprStartDelimiter = value.indexOf( "${" );
if ( exprStartDelimiter >= 0 )
{
if ( exprStartDelimiter > 0 )
{
value = value.substring( 0, exprStartDelimiter )
+ evaluate( value.substring( exprStartDelimiter ), properties );
}
else
{
value = evaluate( value.substring( exprStartDelimiter ), properties );
}
}
}
else
{
// TODO find a way to log that and not use this System.out!!
// this class could be a component with logger injected !!
System.out.println( "expression: " + expression + " no value " );
}
return value == null ? expr : value;
}
/**
* Strips the expression token markers from the start and end of the string.
*
* @param expr the string (perhaps with token markers)
* @return the string (definately without token markers)
*/
private static String stripTokens( String expr )
{
if ( expr.startsWith( "${" ) && expr.indexOf( "}" ) == expr.length() - 1 )
{
expr = expr.substring( 2, expr.length() - 1 );
}
return expr;
}
/**
* Checks if two versions or ranges have an overlap.
*
* @param leftVersionOrRange the 1st version number or range to test
* @param rightVersionOrRange the 2nd version number or range to test
* @return true if both versions have an overlap
* @throws InvalidVersionSpecificationException if the versions can't be parsed to a range
*/
public static boolean isVersionOverlap( String leftVersionOrRange, String rightVersionOrRange )
throws InvalidVersionSpecificationException
{
VersionRange pomVersionRange = createVersionRange( leftVersionOrRange );
if ( !pomVersionRange.hasRestrictions() )
{
return true;
}
VersionRange oldVersionRange = createVersionRange( rightVersionOrRange );
if ( !oldVersionRange.hasRestrictions() )
{
return true;
}
VersionRange result = oldVersionRange.restrict( pomVersionRange );
return result.hasRestrictions();
}
private static VersionRange createVersionRange( String versionOrRange )
throws InvalidVersionSpecificationException
{
VersionRange versionRange = VersionRange.createFromVersionSpec( versionOrRange );
if ( versionRange.getRecommendedVersion() != null )
{
versionRange = VersionRange.createFromVersionSpec( "[" + versionOrRange + "]" );
}
return versionRange;
}
/**
* Searches the pom re-defining the specified plugin to the specified version.
*
* @param pom The pom to modify.
* @param groupId The groupId of the dependency.
* @param artifactId The artifactId of the dependency.
* @param oldVersion The old version of the dependency.
* @param newVersion The new version of the dependency.
* @return <code>true</code> if a replacement was made.
* @throws XMLStreamException if somethinh went wrong.
*/
public static boolean setPluginVersion( final ModifiedPomXMLEventReader pom, final String groupId,
final String artifactId, final String oldVersion, final String newVersion )
throws XMLStreamException
{
Stack<String> stack = new Stack<>();
String path = "";
final Pattern matchScopeRegex;
final Pattern matchTargetRegex;
boolean inMatchScope = false;
boolean madeReplacement = false;
boolean haveGroupId = false;
boolean needGroupId = groupId != null && !APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId );
boolean haveArtifactId = false;
boolean haveOldVersion = false;
matchScopeRegex = Pattern.compile( "/project" + "(/profiles/profile)?"
+ "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin" );
matchTargetRegex = Pattern.compile( "/project" + "(/profiles/profile)?"
+ "((/build(/pluginManagement)?)|(/reporting))/plugins/plugin"
+ "((/groupId)|(/artifactId)|(/version))" );
pom.rewind();
while ( pom.hasNext() )
{
XMLEvent event = pom.nextEvent();
if ( event.isStartElement() )
{
stack.push( path );
final String elementName = event.asStartElement().getName().getLocalPart();
path = path + "/" + elementName;
if ( matchScopeRegex.matcher( path ).matches() )
{
// we're in a new match scope
// reset any previous partial matches
inMatchScope = true;
pom.clearMark( 0 );
pom.clearMark( 1 );
haveGroupId = false;
haveArtifactId = false;
haveOldVersion = false;
}
else if ( inMatchScope && matchTargetRegex.matcher( path ).matches() )
{
if ( "groupId".equals( elementName ) )
{
haveGroupId = pom.getElementText().trim().equals( groupId );
path = stack.pop();
}
else if ( "artifactId".equals( elementName ) )
{
haveArtifactId = artifactId.equals( pom.getElementText().trim() );
path = stack.pop();
}
else if ( "version".equals( elementName ) )
{
pom.mark( 0 );
}
}
}
if ( event.isEndElement() )
{
if ( matchTargetRegex.matcher( path ).matches()
&& "version".equals( event.asEndElement().getName().getLocalPart() ) )
{
pom.mark( 1 );
try
{
haveOldVersion = isVersionOverlap( oldVersion, pom.getBetween( 0, 1 ).trim() );
}
catch ( InvalidVersionSpecificationException e )
{
// fall back to string comparison
haveOldVersion = oldVersion.equals( pom.getBetween( 0, 1 ).trim() );
}
}
else if ( matchScopeRegex.matcher( path ).matches() )
{
if ( inMatchScope && pom.hasMark( 0 ) && pom.hasMark( 1 ) && ( haveGroupId || !needGroupId )
&& haveArtifactId && haveOldVersion )
{
pom.replaceBetween( 0, 1, newVersion );
madeReplacement = true;
pom.clearMark( 0 );
pom.clearMark( 1 );
haveArtifactId = false;
haveGroupId = false;
haveOldVersion = false;
}
inMatchScope = false;
}
path = stack.pop();
}
}
return madeReplacement;
}
/**
* Traverses the project tree upwards, adding the raw models of every project it encounters to the map
*
* @param project maven project of the child for which the models need to be gathered
* @return gathered map of raw models per project
*/
private static Map<MavenProject, Model> getRawModelWithParents( MavenProject project ) throws IOException
{
// constructs a tree sorted from children to parents
Map<MavenProject, Model> models = new TreeMap<>( ( p1, p2 ) ->
{
for ( MavenProject p = p1; p != null; p = p.getParent() )
{
if ( p == p2 ) // meaning p2 is an ancestor to p1 or p1 == p2
{
return p == p1
? 0
: -1; // p1 is the child
}
}
return 1;
} );
for ( MavenProject p = project; p != null; p = p.getParent() )
{
models.put( p, p.getFile() != null
? getRawModel( p )
: p.getOriginalModel() );
}
return models;
}
/**
* Examines the project to find any properties which are associated with versions of artifacts in the project.
*
* @param helper Our versions helper.
* @param project The project to examine.
* @param includeParent whether parent POMs should be included
* @return An array of properties that are associated within the project.
* @throws ExpressionEvaluationException if an expression cannot be evaluated.
* @throws IOException if the project's pom file cannot be parsed.
* @since 1.0-alpha-3
*/
public static PropertyVersionsBuilder[] getPropertyVersionsBuilders( VersionsHelper helper, MavenProject project,
boolean includeParent )
throws ExpressionEvaluationException, IOException
{
ExpressionEvaluator expressionEvaluator = helper.getExpressionEvaluator( project );
Map<MavenProject, Model> reactorModels = includeParent
? getRawModelWithParents( project )
: singletonMap( project, getRawModel( project ) );
Map<String, PropertyVersionsBuilder> propertiesMap = new TreeMap<>();
Set<String> activeProfiles = new TreeSet<>();
for ( Profile profile : project.getActiveProfiles() )
{
activeProfiles.add( profile.getId() );
}
// add any properties from profiles first (as they override properties from the project
for ( Iterator<Profile> it = reactorModels.values().stream()
.flatMap( model -> model.getProfiles().stream() )
.filter( profile -> activeProfiles.contains( profile.getId() ) )
.iterator(); it.hasNext(); )
{
Profile profile = it.next();
try
{
addProperties( helper, propertiesMap, profile.getId(), profile.getProperties() );
if ( profile.getDependencyManagement() != null )
{
addDependencyAssocations( helper, expressionEvaluator, propertiesMap,
profile.getDependencyManagement().getDependencies(), false );