Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tag: v1.2.4
Fetching contributors…

Cannot retrieve contributors at this time

file 1527 lines (1351 sloc) 58.497 kb
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
/*
* 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 grails.util.BuildSettings
import grails.util.GrailsNameUtils
import grails.util.GrailsUtil

import groovy.xml.DOMBuilder
import groovy.xml.MarkupBuilder
import groovy.xml.dom.DOMCategory

import java.util.regex.Matcher
import java.util.zip.ZipFile
import java.util.zip.ZipEntry

import javax.xml.transform.OutputKeys
import javax.xml.transform.Transformer
import javax.xml.transform.TransformerFactory
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.stream.StreamResult

import org.apache.commons.io.FilenameUtils
import org.apache.commons.lang.ArrayUtils
import org.codehaus.groovy.control.CompilationUnit
import org.codehaus.groovy.grails.commons.DefaultGrailsApplication
import org.codehaus.groovy.grails.documentation.DocumentationContext
import org.codehaus.groovy.grails.documentation.DocumentedMethod
import org.codehaus.groovy.grails.documentation.DocumentedProperty
import org.codehaus.groovy.grails.plugins.DefaultGrailsPluginManager
import org.codehaus.groovy.grails.plugins.GrailsPluginUtils
import org.codehaus.groovy.grails.plugins.PluginManagerHolder
import org.codehaus.groovy.grails.resolve.IvyDependencyManager
import org.springframework.core.io.Resource
import org.tmatesoft.svn.core.*
import org.tmatesoft.svn.core.auth.*
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.wc.SVNWCUtil
import grails.util.PluginBuildSettings
import org.codehaus.groovy.control.MultipleCompilationErrorsException
import org.codehaus.groovy.control.CompilationFailedException
import org.codehaus.groovy.grails.commons.ApplicationHolder

/**
* Plugin stuff. If included, must be included after "_ClasspathAndEvents".
*
* @author Graeme Rocher
*
* @since 1.1
*/
if (getBinding().variables.containsKey("_plugin_dependencies_called")) return
_plugin_dependencies_called = true


includeTargets << grailsScript("_GrailsClean")
includeTargets << grailsScript("_GrailsArgParsing")
includeTargets << grailsScript("_GrailsProxy")


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"


// TODO: temporary until we refactor Grails core into real plugins
CORE_PLUGINS = ['core', 'i18n','converters','mimeTypes', 'controllers','webflow', 'dataSource', 'domainClass', 'filters','logging', 'groovyPages']


// Properties
pluginsList = null
globalInstall = false
pluginsBase = "${grailsWorkDir}/plugins".toString().replaceAll('\\\\','/')

// 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]
}




pluginResolveOrder = grailsSettings?.config?.grails?.plugin?.repos?.resolveOrder
if(!pluginResolveOrder) {
    pluginResolveOrder = pluginDiscoveryRepositories.keySet()
}
else {
    event("StatusUpdate", ["Using explicit plugin resolve order ${pluginResolveOrder}"])
}

installedPlugins = [] // a list of plugins that have been installed

boolean isCorePlugin(name) {
    CORE_PLUGINS.contains(name)
}

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)
    }
}

eachRepository = { Closure callable ->
    for(repoName in pluginResolveOrder) {
  
       configureRepositoryForName(repoName)
       updatePluginsList()
       if(!callable(repoName, pluginSVN)) {
         break
       }
    }
}
// Targets
target(resolveDependencies:"Resolve plugin dependencies") {
    depends(parseArguments, initInplacePlugins)
    def plugins = metadata.findAll { it.key.startsWith("plugins.")}.collect {
       [
        name:it.key[8..-1],
        version: it.value
       ]
    }
    boolean installedPlugins = false


    for(p in plugins) {
        def name = p.name
        def version = p.version
        def fullName = "$name-$version"
        def pluginLoc = getPluginDirForName(name)
        if(!pluginLoc?.exists()) {
            println "Plugin [${fullName}] not installed, resolving.."

            doInstallPluginFromGrailsHomeOrRepository name, version
            installedPlugins = true
        }
        else if(pluginLoc) {
            def dirName = pluginLoc.filename
            PluginBuildSettings settings = pluginSettings
            if(!dirName.endsWith(version) && !settings.isInlinePluginLocation(pluginLoc)) {
                println "Upgrading plugin [$dirName] to [${fullName}], resolving.."

                doInstallPluginFromGrailsHomeOrRepository name, version
                installedPlugins = true
            }
        }

    }
    if(installedPlugins) {
        resetClasspathAndState()
    }

    // Find out which plugins are in the search path but not in the
    // metadata. We only check on the plugins in the project's "plugins"
    // directory and the global "plugins" dir. Plugins loaded via an
    // explicit path should be left alone.
    def pluginDirs = pluginSettings.implicitPluginDirectories
    def pluginsToUninstall = pluginDirs.findAll { Resource r -> !plugins.find { plugin ->
        r.filename ==~ "$plugin.name-.+"
    }}

    for(Resource pluginDir in pluginsToUninstall) {
        if(pluginSettings.isGlobalPluginLocation(pluginDir)) {
            registerMetadataForPluginLocation(pluginDir)
        }
        else {
            if(!isInteractive || confirmInput("Plugin [${pluginDir.filename}] is installed, but was not found in the application's metadata, do you want to uninstall?", "confirm.${pluginDir.filename}.uninstall")) {
                uninstallPluginForName(pluginDir.filename)
            }
            else {
                registerMetadataForPluginLocation(pluginDir)
            }
        }
    }
}

target(initInplacePlugins: "Generates the plugin.xml descriptors for inplace plugins.") {
    depends(classpath)

    // Ensure that the "plugin.xml" is up-to-date for plugins
    // that haven't been installed, i.e. their path is declared
    // explicitly by the project.

    // TODO: At the moment we simple check whether plugin.xml exists for each plugin
    // TODO: otherwise fail
    PluginBuildSettings settings = pluginSettings

    Resource[] pluginDirs = settings.getInlinePluginDirectories()
    pluginDirs.each { Resource r ->
        def dir = r.file
        def pluginXml = new File(dir, "plugin.xml")
        if(!pluginXml.exists()) {
            println "The inplace plugin at [$dir.absolutePath] does not have a plugin.xml. Please run the package-plugin command inside the plugin directory."
            exit 1
        }
    }

// File pluginsDir = grailsSettings.projectPluginsDir.canonicalFile.absoluteFile
// File globalDir = grailsSettings.globalPluginsDir.canonicalFile.absoluteFile
// Resource basePluginDescriptor = pluginSettings.basePluginDescriptor
//
// pluginSettings.pluginDescriptors.findAll { Resource r ->
// pluginSettings.isInlinePluginLocation(r)
// }.each { Resource r ->
// compileInplacePlugin(r.file.parentFile)
// generatePluginXml(r.file)
// }
}

/**
* Compiles the sources for a single in-place plugin. A bit of a hack,
* but any other solution would require too much refactoring to make it
* into the 1.2 release.
*/
compileInplacePlugin = { File pluginDir ->
    def classesDirPath = grailsSettings.classesDir.path
    ant.mkdir(dir: classesDirPath)

    profile("Compiling inplace plugin sources to location [$classesDirPath]") {
        // First compile the plugins so that we can exclude any
        // classes that might conflict with the project's.
        def classpathId = "grails.compile.classpath"
        def pluginResources = pluginSettings.getPluginSourceFiles(pluginDir)
        
        if (pluginResources) {
            // Only perform the compilation if there are some plugins
            // installed or otherwise referenced.
            try {
                ant.groovyc(
                    destdir: classesDirPath,
                        classpathref: classpathId,
                        encoding:"UTF-8",
                        verbose: grailsSettings.verboseCompile,
                        listfiles: grailsSettings.verboseCompile) {
                    for(File dir in pluginResources.file) {
                        if (dir.exists() && dir.isDirectory()) {
                            src(path: dir.absolutePath)
                        }
                    }
                    exclude(name: "**/BootStrap.groovy")
                    exclude(name: "**/BuildConfig.groovy")
                    exclude(name: "**/Config.groovy")
                    exclude(name: "**/*DataSource.groovy")
                    exclude(name: "**/UrlMappings.groovy")
                    exclude(name: "**/resources.groovy")
                    javac(classpathref: classpathId, encoding: "UTF-8", debug: "yes")
                }
            }
            catch (e) {
                println "Failed to compile plugin at location [$pluginDir] with error: ${e.message}"
                exit 1
            }
        }
    }
}

private registerMetadataForPluginLocation(Resource pluginDir) {
    def plugin = pluginSettings.getMetadataForPlugin(pluginDir.filename)
    registerPluginWithMetadata(plugin.@name.text(), plugin.@version.text())
}

/**
* Generates the 'plugin.xml' file for a plugin. Returns an instance
* of the plugin descriptor.
*/
generatePluginXml = { File descriptor ->
    // Load the plugin descriptor class and instantiate it so we can
    // access its properties.
    Class pluginClass
    def plugin
    try {
        // Rather than compiling the descriptor via Ant, we just load
        // the Groovy file into a GroovyClassLoader. We add the classes
        // directory to the class loader in case it didn't exist before
        // the associated plugin's sources were compiled.
        def gcl = new GroovyClassLoader(classLoader)
        gcl.addURL(grailsSettings.classesDir.toURI().toURL())

        pluginClass = gcl.parseClass(descriptor)
        plugin = pluginClass.newInstance()
    }
    catch (Throwable t) {
        event("StatusError", [ t.message])
        t.printStackTrace(System.out)
        ant.fail("Cannot instantiate plugin file")
    }

    // Work out what the name of the plugin is from the name of the
    // descriptor file.
    pluginName = GrailsNameUtils.getPluginName(descriptor.name)

    // Remove the existing 'plugin.xml' if there is one.
    def pluginXml = new File(descriptor.parentFile, "plugin.xml")
    pluginXml.delete()

    // Use MarkupBuilder with indenting to generate the file.
    def writer = new IndentPrinter(new PrintWriter(new FileWriter(pluginXml)))
    def xml = new MarkupBuilder(writer)

    // Write the content!
    def props = ['author','authorEmail','title','description','documentation']
    def resourceList = pluginSettings.getArtefactResourcesForOne(descriptor.parentFile.absolutePath)

    def rcComparator = [ compare: {a, b -> a.URI.compareTo(b.URI) } ] as Comparator
    Arrays.sort(resourceList, rcComparator)

    pluginGrailsVersion = "${GrailsUtil.grailsVersion} > *"
    if(plugin.metaClass.hasProperty(plugin,"grailsVersion")) {
        pluginGrailsVersion = plugin.grailsVersion
    }

    xml.plugin(name:"${pluginName}",version:"${plugin.version}", grailsVersion:pluginGrailsVersion) {
        props.each {
            if( plugin.properties[it] ) "${it}"(plugin.properties[it])
        }
        resources {
            for(r in resourceList) {
                 def matcher = r.URL.toString() =~ artefactPattern
                 def name = matcher[0][1].replaceAll('/', /\./)
                 resource(name)
            }
        }
        dependencies {
            if(plugin.metaClass.hasProperty(plugin,'dependsOn')) {
                for(d in plugin.dependsOn) {
                    delegate.plugin(name:d.key, version:d.value)
                }
            }

            IvyDependencyManager dependencyManager = grailsSettings.dependencyManager
            dependencyManager.serialize(delegate, false)
        }

        def docContext = DocumentationContext.instance
        if(docContext) {
            behavior {
                for(DocumentedMethod m in docContext.methods) {
                    method(name:m.name, artefact:m.artefact, type:m.type?.name) {
                        description m.text
                        if(m.arguments) {
                            for(arg in m.arguments) {
                                argument type:arg.name
                            }
                        }
                    }
                }
                for(DocumentedMethod m in docContext.staticMethods) {
                    'static-method'(name:m.name, artefact:m.artefact, type:m.type?.name) {
                        description m.text
                        if(m.arguments) {
                            for(arg in m.arguments) {
                                argument type:arg.name
                            }
                        }
                    }
                }
                for(DocumentedProperty p in docContext.properties) {
                    property(name:p.name, type:p?.type?.name, artefact:p.artefact) {
                        description p.text
                    }
                }
            }
        }
    }

    return plugin
}

target(loadPlugins:"Loads Grails' plugins") {
    if(!PluginManagerHolder.pluginManager) { // plugin manager already loaded?
compConfig.setTargetDirectory(classesDir)
def unit = new CompilationUnit ( compConfig , null , new GroovyClassLoader(classLoader) )
def pluginFiles = pluginSettings.pluginDescriptors

        for(plugin in pluginFiles) {
            def pluginFile = plugin.file
            def className = pluginFile.name - '.groovy'
def classFile = new File("${classesDirPath}/${className}.class")

            if(pluginFile.lastModified() > classFile.lastModified()) {
                unit.addSource ( pluginFile )
            }
}

        try {
            profile("compiling plugins") {
unit.compile ()
}

def application
            def pluginClasses = []
            profile("construct plugin manager with ${pluginFiles.inspect()}") {
for(plugin in pluginFiles) {
def className = plugin.file.name - '.groovy'
pluginClasses << classLoader.loadClass(className)
}

                profile("creating plugin manager with classes ${pluginClasses}") {
                    if(grailsApp == null) {
                        grailsApp = new DefaultGrailsApplication(new Class[0], new GroovyClassLoader(classLoader))
                        ApplicationHolder.application = grailsApp
                    }
                    pluginManager = new DefaultGrailsPluginManager(pluginClasses as Class[], grailsApp)

                    PluginManagerHolder.setPluginManager(pluginManager)
                    pluginSettings.pluginManager = pluginManager
                }
}
profile("loading plugins") {
event("PluginLoadStart", [pluginManager])
pluginManager.loadPlugins()
                def baseDescriptor = pluginSettings.basePluginDescriptor
                if(baseDescriptor) {
                    def baseName = FilenameUtils.getBaseName(baseDescriptor.filename)
                    def plugin = pluginManager.getGrailsPluginForClassName(baseName)
                    if(plugin) {
                        plugin.basePlugin = true
                    }
                }
                if(pluginManager.failedLoadPlugins) {
                    event("StatusError", ["Error: The following plugins failed to load due to missing dependencies: ${pluginManager.failedLoadPlugins*.name}"])
                    for(p in pluginManager.failedLoadPlugins) {
                        println "- Plugin: $p.name, Dependencies: $p.dependencyNames"
                    }
                    exit(1)
                }

                pluginManager.doArtefactConfiguration()
                grailsApp.initialise()
                event("PluginLoadEnd", [pluginManager])
            }
}
        catch (Exception e) {
            GrailsUtil.deepSanitize(e).printStackTrace()
            event("StatusFinal", [ "Error loading plugin manager: " + e.message ])
exit(1)
}
    }
    else {
        // Add the plugin manager to the binding so that it can be accessed
        // from any target.
        pluginManager = PluginManagerHolder.pluginManager
    }
}

target(updatePluginsList:"Updates the plugin list from the remote plugin-list.xml") {
    try {
        println "Reading remote plugin list ..."
        if(!pluginsListFile.exists())
            readRemotePluginList()

        parsePluginList()
        def localRevision = pluginsList ? new Integer(pluginsList.getAttribute('revision')) : -1
        // extract plugins svn repository revision - used for determining cache up-to-date
        def remoteRevision = 0
        fetchPluginListFile(remotePluginList).withReader { Reader reader ->
            def line = reader.readLine()
            while(line) {
                Matcher matcher = line =~ /<plugins revision="(\d+?)">/
                if(matcher) {
                    remoteRevision = matcher.group(1).toInteger()
                    break
                }
                else {
                    line = reader.readLine()
                }

            }
        }
        profile("Updating plugin list if remote list [$remoteRevision] is newer than local ${localRevision}") {
            if (remoteRevision > localRevision) {
                println "Plugin list out-of-date, retrieving.."
                readRemotePluginList()

                // Load up the new plugin list.
                pluginsList = null
                parsePluginList()
            }
        }

    } catch (Exception e) {
        println "Error reading remote plugin list [${e.message}], building locally..."
        updatePluginsListManually()
    }
}


def resetClasspathAndState() {

    // Update the cached dependencies in grailsSettings, and add new jars to the root loader
    ['compile', 'build', 'test', 'runtime'].each { type ->
        def existing = grailsSettings."${type}Dependencies"
        def all = grailsSettings.dependencyManager.resolveDependencies(IvyDependencyManager."${type.toUpperCase()}_CONFIGURATION").allArtifactsReports.localFile
        def toAdd = all - existing
        if (toAdd) {
            existing.addAll(toAdd)
            if (type in ['build', 'test']) {
                toAdd.each {
                    grailsSettings.rootLoader.addURL(it.toURL())
                }
            }
        }
    }

    pluginSettings.clearCache()
    classpathSet = false
    classpath()
    PluginManagerHolder.pluginManager = null
}
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)
}

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}" ])
    }
}

shouldUseSVNProtocol = { pluginDistURL ->
    return isSecureUrl(pluginDistURL) || pluginDistURL.startsWith("file://")
}

// Utility Closures

/**
* Reads a plugin.xml descriptor for the given plugin name
*/
readPluginXmlMetadata = { String pluginName ->
    def pluginDir = getPluginDirForName(pluginName)?.file
    new XmlSlurper().parse(new File("${pluginDir}/plugin.xml"))
}

/**
* Reads all installed plugin descriptors returning a list
*/
readAllPluginXmlMetadata = {->
    pluginSettings.pluginXmlMetadata.collect { new XmlSlurper().parse(it.file) }
}

/**
* @deprecated Use "pluginSettings.pluginXmlMetadata" instead.
*/
getPluginXmlMetadata = {
    pluginSettings.pluginXmlMetadata
}
/**
* Obtains the directory for the given plugin name
*/
getPluginDirForName = { String pluginName ->
    pluginSettings.getPluginDirForName(pluginName)
}
/**
* Obtains all of the plugin directories
* @deprecated Use "pluginSettings.pluginDirectories".
*/
getPluginDirectories = {->
    pluginSettings.pluginDirectories
}
/**
* Obtains an array of all plugin source files as Spring Resource objects
* @deprecated Use "pluginSettings.pluginSourceFiles".
*/
getPluginSourceFiles = {
    pluginSettings.pluginSourceFiles
}
/**
* Obtains an array of all the plugin provides Gant scripts
* @deprecated Use "pluginSettings.pluginScripts".
*/
getPluginScripts = {
    pluginSettings.pluginScripts
}
/**
* Gets a list of all scripts known to the application (excluding private scripts starting with _)
* @deprecated Use "pluginSettings.availableScripts".
*/
getAllScripts = {
    pluginSettings.availableScripts
}
/**
* Obtains a list of all Grails plugin descriptor classes
* @deprecated Use "pluginSettings.pluginDescriptors".
*/
getPluginDescriptors = {
    pluginSettings.pluginDescriptors
}
/**
* Gets the base plugin descriptor
* @deprecated Use "pluginSettings.basePluginDescriptor".
*/
getBasePluginDescriptor = {
    pluginSettings.basePluginDescriptor
}
/**
* Runs a script contained within a plugin
*/
runPluginScript = { File scriptFile, fullPluginName, msg ->
    if (scriptFile.exists()) {
        event("StatusUpdate", ["Executing ${fullPluginName} plugin $msg"])
        // instrumenting plugin scripts adding 'pluginBasedir' variable
        def instrumentedInstallScript = "def pluginBasedir = '${pluginsHome}/${fullPluginName}'\n".toString().replaceAll('\\\\','/') + scriptFile.text
        // we are using text form of script here to prevent Gant caching
        includeTargets << instrumentedInstallScript
    }
}
/**
* 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
}


/**
* Caches a local plugin into the plugins directory
*/
cacheLocalPlugin = { pluginFile ->
    fullPluginName = "${pluginFile.name[7..-5]}"
    String zipLocation = "${pluginsBase}/grails-${fullPluginName}.zip"
    ant.copy(file: pluginFile, tofile: zipLocation)
    readMetadataFromZip(zipLocation, pluginFile)

    return fullPluginName
}

private readMetadataFromZip(String zipLocation, pluginFile) {
    def zipFile = new ZipFile(zipLocation)

    ZipEntry entry = zipFile.entries().find {ZipEntry entry -> entry.name == 'plugin.xml'}

    if (entry) {
        pluginXml = new XmlSlurper().parse(zipFile.getInputStream(entry))
        currentPluginName = pluginXml.'@name'.text()
        currentPluginRelease = pluginXml.'@version'.text()
        fullPluginName = "$currentPluginName-$currentPluginRelease"
    }
    else {
        cleanupPluginInstallAndExit("Plug-in $pluginFile is not a valid Grails plugin. No plugin.xml descriptor found!")
    }
}

/**
* Searches the downloaded plugin-list.xml files for each repository for a plugin that matches the given name
*/
findPlugin = { pluginName ->
  pluginName = pluginName?.toLowerCase()
  plugin = null
  if(pluginName) {
    if(!plugin) {
       eachRepository { name, url ->
          plugin = pluginsList.'plugin'.find { it.'@name' == pluginName }
          (!plugin)
       }
    }
    return plugin
  }
}
/**
* Stores a plugin from the plugin central repo into the local plugin cache
*/
cacheKnownPlugin = { String pluginName, String pluginRelease ->
    def pluginDistName
    def plugin
    def fullPluginName
    try {
      use(DOMCategory) {
          plugin = findPlugin(pluginName)

          if (plugin) {
              pluginRelease = pluginRelease ? pluginRelease : plugin.'@latest-release'
              if (pluginRelease) {
                  def release = plugin.'release'.find {rel -> rel.'@version' == pluginRelease }
                  if (release) {
                      pluginDistName = release.'file'.text()
                  } else {
                      cleanupPluginInstallAndExit("Release ${pluginRelease} was not found for this plugin. Type 'grails plugin-info ${pluginName}'")
                  }
              } else {
                  cleanupPluginInstallAndExit("Latest release information is not available for plugin '${pluginName}', specify concrete release to install")
              }
          } else {
              cleanupPluginInstallAndExit("Plugin '${pluginName}' was not found in repository. If it is not stored in a configured repository you will need to install it manually. Type 'grails list-plugins' to find out what plugins are available.")
          }


          def pluginCacheFileName = "${pluginsBase}/grails-${plugin.'@name'}-${pluginRelease}.zip"
          if (!new File(pluginCacheFileName).exists() || pluginRelease.endsWith("SNAPSHOT")) {
              ant.mkdir(dir:pluginsBase)
              if(!pluginDistName) {
                cleanupPluginInstallAndExit("Plugin '${pluginName}' is in the [$repositoryName] repository, but contains no valid releases.")
              }
              else {
                fetchRemoteFile("${pluginDistName}", pluginCacheFileName)
              }
          }
          fullPluginName = "$pluginName-$pluginRelease"
          currentPluginName = pluginName
          currentPluginRelease = pluginRelease

          ant.copy(file:"${pluginsBase}/grails-${fullPluginName}.zip",tofile:"${pluginsHome}/grails-${fullPluginName}.zip")
      }
      return fullPluginName
    }
    finally {
       configureRepository(DEFAULT_PLUGIN_DIST)
    }
}

cleanupPluginInstallAndExit = { message ->
  event("StatusError", [message])
  for(pluginDir in installedPlugins) {
    if (checkPluginPath(pluginDir)) {
        ant.delete(dir:pluginDir, failonerror:false)
    }
  }
  exit(1)
}

/**
* Uninstalls a plugin for the given name and version
*/
uninstallPluginForName = { name, version=null ->

    String pluginKey = "plugins.$name"
    metadata.remove(pluginKey)
    metadata.persist()


    def pluginDir
    if(name && version) {
        pluginDir = new File("${pluginsHome}/$name-$version")
    }
    else {
        pluginDir = getPluginDirForName(name)?.file
    }
    if(pluginDir?.exists()) {

        def uninstallScript = new File("${pluginDir}/scripts/_Uninstall.groovy")
        runPluginScript(uninstallScript, pluginDir.name, "uninstall script")
        if (checkPluginPath(pluginDir)) {
            ant.delete(dir:pluginDir, failonerror:true)
        }
        resetClasspathAndState()
    }
    else {
        event("StatusError", ["No plugin [$name${version ? '-' + version : ''}] installed, cannot uninstall"])
    }
}
/**
* Installs a plugin for the given name and optional version
*/
installPluginForName = { String fullPluginName ->

    if (fullPluginName) {
        event("InstallPluginStart", [fullPluginName])
        def pluginInstallPath = "${globalInstall ? globalPluginsDirPath : pluginsHome}/${fullPluginName}"


        def pluginReference = grailsSettings.config.grails.plugin.location[currentPluginName]
        if(pluginReference) {
           cleanupPluginInstallAndExit("""\
Plugin [$currentPluginName] is aliased as [grails.plugin.location.$currentPluginName] to the location [$pluginReference] in grails-app/conf/BuildConfig.groovy.
You cannot upgrade a plugin that is configured via BuildConfig.groovy, remove the configuration to continue.""" );
        }

        Resource currentInstall = getPluginDirForName(currentPluginName)
        PluginBuildSettings pluginSettings = pluginSettings
        if(currentInstall?.exists()) {
if(pluginSettings.isInlinePluginLocation(currentInstall)) {
cleanupPluginInstallAndExit("The plugin you are trying to install [${fullPluginName}] is already configured as an inplace plugin in grails-app/conf/BuildConfig.groovy. You cannot overwrite inplace plugins." );
}
else if(!isInteractive || confirmInput("You currently already have a version of the plugin installed [$currentInstall.filename]. Do you want to upgrade this version?", "upgrade.${fullPluginName}.plugin")) {
                ant.delete(dir:currentInstall.file)
            }
            else {
                cleanupPluginInstallAndExit("Plugin $fullPluginName install aborted" );
            }
        }
        installedPlugins << pluginInstallPath

        if (checkPluginPath(pluginInstallPath)) {
            ant.delete(dir: pluginInstallPath, failonerror: false)
            ant.mkdir(dir: pluginInstallPath)
            ant.unzip(dest: pluginInstallPath, src: "${pluginsBase}/grails-${fullPluginName}.zip")
            println "Installed plugin ${fullPluginName} to location ${pluginInstallPath}."
        }
        else {
            println "Cannot install plugin. Plugin install would override inline plugin configuration which is not allowed."
            exit 1
        }


        def pluginXmlFile = new File("${pluginInstallPath}/plugin.xml")
        if (!pluginXmlFile.exists()) {
            cleanupPluginInstallAndExit("Plugin $fullPluginName is not a valid Grails plugin. No plugin.xml descriptor found!")
        }
        def pluginXml = new XmlSlurper().parse(pluginXmlFile)
        def pluginName = pluginXml.@name.toString()
        def pluginVersion = pluginXml.@version.toString()
        def pluginGrailsVersion = pluginXml.@grailsVersion.toString()
        if(pluginGrailsVersion) {
            if(!GrailsPluginUtils.isValidVersion(GrailsUtil.grailsVersion, pluginGrailsVersion)) {
                cleanupPluginInstallAndExit("Plugin $fullPluginName requires version [${pluginGrailsVersion}] of Grails which your current Grails installation does not meet. Please try install a different version of the plugin or Grails.")
            }
        }

        // Add the plugin's directory to the binding so that any event
        // handlers in the plugin have access to it. Normally, this
        // variable is added in GrailsScriptRunner, but this plugin
        // hasn't been installed by that point.
        binding.setVariable("${GrailsNameUtils.getPropertyNameForLowerCaseHyphenSeparatedName(pluginName)}PluginDir", new File(pluginInstallPath).absoluteFile)

        def dependencies = [:]

        for (dep in pluginXml.dependencies.plugin) {
            def depName = dep.@name.toString()
            String depVersion = dep.@version.toString()
            if(isCorePlugin(depName)) {
                def grailsVersion = GrailsUtil.getGrailsVersion()
                if(!GrailsPluginUtils.isValidVersion(grailsVersion, depVersion ))
                    cleanupPluginInstallAndExit("Plugin requires version [$depVersion] of Grails core, but installed version is [${grailsVersion}]. Please upgrade your Grails installation and try again.")
            }
            else {
                dependencies[depName] = depVersion
                def depDirName = GrailsNameUtils.getScriptName(depName)
                def depPluginDir = getPluginDirForName(depDirName)?.file
                if (!depPluginDir?.exists()) {
                    event("StatusUpdate", ["Plugin dependency [$depName] not found. Attempting to resolve..."])
                    // recursively install dependent plugins
                    def upperVersion = GrailsPluginUtils.getUpperVersion(depVersion)
                    def installVersion = upperVersion
                    if(installVersion == '*') {
                        installVersion = grailsSettings.defaultPluginSet.contains(depDirName) ? GrailsUtil.getGrailsVersion() : null
                    }

                    def release = cacheKnownPlugin(depDirName, installVersion)

                    ant.copy(file:"${pluginsBase}/grails-${release}.zip",tofile:"${pluginsDirPath}/grails-${release}.zip")

                    installPluginForName(release)
                    dependencies.remove(depName)
                }
                else {
                    def dependency = readPluginXmlMetadata(depDirName)
def dependencyVersion = dependency.@version.toString()
                    if (!GrailsPluginUtils.isValidVersion(dependencyVersion, depVersion)) {
                        cleanupPluginInstallAndExit("Plugin requires version [$depVersion] of plugin [$depName], but installed version is [${dependencyVersion}]. Please upgrade this plugin and try again.")
                    }
                    else {
                        dependencies.remove(depName)
                    }
                }
            }
        }

        if (dependencies) {
            ant.delete(dir: "${pluginInstallPath}", quiet: true, failOnError: false)
            clean()

            cleanupPluginInstallAndExit("Failed to install plugin [${fullPluginName}]. Missing dependencies: ${dependencies.inspect()}")

        }
        else {
            def pluginDependencyDescriptor = new File("$pluginInstallPath/dependencies.groovy")
            if(pluginDependencyDescriptor.exists()) {
                println "Resolving plugin JAR dependencies"
                BuildSettings settings = grailsSettings
                def callable = settings.pluginDependencyHandler()
                callable.call(new File("$pluginInstallPath"))
                IvyDependencyManager dependencyManager = settings.dependencyManager
                dependencyManager.resetGrailsPluginsResolver()
                def resolveReport = dependencyManager.resolveDependencies(IvyDependencyManager.RUNTIME_CONFIGURATION)
                if(resolveReport.hasError()) {
                    cleanupPluginInstallAndExit("Failed to install plugin [${fullPluginName}]. Plugin has missing JAR dependencies.")
                }
            }
            else {
                def pluginJars = resolveResources("file:${pluginInstallPath}/lib/*.jar")
                for(jar in pluginJars) {
                    rootLoader.addURL(jar.URL)
                }
            }

            // proceed _Install.groovy plugin script if exists
            def installScript = new File("${pluginInstallPath}/scripts/_Install.groovy")
            runPluginScript(installScript, fullPluginName, "post-install script")

            registerPluginWithMetadata(pluginName, pluginVersion)


            def providedScripts = resolveResources("file:${pluginInstallPath}/scripts/*.groovy").findAll { !it.filename.startsWith('_')}
            event("StatusFinal", ["Plugin ${fullPluginName} installed"])
            if (providedScripts) {
                println "Plug-in provides the following new scripts:"
                println "------------------------------------------"
                providedScripts.file.each {file ->
                    def scriptName = GrailsNameUtils.getScriptName(file.name)
                    println "grails ${scriptName}"
                }
            }

            File pluginEvents = new File("${pluginInstallPath}/scripts/_Events.groovy")
            if (pluginEvents.exists()) {
                println "Found events script in plugin ${pluginName}"
                eventListener.loadEventsScript(pluginEvents)
            }
            
            event("PluginInstalled", [fullPluginName])
        }

    }
}


doInstallPluginFromURL = { URL url ->
    withPluginInstall {
        downloadRemotePlugin(url, pluginsBase)
    }
}

doInstallPluginZip = { File file ->
    withPluginInstall {
        cacheLocalPlugin(file)
    }
}

doInstallPlugin = { name, version = null ->
    withPluginInstall {
        cacheKnownPlugin(name,version)
    }
}

doInstallPluginFromGrailsHomeOrRepository = { name, version = null ->
    withPluginInstall {
        boolean hasVersion = name && version
        File pluginZip
        if(hasVersion) {
            def zipName = "grails-${name}-${version}"
            pluginZip = new File("${grailsSettings.grailsHome}/plugins/${zipName}.zip")
            if(!pluginZip.exists()) {
                pluginZip = new File("${grailsSettings.grailsWorkDir}/plugins/${zipName}.zip")
            }
        }
        else {
           def zipNameNoVersion = "grails-${name}"
           pluginZip = findZip(zipNameNoVersion,"${grailsSettings.grailsHome}/plugins")
           if(!pluginZip?.exists()) {
              pluginZip = findZip(zipNameNoVersion,"${grailsSettings.grailsWorkDir}/plugins")
           }
        }


        if(pluginZip?.exists()) {
           cacheLocalPlugin(pluginZip)
        }
        else {
           cacheKnownPlugin(name,version)
        }
    }
}

File findZip(String name, String dir) {
    new File(dir).listFiles().find {it.name.startsWith(name)}
}

private withPluginInstall(Closure callable) {
    try {
        fullPluginName = callable.call()
        completePluginInstall(fullPluginName)
    }
    catch (e) {
        logError("Error installing plugin: ${e.message}", e)
        exit(1)
    }
}


private completePluginInstall (fullPluginName) {
    classpath ()
    println "Installing plugin $fullPluginName"
    installPluginForName(fullPluginName)
}



def registerPluginWithMetadata(String pluginName, pluginVersion) {
    metadata['plugins.' + pluginName] = pluginVersion
    metadata.persist()
}


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 writePluginsFile() {
    pluginsListFile.parentFile.mkdirs()

    Transformer transformer = TransformerFactory.newInstance().newTransformer()
    transformer.setOutputProperty(OutputKeys.INDENT, "true")
    transformer.transform(new DOMSource(document), new StreamResult(pluginsListFile))
}

def parseRemoteXML(url) {
    fetchPluginListFile(url).withReader() { DOMBuilder.parse(it) }
}


def buildBinaryPluginInfo(root, pluginName ){
    // split plugin name in form of 'plugin-name-0.1' to name ('plugin-name') and version ('0.1')
    def matcher = (pluginName =~ /^([^\d]+)-(.++)/)
    // convert to new plugin naming convention (MyPlugin -> my-plugin)
    def name = GrailsNameUtils.getScriptName(matcher[0][1])
    def release = matcher[0][2]
    use(DOMCategory) {
        def pluginNode = root.'plugin'.find {it.'@name' == name}
        if (!pluginNode) {
            pluginNode = builder.'plugin'(name: name)
            root.appendChild(pluginNode)
        }
        def releaseNode = pluginNode.'release'.find {it.'@version' == release && it.'@type' == 'zip'}
        // SVN releases have higher precedence than binary releases
        if (pluginNode.'release'.find {it.'@version' == release && it.'@type' == 'svn'}) {
            if (releaseNode) pluginNode.removeChild(releaseNode)
            return
        }
        if (!releaseNode) {
            releaseNode = builder.'release'(type: 'zip', version: release) {
                title("This is a zip release, no info available for it")
                file("${pluginBinaryDistURL}/grails-${pluginName}.zip")
            }
            pluginNode.appendChild(releaseNode)
        }
    }
}


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"
        }
    }
}

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()
            def ver = repo.getFile(file , (long)-1L, props , baos)
            def mimeType = props.getSVNPropertyValue(SVNProperty.MIME_TYPE)
            if (!SVNProperty.isTextMimeType(mimeType)) {
                throw new Exception("Must be a text file..")
            }
            def bytes = baos.toByteArray()
            def str = new String(bytes, 'utf-8')
            def r = new StringReader(str)
            return r
        }
        return rdr
    }
    // attempt using URL
    return new URL(url)
}

def fetchRemote(url, closure) {
    def idx = url.lastIndexOf('/')
    def svnUrl = url.substring(0,idx)
    def file = url.substring(idx+1,url.length())

    withSVNRepo(svnUrl) { repo ->
        // determine if the file exists
        SVNNodeKind nodeKind = repo.checkPath(file , -1)
        if (nodeKind == SVNNodeKind.NONE) {
            throw new Exception("The file does not exist.: " + url)
        } else if (nodeKind != SVNNodeKind.FILE) {
            throw new Exception("Error not a file..: " + url)
        }
        // present w/ file etc for repo extraction
        closure.call(repo, file)
    }
}

def isSecureUrl(Object url) {
    url.startsWith('https://') || url.startsWith('svn://')
}

withSVNRepo = { url, closure ->
    // create a authetication manager using the defaults
    ISVNAuthenticationManager authMgr = getAuthFromUrl(url,"discovery")
    
    // create the url
    def svnUrl = SVNURL.parseURIEncoded(url)
    def repo = SVNRepositoryFactory.create(svnUrl, null)
    repo.authenticationManager = authMgr
    // trigger authentication failure?.?.
    try {
        repo.getLatestRevision()
    } catch (SVNAuthenticationException ex) {
        event "StatusUpdate", ["Default authentication failed please enter credentials."]
        // prompt for login information..
        ant.input(message:"Please enter your SVN username:", addproperty:"user.svn.username")
        ant.input(message:"Please enter your SVN password:", addproperty:"user.svn.password")
        def username = ant.antProject.properties."user.svn.username"
        def password = ant.antProject.properties."user.svn.password"
        authMgr = SVNWCUtil.createDefaultAuthenticationManager( username , password )
        repo.setAuthenticationManager(authMgr)
        // don't bother to catch this one let it bubble up..
        repo.getLatestRevision()
    }
    // make sure the closure return is returned..
    closure.call(repo)
}

/**
* Check to see if the plugin directory is in plugins home.
*/
checkPluginPath = { pluginDir ->
  // insure all the directory is in the pluginsHome
  checkPluginPathWithPluginDir(pluginsHome, pluginDir) ||
          checkPluginPathWithPluginDir(globalPluginsDirPath, pluginDir)
}
def checkPluginPathWithPluginDir (pluginsHome, pluginDir) {
    def absPluginsHome = pluginsHome instanceof File ? pluginsHome : new File (pluginsHome).absolutePath
    if (pluginDir instanceof File) {
        pluginDir.absolutePath.startsWith(absPluginsHome)
    }
    else {
        new File(pluginDir).absolutePath.startsWith(absPluginsHome)
    }
}
Something went wrong with that request. Please try again.