From 503a815d9c47d71bc2fdba8bba3dd3cd3de3e423 Mon Sep 17 00:00:00 2001 From: James Daugherty Date: Fri, 20 Nov 2026 11:09:21 -0500 Subject: [PATCH 1/4] Record the Forge feature pack of a plugin version in the index When the main jar of a version contains META-INF/grails-forge/feature.yml, add a pack property to that version: the format, kind, name, template API, application types and compatibility ranges of the descriptor, read as data with bounds, and the SHA-256 of the jar. A jar whose descriptor cannot be used gets no pack and does not fail the run. Versions already indexed are looked at again only with --rescan-packs. --- README.md | 26 +++++ index-plugins.groovy | 222 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 229 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 7cf4150..6fd8efd 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,32 @@ versions: grailsVersion: 7.0.0 > * ``` +### Forge feature packs + +If the main jar of a plugin release contains a Forge feature pack (`META-INF/grails-forge/feature.yml`, which the `grails-plugin` Gradle plugin packages from `src/main/forge`), the indexer adds a `pack` property to that version. It lets the Grails CLI select the feature of your plugin by its name (`grails create-app --features `) without downloading every release to find it. + +```yaml +versions: + - version: 4.1.0 + date: 2026-11-20T10:00:00Z + grailsVersion: 9.0.0 > * + pack: + format: 1 + kind: feature + name: my-feature + templateApi: 1 + applicationTypes: # only if the pack declares them + - web + compatibility: + grails: '[9.0.0,10.0.0)' + forge: '[9.0.0,10.0.0)' + sha256: 5f2c... # of the jar; the CLI refuses a jar with another one +``` + +The `pack` property is copied from the descriptor inside the jar, which is read as data only; nothing of the jar is executed. Only the properties shown are copied, and the `sha256` is that of the jar as it was downloaded. **Do not write or edit `pack` by hand**: the `sha256` is what ties the entry to one jar. A jar whose descriptor cannot be read gets no `pack` (the indexer logs a warning and goes on). + +Versions that were indexed before they had a pack recorded are only looked at again when the indexer is run with `--rescan-packs`, for example `groovy index-plugins.groovy --rescan-packs grails-plugins/com/example/my-plugin.yml`. + ## Updating Your Plugin Once your plugin's YAML file is accepted and merged into this repository, the system will periodically scan for new plugin versions and update the `versions` list accordingly. You do not need to manually update the YAML file when you release a new version of your plugin. diff --git a/index-plugins.groovy b/index-plugins.groovy index 8828896..69c8fc5 100644 --- a/index-plugins.groovy +++ b/index-plugins.groovy @@ -1,7 +1,10 @@ #!/usr/bin/env groovy @Grab('org.yaml:snakeyaml:2.4') +import java.nio.charset.StandardCharsets +import java.security.MessageDigest import java.util.regex.Pattern +import java.util.zip.ZipEntry import java.util.zip.ZipException import java.util.zip.ZipFile @@ -12,7 +15,13 @@ import groovy.transform.CompileStatic import groovy.xml.XmlSlurper import org.yaml.snakeyaml.DumperOptions +import org.yaml.snakeyaml.LoaderOptions import org.yaml.snakeyaml.Yaml +import org.yaml.snakeyaml.constructor.SafeConstructor +import org.yaml.snakeyaml.events.AliasEvent +import org.yaml.snakeyaml.events.CollectionStartEvent +import org.yaml.snakeyaml.events.NodeEvent +import org.yaml.snakeyaml.events.ScalarEvent /** * Represents a software version with major, minor and optional patch and modifier. @@ -300,6 +309,7 @@ class Utils { Date lastModified = null String grailsCompatibility = null + Map forgePack = null def candidateUrls = [ artifactUrl, artifactUrl.replaceFirst(/\.jar$/, '-plain.jar'), @@ -320,8 +330,13 @@ class Utils { // Try the candidate urls in order for (url in candidateUrls) { try { - grailsCompatibility = extractGrailsVersionFromPluginJar(url) - if (grailsCompatibility) { + def artifactInfo = readPluginArtifact(url) + grailsCompatibility = artifactInfo.grailsVersion as String + // A Forge feature pack is only ever read from the main jar of the plugin + if (url == artifactUrl) { + forgePack = artifactInfo.pack as Map + } + if (grailsCompatibility || forgePack) { break } } catch(FileNotFoundException ignore) { @@ -329,7 +344,7 @@ class Utils { } } - if (!grailsCompatibility) { + if (!grailsCompatibility && !forgePack) { System.err.println("WARNING: Could not find plugin artifact for $coords:$version") } @@ -340,10 +355,124 @@ class Utils { if (grailsCompatibility) { versionInfo.put('grailsVersion', grailsCompatibility) } + if (forgePack) { + versionInfo.put('pack', forgePack) + } return versionInfo } + /** The descriptor of a Forge feature pack inside the main jar of a plugin. */ + static final String FORGE_PACK_DESCRIPTOR = 'META-INF/grails-forge/feature.yml' + + /** The same limits Forge applies when it reads the descriptor. */ + static final int FORGE_PACK_MAX_LENGTH = 256 * 1024 + static final int FORGE_PACK_MAX_DEPTH = 20 + + private static final Pattern FORGE_PACK_NAME = ~/[a-z][a-z0-9]*(-[a-z0-9]+)*/ + private static final Pattern FORGE_PACK_RANGE = ~/[A-Za-z0-9_.+\-\[\](), ]{1,200}/ + private static final List FORGE_PACK_KINDS = ['feature', 'preset'] + private static final List FORGE_PACK_APPLICATION_TYPES = ['web', 'rest-api', 'web-plugin', 'plugin'] + + /** + * Reads the Forge feature pack of a plugin jar, if it has one, as the `pack` member of a version. + * + * The descriptor is read as data only (SnakeYAML's SafeConstructor, no aliases, anchors or tags, + * bounded in size and depth) and nothing of the jar is executed. Only the members the Forge CLI + * needs to choose a version without downloading the jar are copied: `format`, `kind`, `name`, + * `templateApi`, `applicationTypes` (when declared) and `compatibility.grails`/`compatibility.forge`, + * plus the SHA-256 of the jar itself, which the CLI holds the jar to when it downloads it. + * + * @return the `pack` member, or null if the jar has no pack or its descriptor cannot be used + */ + @CompileDynamic + static Map readForgePack(ZipFile zip, File jar, String artifactUrl) { + ZipEntry entry = zip.getEntry(FORGE_PACK_DESCRIPTOR) + if (!entry) { + return null + } + try { + byte[] bytes = null + zip.getInputStream(entry).withCloseable { is -> + bytes = is.readNBytes(FORGE_PACK_MAX_LENGTH + 1) + } + if (bytes.length > FORGE_PACK_MAX_LENGTH) { + throw new IllegalArgumentException("is larger than $FORGE_PACK_MAX_LENGTH bytes") + } + def text = new String(bytes, StandardCharsets.UTF_8) + def options = new LoaderOptions().tap { + it.allowDuplicateKeys = false + it.maxAliasesForCollections = 0 + it.allowRecursiveKeys = false + it.nestingDepthLimit = FORGE_PACK_MAX_DEPTH + 1 + it.codePointLimit = FORGE_PACK_MAX_LENGTH + } + def yaml = new Yaml(new SafeConstructor(options)) + for (event in yaml.parse(new StringReader(text))) { + if (event instanceof AliasEvent || (event instanceof NodeEvent && event.anchor != null)) { + throw new IllegalArgumentException('uses an anchor or an alias') + } + if ((event instanceof ScalarEvent || event instanceof CollectionStartEvent) && event.tag != null) { + throw new IllegalArgumentException('uses a tag') + } + } + def descriptor = new Yaml(new SafeConstructor(options)).load(text) + if (!(descriptor instanceof Map)) { + throw new IllegalArgumentException('is not a mapping') + } + def pack = [:] as Map + ['format', 'templateApi'].each { key -> + def value = descriptor[key] + if (!(value instanceof Integer) || value < 1) { + throw new IllegalArgumentException("has no whole number for '$key'") + } + } + if (!(descriptor.kind in FORGE_PACK_KINDS)) { + throw new IllegalArgumentException("has a 'kind' that is not one of $FORGE_PACK_KINDS") + } + if (!(descriptor.name instanceof String) || descriptor.name.length() > 100 || !FORGE_PACK_NAME.matcher(descriptor.name).matches()) { + throw new IllegalArgumentException("has a 'name' that is not the name of a feature") + } + pack.format = descriptor.format + pack.kind = descriptor.kind + pack.name = descriptor.name + pack.templateApi = descriptor.templateApi + if (descriptor.containsKey('applicationTypes')) { + def types = descriptor.applicationTypes + if (!(types instanceof List) || !types || !types.every { it in FORGE_PACK_APPLICATION_TYPES }) { + throw new IllegalArgumentException("has 'applicationTypes' that are not a list of $FORGE_PACK_APPLICATION_TYPES") + } + pack.applicationTypes = types.unique(false) + } + def compatibility = descriptor.compatibility + if (!(compatibility instanceof Map)) { + throw new IllegalArgumentException("has no 'compatibility'") + } + pack.compatibility = ['grails', 'forge'].collectEntries { key -> + def range = compatibility[key] + if (!(range instanceof String) || !FORGE_PACK_RANGE.matcher(range).matches()) { + throw new IllegalArgumentException("has no version range for 'compatibility.$key'") + } + [(key): range] + } + def digest = MessageDigest.getInstance('SHA-256') + jar.withInputStream { is -> + byte[] buffer = new byte[64 * 1024] + int read + while ((read = is.read(buffer)) != -1) { + digest.update(buffer, 0, read) + } + } + pack.sha256 = digest.digest().encodeHex().toString() + return pack + } + catch(Exception ex) { + // One jar with a pack that cannot be used must never fail the index + System.err.println("WARNING: Ignoring the Forge feature pack of $artifactUrl: $FORGE_PACK_DESCRIPTOR ${ex.message ?: ex.class.simpleName}") + return null + } + } + /** * Extracts the grailsVersion compatibility string from a Grails plugin JAR. * @@ -354,13 +483,23 @@ class Utils { * @param jarFile the plugin JAR file * @return the grailsVersion string (e.g. "6.0.0 > *"), or null if not found */ - @CompileDynamic static String extractGrailsVersionFromPluginJar(String artifactUrl) throws FileNotFoundException { + readPluginArtifact(artifactUrl).grailsVersion as String + } + + /** + * Downloads a plugin artifact once and reads what the index records of it: the grailsVersion of + * its plugin descriptor and, if it has one, its Forge feature pack (see readForgePack). + * + * @return a map with the keys 'grailsVersion' and 'pack', each null if not found + */ + @CompileDynamic + static Map readPluginArtifact(String artifactUrl) throws FileNotFoundException { def file = File.createTempFile('plugin-', '.jar').tap { it.deleteOnExit() } - println("Downloading plugin artifact from $artifactUrl to extract grailsVersion...") + println("Downloading plugin artifact from $artifactUrl to extract grailsVersion and Forge feature pack...") doWithConnection(artifactUrl, 'GET') { inputStream.withCloseable { is -> file.withOutputStream { os -> @@ -370,12 +509,29 @@ class Utils { } if (!file || !file.exists()) { - return null + return [:] } ZipFile zip = null try { zip = new ZipFile(file) + def pack = readForgePack(zip, file, artifactUrl) + return [grailsVersion: readGrailsVersion(zip), pack: pack] + } + catch(ZipException ex) { + System.err.println("Invalid Zip file at $artifactUrl : ${ex.message}") + return [:] + } + finally { + if (zip != null) { + zip.close() + } + file.delete() + } + } + + @CompileDynamic + private static String readGrailsVersion(ZipFile zip) { def candidates = [ 'META-INF/grails-plugin.xml', 'plugin.xml' // Grails 2 @@ -410,15 +566,35 @@ class Utils { } return null + } - } - catch(ZipException ex) { - System.err.println("Invalid Zip file at $artifactUrl : ${ex.message}") - return null - } - finally { - if (zip != null) { - zip.close() + /** + * Adds the `pack` member to versions that are already in the YAML file and have none. + * + * A version already present is never updated by the normal run, so a plugin that gained a Forge + * feature pack before this indexer recorded packs would never get one. This downloads the main jar + * of each such version once (honouring the version's own `coords` and `maven-repo`) and changes + * nothing but `pack`. It is only done when the script is run with --rescan-packs. + */ + static void rescanForgePacks(Map pluginInfo) { + (pluginInfo.get('versions') ?: [] as List).each { Map v -> + if (v.containsKey('pack') || v.artifactAvailable == false) { + return + } + def mavenRepo = (v['maven-repo'] ?: pluginInfo['maven-repo']) as String + def coords = (v.coords ?: pluginInfo.coords) as String + if (!mavenRepo || !coords) { + return + } + try { + def version = Version.build(v.version as String) + def pack = readPluginArtifact(createArtifactUrl(mavenRepo, coords, version)).pack + if (pack) { + v.pack = pack + } + } + catch(Exception ex) { + System.err.println("INFO: No Forge feature pack read for $coords:${v.version}: ${ex.message ?: ex.class.simpleName}") } } } @@ -470,7 +646,7 @@ class Utils { new Yaml(options) } - static Map processPluginFile(File f) { + static Map processPluginFile(File f, boolean rescanPacks = false) { if (!(f.name.endsWith('.yml') || f.name.endsWith('.yaml'))) { System.err.println("INFO: Skipping non-YAML file: $f.path") return null @@ -531,7 +707,8 @@ class Utils { def entry = [ version: version.versionText, date: versionInfo.date, - grailsVersion: versionInfo.grailsVersion + grailsVersion: versionInfo.grailsVersion, + pack: versionInfo.pack ].findAll { k, v -> v != null } existingVersions << entry @@ -544,6 +721,10 @@ class Utils { } } + if (rescanPacks) { + rescanForgePacks(pluginInfo) + } + // Restore the date types (YAML parser converts to String) (pluginInfo.versions as List).each { v -> if (v.date && v.date instanceof String) { @@ -557,10 +738,13 @@ class Utils { } } -def fileArg = (args && args.length > 0) ? new File(args[0]) : 'grails-plugins' as File +// --rescan-packs: also look for a Forge feature pack in the versions already present (see rescanForgePacks) +def rescanPacks = args?.contains('--rescan-packs') +def fileArgs = (args ?: []).findAll { it != '--rescan-packs' } +def fileArg = fileArgs ? new File(fileArgs[0]) : 'grails-plugins' as File if (fileArg.file) { - Utils.processPluginFile(fileArg) + Utils.processPluginFile(fileArg, rescanPacks) println("Processed single file: $fileArg.path") } else { @@ -570,7 +754,7 @@ else { } List indexEntries = [] fileArg.eachFileRecurse(FileType.FILES) { f -> - def pluginInfo = Utils.processPluginFile(f) + def pluginInfo = Utils.processPluginFile(f, rescanPacks) // Add to index (include everything from YAML) if (pluginInfo) { indexEntries << pluginInfo From 5e51ab5347befcaed05bf4947cd716685882c2d0 Mon Sep 17 00:00:00 2001 From: James Daugherty Date: Wed, 25 Nov 2026 12:34:38 -0500 Subject: [PATCH 2/4] Record packs for rest-api-plugin, unknown types and presets with their types The indexer held the application types of a Forge feature pack to a list of four, while Grails 9 creates five kinds of application: rest-api-plugin was missing. A pack that declared [web, rest-api-plugin] was refused as a whole, so its version was indexed without a pack and the feature was not offered for web applications either. Since a version already indexed is not looked at again without --rescan-packs, the loss was permanent. The list now has all five types. A name that has the form of a type but is not among them no longer costs the pack its entry: the types are recorded as the descriptor names them and a warning names the unknown one. The Grails command line passes over a type it does not know, so the pack stays offered for the types it is validly for, and a type a later Grails adds does not need a new indexer first. Only a value that cannot be a list of names of types is still refused, with the warning the indexer gives for every descriptor it cannot use. A preset names the one type it is for in applicationType and has no applicationTypes, so the indexer recorded no type for it and the index offered every preset for every type. The type of a preset is now recorded as the one entry of applicationTypes, which is where the command line reads it, and a preset without a type gets no entry. index-plugins-test.groovy tests what is recorded of a pack. It compiles the classes of the indexer without running it, so it reads no plugin file and downloads no plugin. --- README.md | 6 +- index-plugins-test.groovy | 159 ++++++++++++++++++++++++++++++++++++++ index-plugins.groovy | 67 +++++++++++++--- 3 files changed, 222 insertions(+), 10 deletions(-) create mode 100644 index-plugins-test.groovy diff --git a/README.md b/README.md index 6fd8efd..eb4d00e 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ versions: kind: feature name: my-feature templateApi: 1 - applicationTypes: # only if the pack declares them + applicationTypes: # left out for a feature pack that is for every type - web compatibility: grails: '[9.0.0,10.0.0)' @@ -101,8 +101,12 @@ versions: The `pack` property is copied from the descriptor inside the jar, which is read as data only; nothing of the jar is executed. Only the properties shown are copied, and the `sha256` is that of the jar as it was downloaded. **Do not write or edit `pack` by hand**: the `sha256` is what ties the entry to one jar. A jar whose descriptor cannot be read gets no `pack` (the indexer logs a warning and goes on). +`applicationTypes` holds the types of application the pack is for: `web`, `rest-api`, `web-plugin`, `plugin` and `rest-api-plugin`. A feature pack that declares none is for all of them and has no `applicationTypes`. A preset (`kind: preset`) is for one type, the `applicationType` of its descriptor, which is recorded as the one entry of `applicationTypes`. A type the indexer does not know is recorded as the descriptor names it, beside the others, and the indexer logs a warning: the pack keeps its entry for the types it is validly for, and the Grails CLI passes over a type it does not know. + Versions that were indexed before they had a pack recorded are only looked at again when the indexer is run with `--rescan-packs`, for example `groovy index-plugins.groovy --rescan-packs grails-plugins/com/example/my-plugin.yml`. +What the indexer records of a pack is tested by `groovy index-plugins-test.groovy`, which reads no plugin file and downloads no plugin. + ## Updating Your Plugin Once your plugin's YAML file is accepted and merged into this repository, the system will periodically scan for new plugin versions and update the `versions` list accordingly. You do not need to manually update the YAML file when you release a new version of your plugin. diff --git a/index-plugins-test.groovy b/index-plugins-test.groovy new file mode 100644 index 0000000..72db0a5 --- /dev/null +++ b/index-plugins-test.groovy @@ -0,0 +1,159 @@ +#!/usr/bin/env groovy + +// Tests of what index-plugins.groovy records of the Forge feature pack of a plugin jar. +// Run with: groovy index-plugins-test.groovy +// The classes of the indexer are compiled from the script beside this one, which is not run: no +// plugin file is read or written and nothing is downloaded but the library the indexer grabs. + +import java.util.zip.ZipEntry +import java.util.zip.ZipFile +import java.util.zip.ZipOutputStream + +def script = new File(getClass().protectionDomain.codeSource.location.toURI()).parentFile +def shell = new GroovyShell() +shell.parse(new File(script, 'index-plugins.groovy')) +utils = shell.classLoader.loadClass('Utils') +directory = File.createTempDir('index-plugins-test') +failures = [] +count = 0 + +/** What the indexer makes of a jar with this descriptor: the `pack` it records, and what it says on the standard error. */ +Map read(String descriptor) { + def jar = new File(directory, "plugin-${++count}.jar") + new ZipOutputStream(jar.newOutputStream()).withCloseable { zip -> + zip.putNextEntry(new ZipEntry('META-INF/grails-forge/feature.yml')) + zip << descriptor.bytes + zip.closeEntry() + } + def said = new ByteArrayOutputStream() + def err = System.err + System.err = new PrintStream(said, true) + try { + def pack = new ZipFile(jar).withCloseable { zip -> utils.readForgePack(zip, jar, "https://repo.example/${jar.name}") } + return [pack: pack, said: said.toString()] + } + finally { + System.err = err + } +} + +String feature(String more) { + """\ +format: 1 +kind: feature +name: my-feature +templateApi: 1 +compatibility: + grails: '[9.0.0,10.0.0)' + forge: '[9.0.0,10.0.0)' +$more +""" +} + +String preset(String more) { + feature(more).replace('kind: feature', 'kind: preset').replace('my-feature', 'my-preset') +} + +void test(String name, Closure body) { + try { + body() + println "passed: $name" + } + catch(Throwable ex) { + failures << name + println "FAILED: $name\n ${ex.message}" + } +} + +test('a feature for every type of application has no applicationTypes') { + def result = read(feature('')) + assert result.pack.kind == 'feature' + assert result.pack.name == 'my-feature' + assert !result.pack.containsKey('applicationTypes') + assert result.pack.sha256 ==~ /[0-9a-f]{64}/ + assert result.said == '' +} + +test('each of the five types of application of Grails 9 is recorded without a warning') { + def result = read(feature('applicationTypes: [web, rest-api, web-plugin, plugin, rest-api-plugin]')) + assert result.pack.applicationTypes == ['web', 'rest-api', 'web-plugin', 'plugin', 'rest-api-plugin'] + assert result.said == '' +} + +test('a pack for web and rest-api-plugin keeps its entry') { + def result = read(feature('applicationTypes: [web, rest-api-plugin]')) + assert result.pack != null + assert result.pack.applicationTypes == ['web', 'rest-api-plugin'] + assert result.said == '' +} + +test('a type named twice is recorded once') { + assert read(feature('applicationTypes: [web, rest-api, web]')).pack.applicationTypes == ['web', 'rest-api'] +} + +test('a type this indexer does not know is recorded beside the others, with a warning') { + def result = read(feature('applicationTypes: [web, batch-job]')) + assert result.pack != null + assert result.pack.applicationTypes == ['web', 'batch-job'] + assert result.said.startsWith('WARNING: ') + assert result.said.contains('[batch-job]') + assert result.said.contains("'applicationTypes'") + assert result.said.contains('https://repo.example/') +} + +test('applicationTypes that cannot be names of types cost the pack its entry, with a warning') { + ['applicationTypes: []', 'applicationTypes: web', 'applicationTypes: [web, 9]', 'applicationTypes: [web, "Not A Type"]', + 'applicationTypes: [web, [plugin]]', 'applicationTypes:', "applicationTypes: [${(1..21).collect { "type-$it" }.join(', ')}]"].each { + def result = read(feature(it)) + assert result.pack == null : it + assert result.said.startsWith('WARNING: Ignoring the Forge feature pack of https://repo.example/') : it + assert result.said.contains("'applicationTypes'") : it + } +} + +test('the one type of application of a preset is recorded as its applicationTypes') { + ['web', 'rest-api', 'web-plugin', 'plugin', 'rest-api-plugin'].each { + def result = read(preset("applicationType: $it")) + assert result.pack.kind == 'preset' + assert result.pack.name == 'my-preset' + assert result.pack.applicationTypes == [it] + assert !result.pack.containsKey('applicationType') + assert result.said == '' + } +} + +test('a preset for a type this indexer does not know is recorded with a warning') { + def result = read(preset('applicationType: batch-job')) + assert result.pack.applicationTypes == ['batch-job'] + assert result.said.startsWith('WARNING: ') + assert result.said.contains("'applicationType'") +} + +test('a preset that names no type of application, or what is none, gets no entry, with a warning') { + ['', 'applicationType: [web]', 'applicationType: 9', 'applicationType: "Not A Type"', 'applicationTypes: [web]'].each { + def result = read(preset(it)) + assert result.pack == null : it + assert result.said.startsWith('WARNING: Ignoring the Forge feature pack of https://repo.example/') : it + assert result.said.contains("'applicationType'") : it + } +} + +test('a feature is not given the applicationType only a preset has') { + def result = read(feature('applicationType: web')) + assert result.pack != null + assert !result.pack.containsKey('applicationTypes') + assert !result.pack.containsKey('applicationType') +} + +test('a descriptor that cannot be used still gets no entry, with a warning') { + def result = read(feature('').replace('kind: feature', 'kind: theme')) + assert result.pack == null + assert result.said.startsWith('WARNING: Ignoring the Forge feature pack of') +} + +directory.deleteDir() +if (failures) { + System.err.println("${failures.size()} of the tests failed: $failures") + System.exit(1) +} +println 'All tests passed' diff --git a/index-plugins.groovy b/index-plugins.groovy index 69c8fc5..3f110d7 100644 --- a/index-plugins.groovy +++ b/index-plugins.groovy @@ -372,7 +372,9 @@ class Utils { private static final Pattern FORGE_PACK_NAME = ~/[a-z][a-z0-9]*(-[a-z0-9]+)*/ private static final Pattern FORGE_PACK_RANGE = ~/[A-Za-z0-9_.+\-\[\](), ]{1,200}/ private static final List FORGE_PACK_KINDS = ['feature', 'preset'] - private static final List FORGE_PACK_APPLICATION_TYPES = ['web', 'rest-api', 'web-plugin', 'plugin'] + /** The types of application Grails 9 creates; a type that is not among them is recorded with a warning (see forgePackApplicationTypes). */ + private static final List FORGE_PACK_APPLICATION_TYPES = ['web', 'rest-api', 'web-plugin', 'plugin', 'rest-api-plugin'] + private static final int FORGE_PACK_MAX_APPLICATION_TYPES = 20 /** * Reads the Forge feature pack of a plugin jar, if it has one, as the `pack` member of a version. @@ -380,8 +382,9 @@ class Utils { * The descriptor is read as data only (SnakeYAML's SafeConstructor, no aliases, anchors or tags, * bounded in size and depth) and nothing of the jar is executed. Only the members the Forge CLI * needs to choose a version without downloading the jar are copied: `format`, `kind`, `name`, - * `templateApi`, `applicationTypes` (when declared) and `compatibility.grails`/`compatibility.forge`, - * plus the SHA-256 of the jar itself, which the CLI holds the jar to when it downloads it. + * `templateApi`, `applicationTypes` (when declared; for a preset, the one `applicationType` it is + * for) and `compatibility.grails`/`compatibility.forge`, plus the SHA-256 of the jar itself, which + * the CLI holds the jar to when it downloads it. * * @return the `pack` member, or null if the jar has no pack or its descriptor cannot be used */ @@ -437,12 +440,9 @@ class Utils { pack.kind = descriptor.kind pack.name = descriptor.name pack.templateApi = descriptor.templateApi - if (descriptor.containsKey('applicationTypes')) { - def types = descriptor.applicationTypes - if (!(types instanceof List) || !types || !types.every { it in FORGE_PACK_APPLICATION_TYPES }) { - throw new IllegalArgumentException("has 'applicationTypes' that are not a list of $FORGE_PACK_APPLICATION_TYPES") - } - pack.applicationTypes = types.unique(false) + def types = forgePackApplicationTypes(descriptor, artifactUrl) + if (types != null) { + pack.applicationTypes = types } def compatibility = descriptor.compatibility if (!(compatibility instanceof Map)) { @@ -473,6 +473,55 @@ class Utils { } } + /** + * The `applicationTypes` of the `pack` member for a descriptor: the types of application the pack + * is for, each once and in the order of the descriptor. + * + * A feature names them in `applicationTypes`, a list, and is for every type when it has no such + * key, which is recorded by leaving `applicationTypes` out. A preset is for one type, which it + * names in `applicationType`, and that one is recorded as the only entry of `applicationTypes`, + * so that a reader of the index finds the types of every kind of pack under one key. + * + * A name that has the form of a type but is not one this indexer knows does not cost the pack its + * entry, and with it the types it is validly for: the name is recorded as it is, which a reader + * passes over when it does not know the type either, and a warning says so. Only a value that + * cannot be a list of names of types is refused. + * + * @return the types, or null for a feature that is for every type + * @throws IllegalArgumentException if the descriptor does not say which types it is for in the form its kind has + */ + @CompileDynamic + static List forgePackApplicationTypes(Map descriptor, String artifactUrl) { + def key = 'applicationTypes' + def names + if (descriptor.kind == 'preset') { + key = 'applicationType' + def type = descriptor[key] + if (!(type instanceof String)) { + throw new IllegalArgumentException("is a preset that has no '$key', the name of the one type of application it is for") + } + names = [type] + } + else if (!descriptor.containsKey(key)) { + return null + } + else { + names = descriptor[key] + if (!(names instanceof List) || !names || names.size() > FORGE_PACK_MAX_APPLICATION_TYPES) { + throw new IllegalArgumentException("has '$key' that are not a list of names of types of application, such as $FORGE_PACK_APPLICATION_TYPES") + } + } + if (!names.every { it instanceof String && it.length() <= 100 && FORGE_PACK_NAME.matcher(it).matches() }) { + throw new IllegalArgumentException("names in '$key' what cannot be the name of a type of application, such as $FORGE_PACK_APPLICATION_TYPES") + } + def unknown = names.findAll { !(it in FORGE_PACK_APPLICATION_TYPES) }.unique(false) + if (unknown) { + System.err.println("WARNING: The Forge feature pack of $artifactUrl names in '$key' $unknown, which is not among the types of " + + "application this indexer knows, $FORGE_PACK_APPLICATION_TYPES. The pack is recorded with every type it names.") + } + return names.unique(false) + } + /** * Extracts the grailsVersion compatibility string from a Grails plugin JAR. * From cd17a34b5c55b56bb1161c150a2b4f56c430663f Mon Sep 17 00:00:00 2001 From: James Daugherty Date: Wed, 2 Dec 2026 17:37:54 -0500 Subject: [PATCH 3/4] Name Grails 10 as the version with feature packs The Grails change this goes with, apache/grails-core#17114, now targets 10.0.x, so the examples and the tests use the range of the Grails 10 line. --- README.md | 6 +++--- index-plugins-test.groovy | 6 +++--- index-plugins.groovy | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index eb4d00e..67d6f78 100644 --- a/README.md +++ b/README.md @@ -85,7 +85,7 @@ If the main jar of a plugin release contains a Forge feature pack (`META-INF/gra versions: - version: 4.1.0 date: 2026-11-20T10:00:00Z - grailsVersion: 9.0.0 > * + grailsVersion: 10.0.0 > * pack: format: 1 kind: feature @@ -94,8 +94,8 @@ versions: applicationTypes: # left out for a feature pack that is for every type - web compatibility: - grails: '[9.0.0,10.0.0)' - forge: '[9.0.0,10.0.0)' + grails: '[10.0.0,11.0.0)' + forge: '[10.0.0,11.0.0)' sha256: 5f2c... # of the jar; the CLI refuses a jar with another one ``` diff --git a/index-plugins-test.groovy b/index-plugins-test.groovy index 72db0a5..ca46f24 100644 --- a/index-plugins-test.groovy +++ b/index-plugins-test.groovy @@ -44,8 +44,8 @@ kind: feature name: my-feature templateApi: 1 compatibility: - grails: '[9.0.0,10.0.0)' - forge: '[9.0.0,10.0.0)' + grails: '[10.0.0,11.0.0)' + forge: '[10.0.0,11.0.0)' $more """ } @@ -74,7 +74,7 @@ test('a feature for every type of application has no applicationTypes') { assert result.said == '' } -test('each of the five types of application of Grails 9 is recorded without a warning') { +test('each of the five types of application of Grails 10 is recorded without a warning') { def result = read(feature('applicationTypes: [web, rest-api, web-plugin, plugin, rest-api-plugin]')) assert result.pack.applicationTypes == ['web', 'rest-api', 'web-plugin', 'plugin', 'rest-api-plugin'] assert result.said == '' diff --git a/index-plugins.groovy b/index-plugins.groovy index 3f110d7..94e44d5 100644 --- a/index-plugins.groovy +++ b/index-plugins.groovy @@ -372,7 +372,7 @@ class Utils { private static final Pattern FORGE_PACK_NAME = ~/[a-z][a-z0-9]*(-[a-z0-9]+)*/ private static final Pattern FORGE_PACK_RANGE = ~/[A-Za-z0-9_.+\-\[\](), ]{1,200}/ private static final List FORGE_PACK_KINDS = ['feature', 'preset'] - /** The types of application Grails 9 creates; a type that is not among them is recorded with a warning (see forgePackApplicationTypes). */ + /** The types of application Grails 10 creates; a type that is not among them is recorded with a warning (see forgePackApplicationTypes). */ private static final List FORGE_PACK_APPLICATION_TYPES = ['web', 'rest-api', 'web-plugin', 'plugin', 'rest-api-plugin'] private static final int FORGE_PACK_MAX_APPLICATION_TYPES = 20 From c5d9f63b7870adf9b06c087a89704bdf1f4bc4fd Mon Sep 17 00:00:00 2001 From: James Daugherty Date: Fri, 4 Dec 2026 08:01:26 -0500 Subject: [PATCH 4/4] Keep a pack name with one plugin and a pack beside a broken plugin descriptor - The name of a pack belongs to the first plugin that is indexed with it: the pack of another plugin with that name is not recorded, with a warning, and two plugins that have one name in their files already are reported. - A grails-plugin.xml that cannot be read no longer costs the jar its pack, nor fails the run. - A main jar with a pack and no plugin descriptor no longer ends the search for the grailsVersion in the other artifacts, and a pack is not read at all from the plain jar or the zip. - --rescan-packs replaces or removes a pack that is not what the jar has, and does not download again a version the same run added. - extractGrailsVersionFromPluginJar, which nothing called, is removed. --- README.md | 13 +- index-plugins-test.groovy | 178 ++++++++++++++++++++++++++++ index-plugins.groovy | 243 +++++++++++++++++++++++++++++--------- 3 files changed, 373 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 67d6f78..737898d 100644 --- a/README.md +++ b/README.md @@ -99,11 +99,20 @@ versions: sha256: 5f2c... # of the jar; the CLI refuses a jar with another one ``` -The `pack` property is copied from the descriptor inside the jar, which is read as data only; nothing of the jar is executed. Only the properties shown are copied, and the `sha256` is that of the jar as it was downloaded. **Do not write or edit `pack` by hand**: the `sha256` is what ties the entry to one jar. A jar whose descriptor cannot be read gets no `pack` (the indexer logs a warning and goes on). +The `pack` property is copied from the descriptor inside the jar, which is read as data only; nothing of the jar is executed. Only the properties shown are copied, and the `sha256` is that of the jar as it was downloaded. **Do not write or edit `pack` by hand**: the `sha256` is what ties the entry to one jar. A jar whose descriptor cannot be read gets no `pack` (the indexer logs a warning and goes on), and a jar whose `grails-plugin.xml` cannot be read keeps its `pack` and gets no `grailsVersion`. `applicationTypes` holds the types of application the pack is for: `web`, `rest-api`, `web-plugin`, `plugin` and `rest-api-plugin`. A feature pack that declares none is for all of them and has no `applicationTypes`. A preset (`kind: preset`) is for one type, the `applicationType` of its descriptor, which is recorded as the one entry of `applicationTypes`. A type the indexer does not know is recorded as the descriptor names it, beside the others, and the indexer logs a warning: the pack keeps its entry for the types it is validly for, and the Grails CLI passes over a type it does not know. -Versions that were indexed before they had a pack recorded are only looked at again when the indexer is run with `--rescan-packs`, for example `groovy index-plugins.groovy --rescan-packs grails-plugins/com/example/my-plugin.yml`. +The Grails CLI selects a pack by its `name`, and refuses a name that more than one plugin has until the plugin is named with it. A name therefore belongs to the first plugin that is indexed with it: the pack of a release of another plugin with that name is not recorded, and the indexer logs a warning. A feature and a preset can have the same name. To hand a name over to another plugin, remove the `pack` of every version of the plugin that holds it. + +Versions that are already in the YAML file are only looked at again when the indexer is run with `--rescan-packs`, for example `groovy index-plugins.groovy --rescan-packs grails-plugins/com/example/my-plugin.yml`. It downloads the main jar of each of them and makes `pack` what the jar has: a version that was indexed before packs were recorded gets its `pack`, and a `pack` that is not what the indexer records of the jar is replaced or removed, with a warning. + +#### For maintainers of this repository + +A `pack` makes a feature name resolve to a jar that takes part in generating an application, so it is reviewed like code: + +- In the "Update Plugin Index" pull request, look at each `pack` that is new: its `name` should be one the plugin can be expected to use, and not one that passes for another plugin or for a feature of Grails itself. +- In a pull request that adds or changes a `pack` by hand, do not accept the change. Run `groovy index-plugins.groovy --rescan-packs ` on it, which restores what the jars have. What the indexer records of a pack is tested by `groovy index-plugins-test.groovy`, which reads no plugin file and downloads no plugin. diff --git a/index-plugins-test.groovy b/index-plugins-test.groovy index ca46f24..22c4e8d 100644 --- a/index-plugins-test.groovy +++ b/index-plugins-test.groovy @@ -151,6 +151,184 @@ test('a descriptor that cannot be used still gets no entry, with a warning') { assert result.said.startsWith('WARNING: Ignoring the Forge feature pack of') } + +// What follows reads jars over HTTP, as the indexer does, from a Maven repository on the loopback interface + +def repository = new File(directory, 'repository') +def server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(InetAddress.loopbackAddress, 0), 0) +requested = [] +server.createContext('/') { exchange -> + requested << exchange.requestURI.path + def file = new File(repository, exchange.requestURI.path) + if (file.file) { + exchange.responseHeaders.add('Last-Modified', 'Fri, 20 Nov 2026 10:00:00 GMT') + if (exchange.requestMethod == 'HEAD') { + exchange.sendResponseHeaders(200, -1) + } + else { + exchange.sendResponseHeaders(200, file.length()) + exchange.responseBody << file.bytes + } + } + else { + exchange.sendResponseHeaders(404, -1) + } + exchange.close() +} +server.start() +repositoryUrl = "http://127.0.0.1:${server.address.port}" + +/** Publishes an artifact of example: to the repository: a zip file with these entries. */ +void publish(File repository, String plugin, String version, String suffix, Map entries) { + def file = new File(repository, "example/$plugin/$version/$plugin-$version$suffix") + file.parentFile.mkdirs() + new ZipOutputStream(file.newOutputStream()).withCloseable { zip -> + entries.each { name, text -> + zip.putNextEntry(new ZipEntry(name)) + zip << text.bytes + zip.closeEntry() + } + } + def versions = new File(repository, "example/$plugin").listFiles().findAll { it.directory }*.name.sort() + new File(repository, "example/$plugin/maven-metadata.xml").text = + "${versions.collect { "$it" }.join()}" +} + +/** Runs the body and gives what it returns and what the indexer said on the standard error meanwhile. */ +Map saying(Closure body) { + def said = new ByteArrayOutputStream() + def err = System.err + def out = System.out + System.err = new PrintStream(said, true) + System.out = new PrintStream(new ByteArrayOutputStream()) + try { + return [result: body(), said: said.toString()] + } + finally { + System.err = err + System.out = out + } +} + +/** Writes a plugin file, has the indexer process it and gives the plugin as the file then has it, and what was said. */ +Map index(String plugin, String versions = '', boolean rescan = false) { + def file = new File(directory, "grails-plugins/example/${plugin}.yml") + file.parentFile.mkdirs() + file.text = "coords: example:$plugin\nmaven-repo: $repositoryUrl\n$versions" + utils.FORGE_PACK_HOLDERS.clear() + def run = saying { + utils.registerForgePackNames(new File(directory, 'grails-plugins')) + utils.processPluginFile(file, rescan) + } + [plugin: new org.yaml.snakeyaml.Yaml().load(file.text), said: run.said] +} + +String descriptorXml = "" + +test('a plugin descriptor that cannot be read does not cost the jar its pack, nor the run') { + [']>'].each { xml -> + publish(repository, 'broken-descriptor', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'broken-descriptor'), 'META-INF/grails-plugin.xml': xml]) + def indexed = index('broken-descriptor') + def version = indexed.plugin.versions[0] + assert version.version == '1.0.0' + assert version.pack.name == 'broken-descriptor' : xml + assert !version.containsKey('grailsVersion') : xml + assert indexed.said.contains('WARNING: Ignoring the plugin descriptor of ') : xml + } +} + +test('a main jar with a pack and no plugin descriptor leaves the grailsVersion to the plain jar') { + publish(repository, 'pack-in-main', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'pack-in-main')]) + publish(repository, 'pack-in-main', '1.0.0', '-plain.jar', ['META-INF/grails-plugin.xml': descriptorXml]) + def indexed = index('pack-in-main') + assert indexed.plugin.versions[0].pack.name == 'pack-in-main' + assert indexed.plugin.versions[0].grailsVersion == '10.0.0 > *' + assert indexed.said == '' +} + +test('a version with a pack and no plugin descriptor anywhere is recorded with the pack, and a warning') { + publish(repository, 'pack-only', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'pack-only')]) + def indexed = index('pack-only') + assert indexed.plugin.versions[0].pack.name == 'pack-only' + assert !indexed.plugin.versions[0].containsKey('grailsVersion') + assert indexed.said.contains('WARNING: No grailsVersion found for example:pack-only:1.0.0') +} + +test('a pack is read from the main jar only: one in the plain jar is not looked at') { + publish(repository, 'pack-in-plain', '1.0.0', '.jar', ['other.txt': '']) + publish(repository, 'pack-in-plain', '1.0.0', '-plain.jar', ['META-INF/grails-forge/feature.yml': 'not: [a pack', 'META-INF/grails-plugin.xml': descriptorXml]) + def indexed = index('pack-in-plain') + assert !indexed.plugin.versions[0].containsKey('pack') + assert indexed.plugin.versions[0].grailsVersion == '10.0.0 > *' + assert indexed.said == '' +} + +test('the name of a pack belongs to the first plugin that is indexed with it') { + publish(repository, 'first', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'shared-name'), 'META-INF/grails-plugin.xml': descriptorXml]) + publish(repository, 'second', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'shared-name'), 'META-INF/grails-plugin.xml': descriptorXml]) + publish(repository, 'second', '1.1.0', '.jar', ['META-INF/grails-forge/feature.yml': preset('applicationType: web').replace('my-preset', 'shared-name'), 'META-INF/grails-plugin.xml': descriptorXml]) + assert index('first').plugin.versions[0].pack.name == 'shared-name' + def indexed = index('second') + def versions = indexed.plugin.versions.collectEntries { [it.version, it] } + assert !versions['1.0.0'].containsKey('pack') + assert versions['1.0.0'].grailsVersion == '10.0.0 > *' + assert indexed.said.contains("WARNING: Ignoring the Forge feature pack of example:second:1.0.0: its name, the feature 'shared-name', is that of a pack of example:first") + // a preset is selected apart from a feature, so it can have the name of one + assert versions['1.1.0'].pack.kind == 'preset' + // a later version of the plugin that holds the name keeps it + publish(repository, 'first', '1.1.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'shared-name'), 'META-INF/grails-plugin.xml': descriptorXml]) + def later = index('first', new File(directory, 'grails-plugins/example/first.yml').text.readLines().drop(2).join('\n')) + assert later.plugin.versions*.pack*.name == ['shared-name', 'shared-name'] + assert later.said == '' +} + +test('two plugins that have one name in their files already are reported and both kept') { + def pack = " pack: {format: 1, kind: feature, name: had-twice, templateApi: 1, compatibility: {grails: '[10,11)', forge: '[10,11)'}, sha256: ${'a' * 64}}" + new File(directory, 'grails-plugins/example/had-twice-a.yml').text = "coords: example:had-twice-a\nversions:\n - version: 1.0.0\n$pack\n" + def indexed = index('had-twice-b', "versions:\n - version: 1.0.0\n$pack\n") + assert indexed.plugin.versions[0].pack.name == 'had-twice' + assert indexed.said.contains("the feature 'had-twice'") + assert indexed.said.contains('The Grails CLI refuses a name that more than one plugin has') + new File(directory, 'grails-plugins/example/had-twice-a.yml').delete() +} + +test('--rescan-packs adds the pack of a version that is already present, and reads no version twice') { + publish(repository, 'rescanned', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'rescanned'), 'META-INF/grails-plugin.xml': descriptorXml]) + publish(repository, 'rescanned', '1.1.0', '.jar', ['META-INF/grails-plugin.xml': descriptorXml]) + def present = "versions:\n - version: 1.0.0\n grailsVersion: 9.0.0 > *\n" + assert !index('rescanned', present).plugin.versions.any { it.containsKey('pack') } + requested.clear() + def indexed = index('rescanned', present, true) + def versions = indexed.plugin.versions.collectEntries { [it.version, it] } + assert versions['1.0.0'].pack.name == 'rescanned' + assert versions['1.0.0'].grailsVersion == '9.0.0 > *' + assert !versions['1.1.0'].containsKey('pack') + assert requested.count { it.endsWith('rescanned-1.1.0.jar') } == 2 // one HEAD for the date and one GET + assert indexed.said == '' +} + +test('--rescan-packs replaces a pack that is not what the jar has, and removes one of a jar without a pack') { + publish(repository, 'by-hand', '1.0.0', '.jar', ['META-INF/grails-forge/feature.yml': feature('').replace('my-feature', 'by-hand'), 'META-INF/grails-plugin.xml': descriptorXml]) + publish(repository, 'by-hand', '1.1.0', '.jar', ['META-INF/grails-plugin.xml': descriptorXml]) + def written = { String version -> " - version: $version\n pack: {format: 1, kind: feature, name: spring-security-core, templateApi: 1, " + + "compatibility: {grails: '[10,11)', forge: '[10,11)'}, sha256: ${'a' * 64}}\n" } + def byHand = "versions:\n${written('1.1.0')}${written('1.0.0')}" + assert index('by-hand', byHand).plugin.versions*.pack*.name == ['spring-security-core', 'spring-security-core'] + def indexed = index('by-hand', byHand, true) + def versions = indexed.plugin.versions.collectEntries { [it.version, it] } + assert versions['1.0.0'].pack.name == 'by-hand' + assert versions['1.0.0'].pack.sha256 != 'a' * 64 + assert !versions['1.1.0'].containsKey('pack') + assert indexed.said.contains('WARNING: The pack of example:by-hand:1.0.0 was not what the indexer records of its jar and is replaced') + assert indexed.said.contains('WARNING: The pack of example:by-hand:1.1.0 was not what the indexer records of its jar and is removed') + // a pack that is what the jar has is left as it is, and so is one whose jar cannot be downloaded + def again = index('by-hand', new File(directory, 'grails-plugins/example/by-hand.yml').text.readLines().drop(2).join('\n') + + "\n${written('0.9.0')}", true) + assert again.plugin.versions.collectEntries { [it.version, it.pack?.name] } == ['1.1.0': null, '1.0.0': 'by-hand', '0.9.0': 'spring-security-core'] + assert !again.said.contains('WARNING') +} + +server.stop(0) directory.deleteDir() if (failures) { System.err.println("${failures.size()} of the tests failed: $failures") diff --git a/index-plugins.groovy b/index-plugins.groovy index 94e44d5..5231691 100644 --- a/index-plugins.groovy +++ b/index-plugins.groovy @@ -330,13 +330,16 @@ class Utils { // Try the candidate urls in order for (url in candidateUrls) { try { - def artifactInfo = readPluginArtifact(url) - grailsCompatibility = artifactInfo.grailsVersion as String // A Forge feature pack is only ever read from the main jar of the plugin - if (url == artifactUrl) { + def mainJar = url == artifactUrl + def artifactInfo = readPluginArtifact(url, mainJar) + grailsCompatibility = artifactInfo.grailsVersion as String + if (mainJar) { forgePack = artifactInfo.pack as Map } - if (grailsCompatibility || forgePack) { + // A pack does not end the search: a main jar without a plugin descriptor leaves the + // grailsVersion to the other artifacts + if (grailsCompatibility) { break } } catch(FileNotFoundException ignore) { @@ -347,6 +350,9 @@ class Utils { if (!grailsCompatibility && !forgePack) { System.err.println("WARNING: Could not find plugin artifact for $coords:$version") } + else if (!grailsCompatibility) { + System.err.println("WARNING: No grailsVersion found for $coords:$version, which is recorded with its Forge feature pack alone") + } def versionInfo = [:] as Map if (lastModified) { @@ -512,7 +518,7 @@ class Utils { } } if (!names.every { it instanceof String && it.length() <= 100 && FORGE_PACK_NAME.matcher(it).matches() }) { - throw new IllegalArgumentException("names in '$key' what cannot be the name of a type of application, such as $FORGE_PACK_APPLICATION_TYPES") + throw new IllegalArgumentException("names in '$key' a value that cannot be the name of a type of application, such as $FORGE_PACK_APPLICATION_TYPES") } def unknown = names.findAll { !(it in FORGE_PACK_APPLICATION_TYPES) }.unique(false) if (unknown) { @@ -522,33 +528,90 @@ class Utils { return names.unique(false) } + /** The plugin that holds each name of a pack, by the kind of the pack: 'feature my-feature' -> the coords of the plugin. */ + static final Map FORGE_PACK_HOLDERS = [:] + /** - * Extracts the grailsVersion compatibility string from a Grails plugin JAR. + * Claims the name of a pack for a plugin. The Grails CLI selects a pack by its name and refuses a + * name that more than one plugin has, so a name belongs to the first plugin that is indexed with + * it; a feature and a preset can have the same name. * - * Looks for META-INF/grails-plugin.xml and reads either: - * - - * - or ... - * - * @param jarFile the plugin JAR file - * @return the grailsVersion string (e.g. "6.0.0 > *"), or null if not found + * @param pack the `pack` member of a version + * @param coords the coords of the plugin, not those a version has of its own + * @return the other plugin that holds the name, or null if this plugin holds it now + */ + @CompileDynamic + static String claimForgePackName(Object pack, String coords) { + if (!(pack instanceof Map) || !(pack.kind instanceof String) || !(pack.name instanceof String)) { + return null + } + def holder = FORGE_PACK_HOLDERS.putIfAbsent("$pack.kind $pack.name".toString(), coords) + holder == null || holder == coords ? null : holder + } + + /** + * Claims the names of the packs that are already in the plugin files, before a version is added + * to any of them: a pack that is read later does not take a name from the plugin that had it. + * Two plugins that have one name already are both kept, with a warning. + */ + @CompileDynamic + static void registerForgePackNames(File directory) { + def reported = [] as Set + directory.eachFileRecurse(FileType.FILES) { File f -> + if (!(f.name.endsWith('.yml') || f.name.endsWith('.yaml'))) { + return + } + def pluginInfo = null + try { + f.withInputStream { + pluginInfo = new Yaml().load(it) + } + } + catch(Exception ignore) { + // Reported when the file is processed + } + if (!(pluginInfo instanceof Map) || !(pluginInfo.coords instanceof String) || !(pluginInfo.versions instanceof List)) { + return + } + pluginInfo.versions.each { v -> + def pack = v instanceof Map ? v.pack : null + def holder = claimForgePackName(pack, pluginInfo.coords) + if (holder && reported.add("$pack.kind $pack.name $pluginInfo.coords".toString())) { + System.err.println("WARNING: $f.path has a Forge feature pack with the name of one of $holder, the $pack.kind '$pack.name'. " + + 'The Grails CLI refuses a name that more than one plugin has until the plugin is named with it.') + } + } + } + } + + /** + * The pack of a version as it is recorded: the pack unless another plugin holds its name, in + * which case it is not recorded and a warning says so. */ - static String extractGrailsVersionFromPluginJar(String artifactUrl) throws FileNotFoundException { - readPluginArtifact(artifactUrl).grailsVersion as String + @CompileDynamic + static Map forgePackToRecord(Map pack, String coords, Object version) { + def holder = claimForgePackName(pack, coords) + if (holder) { + System.err.println("WARNING: Ignoring the Forge feature pack of $coords:$version: its name, the $pack.kind '$pack.name', is that of a pack of " + + "$holder. A name belongs to the first plugin that is indexed with it.") + return null + } + pack } /** - * Downloads a plugin artifact once and reads what the index records of it: the grailsVersion of - * its plugin descriptor and, if it has one, its Forge feature pack (see readForgePack). + * Downloads a plugin artifact once and reads what the index records of it (see readPluginArtifactFile). * - * @return a map with the keys 'grailsVersion' and 'pack', each null if not found + * @param withPack whether its Forge feature pack is read, which is the case for the main jar of a plugin only + * @return a map with the keys 'grailsVersion' and 'pack', each null if not found, or an empty map if the artifact is no zip file */ @CompileDynamic - static Map readPluginArtifact(String artifactUrl) throws FileNotFoundException { + static Map readPluginArtifact(String artifactUrl, boolean withPack = true) throws FileNotFoundException { def file = File.createTempFile('plugin-', '.jar').tap { it.deleteOnExit() } - println("Downloading plugin artifact from $artifactUrl to extract grailsVersion and Forge feature pack...") + println("Downloading plugin artifact from $artifactUrl to extract grailsVersion${withPack ? ' and Forge feature pack' : ''}...") doWithConnection(artifactUrl, 'GET') { inputStream.withCloseable { is -> file.withOutputStream { os -> @@ -561,11 +624,37 @@ class Utils { return [:] } + try { + return readPluginArtifactFile(file, artifactUrl, withPack) + } + finally { + file.delete() + } + } + + /** + * Reads what the index records of a plugin artifact: the grailsVersion of its plugin descriptor + * and, if it has one and it is asked for, its Forge feature pack (see readForgePack). The two are + * read independently: a plugin descriptor that cannot be read does not cost the artifact its pack. + * + * @param artifactUrl where the artifact was downloaded from, for the messages + * @return a map with the keys 'grailsVersion' and 'pack', each null if not found, or an empty map if the file is no zip file + */ + @CompileDynamic + static Map readPluginArtifactFile(File file, String artifactUrl, boolean withPack = true) { ZipFile zip = null try { zip = new ZipFile(file) - def pack = readForgePack(zip, file, artifactUrl) - return [grailsVersion: readGrailsVersion(zip), pack: pack] + def pack = withPack ? readForgePack(zip, file, artifactUrl) : null + String grailsVersion = null + try { + grailsVersion = readGrailsVersion(zip) + } + catch(Exception ex) { + // One jar with a plugin descriptor that cannot be read must never fail the index + System.err.println("WARNING: Ignoring the plugin descriptor of $artifactUrl: ${ex.message ?: ex.class.simpleName}") + } + return [grailsVersion: grailsVersion, pack: pack] } catch(ZipException ex) { System.err.println("Invalid Zip file at $artifactUrl : ${ex.message}") @@ -575,59 +664,74 @@ class Utils { if (zip != null) { zip.close() } - file.delete() } } + /** + * Extracts the grailsVersion compatibility string from a Grails plugin artifact. + * + * Looks for META-INF/grails-plugin.xml (plugin.xml for Grails 2) and reads either: + * - + * - or ... + * + * @param zip the plugin artifact + * @return the grailsVersion string (e.g. "6.0.0 > *"), or null if not found + */ @CompileDynamic private static String readGrailsVersion(ZipFile zip) { - def candidates = [ - 'META-INF/grails-plugin.xml', - 'plugin.xml' // Grails 2 - ] - def entry = candidates.findResult { - zip.getEntry(it) - } + def candidates = [ + 'META-INF/grails-plugin.xml', + 'plugin.xml' // Grails 2 + ] + def entry = candidates.findResult { + zip.getEntry(it) + } - if (!entry) { - return null - } + if (!entry) { + return null + } - def xml = null - zip.getInputStream(entry).withCloseable { is -> - xml = new XmlSlurper().parse(is) - } + def xml = null + zip.getInputStream(entry).withCloseable { is -> + xml = new XmlSlurper().parse(is) + } - if (!xml) { - return null - } + if (!xml) { + return null + } - // 1) Try attribute on - String attrVersion = xml.@grailsVersion?.toString() - if (attrVersion) { - return attrVersion - } + // 1) Try attribute on + String attrVersion = xml.@grailsVersion?.toString() + if (attrVersion) { + return attrVersion + } - // 2) Fallback: ... - String elemVersion = xml.grailsVersion?.text() - if (elemVersion) { - return elemVersion - } + // 2) Fallback: ... + String elemVersion = xml.grailsVersion?.text() + if (elemVersion) { + return elemVersion + } - return null + return null } /** - * Adds the `pack` member to versions that are already in the YAML file and have none. + * Makes the `pack` member of the versions that are already in the YAML file what their jars have. * * A version already present is never updated by the normal run, so a plugin that gained a Forge - * feature pack before this indexer recorded packs would never get one. This downloads the main jar - * of each such version once (honouring the version's own `coords` and `maven-repo`) and changes - * nothing but `pack`. It is only done when the script is run with --rescan-packs. + * feature pack before this indexer recorded packs would never get one, and a `pack` that was + * written or edited by hand would stay. This downloads the main jar of each such version once + * (honouring the version's own `coords` and `maven-repo`) and changes nothing but `pack`: it is + * added, and one that is not what the jar has is replaced or removed, with a warning. A version + * whose jar cannot be read is left as it is. It is only done when the script is run with + * --rescan-packs. + * + * @param addedVersions the versions this run added, which were read from their jars just now */ - static void rescanForgePacks(Map pluginInfo) { + @CompileDynamic + static void rescanForgePacks(Map pluginInfo, Collection addedVersions = []) { (pluginInfo.get('versions') ?: [] as List).each { Map v -> - if (v.containsKey('pack') || v.artifactAvailable == false) { + if (v.artifactAvailable == false || v.version in addedVersions) { return } def mavenRepo = (v['maven-repo'] ?: pluginInfo['maven-repo']) as String @@ -637,10 +741,20 @@ class Utils { } try { def version = Version.build(v.version as String) - def pack = readPluginArtifact(createArtifactUrl(mavenRepo, coords, version)).pack + def artifactInfo = readPluginArtifact(createArtifactUrl(mavenRepo, coords, version)) + if (!artifactInfo.containsKey('pack')) { + return + } + def pack = forgePackToRecord(artifactInfo.pack as Map, pluginInfo.coords as String, v.version) + if (v.containsKey('pack') && v.pack != pack) { + System.err.println("WARNING: The pack of $coords:${v.version} was not what the indexer records of its jar and is ${pack ? 'replaced' : 'removed'}") + } if (pack) { v.pack = pack } + else { + v.remove('pack') + } } catch(Exception ex) { System.err.println("INFO: No Forge feature pack read for $coords:${v.version}: ${ex.message ?: ex.class.simpleName}") @@ -725,6 +839,7 @@ class Utils { return null } + def addedVersions = [] as List def mavenRepo = pluginInfo['maven-repo'] as String if (!mavenRepo) { // No mavenRepo -> can't sync versions, but still include in index @@ -757,10 +872,11 @@ class Utils { version: version.versionText, date: versionInfo.date, grailsVersion: versionInfo.grailsVersion, - pack: versionInfo.pack + pack: forgePackToRecord(versionInfo.pack as Map, coords, version) ].findAll { k, v -> v != null } existingVersions << entry + addedVersions << version.versionText } pluginInfo.versions = existingVersions.sort { a, b -> @@ -771,7 +887,7 @@ class Utils { } if (rescanPacks) { - rescanForgePacks(pluginInfo) + rescanForgePacks(pluginInfo, addedVersions) } // Restore the date types (YAML parser converts to String) @@ -793,6 +909,14 @@ def fileArgs = (args ?: []).findAll { it != '--rescan-packs' } def fileArg = fileArgs ? new File(fileArgs[0]) : 'grails-plugins' as File if (fileArg.file) { + // The names the other plugins hold are those of the grails-plugins directory the file is in + def pluginsDirectory = fileArg.absoluteFile.parentFile + while (pluginsDirectory && pluginsDirectory.name != 'grails-plugins') { + pluginsDirectory = pluginsDirectory.parentFile + } + if (pluginsDirectory) { + Utils.registerForgePackNames(pluginsDirectory) + } Utils.processPluginFile(fileArg, rescanPacks) println("Processed single file: $fileArg.path") } @@ -801,6 +925,7 @@ else { System.err.println("ERROR: Directory '$fileArg.path' not found in ${('.' as File).absolutePath}") System.exit(1) } + Utils.registerForgePackNames(fileArg) List indexEntries = [] fileArg.eachFileRecurse(FileType.FILES) { f -> def pluginInfo = Utils.processPluginFile(f, rescanPacks)