/
PluginInstallEngine.groovy
529 lines (458 loc) · 21.3 KB
/
PluginInstallEngine.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
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.resolve
import grails.build.logging.GrailsConsole
import grails.util.BuildSettings
import grails.util.GrailsNameUtils
import grails.util.Metadata
import grails.util.PluginBuildSettings
import groovy.transform.CompileStatic
import org.apache.ivy.plugins.latest.LatestTimeStrategy
import org.apache.ivy.plugins.resolver.ChainResolver
import org.apache.ivy.plugins.resolver.FileSystemResolver
import org.codehaus.groovy.grails.cli.ScriptExitException
import org.codehaus.groovy.grails.io.support.FileSystemResource
import org.codehaus.groovy.grails.io.support.Resource
import org.codehaus.groovy.grails.plugins.BasicGrailsPluginInfo
import org.codehaus.groovy.grails.plugins.GrailsPluginInfo
import org.codehaus.groovy.grails.plugins.GrailsPluginUtils
import org.codehaus.groovy.grails.plugins.GrailsVersionUtils
import org.codehaus.groovy.grails.cli.interactive.InteractiveMode
import org.codehaus.groovy.grails.io.support.IOUtils
/**
* Manages the installation and uninstallation of plugins from a Grails project.
*
* @author Graeme Rocher
* @since 1.3
*/
class PluginInstallEngine {
static final List CORE_PLUGINS = [
'codecs', 'controllers', 'converters', 'core', 'dataSource', 'domainClass',
'filters', 'groovyPages', 'i18n', 'logging', 'mimeTypes',
'services', 'servlets', 'urlMappings', 'validation']
Closure errorHandler = { String msg -> throw new ScriptExitException(msg) }
Closure eventHandler = { String name, String msg -> GrailsConsole.instance.updateStatus msg }
Closure pluginScriptRunner
Closure postInstallEvent
Closure postUninstallEvent
/**
* plugins that were installed in the last execution of installPlugin
*/
List installedPlugins = []
def pluginDirVariableStore = [:]
boolean isInteractive = true
protected Metadata metadata
protected PluginBuildSettings pluginSettings
protected BuildSettings settings
protected applicationPluginsLocation
protected ant
protected PluginResolveEngine resolveEngine
PluginInstallEngine(BuildSettings settings, PluginBuildSettings pbs = GrailsPluginUtils.getPluginBuildSettings(settings), Metadata md = Metadata.getCurrent(), AntBuilder ant = new AntBuilder()) {
if (settings == null) throw new IllegalArgumentException("Argument [settings] cannot be null")
if (pbs == null) throw new IllegalArgumentException("Argument [pbs] cannot be null")
if (md == null) throw new IllegalArgumentException("Argument [md] cannot be null")
if (ant== null) throw new IllegalArgumentException("Argument [ant] cannot be null")
applicationPluginsLocation = settings.getProjectPluginsDir()
pluginSettings = pbs
this.settings = settings
this.ant = ant
metadata = md
resolveEngine = new PluginResolveEngine(settings.dependencyManager, settings)
}
@CompileStatic
boolean resolveAndInstallDepdendencies() {
// we get the 'build' and 'test' dependencies because that is the scope that
// includes all possible plugins in all scopes
def pluginZips = (settings.pluginTestDependencies + settings.pluginBuildDependencies)
boolean hasNewPluginInstalls = installResolvePlugins(pluginZips)
checkPluginsToUninstall(pluginZips.toList())
return hasNewPluginInstalls
}
@CompileStatic
boolean installedResolvedPlugins() {
def pluginZips = (settings.pluginTestDependencies + settings.pluginBuildDependencies)
installResolvePlugins(pluginZips)
}
@CompileStatic
protected boolean installResolvePlugins(Collection<File> pluginZips) {
try {
boolean newInstalls = false
for (zip in pluginZips) {
if ( installResolvedPlugin(zip) ) {
newInstalls = true
}
}
return newInstalls
} finally {
final im = InteractiveMode.current
if(im) {
im.refresh()
}
}
}
@CompileStatic
void checkPluginsToUninstall() {
def pluginZips = (settings.pluginTestDependencies + settings.pluginBuildDependencies).toList()
checkPluginsToUninstall(pluginZips)
}
@CompileStatic
void checkPluginsToUninstall(List<File> pluginZips) {
List<GrailsPluginInfo> resolvedPluginInfos = pluginZips.collect { File f -> readPluginInfoFromZip(f.absolutePath) }
GrailsPluginInfo[] installedPluginInfos = pluginSettings.getPluginInfos()
def pluginsToUninstall = installedPluginInfos.findAll { GrailsPluginInfo info -> !resolvedPluginInfos.any { GrailsPluginInfo resolvedInfo -> info.fullName == resolvedInfo.fullName}}
for (GrailsPluginInfo pluginInfo in pluginsToUninstall) {
Resource pluginDir = pluginInfo.pluginDir
final pluginDirFile = pluginDir.file.canonicalFile
if ((pluginDirFile == settings.baseDir) || settings.isInlinePluginLocation(pluginDirFile)) continue
if (pluginSettings.isGlobalPluginLocation(pluginDir)) {
uninstallPlugin(pluginInfo.name, pluginInfo.version)
}
else {
uninstallPlugin(pluginInfo.name, pluginInfo.version)
}
}
}
/**
* Installs a plugin for the given name and optional version.
*
* @param name The plugin name
* @param version The plugin version (optional)
* @return true if installed and not cancelled by user
*/
boolean installPlugin(String name, String version = null) {
installedPlugins.clear()
def pluginZip = resolveEngine.resolvePluginZip(name, version)
if (!pluginZip) {
errorHandler "Plugin not found for name [$name] and version [${version ?: 'not specified'}]"
}
try {
(name, version) = readMetadataFromZip(pluginZip.absolutePath)
return installPluginZipInternal(name, version, pluginZip)
}
catch (e) {
errorHandler "Error installing plugin: ${e.message}"
}
}
/**
* Installs a plugin from the given ZIP file. Differs from #installPlugin(zipFile) in that the plugin to be installed is assumed to already be resolved and
* hence not placed in the users local cache
*
* @param zipFile The plugin zip file
*/
boolean installResolvedPlugin(File zipFile) {
def inlinePlugins = settings.config.grails.plugin.location
if (!zipFile.exists()) {
errorHandler "Plugin zip not found at location: ${zipFile.absolutePath}. Potential corrupt cache. Try running: grails --refresh-dependencies compile"
}
def (name, version) = readMetadataFromZip(zipFile.absolutePath)
/*
* Determine if the plugin is currently configured to be used inline.
* If the plugin is NOT configured to run inline, install it.
* Otherwise, remove the previously installed ZIP file if present
* to prevent duplicate class errors during compilation.
*/
if (!inlinePlugins.find {
def pluginName = it.key.toString()
if (pluginName.contains(':')) {
pluginName = pluginName.split(':')[-1]
}
return pluginName.equals(name)
} ) {
installPluginZipInternal name, version, zipFile, false, true
} else {
// Remove the plugin to prevent duplicate class compile errors with inline version.
uninstallPlugin name, version
}
}
/**
* Installs a plugin from the given ZIP file
*
* @param zipFile The plugin zip file
*/
boolean installPlugin(File zipFile, boolean overwrite = false) {
if (!zipFile.exists()) {
errorHandler "Plugin zip not found at location: ${zipFile.absolutePath}. Potential corrupt cache. Try running: grails --refresh-dependencies compile"
}
def (name, version) = readMetadataFromZip(zipFile.absolutePath)
def parentDir = zipFile.canonicalFile.parentFile
final currentDependencyManager = resolveEngine.dependencyManager
final ivySettings = currentDependencyManager.ivySettings
IvyDependencyManager dependencyManager = new IvyDependencyManager(currentDependencyManager.applicationName,
currentDependencyManager.applicationVersion, settings, Metadata.current, ivySettings)
dependencyManager.chainResolver = new ChainResolver(name: "chain", settings: ivySettings)
dependencyManager.parseDependencies {
log "warn"
useOrigin true
cacheDir ivySettings.getDefaultCache().absolutePath
repositories {
grailsHome()
def pluginResolver = new FileSystemResolver(name: "$name plugin install resolver")
final parentPath = parentDir.canonicalPath
pluginResolver.addArtifactPattern("${parentPath}/[module]-[revision].[ext]")
pluginResolver.addArtifactPattern("${parentPath}/grails-[module]-[revision].[ext]")
pluginResolver.settings = ivySettings
pluginResolver.latestStrategy = new LatestTimeStrategy()
pluginResolver.changingPattern = ".*SNAPSHOT"
pluginResolver.setCheckmodified(true)
resolver pluginResolver
}
plugins {
compile ":$name:$version"
}
}
final report = dependencyManager.resolveDependencies()
if (report.hasError()) {
errorHandler "Could not resolve all dependencies for plugin $name"
}
final reports = report.allArtifactsReports
if (!reports) {
return
}
final localFile = reports[0].localFile
ant.mkdir(dir:"${settings.grailsWorkDir}/cached-installed-plugins")
ant.copy(file:localFile, tofile:"${settings.grailsWorkDir}/cached-installed-plugins/$name-${version}.zip")
installPluginZipInternal name, version, localFile, overwrite
}
/**
* Installs a plugin from the given URL
*
* @param zipURL The zip URL
*/
boolean installPlugin(URL zipURL) {
def s = zipURL.toString()
def filename = s[s.lastIndexOf("/")..-1]
def file = File.createTempFile(filename[0..-4], ".zip")
file.deleteOnExit()
eventHandler "StatusUpdate", "Downloading zip ${zipURL}. Please wait..."
try {
ant.get(src: zipURL, dest: file, verbose:"on")
}
catch (e) {
errorHandler "Error downloading plugin ${zipURL}: ${e.message}"
}
installPlugin(file, true)
}
protected boolean installPluginZipInternal(String name, String version, File pluginZip,
boolean overwrite = false, boolean isResolve = false) {
def fullPluginName = "$name-$version"
def pluginInstallPath = "$applicationPluginsLocation/$fullPluginName"
assertNoExistingInlinePlugin(name)
def abort = checkExistingPluginInstall(name, version, pluginZip,isResolve)
if (abort && !overwrite) {
return false
}
eventHandler "StatusUpdate", "Installing zip ${pluginZip.name}..."
installedPlugins << pluginInstallPath
if (isNotInlinePluginLocation(new File(pluginInstallPath))) {
ant.delete(dir: pluginInstallPath, failonerror: false)
ant.mkdir(dir: pluginInstallPath)
ant.unzip(dest: pluginInstallPath, src: pluginZip)
eventHandler "StatusUpdate", "Installed plugin ${fullPluginName}"
}
else {
errorHandler "Cannot install plugin. Plugin install would override inline plugin configuration which is not allowed."
}
def pluginXmlFile = new File(pluginInstallPath, "plugin.xml")
if (!pluginXmlFile.exists()) {
errorHandler("Plugin $fullPluginName is not a valid Grails plugin. No plugin.xml descriptor found!")
}
def pluginXml = IOUtils.createXmlSlurper().parse(pluginXmlFile)
def pluginName = pluginXml.@name.toString()
def pluginVersion = pluginXml.@version.toString()
def pluginGrailsVersion = pluginXml.@grailsVersion.toString()
assertGrailsVersionValid(fullPluginName, pluginGrailsVersion)
// 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.
pluginDirVariableStore["${GrailsNameUtils.getPropertyNameForLowerCaseHyphenSeparatedName(pluginName)}PluginDir"] = new File(pluginInstallPath).absoluteFile
// proceed _Install.groovy plugin script if exists
def installScript = new File(pluginInstallPath, "scripts/_Install.groovy")
runPluginScript(installScript, fullPluginName, "post-install script")
pluginSettings.clearCache()
pluginSettings.registerNewPluginInstall(pluginZip)
postInstall(pluginInstallPath)
eventHandler("PluginInstalled", fullPluginName)
true
}
/**
* Reads plugin metadata from a plugin zip file and returns a list containing the plugin name, version and
* XML metadata. Designed for use with Groovy's multiple assignment operator
*
* @param zipLocation The zip location
* @return A list
*/
List readMetadataFromZip(String zipLocation) {
def list = pluginSettings.readMetadataFromZip(zipLocation)
if (list == null) {
errorHandler "Zip $zipLocation is not a valid plugin"
}
return list
}
/**
* Reads plugin info from the zip file location
*
* @param zipLocation The zip location
* @return
*/
GrailsPluginInfo readPluginInfoFromZip(String zipLocation) {
def (name, version, xml) = readMetadataFromZip(zipLocation)
def info = new BasicGrailsPluginInfo(new FileSystemResource(new File(zipLocation)))
info.name = name
info.version = version
return info
}
/**
* Checks an existing plugin path to install and returns true if the installation should be aborted or false if it should continue
*
* If an error occurs the errorHandler is invoked.
*
* @param name The plugin name
* @param version The plugin version
* @return true if the installation should be aborted
*/
protected boolean checkExistingPluginInstall(String name, version, File pluginZip, boolean isResolve = true) {
Resource currentInstall = pluginSettings.getPluginDirForName(name)
def inlinePlugins = settings.config.grails.plugin.location
if (!currentInstall?.exists()) {
return false
}
/*
* If the plugin to be installed is currently configured to be inline,
* do not install it. This is because we want to use the inline over
* the modified dependency artifact. The comparison to find the inline
* plugin uses "endsWith", as inline plugins can be declared with a full
* vector in settings.groovy (i.e. 'com.mycompany:my-plugin")
*/
if (inlinePlugins.find {
def pluginName = it.key.toString()
if (pluginName.contains(':')) {
pluginName = pluginName.split(':')[-1]
}
return pluginName.equals(name)
} ) {
return true
}
PluginBuildSettings pluginSettings = pluginSettings
def pluginDir = currentInstall.file.canonicalFile
def pluginInfo = pluginSettings.getPluginInfo(pluginDir.absolutePath)
// if the versions are the same no need to continue
boolean isSnapshotUpdate = pluginDir.lastModified() < pluginZip.lastModified() && version.toString().endsWith("-SNAPSHOT")
if (version == pluginInfo?.version && !isSnapshotUpdate) {
if (!isResolve) {
GrailsConsole.instance.addStatus("Plugin '$name' with version '${pluginInfo?.version}' is already installed")
}
return true
}
if (pluginSettings.isInlinePluginLocation(currentInstall)) {
errorHandler("The plugin you are trying to install [$name-${version}] is already configured as an inplace plugin in grails-app/conf/BuildConfig.groovy. You cannot overwrite inplace plugins.")
return true
}
def upgradeOrDowngrade = !pluginInfo || GrailsVersionUtils.isVersionGreaterThan(pluginInfo.version, version) ? 'upgrade' : 'downgrade'
if (!isInteractive || isSnapshotUpdate || confirmInput("You currently already have a version of the plugin installed [${pluginDir.name}]. Do you want to $upgradeOrDowngrade to [$name-$version]? ")) {
if (isSnapshotUpdate) {
GrailsConsole.instance.addStatus("Updating snapshot plugin '$name' with version '${pluginInfo?.version}'")
}
ant.delete(dir: currentInstall.file)
return false
}
eventHandler("StatusUpdate", "Plugin $name-$version install aborted")
return true
}
protected void assertNoExistingInlinePlugin(String name) {
def inlinePlugins = settings.config.grails.plugin.location
if (inlinePlugins.containsKey(name)) {
def pluginReference = inlinePlugins[name]
errorHandler("""\
Plugin [$name] is aliased as [grails.plugin.location.$name] 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.""")
}
}
private assertGrailsVersionValid(String pluginName, String grailsVersion) {
if (!grailsVersion || GrailsPluginUtils.isValidVersion(settings.grailsVersion, grailsVersion)) {
return
}
errorHandler("Plugin " + pluginName + " requires version [" + grailsVersion +
"] of Grails which your current Grails installation does not meet. " +
"Please try install a different version of the plugin or Grails.")
}
/**
* Uninstalls a plugin for the given name and optional version
*
* @param name The plugin name
* @param version The version
*/
void uninstallPlugin(String name, String version = null) {
try {
String pluginKey = "plugins.$name"
if (metadata.remove(pluginKey)) {
metadata.persist()
}
def pluginDir
if (name && version) {
pluginDir = new File(applicationPluginsLocation, "$name-$version")
}
else {
pluginDir = pluginSettings.getPluginDirForName(name)?.file
}
if (pluginDir?.exists()) {
def uninstallScript = new File(pluginDir, "scripts/_Uninstall.groovy")
runPluginScript(uninstallScript, pluginDir.canonicalFile.name, "uninstall script")
if (isNotInlinePluginLocation(pluginDir)) {
ant.delete(dir:pluginDir, failonerror:true)
}
postUninstall()
eventHandler "PluginUninstalled", "Uninstalled plugin [${name}]."
GrailsConsole.getInstance().addStatus("Uninstalled plugin [$name]")
}
else {
GrailsConsole.getInstance().warning("No plugin [$name${version ? '-' + version : ''}] installed, cannot uninstall")
}
}
catch (e) {
errorHandler("An error occurred installing the plugin [$name${version ? '-' + version : ''}]: ${e.message}")
}
}
private void runPluginScript(File scriptFile, fullPluginName, msg) {
if (pluginScriptRunner == null) {
return
}
if (pluginScriptRunner.maximumNumberOfParameters < 3) {
throw new IllegalStateException("The [pluginScriptRunner] closure property must accept at least 3 arguments")
}
pluginScriptRunner.call(scriptFile, fullPluginName, msg)
}
/**
* Check to see if the plugin directory is in plugins home.
*/
boolean isNotInlinePluginLocation(File pluginDir) {
// insure all the directory is in the pluginsHome
pluginDir.absolutePath.startsWith(applicationPluginsLocation.absolutePath)
}
protected postUninstall() {
// Update the cached dependencies in grailsSettings, and add new jars to the root loader
pluginSettings.clearCache()
postUninstallEvent?.call()
}
protected postInstall(String pluginInstallPath) {
// Update the cached dependencies in grailsSettings, and add new jars to the root loader
pluginSettings.clearCache()
postInstallEvent?.call(pluginInstallPath)
}
private boolean confirmInput(String msg) {
GrailsConsole.getInstance().userInput(msg, ['y','n'] as String[]) == 'y'
}
}