-
Notifications
You must be signed in to change notification settings - Fork 951
/
IvyDependencyManager.groovy
1136 lines (998 loc) · 45.7 KB
/
IvyDependencyManager.groovy
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
/* Copyright 2004-2005 the original author or authors.
*
* Licensed 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.
*/
package org.codehaus.groovy.grails.resolve
import org.apache.ivy.core.event.EventManager
import org.apache.ivy.core.module.descriptor.Configuration
import org.apache.ivy.core.module.descriptor.DefaultModuleDescriptor
import org.apache.ivy.core.module.descriptor.DependencyDescriptor
import org.apache.ivy.core.module.id.ModuleRevisionId
import org.apache.ivy.core.report.ResolveReport
import org.apache.ivy.core.resolve.IvyNode
import org.apache.ivy.core.resolve.ResolveEngine
import org.apache.ivy.core.resolve.ResolveOptions
import org.apache.ivy.core.settings.IvySettings
import org.apache.ivy.core.sort.SortEngine
import org.apache.ivy.plugins.resolver.ChainResolver
import org.apache.ivy.plugins.resolver.FileSystemResolver
import org.apache.ivy.plugins.resolver.IBiblioResolver
import org.apache.ivy.util.DefaultMessageLogger
import org.apache.ivy.util.Message
import grails.util.BuildSettings
import org.apache.ivy.core.module.descriptor.ExcludeRule
import grails.util.GrailsNameUtils
import org.apache.ivy.plugins.parser.m2.PomReader
import org.apache.ivy.plugins.repository.file.FileResource
import org.apache.ivy.plugins.repository.file.FileRepository
import org.apache.ivy.plugins.parser.m2.PomDependencyMgt
import org.apache.ivy.core.module.id.ModuleId
import org.apache.ivy.core.report.ArtifactDownloadReport
import org.apache.ivy.util.url.CredentialsStore
import org.apache.ivy.core.module.descriptor.ModuleDescriptor
import org.apache.ivy.core.module.descriptor.DefaultDependencyArtifactDescriptor
import grails.util.Metadata
import org.apache.ivy.plugins.latest.LatestTimeStrategy
import org.apache.ivy.util.MessageLogger
import org.apache.ivy.core.module.descriptor.Artifact
import org.apache.ivy.core.report.ConfigurationResolveReport
import org.apache.ivy.core.report.DownloadReport
import org.apache.ivy.core.report.DownloadStatus
import org.apache.ivy.plugins.matcher.PatternMatcher
import org.apache.ivy.plugins.matcher.ExactPatternMatcher
import org.apache.ivy.core.module.descriptor.DefaultExcludeRule
import org.apache.ivy.core.module.id.ArtifactId
import org.apache.ivy.core.module.descriptor.DefaultDependencyDescriptor
import org.apache.ivy.plugins.repository.TransferListener
import java.util.concurrent.ConcurrentLinkedQueue
import org.apache.ivy.plugins.resolver.RepositoryResolver
/**
* Implementation that uses Apache Ivy under the hood.
*
* @author Graeme Rocher
* @since 1.2
*/
class IvyDependencyManager extends AbstractIvyDependencyManager implements DependencyResolver, DependencyDefinitionParser{
private hasApplicationDependencies = false
ResolveEngine resolveEngine
BuildSettings buildSettings
IvySettings ivySettings
MessageLogger logger
Metadata metadata
ChainResolver chainResolver = new ChainResolver(name:"default",returnFirst:true)
DefaultModuleDescriptor moduleDescriptor
DefaultDependencyDescriptor currentDependencyDescriptor
Collection repositoryData = new ConcurrentLinkedQueue()
Collection<String> configuredPlugins = new ConcurrentLinkedQueue()
Collection<String> usedConfigurations = new ConcurrentLinkedQueue()
Collection moduleExcludes = new ConcurrentLinkedQueue()
TransferListener transferListener
boolean readPom = false
boolean inheritsAll = false
boolean resolveErrors = false
boolean defaultDependenciesProvided = false
/**
* Creates a new IvyDependencyManager instance
*/
IvyDependencyManager(String applicationName, String applicationVersion, BuildSettings settings=null, Metadata metadata = null) {
ivySettings = new IvySettings()
ivySettings.defaultInit()
// don't cache for snapshots
if (settings?.grailsVersion?.endsWith("SNAPSHOT")) {
ivySettings.setDefaultUseOrigin(true)
}
ivySettings.validate = false
chainResolver.settings = ivySettings
def eventManager = new EventManager()
def sortEngine = new SortEngine(ivySettings)
resolveEngine = new ResolveEngine(ivySettings,eventManager,sortEngine)
resolveEngine.dictatorResolver = chainResolver
this.applicationName = applicationName
this.applicationVersion = applicationVersion
this.buildSettings = settings
this.metadata = metadata
}
/**
* Allows settings an alternative chain resolver to be used
* @param resolver The resolver to be used
*/
void setChainResolver(ChainResolver resolver) {
this.chainResolver = resolver
resolveEngine.dictatorResolver = chainResolver
}
/**
* Sets the default message logger used by Ivy
*
* @param logger
*/
void setLogger(MessageLogger logger) {
Message.setDefaultLogger logger
this.logger = logger
}
MessageLogger getLogger() { this.logger }
/**
* @return The current chain resolver
*/
ChainResolver getChainResolver() { chainResolver }
/**
* Resets the Grails plugin resolver if it is used
*/
void resetGrailsPluginsResolver() {
def resolver = chainResolver.resolvers.find { it.name == 'grailsPlugins' }
chainResolver.resolvers.remove(resolver)
chainResolver.resolvers.add(new GrailsPluginsDirectoryResolver(buildSettings, ivySettings))
}
/**
* Returns true if the application has any dependencies that are not inherited
* from the framework or other plugins
*/
boolean hasApplicationDependencies() { this.hasApplicationDependencies }
/**
* Serializes the parsed dependencies using the given builder.
*
* @param builder A builder such as groovy.xml.MarkupBuilder
*/
void serialize(builder, boolean createRoot = true) {
if (createRoot) {
builder.dependencies {
serializeResolvers(builder)
serializeDependencies(builder)
}
}
else {
serializeResolvers(builder)
serializeDependencies(builder)
}
}
private serializeResolvers(builder) {
builder.resolvers {
for (resolverData in repositoryData) {
if (resolverData.name=='grailsHome') continue
builder.resolver resolverData
}
}
}
private serializeDependencies(builder) {
for (EnhancedDefaultDependencyDescriptor dd in dependencyDescriptors) {
// dependencies inherited by Grails' global config are not included
if (dd.inherited) continue
def mrid = dd.dependencyRevisionId
builder.dependency( group: mrid.organisation, name: mrid.name, version: mrid.revision, conf: dd.scope, transitive: dd.transitive) {
for (ExcludeRule er in dd.allExcludeRules) {
def mid = er.id.moduleId
excludes group:mid.organisation,name:mid.name
}
}
}
}
/**
* Obtains the default dependency definitions for the given Grails version
*/
static Closure getDefaultDependencies(String grailsVersion) {
return {
// log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
log "warn"
repositories {
grailsPlugins()
grailsHome()
// uncomment the below to enable remote dependency resolution
// from public Maven repositories
//mavenCentral()
//mavenLocal()
//mavenRepo "http://snapshots.repository.codehaus.org"
//mavenRepo "http://repository.codehaus.org"
//mavenRepo "http://download.java.net/maven/2/"
//mavenRepo "http://repository.jboss.com/maven2/
}
dependencies {
def compileTimeDependenciesMethod = defaultDependenciesProvided ? 'provided' : 'compile'
def runtimeDependenciesMethod = defaultDependenciesProvided ? 'provided' : 'runtime'
// dependencies needed by the Grails build system
build "org.codehaus.gpars:gpars:0.9",
"org.tmatesoft.svnkit:svnkit:1.3.1",
"org.apache.ant:ant:1.7.1",
"org.apache.ant:ant-launcher:1.7.1",
"org.apache.ant:ant-junit:1.7.1",
"org.apache.ant:ant-nodeps:1.7.1",
"org.apache.ant:ant-trax:1.7.1",
"jline:jline:0.9.94",
"org.fusesource.jansi:jansi:1.2.1",
"xalan:serializer:2.7.1",
"org.grails:grails-docs:$grailsVersion",
"org.grails:grails-bootstrap:$grailsVersion",
"org.grails:grails-scripts:$grailsVersion",
"org.grails:grails-core:$grailsVersion",
"org.grails:grails-resources:$grailsVersion",
"org.grails:grails-web:$grailsVersion",
"org.slf4j:slf4j-api:1.5.8",
"org.slf4j:slf4j-log4j12:1.5.8",
"org.springframework:org.springframework.test:3.0.3.RELEASE"
docs "org.xhtmlrenderer:core-renderer:R8",
"com.lowagie:itext:2.0.8",
"radeox:radeox:1.0-b2"
// dependencies needed during development, but not for deployment
provided "javax.servlet:servlet-api:2.5",
"javax.servlet:jsp-api:2.1"
// dependencies needed for compilation
"${compileTimeDependenciesMethod}"("org.codehaus.groovy:groovy-all:1.7.4") {
excludes 'jline'
}
"${compileTimeDependenciesMethod}"("commons-beanutils:commons-beanutils:1.8.0", "commons-el:commons-el:1.0", "commons-validator:commons-validator:1.3.1") {
excludes "commons-logging", "xml-apis"
}
"${compileTimeDependenciesMethod}"("aopalliance:aopalliance:1.0",
"commons-codec:commons-codec:1.3",
"commons-collections:commons-collections:3.2.1",
"commons-io:commons-io:1.4",
"commons-lang:commons-lang:2.4",
"javax.transaction:jta:1.1",
"org.hibernate:ejb3-persistence:1.0.2.GA",
"opensymphony:sitemesh:2.4",
"org.grails:grails-bootstrap:$grailsVersion",
"org.grails:grails-core:$grailsVersion",
"org.grails:grails-crud:$grailsVersion",
"org.grails:grails-gorm:$grailsVersion",
"org.grails:grails-resources:$grailsVersion",
"org.grails:grails-spring:$grailsVersion",
"org.grails:grails-web:$grailsVersion",
"org.springframework:org.springframework.core:3.0.3.RELEASE",
"org.springframework:org.springframework.aop:3.0.3.RELEASE",
"org.springframework:org.springframework.aspects:3.0.3.RELEASE",
"org.springframework:org.springframework.asm:3.0.3.RELEASE",
"org.springframework:org.springframework.beans:3.0.3.RELEASE",
"org.springframework:org.springframework.context:3.0.3.RELEASE",
"org.springframework:org.springframework.context.support:3.0.3.RELEASE",
"org.springframework:org.springframework.expression:3.0.3.RELEASE",
"org.springframework:org.springframework.instrument:3.0.3.RELEASE",
"org.springframework:org.springframework.jdbc:3.0.3.RELEASE",
"org.springframework:org.springframework.jms:3.0.3.RELEASE",
"org.springframework:org.springframework.orm:3.0.3.RELEASE",
"org.springframework:org.springframework.oxm:3.0.3.RELEASE",
"org.springframework:org.springframework.transaction:3.0.3.RELEASE",
"org.springframework:org.springframework.web:3.0.3.RELEASE",
"org.springframework:org.springframework.web.servlet:3.0.3.RELEASE",
"org.slf4j:slf4j-api:1.5.8") {
transitive = false
}
// dependencies needed for running tests
test "junit:junit:4.8.1",
"org.grails:grails-test:$grailsVersion",
"org.springframework:org.springframework.test:3.0.3.RELEASE"
// dependencies needed at runtime only
"${runtimeDependenciesMethod}" "org.aspectj:aspectjweaver:1.6.8",
"org.aspectj:aspectjrt:1.6.8",
"cglib:cglib-nodep:2.1_3",
"commons-fileupload:commons-fileupload:1.2.1",
"oro:oro:2.0.8",
"javax.servlet:jstl:1.1.2"
// data source
"${runtimeDependenciesMethod}" "commons-dbcp:commons-dbcp:1.2.2",
"commons-pool:commons-pool:1.5.3",
"hsqldb:hsqldb:1.8.0.10"
// caching
"${runtimeDependenciesMethod}" ("net.sf.ehcache:ehcache-core:1.7.1") {
excludes 'jms', 'commons-logging', 'servlet-api'
}
// logging
"${runtimeDependenciesMethod}"("log4j:log4j:1.2.16",
"org.slf4j:jcl-over-slf4j:1.5.8",
"org.slf4j:jul-to-slf4j:1.5.8",
"org.slf4j:slf4j-log4j12:1.5.8" ) {
excludes 'mail', 'jms', 'jmxtools', 'jmxri'
}
// JSP support
"${runtimeDependenciesMethod}" "apache-taglibs:standard:1.1.2",
"xpp3:xpp3_min:1.1.3.4.O"
}
}
}
/**
* Returns all of the dependency descriptors for dependencies of the application and not
* those inherited from frameworks or plugins
*/
Set<DependencyDescriptor> getApplicationDependencyDescriptors(String scope = null) {
dependencyDescriptors.findAll { EnhancedDefaultDependencyDescriptor dd ->
!dd.inherited && (!scope || dd.scope == scope)
}
}
/**
* Returns all the dependency descriptors for dependencies of a plugin that have been exported for use in the application
*/
Set<DependencyDescriptor> getExportedDependencyDescriptors(String scope = null) {
getApplicationDependencyDescriptors(scope).findAll { it.exported }
}
boolean isExcluded(String name) {
def aid = createExcludeArtifactId(name)
return moduleDescriptor.doesExclude(configurationNames, aid)
}
/**
* For usages such as addPluginDependency("foo", [group:"junit", name:"junit", version:"4.8.1"])
*
* This method is designed to be used by the internal framework and plugins and not be end users.
* The idea is that plugins can provide dependencies at runtime which are then inherited by
* the user's dependency configuration
*
* A user can however override a plugin's dependencies inside the dependency resolution DSL
*/
void addPluginDependency(String pluginName, Map args) {
// do nothing if the dependencies of the plugin are configured by the application
if (isPluginConfiguredByApplication(pluginName)) return
if (args?.group && args?.name && args?.version) {
def transitive = getBooleanValue(args, 'transitive')
def exported = getBooleanValue(args, 'export')
def scope = args.conf ?: 'runtime'
def mrid = ModuleRevisionId.newInstance(args.group, args.name, args.version)
def dd = new EnhancedDefaultDependencyDescriptor(mrid, true, transitive, scope)
dd.exported = exported
dd.inherited = true
dd.plugin = pluginName
configureDependencyDescriptor(dd, scope)
if (args.excludes) {
for (ex in excludes) {
dd.exclude(ex)
}
}
addDependencyDescriptor dd
}
}
boolean isPluginConfiguredByApplication(String name) {
(configuredPlugins.contains(name) || configuredPlugins.contains(GrailsNameUtils.getPropertyNameForLowerCaseHyphenSeparatedName(name)))
}
def configureDependencyDescriptor(EnhancedDefaultDependencyDescriptor dependencyDescriptor, String scope, Closure dependencyConfigurer=null, boolean pluginMode = false) {
if (!usedConfigurations.contains(scope)) {
usedConfigurations << scope
}
try {
this.currentDependencyDescriptor = dependencyDescriptor
if (dependencyConfigurer) {
dependencyConfigurer.resolveStrategy = Closure.DELEGATE_ONLY
dependencyConfigurer.setDelegate(dependencyDescriptor)
dependencyConfigurer.call()
}
}
finally {
this.currentDependencyDescriptor = null
}
if (dependencyDescriptor.getModuleConfigurations().length == 0){
def mappings = configurationMappings[scope]
if(mappings) {
for(m in mappings) {
dependencyDescriptor.addDependencyConfiguration scope, m
}
}
}
if (!dependencyDescriptor.inherited) {
hasApplicationDependencies = true
}
if (pluginMode) {
def name = dependencyDescriptor.dependencyId.name
pluginDependencyNames << name
pluginDependencyDescriptors << dependencyDescriptor
pluginNameToDescriptorMap[name] = dependencyDescriptor
}
else {
dependencyDescriptors << dependencyDescriptor
if (dependencyDescriptor.isExportedToApplication())
moduleDescriptor.addDependency dependencyDescriptor
}
}
Set<ModuleRevisionId> getModuleRevisionIds(String org) { orgToDepMap[org] }
/**
* Lists all known dependencies for the given configuration name (defaults to all dependencies)
*/
IvyNode[] listDependencies(String conf = null) {
def options = new ResolveOptions()
if (conf) {
options.confs = [conf] as String[]
}
resolveEngine.getDependencies(moduleDescriptor, options, new ResolveReport(moduleDescriptor))
}
ResolveReport resolveDependencies(Configuration conf) {
resolveDependencies(conf.name)
}
/**
* Performs a resolve of all dependencies for the given configuration,
* potentially going out to the internet to download jars if they are not found locally
*/
ResolveReport resolveDependencies(String conf) {
resolveErrors = false
if (usedConfigurations.contains(conf) || conf == '') {
def options = new ResolveOptions(checkIfChanged:false, outputReport:true, validate:false)
if (conf) {
options.confs = [conf] as String[]
}
ResolveReport resolve = resolveEngine.resolve(moduleDescriptor, options)
resolveErrors = resolve.hasError()
return resolve
}
// return an empty resolve report
return new ResolveReport(moduleDescriptor)
}
/**
* Similar to resolveDependencies, but will load the resolved dependencies into the
* application RootLoader if it exists
*
* @return The ResolveReport
* @throws IllegalStateException If no RootLoader exists
*/
ResolveReport loadDependencies(String conf = '') {
URLClassLoader rootLoader = getClass().classLoader.rootLoader
if (rootLoader) {
def urls = rootLoader.URLs.toList()
ResolveReport report = resolveDependencies(conf)
for (ArtifactDownloadReport downloadReport in report.allArtifactsReports) {
def url = downloadReport.localFile.toURL()
if (!urls.contains(url)) {
rootLoader.addURL(url)
}
}
}
else {
throw new IllegalStateException("No root loader found. Could not load dependencies. Note this method cannot be called when running in a WAR.")
}
}
/**
* Resolves only application dependencies and returns a list of the resolves JAR files
*/
List<ArtifactDownloadReport> resolveApplicationDependencies(String conf = '') {
ResolveReport report = resolveDependencies(conf)
def descriptors = getApplicationDependencyDescriptors(conf)
report.allArtifactsReports.findAll { ArtifactDownloadReport downloadReport ->
def mrid = downloadReport.artifact.moduleRevisionId
descriptors.any { DependencyDescriptor dd -> mrid == dd.dependencyRevisionId}
}
}
/**
* Resolves only plugin dependencies that should be exported to the application
*/
List<ArtifactDownloadReport> resolveExportedDependencies(String conf='') {
def descriptors = getExportedDependencyDescriptors(conf)
resolveApplicationDependencies(conf)?.findAll { ArtifactDownloadReport downloadReport ->
def mrid = downloadReport.artifact.moduleRevisionId
descriptors.any { DependencyDescriptor dd -> mrid == dd.dependencyRevisionId}
}
}
/**
* Performs a resolve of all dependencies, potentially going out to the internet to download jars
* if they are not found locally
*/
ResolveReport resolveDependencies() {
resolveDependencies('')
}
/**
* Performs a resolve of declared plugin dependencies (zip files containing plugin distributions)
*/
ResolveReport resolvePluginDependencies(String conf = '', Map args = [:]) {
resolveErrors = false
if (usedConfigurations.contains(conf) || conf == '') {
if (args.checkIfChanged == null) args.checkIfChanged = true
if (args.outputReport == null) args.outputReport = true
if (args.validate == null) args.validate = false
def options = new ResolveOptions(args)
if (conf) {
options.confs = [conf] as String[]
}
def md = createModuleDescriptor()
for (dd in pluginDependencyDescriptors) {
md.addDependency dd
}
if (!options.download) {
def date = new Date()
def report = new ResolveReport(md)
def ivyNodes = resolveEngine.getDependencies(md, options, report)
for (IvyNode node in ivyNodes) {
if (node.isLoaded()) {
for (Artifact a in node.allArtifacts) {
def origin = resolveEngine.locate(a)
def cr = new ConfigurationResolveReport(resolveEngine, md, conf, date, options)
def dr = new DownloadReport()
def adr = new ArtifactDownloadReport(a)
adr.artifactOrigin = origin
adr.downloadStatus = DownloadStatus.NO
dr.addArtifactReport(adr)
cr.addDependency(node, dr)
report.addReport(conf, cr)
}
}
}
return report
}
ResolveReport resolve = resolveEngine.resolve(md, options)
resolveErrors = resolve.hasError()
return resolve
}
// return an empty resolve report
return new ResolveReport(createModuleDescriptor())
}
/**
* Tests whether the given ModuleId is defined in the list of dependencies
*/
boolean hasDependency(ModuleId mid) {
return modules.contains(mid)
}
/**
* Tests whether the given group and name are defined in the list of dependencies
*/
boolean hasDependency(String group, String name) {
return hasDependency(ModuleId.newInstance(group, name))
}
/**
* Parses the Ivy DSL definition
*/
void parseDependencies(Closure definition) {
if (definition && applicationName && applicationVersion) {
if (this.moduleDescriptor == null) {
this.moduleDescriptor = createModuleDescriptor()
}
def evaluator = new IvyDomainSpecificLanguageEvaluator(this)
definition.delegate = evaluator
definition.resolveStrategy = Closure.DELEGATE_FIRST
definition()
evaluator = null
if (readPom && buildSettings) {
List dependencies = readDependenciesFromPOM()
if (dependencies != null) {
for (PomDependencyMgt dep in dependencies) {
final String scope = dep.scope ?: 'runtime'
Message.debug("Read dependency [$dep.groupId:$dep.artifactId:$dep.version] (scope $scope) from Maven pom.xml")
def mrid = ModuleRevisionId.newInstance(dep.groupId, dep.artifactId, dep.version)
def mid = mrid.getModuleId()
if (!hasDependency(mid)) {
def dd = new EnhancedDefaultDependencyDescriptor(mrid, false, true, scope)
for (ModuleId ex in dep.excludedModules) {
dd.addRuleForModuleId(ex, scope)
}
configureDependencyDescriptor(dd, scope)
addDependencyDescriptor dd
}
}
}
}
def installedPlugins = metadata?.getInstalledPlugins()
if (installedPlugins) {
for (entry in installedPlugins) {
if (!pluginDependencyNames.contains(entry.key)) {
def name = entry.key
def scope = "runtime"
def mrid = ModuleRevisionId.newInstance("org.grails.plugins", name, entry.value)
def dd = new EnhancedDefaultDependencyDescriptor(mrid, true, true, scope)
def artifact = new DefaultDependencyArtifactDescriptor(dd, name, "zip", "zip", null, null )
dd.addDependencyArtifact(scope, artifact)
metadataRegisteredPluginNames << name
configureDependencyDescriptor(dd, scope, null, true)
pluginDependencyDescriptors << dd
}
}
}
}
}
List readDependenciesFromPOM() {
def dependencies = null
def pom = new File("${buildSettings.baseDir.path}/pom.xml")
if (pom.exists()) {
def reader = new PomReader(pom.toURL(), new FileResource(new FileRepository(), pom))
dependencies = reader.getDependencies()
}
return dependencies
}
/**
* Parses dependencies of a plugin
*
* @param pluginName the name of the plugin
* @param definition the Ivy DSL definition
*/
void parseDependencies(String pluginName,Closure definition) {
if (definition) {
if (moduleDescriptor == null) {
throw new IllegalStateException("Call parseDependencies(Closure) first to parse the application dependencies")
}
def evaluator = new IvyDomainSpecificLanguageEvaluator(this)
evaluator.currentPluginBeingConfigured = pluginName
definition.delegate = evaluator
definition.resolveStrategy = Closure.DELEGATE_FIRST
definition()
}
}
boolean getBooleanValue(dependency, String name) {
return dependency.containsKey(name) ? Boolean.valueOf(dependency[name]) : true
}
}
class IvyDomainSpecificLanguageEvaluator {
static final String WILDCARD = '*'
boolean inherited = false
boolean pluginMode = false
String currentPluginBeingConfigured = null
@Delegate IvyDependencyManager delegate
IvyDomainSpecificLanguageEvaluator(IvyDependencyManager delegate) {
this.delegate = delegate
}
void useOrigin(boolean b) {
ivySettings.setDefaultUseOrigin(b)
}
void credentials(Closure c) {
def creds = [:]
c.delegate = creds
c.resolveStrategy = Closure.DELEGATE_FIRST
c.call()
if (creds) {
CredentialsStore.INSTANCE.addCredentials(creds.realm ?: null, creds.host ?: 'localhost', creds.username ?: '', creds.password ?: '')
}
}
void pom(boolean b) {
delegate.readPom = b
}
void excludes(Map exclude) {
def anyExpression = PatternMatcher.ANY_EXPRESSION
def mid = ModuleId.newInstance(exclude.group ?: anyExpression, exclude.name.toString())
def aid = new ArtifactId(mid, anyExpression, anyExpression, anyExpression)
def excludeRule = new DefaultExcludeRule(aid, ExactPatternMatcher.INSTANCE, null)
for (String conf in configurationNames) {
excludeRule.addConfiguration conf
}
if (currentDependencyDescriptor == null) {
moduleDescriptor.addExcludeRule(excludeRule)
}
else {
for (String conf in configurationNames) {
currentDependencyDescriptor.addExcludeRule(conf, excludeRule)
}
}
}
void excludes(String... excludeList) {
for (exclude in excludeList) {
excludes name:exclude
}
}
void defaultDependenciesProvided(boolean b) {
delegate.defaultDependenciesProvided = b
}
void inherits(String name, Closure configurer) {
// plugins can't configure inheritance
if (currentPluginBeingConfigured) return
configurer?.delegate = this
configurer?.call()
def config = buildSettings?.config?.grails
if (config) {
def dependencies = config[name]?.dependency?.resolution
if (dependencies instanceof Closure) {
try {
inherited = true
dependencies.delegate = this
dependencies.call()
moduleExcludes.clear()
}
finally {
inherited = false
}
}
}
}
void inherits(String name) {
inherits name, null
}
void plugins(Closure callable) {
try {
pluginMode = true
callable.call()
}
finally {
pluginMode = false
}
}
void plugin(String name, Closure callable) {
configuredPlugins << name
try {
currentPluginBeingConfigured = name
callable?.delegate = this
callable?.call()
}
finally {
currentPluginBeingConfigured = null
}
}
void log(String level) {
// plugins can't configure log
if (currentPluginBeingConfigured) return
switch(level) {
case "warn": setLogger(new DefaultMessageLogger(Message.MSG_WARN)); break
case "error": setLogger(new DefaultMessageLogger(Message.MSG_ERR)); break
case "info": setLogger(new DefaultMessageLogger(Message.MSG_INFO)); break
case "debug": setLogger(new DefaultMessageLogger(Message.MSG_DEBUG)); break
case "verbose": setLogger(new DefaultMessageLogger(Message.MSG_VERBOSE)); break
default: setLogger(new DefaultMessageLogger(Message.MSG_WARN))
}
Message.setDefaultLogger logger
}
/**
* Defines dependency resolvers
*/
void resolvers(Closure resolvers) {
repositories resolvers
}
/**
* Same as #resolvers(Closure)
*/
void repositories(Closure repos) {
repos?.delegate = this
repos?.call()
}
void flatDir(Map args) {
def name = args.name?.toString()
if (name && args.dirs) {
def fileSystemResolver = new FileSystemResolver()
fileSystemResolver.local = true
fileSystemResolver.name = name
def dirs = args.dirs instanceof Collection ? args.dirs : [args.dirs]
repositoryData << ['type':'flatDir', name:name, dirs:dirs.join(',')]
dirs.each { dir ->
def path = new File(dir?.toString()).absolutePath
fileSystemResolver.addIvyPattern( "${path}/[module]-[revision](-[classifier]).xml")
fileSystemResolver.addArtifactPattern "${path}/[module]-[revision](-[classifier]).[ext]"
}
fileSystemResolver.settings = ivySettings
addToChainResolver(fileSystemResolver)
}
}
private addToChainResolver(org.apache.ivy.plugins.resolver.DependencyResolver resolver) {
if (transferListener !=null && (resolver instanceof RepositoryResolver)) {
((RepositoryResolver)resolver).repository.addTransferListener transferListener
}
// Fix for GRAILS-5805
synchronized(chainResolver.resolvers) {
chainResolver.add resolver
}
}
void grailsPlugins() {
if (isResolverNotAlreadyDefined('grailsPlugins')) {
repositoryData << [type: 'grailsPlugins', name:"grailsPlugins"]
if (buildSettings != null) {
def pluginResolver = new GrailsPluginsDirectoryResolver(buildSettings, ivySettings)
addToChainResolver(pluginResolver)
}
}
}
void grailsHome() {
if (!isResolverNotAlreadyDefined('grailsHome')) {
return
}
def grailsHome = buildSettings?.grailsHome?.absolutePath ?: System.getenv("GRAILS_HOME")
if (!grailsHome) {
return
}
flatDir(name:"grailsHome", dirs:"${grailsHome}/lib")
flatDir(name:"grailsHome", dirs:"${grailsHome}/dist")
if (grailsHome!='.') {
def resolver = createLocalPluginResolver("grailsHome", grailsHome)
addToChainResolver(resolver)
}
}
FileSystemResolver createLocalPluginResolver(String name, String location) {
def pluginResolver = new FileSystemResolver(name: name)
pluginResolver.addArtifactPattern("${location}/plugins/grails-[artifact]-[revision].[ext]")
pluginResolver.settings = ivySettings
pluginResolver.latestStrategy = new LatestTimeStrategy()
pluginResolver.changingPattern = ".*SNAPSHOT"
pluginResolver.setCheckmodified(true)
return pluginResolver
}
private boolean isResolverNotAlreadyDefined(String name) {
def resolver
// Fix for GRAILS-5805
synchronized(chainResolver.resolvers) {
resolver = chainResolver.resolvers.any { it.name == name }
}
if (resolver) {
Message.debug("Dependency resolver $name already defined. Ignoring...")
return false
}
return true
}
void mavenRepo(String url) {
if (isResolverNotAlreadyDefined(url)) {
repositoryData << ['type':'mavenRepo', root:url, name:url, m2compatbile:true]
def resolver = new IBiblioResolver(name: url, root: url, m2compatible: true, settings: ivySettings, changingPattern: ".*SNAPSHOT")
addToChainResolver(resolver)
}
}
void mavenRepo(Map args) {
if (args && args.name) {
if (isResolverNotAlreadyDefined(args.name)) {
repositoryData << ( ['type':'mavenRepo'] + args )
args.settings = ivySettings
def resolver = new IBiblioResolver(args)
addToChainResolver(resolver)
}
}
else {
Message.warn("A mavenRepo specified doesn't have a name argument. Please specify one!")
}
}
void resolver(org.apache.ivy.plugins.resolver.DependencyResolver resolver) {
if (resolver) {
resolver.setSettings(ivySettings)
addToChainResolver(resolver)
}
}
void ebr() {
if (isResolverNotAlreadyDefined('ebr')) {
repositoryData << ['type':'ebr']
IBiblioResolver ebrReleaseResolver = new IBiblioResolver(name:"ebrRelease",
root:"http://repository.springsource.com/maven/bundles/release",
m2compatible:true,
settings:ivySettings)
addToChainResolver(ebrReleaseResolver)
IBiblioResolver ebrExternalResolver = new IBiblioResolver(name:"ebrExternal",
root:"http://repository.springsource.com/maven/bundles/external",
m2compatible:true,
settings:ivySettings)
addToChainResolver(ebrExternalResolver)
}
}
/**
* Defines a repository that uses Grails plugin repository format. Grails repositories are
* SVN repositories that follow a particular convention that is not Maven compatible.
*
* Ivy is flexible enough to allow the configuration of a resolver that resolves artifacts
* against non-Maven repositories
*/
void grailsRepo(String url, String name=null) {
if (isResolverNotAlreadyDefined(name ?: url)) {
repositoryData << ['type':'grailsRepo', url:url]
def urlResolver = new GrailsRepoResolver(name ?: url, new URL(url) )
urlResolver.addArtifactPattern("${url}/grails-[artifact]/tags/RELEASE_*/grails-[artifact]-[revision].[ext]")
urlResolver.settings = ivySettings
urlResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy()
urlResolver.changingPattern = ".*"
urlResolver.setCheckmodified(true)
addToChainResolver(urlResolver)
}
}
void grailsCentral() {
if (isResolverNotAlreadyDefined('grailsCentral')) {
grailsRepo("http://svn.codehaus.org/grails-plugins", "grailsCentral")
grailsRepo("http://svn.codehaus.org/grails/trunk/grails-plugins", "grailsCore")
}
}
void mavenCentral() {
if (isResolverNotAlreadyDefined('mavenCentral')) {
repositoryData << ['type':'mavenCentral']
IBiblioResolver mavenResolver = new IBiblioResolver(name:"mavenCentral")
mavenResolver.m2compatible = true
mavenResolver.settings = ivySettings
mavenResolver.changingPattern = ".*SNAPSHOT"
addToChainResolver(mavenResolver)
}
}
void mavenLocal(String repoPath = "${System.getProperty('user.home')}/.m2/repository") {
if (isResolverNotAlreadyDefined('mavenLocal')) {
repositoryData << ['type':'mavenLocal']
FileSystemResolver localMavenResolver = new FileSystemResolver(name:'localMavenResolver')
localMavenResolver.local = true
localMavenResolver.m2compatible = true
localMavenResolver.changingPattern = ".*SNAPSHOT"
localMavenResolver.addIvyPattern(