Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -143,13 +143,14 @@ dependencies {

spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0'

testRuntimeOnly "org.slf4j:slf4j-simple:${versions.slf4j}"
testRuntimeOnly(project(':')) {
because 'Tests are using Grapes'
capabilities {
requireCapability 'org.apache.groovy:groovy-grapes'
}
}
testRuntimeOnly projects.groovyGrapeIvy

testRuntimeOnly(project(':')) {
because 'Tests are using GPars'
capabilities {
Expand Down
332 changes: 251 additions & 81 deletions gradle/verification-metadata.xml

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ def subprojects = [
'groovy-datetime',
'groovy-dateutil',
'groovy-docgenerator',
'groovy-grape-ivy',
'groovy-grape-maven',
'groovy-grape-test',
'groovy-groovydoc',
'groovy-groovysh',
'groovy-jmx',
Expand Down
158 changes: 158 additions & 0 deletions src/main/groovy/groovy/grape/GrapeUtil.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package groovy.grape

import groovy.transform.CompileStatic
import org.apache.groovy.plugin.GroovyRunner
import org.apache.groovy.plugin.GroovyRunnerRegistry
import org.codehaus.groovy.reflection.CachedClass
import org.codehaus.groovy.reflection.ClassInfo
import org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner
import org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl

import java.util.jar.JarFile
import java.util.zip.ZipEntry
import java.util.zip.ZipException
import java.util.zip.ZipFile

/**
* Utility methods shared between GrapeIvy and GrapeMaven implementations.
*/
@CompileStatic
class GrapeUtil {

private static final String METAINF_PREFIX = 'META-INF/services/'
private static final String RUNNER_PROVIDER_CONFIG = GroovyRunner.name
private static final boolean DEBUG_GRAPE = Boolean.getBoolean('groovy.grape.debug')

/**
* Adds a URI to a classloader's classpath via reflection.
*/
static void addURL(ClassLoader loader, URI uri) {
// Dynamic invocation needed as addURL is not part of ClassLoader interface
loader.metaClass.invokeMethod(loader, 'addURL', uri.toURL())
}
Comment on lines +47 to +50
Copy link

Copilot AI Mar 11, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GrapeUtil is @CompileStatic but addURL uses loader.metaClass.invokeMethod(...), which relies on Groovy's dynamic metaClass property and is likely to fail static compilation. Consider marking addURL as @CompileDynamic (as the old Ivy implementation did) or using a statically-compilable reflective call (e.g., via InvokerHelper/reflection) to invoke addURL.

Copilot uses AI. Check for mistakes.

/**
* Processes and registers category methods (extension modules) from a JAR file.
*
* @param loader the classloader to register methods with
* @param file the JAR file to process
*/
static void processExtensionMethods(ClassLoader loader, File file) {
// register extension methods if jar
if (file.getName().toLowerCase().endsWith('.jar')) {
def mcRegistry = GroovySystem.metaClassRegistry
if (mcRegistry instanceof MetaClassRegistryImpl) {
try (JarFile jar = new JarFile(file)) {
ZipEntry entry = jar.getEntry(ExtensionModuleScanner.MODULE_META_INF_FILE)
if (!entry) {
entry = jar.getEntry(ExtensionModuleScanner.LEGACY_MODULE_META_INF_FILE)
}
if (entry) {
Properties props = new Properties()

try (InputStream is = jar.getInputStream(entry)) {
props.load(is)
}

Map<CachedClass, List<MetaMethod>> metaMethods = [:]
mcRegistry.registerExtensionModuleFromProperties(props, loader, metaMethods)
// add old methods to the map
metaMethods.each { CachedClass c, List<MetaMethod> methods ->
// GROOVY-5543: if a module was loaded using grab, there are chances that subclasses
// have their own ClassInfo, and we must change them as well!
Set<CachedClass> classesToBeUpdated = [c].toSet()
ClassInfo.onAllClassInfo { ClassInfo info ->
if (c.getTheClass().isAssignableFrom(info.getCachedClass().getTheClass())) {
classesToBeUpdated << info.getCachedClass()
}
}
classesToBeUpdated*.addNewMopMethods(methods)
}
}
} catch (ZipException e) {
throw new RuntimeException("Grape could not load jar '$file'", e)
}
}
}
}

/**
* Searches the given File for known service provider configuration files to process.
*
* @param loader used to locate service provider files
* @param f ZipFile in which to search for services
* @return a collection of service provider files that were found
*/
static Collection<String> processMetaInfServices(ClassLoader loader, File f) {
List<String> services = []
try (ZipFile zf = new ZipFile(f)) {
// TODO: remove in a future release (replaced by GroovyRunnerRegistry)
String providerConfig = 'org.codehaus.groovy.plugins.Runners'
ZipEntry pluginRunners = zf.getEntry(METAINF_PREFIX + providerConfig)
if (pluginRunners != null) {
services.add(providerConfig)

try (InputStream is = zf.getInputStream(pluginRunners)) {
processRunners(is, f.getName(), loader)
}
}
// GroovyRunners are loaded per ClassLoader using a ServiceLoader so here
// it only needs to be indicated that the service provider file was found
if (zf.getEntry(METAINF_PREFIX + RUNNER_PROVIDER_CONFIG) != null) {
services.add(RUNNER_PROVIDER_CONFIG)
}
} catch (ZipException ignore) {
// ignore files we can't process, e.g. non-jar/zip artifacts
if (DEBUG_GRAPE) {
System.err.println "Grape could not process file '$f' for service provider configuration: ${ignore.message}"
}
}
services
}

/**
* Processes and registers Groovy runner implementations from a service provider file.
*
* @param is the input stream containing runner class names
* @param name the name to register the runners under
* @param loader the classloader to load runner classes from
*/
static void processRunners(InputStream is, String name, ClassLoader loader) {
GroovyRunnerRegistry registry = GroovyRunnerRegistry.instance
is.getText().readLines()*.trim().each { String line ->
if (!line.isEmpty() && line[0] != '#') {
try {
registry[name] = (GroovyRunner) loader.loadClass(line).getDeclaredConstructor().newInstance()
} catch (Exception e) {
throw new IllegalStateException("Error registering runner class '$line'", e)
}
}
}
}

static boolean checkForRunner(Collection<String> services) {
services.contains(RUNNER_PROVIDER_CONFIG)
}

static void registryLoad(ClassLoader classLoader) {
GroovyRunnerRegistry.instance.load(classLoader)
}
}
46 changes: 28 additions & 18 deletions src/main/groovy/org/codehaus/groovy/tools/GrapeMain.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
package org.codehaus.groovy.tools

import groovy.grape.Grape
import org.apache.ivy.util.DefaultMessageLogger
import org.apache.ivy.util.Message
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.Option
Expand Down Expand Up @@ -65,12 +63,14 @@ class GrapeMain implements Runnable {
parser.subcommands.findAll { k, v -> k != 'help' }.each { k, v -> v.addMixin('helpOptions', new HelpOptionsMixin()) }

grape.parser = parser
parser.execute(args)
int exitCode = parser.execute(args)
System.exit(exitCode)
}

void run() {
if (unmatched) {
System.err.println "grape: '${unmatched[0]}' is not a grape command. See 'grape --help'"
throw new CommandLine.ParameterException(parser, "Unknown command: ${unmatched[0]}")
} else {
parser.usage(System.out) // if no subcommand was specified
}
Expand All @@ -84,20 +84,20 @@ class GrapeMain implements Runnable {
}

@SuppressWarnings('UnusedPrivateMethod') // used in run()
private void setupLogging(int defaultLevel = Message.MSG_INFO) {
private void setupLogging(int defaultLevel = 2) {
int level = defaultLevel
if (quiet) {
Message.defaultLogger = new DefaultMessageLogger(Message.MSG_ERR)
level = 0
} else if (warn) {
Message.defaultLogger = new DefaultMessageLogger(Message.MSG_WARN)
level = 1
} else if (info) {
Message.defaultLogger = new DefaultMessageLogger(Message.MSG_INFO)
level = 2
} else if (verbose) {
Message.defaultLogger = new DefaultMessageLogger(Message.MSG_VERBOSE)
level = 3
} else if (debug) {
Message.defaultLogger = new DefaultMessageLogger(Message.MSG_DEBUG)
} else {
Message.defaultLogger = new DefaultMessageLogger(defaultLevel)
level = 4
}
Grape.instance?.setLoggingLevel(level)
}

/**
Expand Down Expand Up @@ -152,10 +152,18 @@ class GrapeMain implements Runnable {
Grape.addResolver(name:url, root:url)
}

try {
Grape.grab(autoDownload: true, group: group, module: module, version: version, classifier: classifier, noExceptions: true)
} catch (Exception ex) {
System.err.println "An error occurred : $ex"
// Call the engine directly to get the exception return value
// The Grape.grab() facade doesn't propagate the return value
def engine = Grape.instance
if (!engine) {
System.err.println "Grape engine not available"
throw new CommandLine.ExecutionException(new CommandLine(this), "Grape engine not initialized")
}

def result = engine.grab(autoDownload: true, group: group, module: module, version: version, classifier: classifier, noExceptions: true)
if (result instanceof Exception) {
System.err.println "Error grabbing Grapes -- ${result.message}"
throw new CommandLine.ExecutionException(new CommandLine(this), "Failed to install grape", result)
}
}
}
Expand All @@ -179,7 +187,7 @@ class GrapeMain implements Runnable {
parentCommand.setupLogging()

Grape.enumerateGrapes().each {String groupName, Map group ->
group.each {String moduleName, List<String> versions ->
group.each { String moduleName, List<String> versions ->
println "$groupName $moduleName $versions"
moduleCount++
versionCount += versions.size()
Expand All @@ -195,6 +203,7 @@ class GrapeMain implements Runnable {
customSynopsis = 'grape resolve [-adhisv] (<groupId> <artifactId> <version>)+',
description = [
'Prints the file locations of the jars representing the artifacts for the specified module(s) and the respective transitive dependencies.',
'The exact format supported by some parameters depends on the Grape implementation, e.g. Ivy or Maven.',
'',
'Parameters:',
' <group> Which module group the module comes from. Translates directly',
Expand Down Expand Up @@ -229,9 +238,9 @@ class GrapeMain implements Runnable {
void run() {
parentCommand.init()

// set the instance so we can re-set the logger
// set the instance so we can re-set the logger (implementation dependent)
Grape.instance
parentCommand.setupLogging(Message.MSG_ERR)
parentCommand.setupLogging(0) // errors only

if ((args.size() % 3) != 0) {
println 'There needs to be a multiple of three arguments: (group module version)+'
Expand Down Expand Up @@ -299,6 +308,7 @@ class GrapeMain implements Runnable {
} catch (Exception e) {
System.err.println "Error in resolve:\n\t$e.message"
if (e.message =~ /unresolved dependency/) println 'Perhaps the grape is not installed?'
throw new CommandLine.ExecutionException(new CommandLine(this), "Failed to resolve grape", e)
}
}
}
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/groovy/grape/GrabAnnotationTransformation.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.ImportNode;
import org.codehaus.groovy.ast.ModuleNode;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ListExpression;
Expand Down Expand Up @@ -392,6 +393,11 @@ private void callGrabAsStaticInitIfNeeded(final ClassNode classNode, final Class
final Collection<Map<String,Object>> grabMapsInit, final Collection<Map<String, Object>> grabExcludeMaps) {
List<Statement> grabInitializers = new ArrayList<>();
MapExpression basicArgs = new MapExpression();
// Pass the class's own ClassLoader so chooseClassLoader doesn't have to walk the
// call stack — the stack-walk depth is tuned for the compile-time path, not the
// generated static-initializer path, and would overshoot into java.lang.reflect frames.
basicArgs.addMapEntryExpression(constX("classLoader"),
callX(new ClassExpression(classNode), "getClassLoader"));
if (autoDownload != null) {
basicArgs.addMapEntryExpression(constX(AUTO_DOWNLOAD_SETTING), constX(autoDownload));
}
Expand Down
Loading
Loading