/
ReleasePlugin.groovy
1063 lines (937 loc) · 39.7 KB
/
ReleasePlugin.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.
*/
import org.tmatesoft.svn.core.io.SVNRepositoryFactory
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl
import org.tmatesoft.svn.core.io.*
import org.tmatesoft.svn.core.*
import org.tmatesoft.svn.core.auth.*
import org.tmatesoft.svn.core.wc.*
import org.codehaus.groovy.grails.documentation.MetadataGeneratingMetaClassCreationHandle
import org.codehaus.groovy.grails.plugins.publishing.DefaultPluginPublisher
import org.springframework.core.io.FileSystemResource
import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory
import javax.xml.transform.TransformerFactory
import javax.xml.transform.OutputKeys
import javax.xml.transform.Transformer
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult
import org.codehaus.groovy.grails.plugins.PluginManagerHolder
/**
* Gant script that handles releasing plugins to a plugin repository.
*
* @author Graeme Rocher
*/
includeTargets << grailsScript("_GrailsPluginDev")
includeTargets << grailsScript("_GrailsBootstrap")
includeTargets << grailsScript("_GrailsDocs")
authManager = null
commitMessage = null
trunk = null
latestRelease = null
versionedRelease = null
skipLatest = false
CORE_PLUGIN_DIST = "http://svn.codehaus.org/grails/trunk/grails-plugins"
CORE_PUBLISH_URL = "https://svn.codehaus.org/grails/trunk/grails-plugins"
DEFAULT_PLUGIN_DIST = "http://plugins.grails.org"
DEFAULT_PUBLISH_URL = "https://svn.codehaus.org/grails-plugins"
// setup default plugin respositories for discovery
pluginDiscoveryRepositories = [core:CORE_PLUGIN_DIST, default:DEFAULT_PLUGIN_DIST]
if (grailsSettings?.config?.grails?.plugin?.repos?.discovery) {
pluginDiscoveryRepositories.putAll(grailsSettings?.config?.grails?.plugin?.repos?.discovery)
}
// setup default plugin respositories for publishing
pluginDistributionRepositories = [core:CORE_PUBLISH_URL, default:DEFAULT_PUBLISH_URL]
if (grailsSettings?.config?.grails?.plugin?.repos?.distribution) {
pluginDistributionRepositories.putAll(grailsSettings?.config?.grails?.plugin?.repos?.distribution)
}
KEY_URL = "url"
KEY_USER_NAME = "user"
KEY_USER_PASS = "pswd"
/**
* authentication manager Map
* EG : INIT CORE OR DEFAULT DISTRIBUTION REPOSITORY
* aMap = [url:CORE_PUBLISH_URL,user:"auser",pswd:"apswd"]
* ALLOWS ANT PROPERTIES DEFINITION
* aAuthManager = getAuthenticationManager("core", "distribution", aMap)
* authManagerMap.put("distribution.core", aAuthManager)
*/
authManagerMap = [:]
/**
* Break down url into separate authentication components from url
* @param url to be parsed
* @return broken down url in these parts (if exist) url, user and pswd
*/
public Map tokenizeUrl(String url) throws SVNException {
SVNURL aURL= SVNURL.parseURIDecoded(url)
def aHashMap = [:]
def userInfo = aURL.userInfo
if (userInfo) {
def userInfoArray = userInfo.split(":")
aHashMap[KEY_USER_NAME] = userInfoArray[0]
if (userInfoArray.length>1) {
aHashMap[KEY_USER_PASS] = userInfoArray[1]
}
}
if (aURL.port == 443) {
aHashMap[KEY_URL] = "${aURL.protocol}://${aURL.host}${aURL.path}".toString()
}
else {
aHashMap[KEY_URL] = "${aURL.protocol}://${aURL.host}:${aURL.port}${aURL.path}".toString()
}
return aHashMap
}
//init SVN Kit one time
// support file based SVN
FSRepositoryFactory.setup()
// support the server http/https
DAVRepositoryFactory.setup()
// support svn protocol
SVNRepositoryFactoryImpl.setup()
/**
* Replace the url with authentication by url without in discovery and distribution
* repository and setup authentication instance in authManagerMap.
* if an url like :
* {protocol}://{user:password}@url is defined the promt does not occur.
* Else the user is prompted for user and password values.
* The repos "core" and "default" are ignored (see above for default configuration)
* For all other repo, a defultAuthenticationManager is created.
*/
public Map configureAuth(Map repoMap,String repoType) {
repoMapTmp = [:]
repoMap.each {
ISVNAuthenticationManager aAuthManager = SVNWCUtil.createDefaultAuthenticationManager()
if ("core" == it.key || "default" == it.key) {
repoMapTmp[it.key] = it.value
if (!isSecureUrl(it.value)) {
authManagerMap[repoType+"."+it.key] = aAuthManager
}
// else no authentication manager provides to authManagerMap : case of CORE_PUBLISH_URL and DEFAULT_PUBLISH_URL
}
else {
if (isSecureUrl(it.value)) {
event "StatusUpdate", ["Authentication for svn repo at ${it.key} ${repoType} is required."]
aMap = tokenizeUrl(it.value)
repoMapTmp[it.key] = aMap[KEY_URL]
aAuthManager = getAuthenticationManager(it.key, repoType, aMap)
authManagerMap[repoType + "." + it.key] = aAuthManager
}
else {
repoMapTmp[it.key] = it.value
event "StatusUpdate", ["No authentication for svn repo at ${it.key}"]
authManagerMap[repoType + "." + it.key] = aAuthManager
}
}
}
return repoMapTmp
}
//configure authentication for discovery repository
pluginDiscoveryRepositories = configureAuth(pluginDiscoveryRepositories, "discovery")
//configure authentication for distribution repository
pluginDistributionRepositories = configureAuth(pluginDistributionRepositories, "distribution")
/**
* Provide an authentication manager object.
* This method tries to use the configuration in settings.groovy
* (see comment of configureAuth for configuration pattern). If
* there's no configuration the user is prompted.
* @param repoKey
* @param repoType discovery or distribution
* @param tokenizeUrl the broken down url
* @return an ISVNAuthenticationManager impl instance building
*/
private ISVNAuthenticationManager getAuthenticationManager(String repoKey, String repoType, Map tokenizeUrl) {
ISVNAuthenticationManager aAuthManager
usr = "user.svn.username.${repoType}.${repoKey}".toString()
psw = "user.svn.password.${repoType}.${repoKey}".toString()
if (tokenizeUrl[KEY_USER_NAME]) {
ant.antProject.setNewProperty usr, ""+tokenizeUrl[KEY_USER_NAME]
String pswd = tokenizeUrl[KEY_USER_PASS] ?: ""
ant.antProject.setNewProperty(psw, pswd)
}
//If no provided info, the user have to be prompt
ant.input(message:"Please enter your SVN username:", addproperty:usr)
ant.input(message:"Please enter your SVN password:", addproperty:psw)
def username = ant.antProject.getProperty(usr)
def password = ant.antProject.getProperty(psw)
authManager = SVNWCUtil.createDefaultAuthenticationManager(username , password)
//Test connection
aUrl = tokenizeUrl[KEY_URL]
def svnUrl = SVNURL.parseURIEncoded(aUrl)
def repo = SVNRepositoryFactory.create(svnUrl, null)
repo.authenticationManager = authManager
try {
repo.testConnection()
//only if it works...
repo.closeSession()
}
catch (SVNAuthenticationException ex) {
//GRAVE BAD CONFIGURATION : EXITING
event("StatusError",["Bad authentication configuration for $aUrl"])
exit(1)
}
return authManager
}
/**
* Get an authenticationManager object starting from url
* @param url of SVN repo
* @param repoType discovery or distribution
* @return ISVNAuthenticationManager for SVN connection on on repo with auth
**/
private ISVNAuthenticationManager getAuthFromUrl(url, repoType) {
keyValue = repoType + "." + pluginDiscoveryRepositories.find { url.startsWith(it.value) }?.key
return authManagerMap[keyValue]
}
configureRepository = { targetRepoURL, String alias = "default" ->
repositoryName = alias
pluginsList = null
pluginsListFile = new File(grailsSettings.grailsWorkDir, "plugins-list-${alias}.xml")
def namedPluginSVN = pluginDistributionRepositories.find { it.key == alias }?.value
if (namedPluginSVN) {
pluginSVN = namedPluginSVN
}
else {
pluginSVN = DEFAULT_PUBLISH_URL
}
pluginDistURL = targetRepoURL
pluginBinaryDistURL = "$targetRepoURL/dist"
remotePluginList = "$targetRepoURL/.plugin-meta/plugins-list.xml"
}
configureRepository(DEFAULT_PLUGIN_DIST)
configureRepositoryForName = { String targetRepository, type="discovery" ->
// Works around a bug in Groovy 1.5.6's DOMCategory that means get on Object returns null. Change to "pluginDiscoveryRepositories.targetRepository" when upgrading
def targetRepoURL = pluginDiscoveryRepositories.find { it.key == targetRepository }?.value
if (targetRepoURL) {
configureRepository(targetRepoURL, targetRepository)
}
else {
println "No repository configured for name ${targetRepository}. Set the 'grails.plugin.repos.${type}.${targetRepository}' variable to the location of the repository."
exit(1)
}
}
target ('default': "A target for plug-in developers that uploads and commits the current plug-in as the latest revision. The command will prompt for your SVN login details.") {
releasePlugin()
}
target(processAuth:"Prompts user for login details to create authentication manager") {
if (!authManager) {
def authKey = argsMap.repository ? "distribution.${argsMap.repository}".toString() : "distribution.default"
if (authManagerMap[authKey]) {
authManager = authManagerMap[authKey]
}
else {
usr = "user.svn.username.distribution"
psw = "user.svn.password.distribution"
if (argsMap.repository) {
usr = usr + "." + argsMap.repository
psw = psw + "." + argsMap.repository
}
else {
usr = usr + ".default"
psw = psw + ".default"
}
def (username, password) = [argsMap.username, argsMap.password]
if (!username) {
ant.input(message:"Please enter your SVN username:", addproperty:usr)
username = ant.antProject.getProperty(usr)
}
if (!password) {
ant.input(message:"Please enter your SVN password:", addproperty:psw)
password = ant.antProject.getProperty(psw)
}
authManager = SVNWCUtil.createDefaultAuthenticationManager(username , password)
authManagerMap.put(authKey,authManager)
}
}
}
target(checkLicense:"Checks the license file for the plugin exists") {
if (!(new File("${basedir}/LICENSE").exists()) && !(new File("${basedir}/LICENSE.txt").exists())) {
println "No LICENSE.txt file for plugin found. Please provide a license file containing the appropriate software licensing information (eg. Apache 2.0, GPL etc.)"
exit(1)
}
}
target(releasePlugin: "The implementation target") {
depends(parseArguments,checkLicense)
if (argsMap.skipMetadata != true) {
println "Generating plugin project behavior metadata..."
try {
MetadataGeneratingMetaClassCreationHandle.enable()
packageApp()
loadApp()
configureApp()
MetadataGeneratingMetaClassCreationHandle.disable()
}
catch (e) {
println "There was an error generating project behavior metadata: [${e.message}]"
}
}
packagePlugin()
if (argsMap.skipDocs != true) {
docs()
}
if (argsMap.packageOnly) {
return
}
processAuth()
if (argsMap.message) {
commitMessage = argsMap.message
}
if (argsMap.repository) {
configureRepositoryForName(argsMap.repository, "distribution")
}
if (argsMap.snapshot || argsMap.'skip-latest') {
skipLatest = true
}
remoteLocation = "${pluginSVN}/grails-${pluginName}"
trunk = SVNURL.parseURIDecoded("${remoteLocation}/trunk")
latestRelease = "${remoteLocation}/tags/LATEST_RELEASE"
versionedRelease = "${remoteLocation}/tags/RELEASE_${plugin.version.toString().replaceAll('\\.','_')}"
FSRepositoryFactory.setup()
DAVRepositoryFactory.setup()
SVNRepositoryFactoryImpl.setup()
try {
if (argsMap.pluginlist) {
commitNewGlobalPluginList()
}
else if (argsMap.zipOnly) {
publishZipOnlyRelease()
}
else {
def statusClient = new SVNStatusClient((ISVNAuthenticationManager)authManager,null)
try {
// get status of base directory, if this fails exception will be thrown
statusClient.doStatus(baseFile, true)
updateAndCommitLatest()
}
catch (SVNException ex) {
// error with status, not in repo, attempt import.
if (ex.message.contains("is not a working copy")) {
boolean notInRepository = isPluginNotInRepository()
if (notInRepository) {
importToSVN()
}
else {
def result = confirmInput("""
The current directory is not a working copy and your latest changes won't be committed.
You need to checkout a working copy and make your changes there.
Alternatively, would you like to publish a zip-only (no sources) release?""")
if (!result) exit(0)
publishZipOnlyRelease()
return
}
}
else {
event('StatusFinal', ["Failed to stat working directory: ${ex.message}"])
exit(1)
}
}
tagPluginRelease()
modifyOrCreatePluginList()
event('StatusFinal', ["Plug-in release successfully published"])
}
}
catch(Exception e) {
logErrorAndExit("Error occurred with release-plugin", e)
}
}
def publishZipOnlyRelease() {
def localWorkingCopy = new File("${projectWorkDir}/working-copy")
ant.mkdir(dir: localWorkingCopy)
if (isPluginNotInRepository()) {
updateLocalZipAndXml(localWorkingCopy)
importBaseToSVN(localWorkingCopy)
}
cleanLocalWorkingCopy(localWorkingCopy)
checkoutFromSVN(localWorkingCopy, trunk)
updateLocalZipAndXml(localWorkingCopy)
addPluginZipAndMetadataIfNeccessary(new File("${localWorkingCopy}/plugin.xml"), new File("${localWorkingCopy}/${new File(pluginZip).name}"))
commitDirectoryToSVN(localWorkingCopy)
tagPluginRelease()
modifyOrCreatePluginList()
deleteZipFromTrunk()
println "Successfully published zip-only plugin release."
}
def deleteZipFromTrunk() {
def commitClient = new SVNCommitClient((ISVNAuthenticationManager) authManager, null)
if (!commitMessage) askForMessage()
if(pluginZip) {
def pluginZipFile = new File(pluginZip)
def zipLocation = SVNURL.parseURIDecoded("${remoteLocation}/trunk/${pluginZipFile.name}")
try { commitClient.doDelete([zipLocation] as SVNURL[], commitMessage) }
catch (SVNException e) {
// ok - the zip doesn't exist yet
}
}
}
def updateLocalZipAndXml(File localWorkingCopy) {
ant.copy(file: pluginZip, todir: localWorkingCopy, overwrite:true)
ant.copy(file: "${basedir}/plugin.xml", todir: localWorkingCopy, overwrite:true)
}
def cleanLocalWorkingCopy(File localWorkingCopy) {
ant.delete(dir: localWorkingCopy)
ant.mkdir(dir: localWorkingCopy)
}
boolean isPluginNotInRepository() {
// Now check whether the plugin is in the repository.
// If not, we ask the user whether they want to import it.
SVNRepository repos = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(pluginSVN))
if(authManager != null)
repos.authenticationManager = authManager
boolean notInRepository = true
try {
notInRepository = !repos.info("grails-$pluginName", -1)
}
catch (e) {
// ignore
}
return notInRepository
}
target(modifyOrCreatePluginList:"Updates the remote plugin.xml descriptor or creates a new one in the repo") {
withPluginListUpdate {
ant.delete(file:pluginsListFile)
// get newest version of plugin list
try {
fetchRemoteFile("${pluginSVN}/.plugin-meta/plugins-list.xml", pluginsListFile)
}
catch (Exception e) {
println "Error reading remote plugin list [${e.message}], building locally..."
updatePluginsListManually()
}
def remoteRevision = "0"
if (shouldUseSVNProtocol(pluginDistURL)) {
withSVNRepo(pluginDistURL) { repo ->
remoteRevision = repo.getLatestRevision().toString()
}
}
else {
new URL(pluginDistURL).withReader { Reader reader ->
def line = reader.readLine()
line.eachMatch(/Revision (.*):/) {
remoteRevision = it[1]
}
}
}
def publisher = new DefaultPluginPublisher(remoteRevision, pluginDistURL)
def updatedList = publisher.publishRelease(pluginName, new FileSystemResource(pluginsListFile), !skipLatest)
pluginsListFile.withWriter("UTF-8") { w ->
publisher.writePluginList(updatedList, w)
}
}
}
target(commitNewGlobalPluginList:"updates the plugins.xml descriptor stored in the repo") {
withPluginListUpdate {
ant.delete(file:pluginsListFile)
println "Building plugin list for commit..."
updatePluginsListManually()
}
}
private withPluginListUpdate(Closure updateLogic) {
if (!commitMessage) {
askForMessage()
}
updateLogic()
def pluginMetaDir = new File("${grailsSettings.grailsWorkDir}/${repositoryName}/.plugin-meta")
def updateClient = new SVNUpdateClient((ISVNAuthenticationManager)authManager, null)
def importClient = new SVNCommitClient((ISVNAuthenticationManager)authManager, null)
def addClient = new SVNWCClient((ISVNAuthenticationManager)authManager, null)
String remotePluginMetadata = "${pluginSVN}/.plugin-meta"
if (!pluginMetaDir.exists()) {
println "Checking out locally to '${pluginMetaDir}'."
checkoutOrImportPluginMetadata(pluginMetaDir, remotePluginMetadata, updateClient, importClient)
}
else {
try {
updateClient.doUpdate(pluginMetaDir, SVNRevision.HEAD, true)
commitNewestPluginList(pluginMetaDir, importClient)
}
catch (SVNException e) {
println "Plugin meta directory corrupt, checking out again"
checkoutOrImportPluginMetadata(pluginMetaDir, remotePluginMetadata, updateClient, importClient)
}
}
}
private checkoutOrImportPluginMetadata (File pluginMetaDir, String remotePluginMetadata, SVNUpdateClient updateClient, SVNCommitClient importClient) {
def svnURL = SVNURL.parseURIDecoded (remotePluginMetadata)
try {
updateClient.doCheckout(svnURL, pluginMetaDir, SVNRevision.HEAD, SVNRevision.HEAD, true)
try {
addClient.doAdd(new File("$pluginMetaDir/plugins-list.xml"), false, false, false, false)
}
catch (e) {
// ignore
}
commitNewestPluginList(pluginMetaDir, importClient)
}
catch (SVNException e) {
println "Importing plugin meta data to ${remotePluginMetadata}. Please wait..."
ant.mkdir(dir: pluginMetaDir)
ant.copy(file: pluginsListFile, tofile: "$pluginMetaDir/plugins-list.xml")
def commit = importClient.doImport(pluginMetaDir, svnURL, commitMessage, true)
println "Committed revision ${commit.newRevision} of plugins-list.xml."
ant.delete(dir: pluginMetaDir)
updateClient.doCheckout(svnURL, pluginMetaDir, SVNRevision.HEAD, SVNRevision.HEAD, true)
}
}
private def commitNewestPluginList(File pluginMetaDir, SVNCommitClient importClient) {
ant.copy(file: pluginsListFile, tofile: "$pluginMetaDir/plugins-list.xml", overwrite: true)
def commit = importClient.doCommit([pluginMetaDir] as File[], false, commitMessage, true, true)
println "Committed revision ${commit.newRevision} of plugins-list.xml."
}
target(checkInPluginZip:"Checks in the plug-in zip if it has not been checked in already") {
def pluginXml = new File("${basedir}/plugin.xml")
addPluginZipAndMetadataIfNeccessary(pluginXml, new File(pluginZip))
}
def addPluginZipAndMetadataIfNeccessary(File pluginXml, File pluginFile) {
def statusClient = new SVNStatusClient((ISVNAuthenticationManager) authManager, null)
def wcClient = new SVNWCClient((ISVNAuthenticationManager) authManager, null)
def addPluginFile = false
try {
def status = statusClient.doStatus(pluginFile, true)
if (status.kind == SVNNodeKind.NONE || status.kind == SVNNodeKind.UNKNOWN) addPluginFile = true
}
catch (SVNException) {
// not checked in add and commit
addPluginFile = true
}
if (addPluginFile) wcClient.doAdd(pluginFile, true, false, false, false)
addPluginFile = false
try {
def status = statusClient.doStatus(pluginXml, true)
if (status.kind == SVNNodeKind.NONE || status.kind == SVNNodeKind.UNKNOWN) addPluginFile = true
}
catch (SVNException e) {
addPluginFile = true
}
if (addPluginFile) wcClient.doAdd(pluginXml, true, false, false, false)
}
target(updateAndCommitLatest:"Commits the latest revision of the Plug-in") {
def result = !isInteractive || confirmInput("""
This command will perform the following steps to release your plug-in to Grails' SVN repository:
* Update your sources to the HEAD revision
* Commit any changes you've made to SVN
* Tag the release
NOTE: This command will not add new resources for you, if you have additional sources to add please run 'svn add' before running this command.
NOTE: Make sure you have updated the version number in your *GrailsPlugin.groovy descriptor.
Are you sure you wish to proceed?
""")
if (!result) exit(0)
println "Checking in plugin zip..."
checkInPluginZip()
long r = updateDirectoryFromSVN(baseFile)
println "Updated to revision ${r}. Committing local, please wait..."
def commit = commitDirectoryToSVN(baseFile)
println "Committed revision ${commit.newRevision}."
}
def commitDirectoryToSVN(baseFile) {
commitClient = new SVNCommitClient((ISVNAuthenticationManager) authManager, null)
if (!commitMessage) askForMessage()
println "Committing code. Please wait..."
return commitClient.doCommit([baseFile] as File[], false, commitMessage, true, true)
}
long updateDirectoryFromSVN(baseFile) {
updateClient = new SVNUpdateClient((ISVNAuthenticationManager) authManager, null)
println "Updating from SVN..."
long r = updateClient.doUpdate(baseFile, SVNRevision.HEAD, true)
return r
}
target(importToSVN:"Imports a plugin project to Grails' remote SVN repository") {
File checkOutDir = new File("${baseFile.parentFile.absolutePath}/checkout/${baseFile.name}")
ant.unzip(src:pluginZip, dest:"${basedir}/unzipped")
ant.copy(file:pluginZip, todir:"${basedir}/unzipped")
ant.mkdir(dir:"${basedir}/unzipped/grails-app")
File importBaseDirectory = new File("${basedir}/unzipped")
String testsDir = "${importBaseDirectory}/test"
ant.mkdir(dir:testsDir)
ant.copy(todir:testsDir) {
fileset(dir:"${grailsSettings.testSourceDir}")
}
try {
def result = !isInteractive || confirmInput("""
This plug-in project is not currently in the repository, this command will now:
* Perform an SVN import into the repository
* Checkout the imported version of the project from SVN to '${checkOutDir}'
* Tag the plug-in project as the LATEST_RELEASE
Are you sure you wish to proceed?
""")
if (!result) {
ant.delete(dir:importBaseDirectory, failonerror:false)
exit(0)
}
svnURL = importBaseToSVN(importBaseDirectory)
}
finally {
ant.delete(dir:importBaseDirectory, failonerror:false)
}
checkOutDir.parentFile.mkdirs()
checkoutFromSVN(checkOutDir, svnURL)
event('StatusFinal', ["""
Completed SVN project import. If you are in terminal navigate to imported project with:
cd ${checkOutDir}
Future changes should be made to the SVN controlled sources!"""])
}
def checkoutFromSVN(File checkOutDir, SVNURL svnURL) {
updateClient = new SVNUpdateClient((ISVNAuthenticationManager) authManager, null)
println "Checking out locally to '${checkOutDir}'."
updateClient.doCheckout(svnURL, checkOutDir, SVNRevision.HEAD, SVNRevision.HEAD, true)
}
SVNURL importBaseToSVN(File importBaseDirectory) {
importClient = new SVNCommitClient((ISVNAuthenticationManager) authManager, null)
if (!commitMessage) askForMessage()
println "Importing project to ${remoteLocation}. Please wait..."
def svnURL = SVNURL.parseURIDecoded("${remoteLocation}/trunk")
importClient.doImport(importBaseDirectory, svnURL, commitMessage, true)
println "Plug-in project imported to SVN at location '${remoteLocation}/trunk'"
return svnURL
}
target(tagPluginRelease:"Tags a plugin-in with the LATEST_RELEASE tag and version tag within the /tags area of SVN") {
println "Preparing to publish the release..."
def copyClient = new SVNCopyClient((ISVNAuthenticationManager) authManager, null)
def commitClient = new SVNCommitClient((ISVNAuthenticationManager) authManager, null)
if (!commitMessage) askForMessage()
tags = SVNURL.parseURIDecoded("${remoteLocation}/tags")
latest = SVNURL.parseURIDecoded(latestRelease)
release = SVNURL.parseURIDecoded(versionedRelease)
try { commitClient.doMkDir([tags] as SVNURL[], commitMessage) }
catch (SVNException e) {
// ok - already exists
}
if (!skipLatest) {
try { commitClient.doDelete([latest] as SVNURL[], commitMessage) }
catch (SVNException e) {
// ok - the tag doesn't exist yet
}
}
try { commitClient.doDelete([release] as SVNURL[], commitMessage) }
catch (SVNException e) {
// ok - the tag doesn't exist yet
}
// Get remote URL for this working copy.
def wcClient = new SVNWCClient((ISVNAuthenticationManager) authManager, null)
def copyFromUrl = trunk
// First tag this release with the version number.
try {
println "Tagging version release, please wait..."
def copySource = new SVNCopySource(SVNRevision.HEAD, SVNRevision.HEAD, copyFromUrl)
def commit = copyClient.doCopy([copySource] as SVNCopySource[], release, false, false, true, commitMessage, new SVNProperties())
println "Copied trunk to ${versionedRelease} with revision ${commit.newRevision} on ${commit.date}"
// And now make it the latest release.
if (!skipLatest) {
println "Tagging latest release, please wait..."
copySource = new SVNCopySource(SVNRevision.HEAD, SVNRevision.HEAD, release)
commit = copyClient.doCopy([copySource] as SVNCopySource[], latest, false, false, true, commitMessage, new SVNProperties())
println "Copied trunk to ${latestRelease} with revision ${commit.newRevision} on ${commit.date}"
}
}
catch (SVNException e) {
logErrorAndExit("Error tagging release", e)
}
}
target(askForMessage:"Asks for the users commit message") {
ant.input(message:"Enter a SVN commit message:", addproperty:"commit.message")
commitMessage = ant.antProject.properties."commit.message"
}
target(updatePluginsListManually: "Updates the plugin list by manually reading each URL, the slow way") {
depends(configureProxy)
try {
def recreateCache = false
document = null
if (!pluginsListFile.exists()) {
println "Plugins list cache doesn't exist creating.."
recreateCache = true
}
else {
try {
document = DOMBuilder.parse(new FileReader(pluginsListFile))
}
catch (Exception e) {
recreateCache = true
println "Plugins list cache is corrupt [${e.message}]. Re-creating.."
}
}
if (recreateCache) {
document = DOMBuilder.newInstance().createDocument()
def root = document.createElement('plugins')
root.setAttribute('revision', '0')
document.appendChild(root)
}
pluginsList = document.documentElement
builder = new DOMBuilder(document)
def localRevision = pluginsList ? new Integer(pluginsList.getAttribute('revision')) : -1
// extract plugins svn repository revision - used for determining cache up-to-date
def remoteRevision = 0
try {
// determine if this is a secure plugin spot..
if (shouldUseSVNProtocol(pluginDistURL)) {
withSVNRepo(pluginDistURL) { repo ->
remoteRevision = repo.getLatestRevision()
if (remoteRevision > localRevision) {
// Plugins list cache is expired, need to update
event("StatusUpdate", ["Plugins list cache has expired. Updating, please wait"])
pluginsList.setAttribute('revision', remoteRevision as String)
repo.getDir('', -1,null,(Collection)null).each() { entry ->
final String PREFIX = "grails-"
if (entry.name.startsWith(PREFIX)) {
def pluginName = entry.name.substring(PREFIX.length())
buildPluginInfo(pluginsList, pluginName)
}
}
}
}
}
else {
new URL(pluginDistURL).withReader { Reader reader ->
def line = reader.readLine()
line.eachMatch(/Revision (.*):/) {
remoteRevision = it[1].toInteger()
}
if (remoteRevision > localRevision) {
// Plugins list cache is expired, need to update
event("StatusUpdate", ["Plugins list cache has expired. Updating, please wait"])
pluginsList.setAttribute('revision', remoteRevision as String)
// for each plugin directory under Grails Plugins SVN in form of 'grails-*'
while (line = reader.readLine()) {
line.eachMatch(/<li><a href="grails-(.+?)">/) {
// extract plugin name
def pluginName = it[1][0..-2]
// collect information about plugin
buildPluginInfo(pluginsList, pluginName)
}
}
}
}
}
}
catch (Exception e) {
event("StatusError", ["Unable to list plugins, please check you have a valid internet connection: ${e.message}" ])
}
// update plugins list cache file
writePluginsFile()
}
catch (Exception e) {
event("StatusError", ["Unable to list plugins, please check you have a valid internet connection: ${e.message}" ])
}
}
def buildPluginInfo(root, pluginName) {
use(DOMCategory) {
// determine the plugin node..
def pluginNode = root.'plugin'.find {it.'@name' == pluginName}
if (!pluginNode) {
// add it if it doesn't exist..
pluginNode = builder.'plugin'(name: pluginName)
root.appendChild(pluginNode)
}
// add each of the releases..
event("StatusUpdate", ["Reading [$pluginName] plugin info"])
// determine if this is a secure plugin spot..
def tagsUrl = "${pluginDistURL}/grails-${pluginName}/tags"
try {
if (shouldUseSVNProtocol(pluginDistURL)) {
withSVNRepo(tagsUrl) { repo ->
repo.getDir('',-1,null,(Collection)null).each() { entry ->
buildReleaseInfo(pluginNode, pluginName, tagsUrl, entry.name)
}
}
}
else {
def releaseTagsList = new URL(tagsUrl).text
releaseTagsList.eachMatch(/<li><a href="(.+?)">/) {
def releaseTag = it[1][0..-2]
buildReleaseInfo(pluginNode, pluginName, tagsUrl, releaseTag)
}
}
}
catch(e) {
// plugin has not tags
println "Plugin [$pluginName] doesn't have any tags"
}
try {
def latestRelease = null
def url = "${pluginDistURL}/grails-${pluginName}/tags/LATEST_RELEASE/plugin.xml"
fetchPluginListFile(url).withReader {Reader reader ->
def line = reader.readLine()
line.eachMatch (/.+?version='(.+?)'.+/) {
latestRelease = it[1]
}
}
if (latestRelease && pluginNode.'release'.find {it.'@version' == latestRelease}) {
pluginNode.setAttribute('latest-release', latestRelease as String)
}
}
catch(e) {
// plugin doesn't have a latest release
println "Plugin [$pluginName] doesn't have a latest release"
}
}
}
def buildReleaseInfo(root, pluginName, releasePath, releaseTag) {
// quick exit nothing to do..
if (releaseTag == '..' || releaseTag == 'LATEST_RELEASE') {
return
}
// remove previous version..
def releaseNode = root.'release'.find() {
it.'@tag' == releaseTag && it.'&type' == 'svn'
}
if (releaseNode) {
root.removeChild(releaseNode)
}
try {
// copy the properties to the new node..
def releaseUrl = "${releasePath}/${releaseTag}"
def properties = ['title', 'author', 'authorEmail', 'description', 'documentation']
def releaseDescriptor = parseRemoteXML("${releaseUrl}/plugin.xml").documentElement
def version = releaseDescriptor.'@version'
releaseNode = builder.createNode('release', [tag: releaseTag, version: version, type: 'svn'])
root.appendChild(releaseNode)
properties.each {
if (releaseDescriptor."${it}") {
releaseNode.appendChild(builder.createNode(it, releaseDescriptor."${it}".text()))
}
}
releaseNode.appendChild(builder.createNode('file', "${releaseUrl}/grails-${pluginName}-${version}.zip"))
}
catch(e) {
// no release info available, probably an older plugin with no plugin.xml defined.
}
}
def parsePluginList() {
if (pluginsList == null) {
profile("Reading local plugin list from $pluginsListFile") {
def document
try {
document = DOMBuilder.parse(new FileReader(pluginsListFile))
}
catch (Exception e) {
println "Plugin list file corrupt, retrieving again.."
readRemotePluginList()
document = DOMBuilder.parse(new FileReader(pluginsListFile))
}
pluginsList = document.documentElement
}
}
}
def readRemotePluginList() {
ant.delete(file:pluginsListFile, failonerror:false)
ant.mkdir(dir:pluginsListFile.parentFile)
fetchRemoteFile(remotePluginList, pluginsListFile)
}
def writePluginsFile() {
pluginsListFile.parentFile.mkdirs()
Transformer transformer = TransformerFactory.newInstance().newTransformer()
transformer.setOutputProperty(OutputKeys.INDENT, "true")
transformer.transform(new DOMSource(document), new StreamResult(pluginsListFile))
}
shouldUseSVNProtocol = { pluginDistURL ->
return isSecureUrl(pluginDistURL) || pluginDistURL.startsWith("file://")
}
def parseRemoteXML(url) {
fetchPluginListFile(url).withReader() { DOMBuilder.parse(it) }
}
/**
* Downloads a remote plugin zip into the plugins dir
*/
downloadRemotePlugin = { url, pluginsBase ->
def slash = url.file.lastIndexOf('/')
def fullPluginName = "${url.file[slash + 8..-5]}"
String zipLocation = "${pluginsBase}/grails-${fullPluginName}.zip"
fetchRemoteFile("${url}", zipLocation)
readMetadataFromZip(zipLocation, url)
return fullPluginName
}
fetchRemoteFile = { url, destfn ->
if (shouldUseSVNProtocol(pluginDistURL)) {
// fetch the remote file..
fetchRemote(url) { repo, file ->
// get the latest file from the repository..
def f = (destfn instanceof File) ? destfn : new File(destfn)
f.withOutputStream() { os ->
def props = new SVNProperties()
repo.getFile(file , (long)-1L, props , os)
}
}
}
else {
ant.get(src:url, dest:destfn, verbose:"yes", usetimestamp:true)
}
}
/**
* Fetch the entire plugin list file.
*/
fetchPluginListFile = { url ->
// attempt to fetch the file using SVN.
if (shouldUseSVNProtocol(pluginDistURL)) {
def rdr = fetchRemote(url) { repo, file ->
// get the latest file from the repository..
def props = new SVNProperties()
def baos = new ByteArrayOutputStream()