diff --git a/README.md b/README.md index 7cf4150..737898d 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,45 @@ 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: 10.0.0 > * + pack: + format: 1 + kind: feature + name: my-feature + templateApi: 1 + applicationTypes: # left out for a feature pack that is for every type + - web + compatibility: + 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 +``` + +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. + +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. + ## 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..22c4e8d --- /dev/null +++ b/index-plugins-test.groovy @@ -0,0 +1,337 @@ +#!/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: '[10.0.0,11.0.0)' + forge: '[10.0.0,11.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 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 == '' +} + +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') +} + + +// 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") + System.exit(1) +} +println 'All tests passed' diff --git a/index-plugins.groovy b/index-plugins.groovy index 8828896..5231691 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,7 +330,15 @@ class Utils { // Try the candidate urls in order for (url in candidateUrls) { try { - grailsCompatibility = extractGrailsVersionFromPluginJar(url) + // A Forge feature pack is only ever read from the main jar of the plugin + def mainJar = url == artifactUrl + def artifactInfo = readPluginArtifact(url, mainJar) + grailsCompatibility = artifactInfo.grailsVersion as String + if (mainJar) { + forgePack = artifactInfo.pack as Map + } + // A pack does not end the search: a main jar without a plugin descriptor leaves the + // grailsVersion to the other artifacts if (grailsCompatibility) { break } @@ -329,9 +347,12 @@ class Utils { } } - if (!grailsCompatibility) { + 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) { @@ -340,27 +361,257 @@ 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'] + /** 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 + /** - * Extracts the grailsVersion compatibility string from a Grails plugin JAR. + * Reads the Forge feature pack of a plugin jar, if it has one, as the `pack` member of a version. * - * Looks for META-INF/grails-plugin.xml and reads either: - * - - * - or ... + * 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; 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. * - * @param jarFile the plugin JAR file - * @return the grailsVersion string (e.g. "6.0.0 > *"), or null if not found + * @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 + def types = forgePackApplicationTypes(descriptor, artifactUrl) + if (types != null) { + pack.applicationTypes = types + } + 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 + } + } + + /** + * 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' 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) { + 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) + } + + /** 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 = [:] + + /** + * 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. + * + * @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. + */ + @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 (see readPluginArtifactFile). + * + * @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 String extractGrailsVersionFromPluginJar(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...") + println("Downloading plugin artifact from $artifactUrl to extract grailsVersion${withPack ? ' and Forge feature pack' : ''}...") doWithConnection(artifactUrl, 'GET') { inputStream.withCloseable { is -> file.withOutputStream { os -> @@ -370,55 +621,143 @@ class Utils { } if (!file || !file.exists()) { - return null + 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 candidates = [ - 'META-INF/grails-plugin.xml', - 'plugin.xml' // Grails 2 - ] - def entry = candidates.findResult { - zip.getEntry(it) + def pack = withPack ? readForgePack(zip, file, artifactUrl) : null + String grailsVersion = null + try { + grailsVersion = readGrailsVersion(zip) } - - if (!entry) { - return null + 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}") } - - def xml = null - zip.getInputStream(entry).withCloseable { is -> - xml = new XmlSlurper().parse(is) + return [grailsVersion: grailsVersion, pack: pack] + } + catch(ZipException ex) { + System.err.println("Invalid Zip file at $artifactUrl : ${ex.message}") + return [:] + } + finally { + if (zip != null) { + zip.close() } + } + } - if (!xml) { - return null - } + /** + * 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) + } - // 1) Try attribute on - String attrVersion = xml.@grailsVersion?.toString() - if (attrVersion) { - return attrVersion - } + if (!entry) { + return null + } - // 2) Fallback: ... - String elemVersion = xml.grailsVersion?.text() - if (elemVersion) { - return elemVersion - } + def xml = null + zip.getInputStream(entry).withCloseable { is -> + xml = new XmlSlurper().parse(is) + } + if (!xml) { return null + } + // 1) Try attribute on + String attrVersion = xml.@grailsVersion?.toString() + if (attrVersion) { + return attrVersion } - catch(ZipException ex) { - System.err.println("Invalid Zip file at $artifactUrl : ${ex.message}") - return null + + // 2) Fallback: ... + String elemVersion = xml.grailsVersion?.text() + if (elemVersion) { + return elemVersion } - finally { - if (zip != null) { - zip.close() + + return null + } + + /** + * 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, 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 + */ + @CompileDynamic + static void rescanForgePacks(Map pluginInfo, Collection addedVersions = []) { + (pluginInfo.get('versions') ?: [] as List).each { Map v -> + if (v.artifactAvailable == false || v.version in addedVersions) { + 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 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}") } } } @@ -470,7 +809,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 @@ -500,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 @@ -531,10 +871,12 @@ class Utils { def entry = [ version: version.versionText, date: versionInfo.date, - grailsVersion: versionInfo.grailsVersion + grailsVersion: versionInfo.grailsVersion, + pack: forgePackToRecord(versionInfo.pack as Map, coords, version) ].findAll { k, v -> v != null } existingVersions << entry + addedVersions << version.versionText } pluginInfo.versions = existingVersions.sort { a, b -> @@ -544,6 +886,10 @@ class Utils { } } + if (rescanPacks) { + rescanForgePacks(pluginInfo, addedVersions) + } + // Restore the date types (YAML parser converts to String) (pluginInfo.versions as List).each { v -> if (v.date && v.date instanceof String) { @@ -557,10 +903,21 @@ 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) + // 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") } else { @@ -568,9 +925,10 @@ 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) + def pluginInfo = Utils.processPluginFile(f, rescanPacks) // Add to index (include everything from YAML) if (pluginInfo) { indexEntries << pluginInfo