From 3bb04df22b30d54a0c8b46701d66c4664c2e141f Mon Sep 17 00:00:00 2001 From: Martin Bonnin Date: Tue, 10 Jun 2025 15:44:58 +0200 Subject: [PATCH 1/2] switch the plugin to gratatouille --- build-logic/build.gradle.kts | 2 +- .../src/main/kotlin/CompilerOptions.kt | 8 - build-logic/src/main/kotlin/Publishing.kt | 6 - build.gradle.kts | 3 +- docs/source/advanced/persisted-queries.mdx | 2 +- docs/source/advanced/plugin-configuration.mdx | 12 +- docs/source/caching/declarative-ids.mdx | 2 +- docs/source/caching/programmatic-ids.mdx | 2 +- docs/source/essentials/modules.mdx | 14 +- gradle.properties | 3 + gradle/libraries.toml | 4 +- intellij-plugin/build.gradle.kts | 8 +- .../apollo-compiler/api/apollo-compiler.api | 38 +- .../apollo/compiler/ApolloCompiler.kt | 12 +- .../ApolloCompilerPluginEnvironment.kt | 2 +- .../apollographql/apollo/compiler/Options.kt | 51 +- .../compiler/codegen/java/JavaResolver.kt | 3 +- .../compiler/codegen/kotlin/KotlinResolver.kt | 3 +- .../apollo/compiler/entrypoints.kt | 158 ++--- .../internal/GradleCompilerPluginLogger.kt | 39 -- .../com/apollographql/apollo/compiler/json.kt | 6 +- .../apollo-gradle-plugin-external/README.md | 9 - .../api/apollo-gradle-plugin-external.api | 225 ------ .../build.gradle.kts | 60 -- .../gradle/internal/ApolloBuildService.kt | 27 - .../internal/ApolloConvertSchemaTask.kt | 66 -- .../internal/ApolloDownloadSchemaTask.kt | 121 ---- .../ApolloGenerateCodegenSchemaTask.kt | 102 --- ...olloGenerateDataBuildersSourcesBaseTask.kt | 9 - .../ApolloGenerateDataBuildersSourcesTask.kt | 90 --- .../ApolloGenerateIrOperationsTask.kt | 89 --- .../internal/ApolloGenerateOptionsTask.kt | 369 ---------- .../internal/ApolloGenerateSourcesBaseTask.kt | 26 - .../ApolloGenerateSourcesFromIrTask.kt | 102 --- .../internal/ApolloGenerateSourcesTask.kt | 100 --- .../apollo/gradle/internal/ApolloPlugin.kt | 59 -- .../gradle/internal/ApolloPushSchemaTask.kt | 81 --- .../internal/ApolloRegisterOperationsTask.kt | 106 --- .../internal/ApolloTaskWithClasspath.kt | 65 -- .../apollo/gradle/internal/BuildDirLayout.kt | 100 --- .../apollo/gradle/internal/TaskExtensions.kt | 11 - .../apollo/gradle/internal/defaults.kt | 115 --- .../apollo/gradle/internal/utils.kt | 61 -- .../apollo-gradle-plugin-tasks/README.md | 5 + .../api/apollo-gradle-plugin-tasks.api | 99 +++ .../build.gradle.kts | 25 + .../gradle.properties | 0 .../task/apolloComputeUsedCoordinates.kt | 22 + .../gradle/task/apolloDownloadSchema.kt | 52 ++ .../task/apolloGenerateCodegenSchema.kt | 41 ++ .../task/apolloGenerateDataBuildersSources.kt | 34 + .../gradle/task/apolloGenerateIrOperations.kt | 32 + .../gradle/task/apolloGenerateOptions.kt | 283 ++++++++ .../gradle/task/apolloGenerateSources.kt | 44 ++ .../task/apolloGenerateSourcesFromIr.kt | 46 ++ .../gradle/task/apolloRegisterOperations.kt | 81 +++ .../apollo/gradle/task/defaults.kt | 12 + .../apollographql/apollo/gradle/task/utils.kt | 31 + libraries/apollo-gradle-plugin/README.md | 4 - .../api/apollo-gradle-plugin.api | 243 +++++++ .../apollo-gradle-plugin/build.gradle.kts | 193 ++---- libraries/apollo-gradle-plugin/rules.pro | 54 -- .../apollo/compiler/OptionsOverlay.kt | 53 ++ .../apollo/gradle/api/ApolloDependencies.kt | 0 .../apollo/gradle/api/ApolloExtension.kt | 1 - .../gradle/api/ApolloGradleToolingModel.kt | 0 .../apollo/gradle/api/CompilerPlugin.kt | 0 .../apollo/gradle/api/Introspection.kt | 0 .../gradle/api/RegisterOperationsConfig.kt | 0 .../apollo/gradle/api/Registry.kt | 0 .../apollo/gradle/api/Service.kt | 50 +- .../gradle/internal/AndroidPluginFacade.kt | 0 .../gradle/internal/ApolloAttributes.kt | 0 .../gradle/internal/ApolloBuildService.kt | 8 + .../apollo/gradle/internal/BuildDirLayout.kt | 33 + .../gradle/internal/DefaultApolloExtension.kt | 655 ++++++++---------- .../DefaultApolloGradleToolingModel.kt | 0 .../gradle/internal/DefaultCompilerPlugin.kt | 0 .../internal/DefaultDirectoryConnection.kt | 0 .../gradle/internal/DefaultIntrospection.kt | 0 .../DefaultRegisterOperationsConfig.kt | 0 .../apollo/gradle/internal/DefaultRegistry.kt | 0 .../apollo/gradle/internal/DefaultService.kt | 0 .../gradle/internal/KotlinPluginFacade.kt | 24 +- .../apollo/gradle/internal/ModelNames.kt | 4 +- .../apollo/gradle/internal/Telemetry.kt | 0 .../apollo/gradle/internal/androidProject.kt | 0 .../apollo/gradle/internal/apolloPlugin.kt | 52 ++ .../apollo/gradle/internal/javaProject.kt | 0 .../apollo/gradle/internal/kotlinProject.kt | 0 .../apollo/gradle/internal/normalization.kt | 0 .../apollo/gradle/internal/project.kt | 0 .../apollo/gradle/internal/utils.kt | 16 + .../src/test-java11/README.md | 1 - .../kotlin/test/ConvertSchemaTests.kt | 103 --- .../kotlin/test/Agp8_2Test.kt | 0 .../kotlin/test/AndroidProjectTests.kt | 14 +- .../kotlin/test/ConfigurationCacheTests.kt | 0 .../kotlin/test/DeprecationTests.kt | 0 .../kotlin/test/DownloadSchemaTests.kt | 60 -- .../kotlin/test/GradleBuildCacheTests.kt | 0 .../kotlin/test/GradleToolingTests.kt | 0 .../kotlin}/test/GradleVersionTests.kt | 4 +- .../kotlin/test/GroovyTests.kt | 0 .../kotlin/test/JavaOnly.kt | 0 .../kotlin/test/KotlinDSLTests.kt | 6 +- .../kotlin/test/KotlinJVMProjectTests.kt | 4 +- .../test/KotlinMultiplatformProjectTests.kt | 0 .../kotlin/test/KotlinPluginVersionTests.kt | 0 .../kotlin/test/LanguageVersionTests.kt | 10 +- .../kotlin/test/LazyTests.kt | 0 .../kotlin/test/MultiModulesTests.kt | 6 +- .../kotlin/test/MultiServicesTests.kt | 12 +- .../kotlin/test/OperationIdGeneratorTests.kt | 6 +- .../kotlin/test/RegisterOperationsTests.kt | 4 +- .../kotlin/test/SchemaResolutionTests.kt | 10 +- .../kotlin/test/ServiceTests.kt | 74 +- .../kotlin/test/UpToDateTests.kt | 20 +- .../src/test/kotlin/util/TestUtils.kt | 4 +- .../gradle-min-version/build.gradle.kts | 1 + .../register-operations/build.gradle.kts | 3 +- settings.gradle.kts | 1 - tests/build.gradle.kts | 5 + tests/compiler-plugins/app/build.gradle.kts | 3 +- .../{TestPlugin.kt => DefaultToNullPlugin.kt} | 2 +- ...aphql.apollo.compiler.ApolloCompilerPlugin | 2 +- .../src/main/kotlin/schema/TestPlugin.kt | 8 +- tests/gradle.properties | 3 + tests/integration-tests/build.gradle.kts | 4 +- .../kotlin/test/OperationOutputTest.kt | 41 -- tests/platform-api/build.gradle.kts | 11 - tests/schema-transform/app/build.gradle.kts | 1 - 132 files changed, 1812 insertions(+), 3179 deletions(-) delete mode 100644 libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger.kt delete mode 100644 libraries/apollo-gradle-plugin-external/README.md delete mode 100644 libraries/apollo-gradle-plugin-external/api/apollo-gradle-plugin-external.api delete mode 100644 libraries/apollo-gradle-plugin-external/build.gradle.kts delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloConvertSchemaTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloDownloadSchemaTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateCodegenSchemaTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesBaseTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateIrOperationsTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateOptionsTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesBaseTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesFromIrTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPlugin.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPushSchemaTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloRegisterOperationsTask.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloTaskWithClasspath.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/TaskExtensions.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/defaults.kt delete mode 100644 libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/README.md create mode 100644 libraries/apollo-gradle-plugin-tasks/api/apollo-gradle-plugin-tasks.api create mode 100644 libraries/apollo-gradle-plugin-tasks/build.gradle.kts rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin-tasks}/gradle.properties (100%) create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloComputeUsedCoordinates.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloDownloadSchema.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateCodegenSchema.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateDataBuildersSources.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateIrOperations.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateOptions.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSources.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSourcesFromIr.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloRegisterOperations.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/defaults.kt create mode 100644 libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/utils.kt delete mode 100644 libraries/apollo-gradle-plugin/rules.pro create mode 100644 libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/compiler/OptionsOverlay.kt rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloDependencies.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt (98%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloGradleToolingModel.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/CompilerPlugin.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/Introspection.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/RegisterOperationsConfig.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/Registry.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt (93%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/AndroidPluginFacade.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloAttributes.kt (100%) create mode 100644 libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt create mode 100644 libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt (60%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloGradleToolingModel.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultCompilerPlugin.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultDirectoryConnection.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultIntrospection.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegisterOperationsConfig.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegistry.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultService.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt (70%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt (93%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/Telemetry.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/androidProject.kt (100%) create mode 100644 libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/apolloPlugin.kt rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/javaProject.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/kotlinProject.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/normalization.kt (100%) rename libraries/{apollo-gradle-plugin-external => apollo-gradle-plugin}/src/main/kotlin/com/apollographql/apollo/gradle/internal/project.kt (100%) create mode 100644 libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt delete mode 100644 libraries/apollo-gradle-plugin/src/test-java11/README.md delete mode 100644 libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ConvertSchemaTests.kt rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/Agp8_2Test.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/AndroidProjectTests.kt (89%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/ConfigurationCacheTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/DeprecationTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/DownloadSchemaTests.kt (75%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/GradleBuildCacheTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/GradleToolingTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java11/kotlin/com/apollographql/apollo/gradle => test/kotlin}/test/GradleVersionTests.kt (94%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/GroovyTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/JavaOnly.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/KotlinDSLTests.kt (91%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/KotlinJVMProjectTests.kt (93%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/KotlinMultiplatformProjectTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/KotlinPluginVersionTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/LanguageVersionTests.kt (91%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/LazyTests.kt (100%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/MultiModulesTests.kt (97%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/MultiServicesTests.kt (83%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/OperationIdGeneratorTests.kt (83%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/RegisterOperationsTests.kt (80%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/SchemaResolutionTests.kt (92%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/ServiceTests.kt (77%) rename libraries/apollo-gradle-plugin/src/{test-java17 => test}/kotlin/test/UpToDateTests.kt (77%) rename tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/{TestPlugin.kt => DefaultToNullPlugin.kt} (97%) delete mode 100644 tests/integration-tests/src/jvmTest/kotlin/test/OperationOutputTest.kt diff --git a/build-logic/build.gradle.kts b/build-logic/build.gradle.kts index ed931a50925..a62d801f437 100644 --- a/build-logic/build.gradle.kts +++ b/build-logic/build.gradle.kts @@ -53,7 +53,7 @@ dependencies { runtimeOnly(libs.sqldelight.plugin) runtimeOnly(libs.gradle.publish.plugin) runtimeOnly(libs.benmanes.versions) - runtimeOnly(libs.gr8) + runtimeOnly(libs.gratatouille) runtimeOnly(libs.kotlinx.binarycompatibilityvalidator) } diff --git a/build-logic/src/main/kotlin/CompilerOptions.kt b/build-logic/src/main/kotlin/CompilerOptions.kt index ace02255166..0a6a5586214 100644 --- a/build-logic/src/main/kotlin/CompilerOptions.kt +++ b/build-logic/src/main/kotlin/CompilerOptions.kt @@ -96,14 +96,6 @@ fun Project.configureJavaAndKotlinCompilers(jvmTarget: Int?, kotlinCompilerOptio allWarningsAsErrors(true) } -fun setTestToolchain(project: Project, test: Test, javaVersion: Int) { - val javaToolchains = project.extensions.getByName("javaToolchains") as JavaToolchainService - test.javaLauncher.set(javaToolchains.launcherFor { - languageVersion.set(JavaLanguageVersion.of(javaVersion)) - }) - -} - fun Project.allWarningsAsErrors(allWarningsAsErrors: Boolean) { kotlinExtensionOrNull?.forEachCompilerOptions { this.allWarningsAsErrors.set(allWarningsAsErrors) diff --git a/build-logic/src/main/kotlin/Publishing.kt b/build-logic/src/main/kotlin/Publishing.kt index 8c721833fe3..777d5253aff 100644 --- a/build-logic/src/main/kotlin/Publishing.kt +++ b/build-logic/src/main/kotlin/Publishing.kt @@ -238,12 +238,6 @@ private fun Project.configurePublishingInternal() { } } - plugins.hasPlugin("com.gradle.plugin-publish") -> { - /** - * com.gradle.plugin-publish creates all publications - */ - } - plugins.hasPlugin("java-gradle-plugin") -> { /** * java-gradle-plugin creates 2 publications (one marker and one regular) but without source/javadoc. diff --git a/build.gradle.kts b/build.gradle.kts index 5e1f6c9b9ce..4c08b8c8b1f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -59,8 +59,7 @@ tasks.register("ciPublishRelease") { tasks.register("ciTestsGradle") { description = "Execute the Gradle tests (slow)" - dependsOn(":apollo-gradle-plugin:allTests") - dependsOn(":apollo-gradle-plugin-external:validatePlugins") + dependsOn(":apollo-gradle-plugin:test") } tasks.register("ciTestsNoGradle") { diff --git a/docs/source/advanced/persisted-queries.mdx b/docs/source/advanced/persisted-queries.mdx index 253faf90a63..0763f07693f 100644 --- a/docs/source/advanced/persisted-queries.mdx +++ b/docs/source/advanced/persisted-queries.mdx @@ -57,7 +57,7 @@ apollo { The operation manifest is generated during code generation. This happens automatically every time you build your project, or you can trigger it manually by executing the `generateApolloSources` Gradle task. -The operation manifest is generated in `build/generated/manifest/apollo/$serviceName/persistedQueryManifest.json`, where `$serviceName` is `"api"` here. The resulting operation manifest looks something like this: +The operation manifest is generated in `build/generated/manifest/apollo/$serviceName/persistedQueryManifest.json`, where `$serviceName` is `"api"` here. The resulting operation manifest is similar to the following example: ```json title="persistedQueryManifest.json" { diff --git a/docs/source/advanced/plugin-configuration.mdx b/docs/source/advanced/plugin-configuration.mdx index 52c9fe13563..f864e8f6fd4 100644 --- a/docs/source/advanced/plugin-configuration.mdx +++ b/docs/source/advanced/plugin-configuration.mdx @@ -22,7 +22,7 @@ apollo { For more advanced usages, below are all Apollo Gradle Plugin options in a single code block. You can also take a look at the [Gradle Plugin recipes](../advanced/plugin-recipes). -Please refer to the [ApolloExtension](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin-external/com.apollographql.apollo.gradle.api/-apollo-extension/index.html) and [Service](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin-external/com.apollographql.apollo.gradle.api/-service/index.html) API reference for details about a specific API. +Refer to the [ApolloExtension](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin/com.apollographql.apollo.gradle.api/-apollo-extension/index.html) and [Service](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin/com.apollographql.apollo.gradle.api/-service/index.html) API reference for details about each API. ```kotlin apollo { @@ -70,10 +70,8 @@ apollo { mapScalarToJavaObject("MyObject") - // The format to output for the operation manifest. One of "operationOutput", "persistedQueryManifest" + // The format to output for the operation manifest. One of "none" (default) or "persistedQueryManifest" operationManifestFormat.set("persistedQueryManifest") - // The file where to write the operation manifest - operationManifest.set(file("build/generated/persistedQueryManifest.json")) // Whether to generate Kotlin or Java models generateKotlinModels.set(true) @@ -123,11 +121,7 @@ apollo { classesForEnumsMatching.set(listOf(".*")) // Whether fields with different shape are disallowed to be merged in disjoint types. fieldsOnDisjointTypesMustMerge.set(false) - - - // The directory where the generated models are written. - outputDir.set(file("build/generated/apollo")) - + // Whether to generate Apollo metadata. Apollo metadata is used for multi-module support. generateApolloMetadata.set(true) // list of [Regex] patterns matching for types and fields that should be generated whether they are used by queries/fragments in this module or not. diff --git a/docs/source/caching/declarative-ids.mdx b/docs/source/caching/declarative-ids.mdx index 94cbf32ae5c..ddd64d47fed 100644 --- a/docs/source/caching/declarative-ids.mdx +++ b/docs/source/caching/declarative-ids.mdx @@ -79,7 +79,7 @@ extend interface Node @typePolicy(keyFields: "id") ## Adding `__typename` to your operations -In addition to the key fields, the declarative cache requires the `__typename` of each object by default. These typenames are not included by default as they make query larger for non-cache users. To avoid cache misses, add `__typename` to every selection using [addTypename](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin-external/com.apollographql.apollo.gradle.api/-service/add-typename.html): +In addition to the key fields, the declarative cache requires the `__typename` of each object by default. These typenames are not included by default because they make the queries larger for users not using the cache. To avoid cache misses, add `__typename` to every selection using [addTypename](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin/com.apollographql.apollo.gradle.api/-service/add-typename.html): ```kotlin apollo { diff --git a/docs/source/caching/programmatic-ids.mdx b/docs/source/caching/programmatic-ids.mdx index a1a08eb7835..81301c550ee 100644 --- a/docs/source/caching/programmatic-ids.mdx +++ b/docs/source/caching/programmatic-ids.mdx @@ -55,7 +55,7 @@ You can also use the current object's typename to use _different_ cache ID gener Note that for cache ID generation to work, your GraphQL operations must return whatever fields your custom code relies on (such as `id` above). If a query does not return a required field, the cache ID will be inconsistent, resulting in data duplication. Also, for interfaces and unions, `context.field.type.rawType().name` yields the typename as it is declared in the schema, as opposed to the runtime value of the type received in the response. Instead, querying for the `__typename` is safer. -To make sure `__typename` is included in all operations set the [addTypename](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin-external/com.apollographql.apollo.gradle.api/-service/add-typename.html) gradle config: +To make sure `__typename` is included in all operations set the [addTypename](https://www.apollographql.com/docs/kotlin/kdoc/apollo-gradle-plugin/com.apollographql.apollo.gradle.api/-service/add-typename.html) gradle config: ``` apollo { diff --git a/docs/source/essentials/modules.mdx b/docs/source/essentials/modules.mdx index 6be3552773e..96715964d8f 100644 --- a/docs/source/essentials/modules.mdx +++ b/docs/source/essentials/modules.mdx @@ -48,21 +48,13 @@ See ["Apollo Compiler plugins"](https://www.apollographql.com/docs/kotlin/advanc `apollo-gradle-plugin` contains the Apollo Gradle plugin. -This module shadows and relocates its runtime dependencies to avoid classpath issues. This can make debugging harder in some cases. - -See `apollo-gradle-plugin-external` for a version of `apollo-gradle-plugin` that does not shadow its dependencies. - See ["Gradle Plugin Configuration"](https://www.apollographql.com/docs/kotlin/advanced/plugin-configuration/) for how to use the Gradle plugin. -### apollo-gradle-plugin-external - -`apollo-gradle-plugin-external` contains the Apollo Gradle plugin. +### apollo-gradle-plugin-tasks -This module does not shadow its runtime dependencies, making it more prone to Gradle classpath issues. +`apollo-gradle-plugin-tasks` contains the task implementations for the Apollo Gradle plugin. -See `apollo-gradle-plugin` for a version of `apollo-gradle-plugin-external` that shadow its dependencies. - -See ["Gradle Plugin Configuration"](https://www.apollographql.com/docs/kotlin/advanced/plugin-configuration/) for how to use the Gradle plugin. +This module is loaded in a separate classloader to allow compiler plugins and avoid polluting the main build script classpath. This module is an implementation detail of `apollo-gradle-plugin` and should not be depended on directly. ### apollo-http-cache diff --git a/gradle.properties b/gradle.properties index 3d4aae13aa4..5f497590ae5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -30,3 +30,6 @@ org.jetbrains.dokka.experimental.tryK2.nowarn=true # https://kotlinlang.slack.com/archives/C0B8L3U69/p1740063113894839 kotlin.js.yarn=false + +# https://github.com/gradle/gradle/issues/31278 +kotlin.internal.collectFUSMetrics=false diff --git a/gradle/libraries.toml b/gradle/libraries.toml index 8f47af553c5..0e712db6ab4 100644 --- a/gradle/libraries.toml +++ b/gradle/libraries.toml @@ -24,6 +24,7 @@ atomicfu = "0.26.0" compat-patrouille = "0.0.0" compose = "1.5.1" guava = "31.1-jre" +gratatouille = "0.0.10" javaPoet = "1.13.0" jetbrains-annotations = "24.0.1" junit = "4.13.2" @@ -97,7 +98,8 @@ dgp = "com.gradle:develocity-gradle-plugin:4.0.2" # // sync with settings.gradle # annotation @org.jetbrains.annotations.Nullable not applicable in this type context google-testing-compile = { group = "com.google.testing.compile", name = "compile-testing", version = "0.19" } google-testparameterinjector = { group = "com.google.testparameterinjector", name = "test-parameter-injector", version = "1.11" } -gr8 = { group = "com.gradleup", name = "gr8-plugin", version = "0.11.1" } +gratatouille = { group = "com.gradleup.gratatouille", name = "gratatouille-gradle-plugin", version.ref = "gratatouille" } + # # See https://github.com/gradle/gradle/issues/1835 # We use the Nokee[redistributed artifacts](https://docs.nokee.dev/manual/gradle-plugin-development.html#sec:gradle-dev-redistributed-gradle-api) diff --git a/intellij-plugin/build.gradle.kts b/intellij-plugin/build.gradle.kts index 81792ea2d96..93c86a68a33 100644 --- a/intellij-plugin/build.gradle.kts +++ b/intellij-plugin/build.gradle.kts @@ -146,7 +146,7 @@ apollo { } } -// We're using project(":apollo-gradle-plugin-external") and the published "apollo-runtime" which do not have the same version +// We're using project(":apollo-gradle-plugin") and the published "apollo-runtime" which do not have the same version tasks.configureEach { if (name == "checkApolloVersions") { enabled = false @@ -171,11 +171,7 @@ dependencies { zipSigner() } - // Coroutines must be excluded to avoid a conflict with the version bundled with the IDE - // See https://plugins.jetbrains.com/docs/intellij/using-kotlin.html#coroutinesLibraries - implementation(project(":apollo-gradle-plugin-external")) { - exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-coroutines-core") - } + implementation(project(":apollo-gradle-plugin")) implementation(project(":apollo-ast")) implementation(project(":apollo-tooling")) { exclude(group = "org.jetbrains.kotlinx", module = "kotlinx-coroutines-core") diff --git a/libraries/apollo-compiler/api/apollo-compiler.api b/libraries/apollo-compiler/api/apollo-compiler.api index 5caf06ba15b..ed51df936e2 100644 --- a/libraries/apollo-compiler/api/apollo-compiler.api +++ b/libraries/apollo-compiler/api/apollo-compiler.api @@ -23,6 +23,9 @@ public final class com/apollographql/apollo/compiler/ApolloCompiler { } public abstract interface class com/apollographql/apollo/compiler/ApolloCompiler$Logger { + public abstract fun debug (Ljava/lang/String;)V + public abstract fun error (Ljava/lang/String;)V + public abstract fun info (Ljava/lang/String;)V public abstract fun warning (Ljava/lang/String;)V } @@ -36,9 +39,9 @@ public abstract interface class com/apollographql/apollo/compiler/ApolloCompiler } public final class com/apollographql/apollo/compiler/ApolloCompilerPluginEnvironment { - public fun (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompilerPluginLogger;)V + public fun (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger;)V public final fun getArguments ()Ljava/util/Map; - public final fun getLogger ()Lcom/apollographql/apollo/compiler/ApolloCompilerPluginLogger; + public final fun getLogger ()Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger; } public abstract interface class com/apollographql/apollo/compiler/ApolloCompilerPluginLogger { @@ -203,12 +206,12 @@ public abstract interface class com/apollographql/apollo/compiler/DocumentTransf } public final class com/apollographql/apollo/compiler/EntryPoints { - public fun ()V - public final fun buildCodegenSchema (Ljava/util/Map;IZLjava/util/List;Ljava/util/function/Consumer;Ljava/io/File;Ljava/io/File;)V - public final fun buildDataBuilders (Ljava/util/Map;IZLjava/util/List;Ljava/util/List;Ljava/util/Map;Ljava/io/File;Ljava/io/File;)V - public final fun buildIr (Ljava/util/Map;ILjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/util/function/Consumer;Ljava/io/File;)V - public final fun buildSources (Ljava/util/Map;IZLjava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/util/function/Consumer;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V - public final fun buildSourcesFromIr (Ljava/util/Map;IZLjava/util/List;Ljava/util/List;Ljava/io/File;Ljava/util/Map;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V + public static final field INSTANCE Lcom/apollographql/apollo/compiler/EntryPoints; + public final fun buildCodegenSchema (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger;ZLjava/util/List;Ljava/io/File;Ljava/io/File;)V + public final fun buildDataBuilders (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger;ZLjava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V + public final fun buildIr (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V + public final fun buildSources (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger;ZLjava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V + public final fun buildSourcesFromIr (Ljava/util/Map;Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger;ZLjava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V } public final class com/apollographql/apollo/compiler/EntrypointsKt { @@ -250,6 +253,7 @@ public final class com/apollographql/apollo/compiler/FileUtils { public static final fun readIrSchema (Ljava/io/File;)Lcom/apollographql/apollo/compiler/ir/IrSchema; public static final fun readOperationOutput (Ljava/io/File;)Ljava/util/Map; public static final fun readPersistedQueryManifest (Ljava/io/File;)Lcom/apollographql/apollo/compiler/pqm/PersistedQueryManifest; + public static final fun toUsedCoordinates (Ljava/io/File;)Lcom/apollographql/apollo/compiler/UsedCoordinates; public static final fun writeCodegenMetadata (Lcom/apollographql/apollo/compiler/CodegenMetadata;Ljava/io/File;)V public static final fun writeCodegenOptions (Lcom/apollographql/apollo/compiler/CodegenOptions;Ljava/io/File;)V public static final fun writeCodegenSchema (Lcom/apollographql/apollo/compiler/CodegenSchema;Ljava/io/File;)V @@ -259,6 +263,7 @@ public final class com/apollographql/apollo/compiler/FileUtils { public static final fun writeIrSchema (Lcom/apollographql/apollo/compiler/ir/IrSchema;Ljava/io/File;)V public static final fun writeOperationOutput (Ljava/util/Map;Ljava/io/File;)V public static final fun writePersistedQueryManifest (Lcom/apollographql/apollo/compiler/pqm/PersistedQueryManifest;Ljava/io/File;)V + public static final fun writeTo (Lcom/apollographql/apollo/compiler/UsedCoordinates;Ljava/io/File;)V } public final class com/apollographql/apollo/compiler/GeneratedMethod : java/lang/Enum { @@ -666,23 +671,6 @@ public final class com/apollographql/apollo/compiler/codegen/kotlin/helpers/Add_ public static final fun addInternal (Lcom/squareup/kotlinpoet/FileSpec$Builder;Ljava/util/List;)Lcom/squareup/kotlinpoet/FileSpec$Builder; } -public final class com/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger : com/apollographql/apollo/compiler/ApolloCompilerPluginLogger { - public static final field Companion Lcom/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger$Companion; - public static final field LOGGING_LEVEL_ERROR I - public static final field LOGGING_LEVEL_INFO I - public static final field LOGGING_LEVEL_LOGGING I - public static final field LOGGING_LEVEL_WARN I - public fun (I)V - public fun error (Ljava/lang/String;)V - public final fun getLoglevel ()I - public fun info (Ljava/lang/String;)V - public fun logging (Ljava/lang/String;)V - public fun warn (Ljava/lang/String;)V -} - -public final class com/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger$Companion { -} - public final class com/apollographql/apollo/compiler/ir/BLabel : com/apollographql/apollo/compiler/ir/BTerm { public fun (Ljava/lang/String;)V public final fun component1 ()Ljava/lang/String; diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompiler.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompiler.kt index 82a5e768d8d..8d42675ed6a 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompiler.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompiler.kt @@ -51,7 +51,10 @@ import java.io.File object ApolloCompiler { interface Logger { + fun debug(message: String) + fun info(message: String) fun warning(message: String) + fun error(message: String) } fun buildCodegenSchema( @@ -412,19 +415,16 @@ object ApolloCompiler { """.trimMargin() } - val operationManifestFormat = codegenOptions.operationManifestFormat - if ((operationManifestFormat ?: defaultOperationManifestFormat) != MANIFEST_NONE) { - check(operationManifestFile != null) { - "Apollo: no operationManifestFile set to output '$operationManifestFormat' operation manifest" - } + if (operationManifestFile != null) { + val operationManifestFormat = codegenOptions.operationManifestFormat @Suppress("DEPRECATION_ERROR") when (operationManifestFormat) { + MANIFEST_NONE -> operationManifestFile.writeText("Use operationManifestFormat to generate the operation manifest.") MANIFEST_OPERATION_OUTPUT -> operationOutput.writeTo(operationManifestFile) MANIFEST_PERSISTED_QUERY -> operationOutput.toPersistedQueryManifest().writeTo(operationManifestFile) } } - @Suppress("NAME_SHADOWING") val layout = layout ?: SchemaAndOperationsLayout( codegenSchema = codegenSchema, diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompilerPluginEnvironment.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompilerPluginEnvironment.kt index 67e939229f6..55b67b17383 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompilerPluginEnvironment.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/ApolloCompilerPluginEnvironment.kt @@ -11,7 +11,7 @@ class ApolloCompilerPluginEnvironment( /** * A logger that can be used by the plugin. */ - val logger: ApolloCompilerPluginLogger, + val logger: ApolloCompiler.Logger, ) /** diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/Options.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/Options.kt index e31479aeb33..04eb2e3aca5 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/Options.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/Options.kt @@ -8,20 +8,30 @@ import com.apollographql.apollo.compiler.operationoutput.OperationOutput import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable -const val MODELS_RESPONSE_BASED = "responseBased" -const val MODELS_OPERATION_BASED = "operationBased" -const val MODELS_OPERATION_BASED_WITH_INTERFACES = "experimental_operationBasedWithInterfaces" - -const val ADD_TYPENAME_IF_FRAGMENTS = "ifFragments" -const val ADD_TYPENAME_IF_POLYMORPHIC = "ifPolymorphic" -const val ADD_TYPENAME_IF_ABSTRACT = "ifAbstract" -const val ADD_TYPENAME_ALWAYS = "always" - -@Deprecated("Use $MANIFEST_PERSISTED_QUERY instead", level = DeprecationLevel.ERROR) +@JvmField +val MODELS_RESPONSE_BASED = "responseBased" +@JvmField +val MODELS_OPERATION_BASED = "operationBased" +@JvmField +val MODELS_OPERATION_BASED_WITH_INTERFACES = "experimental_operationBasedWithInterfaces" + +@JvmField +val ADD_TYPENAME_IF_FRAGMENTS = "ifFragments" +@JvmField +val ADD_TYPENAME_IF_POLYMORPHIC = "ifPolymorphic" +@JvmField +val ADD_TYPENAME_IF_ABSTRACT = "ifAbstract" +@JvmField +val ADD_TYPENAME_ALWAYS = "always" + +@Deprecated("Use persistedQueryManifest instead", level = DeprecationLevel.ERROR) @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v4_0_1) -const val MANIFEST_OPERATION_OUTPUT = "operationOutput" -const val MANIFEST_PERSISTED_QUERY = "persistedQueryManifest" -const val MANIFEST_NONE = "none" +@JvmField +val MANIFEST_OPERATION_OUTPUT = "operationOutput" +@JvmField +val MANIFEST_PERSISTED_QUERY = "persistedQueryManifest" +@JvmField +val MANIFEST_NONE = "none" enum class TargetLanguage { // The order is important. See [isTargetLanguageVersionAtLeast] @@ -587,7 +597,7 @@ fun CodegenOptions.validate() { if (generateFilterNotNull != null) { error("Apollo: generateFilterNotNull is not used in Java") } - if (sealedClassesForEnumsMatching != null) { + if (sealedClassesForEnumsMatching.orEmpty().isNotEmpty()) { error("Apollo: sealedClassesForEnumsMatching is not used in Java") } if (addJvmOverloads != null) { @@ -609,7 +619,7 @@ fun CodegenOptions.validate() { if (generateModelBuilders != null) { error("Apollo: generateModelBuilders is not used in Kotlin") } - if (classesForEnumsMatching != null) { + if (classesForEnumsMatching.orEmpty().isNotEmpty()) { error("Apollo: classesForEnumsMatching is not used in Kotlin") } if (generatePrimitiveTypes != null) { @@ -641,8 +651,17 @@ class ExpressionAdapterInitializer(val expression: String) : AdapterInitializer object RuntimeAdapterInitializer : AdapterInitializer private val NoOpLogger = object : ApolloCompiler.Logger { + override fun debug(message: String) { + } + + override fun info(message: String) { + } + override fun warning(message: String) { } + + override fun error(message: String) { + } } internal val defaultAlwaysGenerateTypesMatching = emptySet() @@ -662,7 +681,7 @@ internal const val defaultGenerateFilterNotNull = false internal const val defaultGenerateFragmentImplementations = false internal const val defaultGenerateResponseFields = true internal const val defaultGenerateQueryDocument = true -internal const val defaultAddTypename = ADD_TYPENAME_IF_FRAGMENTS +internal val defaultAddTypename = ADD_TYPENAME_IF_FRAGMENTS internal const val defaultRequiresOptInAnnotation = "none" internal const val defaultFlattenModels = true internal const val defaultGenerateSchema = false diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/java/JavaResolver.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/java/JavaResolver.kt index c4d239cd654..c6b2317480a 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/java/JavaResolver.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/java/JavaResolver.kt @@ -101,8 +101,7 @@ internal class JavaResolver( val result = resolve(ResolverKey(kind, id)) check(result != null) { - "Cannot resolve $kind($id). " + - "Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?" + "Cannot resolve $kind($id). Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?" } return result } diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/kotlin/KotlinResolver.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/kotlin/KotlinResolver.kt index 115b60849ed..331d62dde36 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/kotlin/KotlinResolver.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/codegen/kotlin/KotlinResolver.kt @@ -65,8 +65,7 @@ internal class KotlinResolver( val result = resolve(ResolverKey(kind, id)) check(result != null) { - "Cannot resolve $kind($id). " + - "Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?" + "Cannot resolve $kind($id). Have you set up an 'opposite link' on the downstream project to the schema module as a isADependencyOf(..)?" } return result } diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/entrypoints.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/entrypoints.kt index ceee935f9e8..8a49f4f8c1d 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/entrypoints.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/entrypoints.kt @@ -5,39 +5,32 @@ import com.apollographql.apollo.compiler.ApolloCompiler.buildIrOperations import com.apollographql.apollo.compiler.ApolloCompiler.buildSchemaAndOperationsSourcesFromIr import com.apollographql.apollo.compiler.codegen.writeTo import com.apollographql.apollo.compiler.internal.DefaultApolloCompilerRegistry -import com.apollographql.apollo.compiler.internal.GradleCompilerPluginLogger import java.io.File import java.util.ServiceLoader -import java.util.function.Consumer /** - * EntryPoints contains code called using reflection from the Gradle plugin. - * This is so that the classloader can be isolated, and we can use our preferred version of - * Kotlin and other dependencies without risking conflicts. - * - * It is a version of [ApolloCompiler] that takes plain [File]s and other classes available to the bootstrap classloader only. + * EntryPoints is a higher level API compared to [ApolloCompiler]. + * It deals with compiler plugins and serializing/deserializing files. */ -@Suppress("UNUSED") // Used from reflection @ApolloInternal -class EntryPoints { +object EntryPoints { fun buildCodegenSchema( arguments: Map, - logLevel: Int, + logger: ApolloCompiler.Logger, warnIfNotFound: Boolean, - normalizedSchemaFiles: List, - warning: Consumer, + normalizedSchemaFiles: List, codegenSchemaOptionsFile: File, codegenSchemaFile: File, ) { val registry = apolloCompilerRegistry( - arguments, - logLevel, - warnIfNotFound, + arguments = arguments, + logger = logger, + warnIfNotFound = warnIfNotFound, ) ApolloCompiler.buildCodegenSchema( - schemaFiles = normalizedSchemaFiles.toInputFiles(), - logger = warning.toLogger(), + schemaFiles = normalizedSchemaFiles, + logger = logger, codegenSchemaOptions = codegenSchemaOptionsFile.toCodegenSchemaOptions(), foreignSchemas = registry.foreignSchemas(), schemaTransform = registry.schemaDocumentTransform() @@ -46,106 +39,106 @@ class EntryPoints { fun buildIr( arguments: Map, - logLevel: Int, - graphqlFiles: List, - codegenSchemaFiles: List, - upstreamIrOperations: List, + logger: ApolloCompiler.Logger, + warnIfNotFound: Boolean, + graphqlFiles: List, + codegenSchemaFiles: List, + upstreamIrOperations: List, irOptionsFile: File, - warning: Consumer, irOperationsFile: File, ) { - val registry = apolloCompilerRegistry(arguments, logLevel, false) + val registry = apolloCompilerRegistry(arguments, logger, warnIfNotFound) - val upstream = upstreamIrOperations.toInputFiles().map { it.file.toIrOperations() } - ApolloCompiler.buildIrOperations( - executableFiles = graphqlFiles.toInputFiles(), - codegenSchema = codegenSchemaFiles.toInputFiles().map { it.file }.findCodegenSchemaFile().toCodegenSchema(), + val upstream = upstreamIrOperations.map { it.file.toIrOperations() } + buildIrOperations( + executableFiles = graphqlFiles, + codegenSchema = codegenSchemaFiles.map { it.file }.findCodegenSchemaFile().toCodegenSchema(), upstreamCodegenModels = upstream.map { it.codegenModels }, upstreamFragmentDefinitions = upstream.flatMap { it.fragmentDefinitions }, documentTransform = registry.executableDocumentTransform(), options = irOptionsFile.toIrOptions(), - logger = warning.toLogger(), + logger = logger, ).writeTo(irOperationsFile) } fun buildSourcesFromIr( arguments: Map, - logLevel: Int, + logger: ApolloCompiler.Logger, warnIfNotFound: Boolean, - codegenSchemaFiles: List, - upstreamMetadata: List, + codegenSchemas: List, + upstreamMetadata: List, irOperations: File, - downstreamUsedCoordinates: Map>>, + usedCoordinates: File, codegenOptions: File, - operationManifestFile: File?, - outputDir: File, - metadataOutputFile: File? + operationManifest: File?, + outputDirectory: File, + metadataOutput: File? ) { val registry = apolloCompilerRegistry( arguments, - logLevel, - warnIfNotFound + logger, + warnIfNotFound, ) - val codegenSchemaFile = codegenSchemaFiles.toInputFiles().map { it.file }.findCodegenSchemaFile() - + val codegenSchemaFile = codegenSchemas.map { it.file }.findCodegenSchemaFile() val codegenSchema = codegenSchemaFile.toCodegenSchema() - val upstreamCodegenMetadata = upstreamMetadata.toInputFiles().map { it.file.toCodegenMetadata() } - ApolloCompiler.buildSchemaAndOperationsSourcesFromIr( + val upstreamCodegenMetadata = upstreamMetadata.map { it.file.toCodegenMetadata() } + buildSchemaAndOperationsSourcesFromIr( codegenSchema = codegenSchema, irOperations = irOperations.toIrOperations(), - downstreamUsedCoordinates = downstreamUsedCoordinates.toUsedCoordinates(), + downstreamUsedCoordinates = usedCoordinates.toUsedCoordinates(), upstreamCodegenMetadata = upstreamCodegenMetadata, codegenOptions = codegenOptions.toCodegenOptions(), layout = registry.layout(codegenSchema), irOperationsTransform = registry.irOperationsTransform(), javaOutputTransform = registry.javaOutputTransform(), kotlinOutputTransform = registry.kotlinOutputTransform(), - operationManifestFile = operationManifestFile, + operationManifestFile = operationManifest, operationIdsGenerator = registry.toOperationIdsGenerator(), - ).writeTo(outputDir, true, metadataOutputFile) + ).writeTo(outputDirectory, true, metadataOutput) if (upstreamCodegenMetadata.isEmpty()) { - registry.schemaCodeGenerator().generate(codegenSchema.schema.toGQLDocument(), outputDir) + registry.schemaCodeGenerator().generate(codegenSchema.schema.toGQLDocument(), outputDirectory) } } fun buildSources( arguments: Map, - logLevel: Int, + logger: ApolloCompiler.Logger, warnIfNotFound: Boolean, - schemaFiles: List, - graphqlFiles: List, + schemas: List, + executableDocuments: List, codegenSchemaOptions: File, codegenOptions: File, irOptions: File, - warning: Consumer, - operationManifestFile: File?, - outputDir: File, - dataBuildersOutputDir: File, + operationManifest: File?, + outputDirectory: File, + dataBuildersOutputDirectory: File, ) { val registry = apolloCompilerRegistry( arguments, - logLevel, - warnIfNotFound + logger, + warnIfNotFound, ) + @Suppress("NAME_SHADOWING") + val codegenSchemaOptions = codegenSchemaOptions.toCodegenSchemaOptions() val codegenSchema = ApolloCompiler.buildCodegenSchema( - schemaFiles = schemaFiles.toInputFiles(), - codegenSchemaOptions = codegenSchemaOptions.toCodegenSchemaOptions(), + schemaFiles = schemas, + codegenSchemaOptions = codegenSchemaOptions, foreignSchemas = registry.foreignSchemas(), - logger = warning.toLogger(), + logger = logger, schemaTransform = registry.schemaDocumentTransform() ) val irOperations = buildIrOperations( codegenSchema = codegenSchema, - executableFiles = graphqlFiles.toInputFiles(), + executableFiles = executableDocuments, upstreamCodegenModels = emptyList(), upstreamFragmentDefinitions = emptyList(), documentTransform = registry.executableDocumentTransform(), options = irOptions.toIrOptions(), - logger = warning.toLogger(), + logger = logger, ) @Suppress("NAME_SHADOWING") @@ -161,7 +154,7 @@ class EntryPoints { irOperationsTransform = registry.irOperationsTransform(), javaOutputTransform = registry.javaOutputTransform(), kotlinOutputTransform = registry.kotlinOutputTransform(), - operationManifestFile = operationManifestFile, + operationManifestFile = operationManifest, operationIdsGenerator = registry.toOperationIdsGenerator(), ) @@ -172,32 +165,32 @@ class EntryPoints { codegenOptions, layout, listOf(sourceOutput.codegenMetadata) - ).writeTo(dataBuildersOutputDir, true, null) + ).writeTo(dataBuildersOutputDirectory, true, null) } - sourceOutput.writeTo(outputDir, true, null) + sourceOutput.writeTo(outputDirectory, true, null) - registry.schemaCodeGenerator().generate(codegenSchema.schema.toGQLDocument(), outputDir) + registry.schemaCodeGenerator().generate(codegenSchema.schema.toGQLDocument(), outputDirectory) } fun buildDataBuilders( arguments: Map, - logLevel: Int, + logger: ApolloCompiler.Logger, warnIfNotFound: Boolean, - codegenSchemaFiles: List, - upstreamMetadata: List, - downstreamUsedCoordinates: Map>>, + codegenSchemas: List, + upstreamMetadatas: List, + downstreamUsedCoordinates: File, codegenOptions: File, - outputDir: File + outputDirectory: File ) { val registry = apolloCompilerRegistry( arguments, - logLevel, + logger, warnIfNotFound, ) - val codegenSchemaFile = codegenSchemaFiles.toInputFiles().map { it.file }.findCodegenSchemaFile() + val codegenSchemaFile = codegenSchemas.map { it.file }.findCodegenSchemaFile() val codegenSchema = codegenSchemaFile.toCodegenSchema() - val upstreamCodegenMetadata = upstreamMetadata.toInputFiles().map { it.file.toCodegenMetadata() } + val upstreamCodegenMetadata = upstreamMetadatas.map { it.file.toCodegenMetadata() } ApolloCompiler.buildDataBuilders( codegenSchema = codegenSchema, @@ -205,15 +198,7 @@ class EntryPoints { codegenOptions = codegenOptions.toCodegenOptions(), layout = registry.layout(codegenSchema), upstreamCodegenMetadata = upstreamCodegenMetadata, - ).writeTo(outputDir, true, null) - } -} - -internal fun Consumer.toLogger(): ApolloCompiler.Logger { - return object : ApolloCompiler.Logger { - override fun warning(message: String) { - accept(message) - } + ).writeTo(outputDirectory, true, null) } } @@ -231,13 +216,13 @@ fun Iterable.findCodegenSchemaFile(): File { internal fun apolloCompilerRegistry( arguments: Map, - logLevel: Int, - warnIfNotFound: Boolean = false + logger: ApolloCompiler.Logger, + warnIfNotFound: Boolean = false, ): DefaultApolloCompilerRegistry { val registry = DefaultApolloCompilerRegistry() val environment = ApolloCompilerPluginEnvironment( arguments, - GradleCompilerPluginLogger(logLevel), + logger, ) var hasPlugin = false val plugins = ServiceLoader.load(ApolloCompilerPlugin::class.java, ApolloCompilerPlugin::class.java.classLoader).toList() @@ -266,10 +251,3 @@ internal fun apolloCompilerRegistry( return registry } - -internal fun List.toInputFiles(): List = buildList { - val iterator = this@toInputFiles.iterator() - while (iterator.hasNext()) { - add(InputFile(normalizedPath = iterator.next() as String, file = iterator.next() as File)) - } -} \ No newline at end of file diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger.kt deleted file mode 100644 index 7b45c5aad26..00000000000 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/internal/GradleCompilerPluginLogger.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.apollographql.apollo.compiler.internal - -import com.apollographql.apollo.annotations.ApolloInternal -import com.apollographql.apollo.compiler.ApolloCompilerPluginLogger - -@ApolloInternal -class GradleCompilerPluginLogger(val loglevel: Int) : ApolloCompilerPluginLogger { - - override fun logging(message: String) { - if (loglevel <= LOGGING_LEVEL_LOGGING) - println("v: [apollo] $message") - } - - override fun info(message: String) { - if (loglevel <= LOGGING_LEVEL_INFO) - println("i: [apollo] $message") - } - - override fun warn(message: String) { - if (loglevel <= LOGGING_LEVEL_WARN) - println("w: [apollo] $message") - } - - override fun error(message: String) { - if (loglevel <= LOGGING_LEVEL_ERROR) - println("e: [apollo] $message") - } - - companion object { - /** - * Matches Gradle LogLevel - * See https://github.com/gradle/gradle/blob/71f42531a742bc263c61f1d0dc21bb6570cc817b/platforms/core-runtime/logging-api/src/main/java/org/gradle/api/logging/LogLevel.java#L21 - */ - const val LOGGING_LEVEL_LOGGING = 0 - const val LOGGING_LEVEL_INFO = 1 - const val LOGGING_LEVEL_WARN = 3 - const val LOGGING_LEVEL_ERROR = 5 - } -} diff --git a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/json.kt b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/json.kt index 13b6f954024..f0df23311b0 100644 --- a/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/json.kt +++ b/libraries/apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/json.kt @@ -69,6 +69,10 @@ fun File.toIrOperations(): IrOperations = parseFromJson() @JvmName("readIrSchema") fun File.toIrSchema(): IrSchema = parseFromJson() +fun File.toUsedCoordinates(): UsedCoordinates { + return parseFromJson() +} + /** * A minimal class that is only used to read a version */ @@ -118,4 +122,4 @@ fun PersistedQueryManifest.writeTo(file: File) = encodeToJson(file) @JvmName("writeOperationOutput") fun OperationOutput.writeTo(file: File) = this.encodeToJson(file) -internal fun UsedCoordinates.writeTo(file: File) = file.writeText(prettyPrintJson.encodeToString(this)) +fun UsedCoordinates.writeTo(file: File) = file.writeText(prettyPrintJson.encodeToString(this)) diff --git a/libraries/apollo-gradle-plugin-external/README.md b/libraries/apollo-gradle-plugin-external/README.md deleted file mode 100644 index 39c0299b6d7..00000000000 --- a/libraries/apollo-gradle-plugin-external/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Module apollo-gradle-plugin-external - -`apollo-gradle-plugin-external` contains the Apollo Gradle plugin. - -This module does not shadow its runtime dependencies, making it more prone to Gradle classpath issues. - -See `apollo-gradle-plugin` for a version of `apollo-gradle-plugin-external` that shadow its dependencies. - -See ["Gradle Plugin Configuration"](https://www.apollographql.com/docs/kotlin/advanced/plugin-configuration/) for how to use the Gradle plugin. diff --git a/libraries/apollo-gradle-plugin-external/api/apollo-gradle-plugin-external.api b/libraries/apollo-gradle-plugin-external/api/apollo-gradle-plugin-external.api deleted file mode 100644 index 424f3120123..00000000000 --- a/libraries/apollo-gradle-plugin-external/api/apollo-gradle-plugin-external.api +++ /dev/null @@ -1,225 +0,0 @@ -public final class com/apollographql/apollo/gradle/api/ApolloDependencies { - public fun (Lorg/gradle/api/artifacts/dsl/DependencyHandler;)V - public final fun getApi ()Lorg/gradle/api/artifacts/Dependency; - public final fun getAst ()Lorg/gradle/api/artifacts/Dependency; - public final fun getMockServer ()Lorg/gradle/api/artifacts/Dependency; - public final fun getNormalizedCache ()Lorg/gradle/api/artifacts/Dependency; - public final fun getNormalizedCacheSqlite ()Lorg/gradle/api/artifacts/Dependency; - public final fun getRuntime ()Lorg/gradle/api/artifacts/Dependency; -} - -public abstract interface class com/apollographql/apollo/gradle/api/ApolloExtension { - public abstract fun createAllAndroidVariantServices (Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/Action;)V - public abstract fun createAllKotlinSourceSetServices (Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/Action;)V - public abstract fun getDeps ()Lcom/apollographql/apollo/gradle/api/ApolloDependencies; - public abstract fun getGenerateSourcesDuringGradleSync ()Lorg/gradle/api/provider/Property; - public abstract fun getLinkSqlite ()Lorg/gradle/api/provider/Property; - public abstract fun service (Ljava/lang/String;Lorg/gradle/api/Action;)V -} - -public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel { - public static final field Companion Lcom/apollographql/apollo/gradle/api/ApolloGradleToolingModel$Companion; - public static final field VERSION_MAJOR I - public abstract fun getProjectName ()Ljava/lang/String; - public abstract fun getProjectPath ()Ljava/lang/String; - public abstract fun getServiceInfos ()Ljava/util/List; - public abstract fun getTelemetryData ()Lcom/apollographql/apollo/gradle/api/ApolloGradleToolingModel$TelemetryData; - public abstract fun getVersionMajor ()I - public abstract fun getVersionMinor ()I -} - -public final class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$Companion { - public static final field VERSION_MAJOR I -} - -public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$ServiceInfo { - public abstract fun getEndpointHeaders ()Ljava/util/Map; - public abstract fun getEndpointUrl ()Ljava/lang/String; - public abstract fun getGraphqlSrcDirs ()Ljava/util/Set; - public abstract fun getName ()Ljava/lang/String; - public abstract fun getSchemaFiles ()Ljava/util/Set; - public abstract fun getUpstreamProjectPaths ()Ljava/util/Set; - public abstract fun getUpstreamProjects ()Ljava/util/Set; - public abstract fun getUseSemanticNaming ()Z -} - -public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$TelemetryData { - public abstract fun getAndroidAgpVersion ()Ljava/lang/String; - public abstract fun getAndroidCompileSdk ()Ljava/lang/String; - public abstract fun getAndroidMinSdk ()Ljava/lang/Integer; - public abstract fun getAndroidTargetSdk ()Ljava/lang/Integer; - public abstract fun getApolloGenerateSourcesDuringGradleSync ()Ljava/lang/Boolean; - public abstract fun getApolloLinkSqlite ()Ljava/lang/Boolean; - public abstract fun getApolloServiceCount ()I - public abstract fun getApolloServiceTelemetryData ()Ljava/util/List; - public abstract fun getGradleVersion ()Ljava/lang/String; -} - -public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$TelemetryData$ServiceTelemetryData { - public abstract fun getAddJvmOverloads ()Ljava/lang/Boolean; - public abstract fun getAddTypename ()Ljava/lang/String; - public abstract fun getCodegenModels ()Ljava/lang/String; - public abstract fun getDecapitalizeFields ()Ljava/lang/Boolean; - public abstract fun getFailOnWarnings ()Ljava/lang/Boolean; - public abstract fun getFieldsOnDisjointTypesMustMerge ()Ljava/lang/Boolean; - public abstract fun getFlattenModels ()Ljava/lang/Boolean; - public abstract fun getGenerateApolloMetadata ()Ljava/lang/Boolean; - public abstract fun getGenerateAsInternal ()Ljava/lang/Boolean; - public abstract fun getGenerateDataBuilders ()Ljava/lang/Boolean; - public abstract fun getGenerateFragmentImplementations ()Ljava/lang/Boolean; - public abstract fun getGenerateInputBuilders ()Ljava/lang/Boolean; - public abstract fun getGenerateKotlinModels ()Ljava/lang/Boolean; - public abstract fun getGenerateMethods ()Ljava/util/List; - public abstract fun getGenerateModelBuilders ()Ljava/lang/Boolean; - public abstract fun getGenerateOptionalOperationVariables ()Ljava/lang/Boolean; - public abstract fun getGeneratePrimitiveTypes ()Ljava/lang/Boolean; - public abstract fun getGenerateQueryDocument ()Ljava/lang/Boolean; - public abstract fun getGenerateSchema ()Ljava/lang/Boolean; - public abstract fun getJsExport ()Ljava/lang/Boolean; - public abstract fun getLanguageVersion ()Ljava/lang/String; - public abstract fun getNullableFieldStyle ()Ljava/lang/String; - public abstract fun getOperationManifestFormat ()Ljava/lang/String; - public abstract fun getUseSemanticNaming ()Ljava/lang/Boolean; - public abstract fun getUsedOptions ()Ljava/util/Set; - public abstract fun getWarnOnDeprecatedUsages ()Ljava/lang/Boolean; -} - -public abstract interface class com/apollographql/apollo/gradle/api/CompilerPlugin { - public abstract fun argument (Ljava/lang/String;Ljava/lang/Object;)V -} - -public abstract interface class com/apollographql/apollo/gradle/api/Introspection { - public abstract fun getEndpointUrl ()Lorg/gradle/api/provider/Property; - public abstract fun getHeaders ()Lorg/gradle/api/provider/MapProperty; - public abstract fun getSchemaFile ()Lorg/gradle/api/file/RegularFileProperty; - public abstract fun schemaConnection (Lorg/gradle/api/Action;)V -} - -public abstract interface class com/apollographql/apollo/gradle/api/RegisterOperationsConfig { - public abstract fun getGraph ()Lorg/gradle/api/provider/Property; - public abstract fun getGraphVariant ()Lorg/gradle/api/provider/Property; - public abstract fun getKey ()Lorg/gradle/api/provider/Property; - public abstract fun getListId ()Lorg/gradle/api/provider/Property; -} - -public abstract interface class com/apollographql/apollo/gradle/api/Registry { - public abstract fun getGraph ()Lorg/gradle/api/provider/Property; - public abstract fun getGraphVariant ()Lorg/gradle/api/provider/Property; - public abstract fun getKey ()Lorg/gradle/api/provider/Property; - public abstract fun getSchemaFile ()Lorg/gradle/api/file/RegularFileProperty; - public abstract fun schemaConnection (Lorg/gradle/api/Action;)V -} - -public final class com/apollographql/apollo/gradle/api/SchemaConnection { - public fun (Lorg/gradle/api/tasks/TaskProvider;Lorg/gradle/api/provider/Provider;)V - public final fun getDownloadedSchema ()Lorg/gradle/api/provider/Provider; - public final fun getTask ()Lorg/gradle/api/tasks/TaskProvider; -} - -public abstract interface class com/apollographql/apollo/gradle/api/Service { - public abstract fun dataBuildersOutputDirConnection (Lorg/gradle/api/Action;)V - public abstract fun dependsOn (Ljava/lang/Object;)V - public abstract fun dependsOn (Ljava/lang/Object;Z)V - public abstract fun getAddJvmOverloads ()Lorg/gradle/api/provider/Property; - public abstract fun getAddTypename ()Lorg/gradle/api/provider/Property; - public abstract fun getAlwaysGenerateTypesMatching ()Lorg/gradle/api/provider/SetProperty; - public abstract fun getClassesForEnumsMatching ()Lorg/gradle/api/provider/ListProperty; - public abstract fun getCodegenModels ()Lorg/gradle/api/provider/Property; - public abstract fun getDataBuildersOutputDir ()Lorg/gradle/api/file/DirectoryProperty; - public abstract fun getDebugDir ()Lorg/gradle/api/file/DirectoryProperty; - public abstract fun getDecapitalizeFields ()Lorg/gradle/api/provider/Property; - public abstract fun getExcludes ()Lorg/gradle/api/provider/ListProperty; - public abstract fun getFailOnWarnings ()Lorg/gradle/api/provider/Property; - public abstract fun getFieldsOnDisjointTypesMustMerge ()Lorg/gradle/api/provider/Property; - public abstract fun getFlattenModels ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateApolloMetadata ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateAsInternal ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateDataBuilders ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateFragmentImplementations ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateInputBuilders ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateKotlinModels ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateMethods ()Lorg/gradle/api/provider/ListProperty; - public abstract fun getGenerateModelBuilders ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateOperationOutput ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateOptionalOperationVariables ()Lorg/gradle/api/provider/Property; - public abstract fun getGeneratePrimitiveTypes ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateQueryDocument ()Lorg/gradle/api/provider/Property; - public abstract fun getGenerateSchema ()Lorg/gradle/api/provider/Property; - public abstract fun getGeneratedSchemaName ()Lorg/gradle/api/provider/Property; - public abstract fun getIncludes ()Lorg/gradle/api/provider/ListProperty; - public abstract fun getJsExport ()Lorg/gradle/api/provider/Property; - public abstract fun getLanguageVersion ()Lorg/gradle/api/provider/Property; - public abstract fun getName ()Ljava/lang/String; - public abstract fun getNullableFieldStyle ()Lorg/gradle/api/provider/Property; - public abstract fun getOperationManifest ()Lorg/gradle/api/file/RegularFileProperty; - public abstract fun getOperationManifestFormat ()Lorg/gradle/api/provider/Property; - public abstract fun getOperationOutputFile ()Lorg/gradle/api/file/RegularFileProperty; - public abstract fun getOutputDir ()Lorg/gradle/api/file/DirectoryProperty; - public abstract fun getPackageName ()Lorg/gradle/api/provider/Property; - public abstract fun getRequiresOptInAnnotation ()Lorg/gradle/api/provider/Property; - public abstract fun getSchemaFile ()Lorg/gradle/api/file/RegularFileProperty; - public abstract fun getSchemaFiles ()Lorg/gradle/api/file/ConfigurableFileCollection; - public abstract fun getSealedClassesForEnumsMatching ()Lorg/gradle/api/provider/ListProperty; - public abstract fun getSourceFolder ()Lorg/gradle/api/provider/Property; - public abstract fun getUseSemanticNaming ()Lorg/gradle/api/provider/Property; - public abstract fun getWarnOnDeprecatedUsages ()Lorg/gradle/api/provider/Property; - public abstract fun introspection (Lorg/gradle/api/Action;)V - public abstract fun isADependencyOf (Ljava/lang/Object;)V - public abstract fun mapScalar (Ljava/lang/String;Ljava/lang/String;)V - public abstract fun mapScalar (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V - public abstract fun mapScalarToJavaBoolean (Ljava/lang/String;)V - public abstract fun mapScalarToJavaDouble (Ljava/lang/String;)V - public abstract fun mapScalarToJavaFloat (Ljava/lang/String;)V - public abstract fun mapScalarToJavaInteger (Ljava/lang/String;)V - public abstract fun mapScalarToJavaLong (Ljava/lang/String;)V - public abstract fun mapScalarToJavaObject (Ljava/lang/String;)V - public abstract fun mapScalarToJavaString (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinAny (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinBoolean (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinDouble (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinFloat (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinInt (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinLong (Ljava/lang/String;)V - public abstract fun mapScalarToKotlinString (Ljava/lang/String;)V - public abstract fun mapScalarToUpload (Ljava/lang/String;)V - public abstract fun operationManifestConnection (Lorg/gradle/api/Action;)V - public abstract fun operationOutputConnection (Lorg/gradle/api/Action;)V - public abstract fun outgoingVariantsConnection (Lorg/gradle/api/Action;)V - public abstract fun outputDirConnection (Lorg/gradle/api/Action;)V - public abstract fun packageNamesFromFilePaths (Ljava/lang/String;)V - public static synthetic fun packageNamesFromFilePaths$default (Lcom/apollographql/apollo/gradle/api/Service;Ljava/lang/String;ILjava/lang/Object;)V - public abstract fun plugin (Ljava/lang/Object;)V - public abstract fun plugin (Ljava/lang/Object;Lorg/gradle/api/Action;)V - public abstract fun registerOperations (Lorg/gradle/api/Action;)V - public abstract fun registry (Lorg/gradle/api/Action;)V - public abstract fun srcDir (Ljava/lang/Object;)V -} - -public abstract interface class com/apollographql/apollo/gradle/api/Service$DirectoryConnection { - public abstract fun connectToAllAndroidVariants ()V - public abstract fun connectToAndroidSourceSet (Ljava/lang/String;)V - public abstract fun connectToAndroidVariant (Ljava/lang/Object;)V - public abstract fun connectToJavaSourceSet (Ljava/lang/String;)V - public abstract fun connectToKotlinSourceSet (Ljava/lang/String;)V - public abstract fun getOutputDir ()Lorg/gradle/api/provider/Provider; - public abstract fun getTask ()Lorg/gradle/api/tasks/TaskProvider; -} - -public final class com/apollographql/apollo/gradle/api/Service$OperationManifestConnection { - public fun (Lorg/gradle/api/tasks/TaskProvider;Lorg/gradle/api/provider/Provider;)V - public final fun getManifest ()Lorg/gradle/api/provider/Provider; - public final fun getTask ()Lorg/gradle/api/tasks/TaskProvider; -} - -public final class com/apollographql/apollo/gradle/api/Service$OperationOutputConnection { - public fun (Lorg/gradle/api/tasks/TaskProvider;Lorg/gradle/api/provider/Provider;)V - public final fun getOperationOutputFile ()Lorg/gradle/api/provider/Provider; - public final fun getTask ()Lorg/gradle/api/tasks/TaskProvider; -} - -public abstract interface class com/apollographql/apollo/gradle/api/Service$OutgoingVariantsConnection { - public abstract fun addToSoftwareComponent (Ljava/lang/String;)V - public abstract fun addToSoftwareComponent (Lorg/gradle/api/component/SoftwareComponent;)V - public abstract fun getOutgoingVariants ()Ljava/util/List; -} - diff --git a/libraries/apollo-gradle-plugin-external/build.gradle.kts b/libraries/apollo-gradle-plugin-external/build.gradle.kts deleted file mode 100644 index 4fae2d83b8f..00000000000 --- a/libraries/apollo-gradle-plugin-external/build.gradle.kts +++ /dev/null @@ -1,60 +0,0 @@ -import org.jetbrains.kotlin.gradle.dsl.KotlinVersion - -plugins { - id("org.jetbrains.kotlin.jvm") - id("java-gradle-plugin") - id("com.gradleup.gr8") // Only used for removeGradleApiFromApi() - id("org.jetbrains.kotlin.plugin.serialization") - id("com.android.lint") -} - -apolloLibrary( - namespace = "com.apollographql.apollo.gradle", - jvmTarget = 11, // AGP requires 11 - kotlinCompilerOptions = KotlinCompilerOptions(KotlinVersion.KOTLIN_1_9) -) - -dependencies { - compileOnly(libs.gradle.api.min) - compileOnly(libs.kotlin.plugin.min) - compileOnly(libs.android.plugin.min) - - api(project(":apollo-compiler")) - implementation(project(":apollo-tooling")) - implementation(project(":apollo-ast")) - implementation(libs.asm) - implementation(libs.kotlinx.serialization.json) -} -dependencies { - lintChecks(libs.androidx.lint.rules) -} - -tasks.withType(ValidatePlugins::class.java).configureEach { - enableStricterValidation.set(true) -} - -gradlePlugin { - website.set("https://github.com/apollographql/apollo-kotlin") - vcsUrl.set("https://github.com/apollographql/apollo-kotlin") - - plugins { - create("apolloGradlePlugin") { - id = "com.apollographql.apollo.external" - displayName = "Apollo Kotlin GraphQL client plugin." - description = "Automatically generates typesafe java and kotlin models from your GraphQL files." - implementationClass = "com.apollographql.apollo.gradle.internal.ApolloPlugin" - tags.set(listOf("graphql", "apollo", "plugin")) - } - } -} - -// The java-gradle-plugin adds `gradleApi()` to the `api` implementation but it contains some JDK15 bytecode at -// org/gradle/internal/impldep/META-INF/versions/15/org/bouncycastle/jcajce/provider/asymmetric/edec/SignatureSpi$EdDSA.class: -// java.lang.IllegalArgumentException: Unsupported class file major version 59 -// So remove it -val apiDependencies = project.configurations.getByName("api").dependencies -apiDependencies.firstOrNull { - it is FileCollectionDependency -}.let { - apiDependencies.remove(it) -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt deleted file mode 100644 index 9894b8c6265..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt +++ /dev/null @@ -1,27 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.FileCollection -import org.gradle.api.services.BuildService -import org.gradle.api.services.BuildServiceParameters -import java.net.URI -import java.net.URL -import java.net.URLClassLoader - -abstract class ApolloBuildService: BuildService, AutoCloseable { - private val classloaders = mutableMapOf, ClassLoader>() - - @Synchronized - fun classloader(classpath: FileCollection): ClassLoader { - val urls = classpath.map { it.toURI() } - return classloaders.getOrPut(urls) { - URLClassLoader( - urls.map { it.toURL() }.toTypedArray(), - ClassLoader.getPlatformClassLoader() - ) - } - } - - override fun close() { - classloaders.clear() - } -} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloConvertSchemaTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloConvertSchemaTask.kt deleted file mode 100644 index 07e721a05fc..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloConvertSchemaTask.kt +++ /dev/null @@ -1,66 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.ast.introspection.toGQLDocument -import com.apollographql.apollo.ast.introspection.toIntrospectionSchema -import com.apollographql.apollo.ast.introspection.writeTo -import com.apollographql.apollo.ast.toFullSchemaGQLDocument -import com.apollographql.apollo.ast.toGQLDocument -import com.apollographql.apollo.ast.toSDL -import com.apollographql.apollo.ast.toUtf8 -import org.gradle.api.DefaultTask -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.TaskAction -import org.gradle.api.tasks.options.Option -import java.io.File - -@CacheableTask -abstract class ApolloConvertSchemaTask : DefaultTask() { - @get:Input - @get:Option(option = "from", description = "schema to convert from") - abstract val from: Property - - // Even if this is points to an output file, for the purpose of the task this is seen as an input - @get:Input - @get:Option(option = "to", description = "schema to convert to") - abstract val to: Property - - @get:Internal - abstract var projectRootDir: String - - init { - /** - * This task is really meant to be called from the command line so don't do any up-to-date checks - * If someone wants to register its own conversion task, it should be easy to do using the - * compiler APIs directly (see [convert] below) - * This code actually redundant because the task has no output but adding it make it explicit. - */ - outputs.upToDateWhen { false } - outputs.cacheIf { false } - } - - private fun File.isIntrospection() = extension == "json" - - fun convert(from: File, to: File) { - check(from.isIntrospection() && !to.isIntrospection() || !from.isIntrospection() && to.isIntrospection()) { - "Cannot convert from ${from.name} to ${to.name}, they are already the same format" - } - - if (from.isIntrospection()) { - from.toIntrospectionSchema().toGQLDocument().toSDL(includeBuiltInScalarDefinitions = true).let { - to.writeText(it) - } - } else { - from.toGQLDocument().toFullSchemaGQLDocument().toIntrospectionSchema().writeTo(to) - } - } - - @TaskAction - fun taskAction() { - // Files are relative to the root project. It is not possible in a consistent way to have them relative to the current - // working directory where the gradle command was started - convert(File(projectRootDir).resolve(from.get()), File(projectRootDir).resolve(to.get())) - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloDownloadSchemaTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloDownloadSchemaTask.kt deleted file mode 100644 index 0a000554320..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloDownloadSchemaTask.kt +++ /dev/null @@ -1,121 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.gradle.internal.ApolloPlugin.Companion.extraHeaders -import com.apollographql.apollo.tooling.SchemaDownloader -import org.gradle.api.DefaultTask -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.TaskAction -import org.gradle.api.tasks.options.Option -import org.gradle.work.DisableCachingByDefault -import java.io.File - -/** - * A task to download a schema either from introspection or from the registry. - * - * This task can either be configured from the command line or from the gradle scripts - */ -@DisableCachingByDefault(because = "This downloads a file from the internet and we cannot track the internet.") -abstract class ApolloDownloadSchemaTask : DefaultTask() { - @get:Optional - @get:Input - @get:Option(option = "endpoint", description = "url of the GraphQL endpoint for introspection.") - abstract val endpoint: Property - - @get:Optional - @get:Input - @get:Option(option = "graph", description = "[Apollo Studio users only] The identifier of the Apollo graph used to download the schema.") - abstract val graph: Property - - @get:Optional - @get:Input - @get:Option(option = "key", description = "[Apollo Studio users only] The Apollo API key. See https://www.apollographql.com/docs/studio/api-keys/ for more information on how to get your API key.") - abstract val key: Property - - @get:Optional - @get:Input - @get:Option(option = "graphVariant", description = "[Apollo Studio users only] The variant of the Apollo graph used to download the schema.") - abstract val graphVariant: Property - - @get:Optional - @get:Input - @get:Option(option = "registryUrl", description = "[Apollo Studio users only] The registry url of the registry instance used to download the schema. Defaults to \"https://api.apollographql.com/graphql\"") - abstract val registryUrl: Property - - - @get:Input - @get:Optional - @get:Option(option = "schema", description = "path where the schema will be downloaded, relative to the root project directory") - abstract val schema: Property - - /** - * This is not declared as an output as it triggers this Gradle error else: - * "Reason: Task ':root:generateServiceApolloCodegenSchema' uses this output of task ':root:downloadServiceApolloSchemaFromIntrospection' without declaring an explicit or implicit dependency." - * - * Since it's unlikely that users want to download the schema every time, just set it as an internal property. - */ - @get:Internal - abstract val outputFile: RegularFileProperty - - @get:Internal - abstract var projectRootDir: String - - @get:Optional - @get:Input - @set:Option(option = "header", description = "HTTP headers in the form 'Name: Value'") - var header = emptyList() // cannot be abstract for @Option to work - - @get:Optional - @get:Input - @get:Option(option = "insecure", description = "if set to true, TLS/SSL certificates will not be checked when downloading") - abstract val insecure: Property - - init { - /** - * We cannot know in advance if the backend schema changed so don't cache or mark this task up-to-date - */ - outputs.upToDateWhen { false } - outputs.cacheIf { false } - } - - @TaskAction - fun taskAction() { - // Schema file is relative to the root project. It is not possible in a consistent way to have it relative to the current - // working directory where the gradle command was started - - val file = if (outputFile.isPresent) { - outputFile.asFile.get() - } else { - check(schema.isPresent) { - "--schema is mandatory" - } - File(projectRootDir).resolve(schema.get()) - } - SchemaDownloader.download( - endpoint = endpoint.orNull, - graph = graph.orNull, - graphVariant = graphVariant.getOrElse("current"), - key = key.orNull, - registryUrl = registryUrl.getOrElse("https://api.apollographql.com/graphql"), - schema = file, - insecure = insecure.getOrElse(false), - headers = header.toMap() + extraHeaders, - ) - - logger.info("Apollo: schema downloaded to ${file.absolutePath}") - } - - private fun List.toMap(): Map { - return map { - val index = it.indexOf(':') - check(index > 0 && index < it.length - 1) { - "header should be in the form 'Name: Value'" - } - - it.substring(0, index).trim() to it.substring(index + 1, it.length).trim() - }.toMap() - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateCodegenSchemaTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateCodegenSchemaTask.kt deleted file mode 100644 index b55b8067e8c..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateCodegenSchemaTask.kt +++ /dev/null @@ -1,102 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.FileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import org.gradle.workers.WorkAction -import org.gradle.workers.WorkParameters -import java.io.File -import java.util.function.Consumer - -@CacheableTask -abstract class ApolloGenerateCodegenSchemaTask : ApolloTaskWithClasspath() { - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val schemaFiles: ConfigurableFileCollection - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val fallbackSchemaFiles: ConfigurableFileCollection - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val upstreamSchemaFiles: ConfigurableFileCollection - - @get:InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenSchemaOptionsFile: RegularFileProperty - - @get:OutputFile - @get:Optional - abstract val codegenSchemaFile: RegularFileProperty - - @TaskAction - fun taskAction() { - if (upstreamSchemaFiles.files.isNotEmpty()) { - /** - * Output an empty file - */ - codegenSchemaFile.get().asFile.let { - it.delete() - it.createNewFile() - } - return - } - - val workQueue = getWorkQueue() - - workQueue.submit(GenerateCodegenSchema::class.java) { - it.codegenSchemaFile = codegenSchemaFile - it.schemaFiles = schemaFiles.isolate() - it.fallbackSchemaFiles = fallbackSchemaFiles.isolate() - it.codegenSchemaOptionsFile.set(codegenSchemaOptionsFile) - it.hasPlugin = hasPlugin.get() - it.arguments = arguments.get() - it.logLevel = logLevel.get().ordinal - it.apolloBuildService.set(apolloBuildService) - it.classpath = classpath - } - } -} - - -private abstract class GenerateCodegenSchema : WorkAction { - override fun execute() { - with(parameters) { - runInIsolation(apolloBuildService.get(), classpath) { - it.reflectiveCall( - "buildCodegenSchema", - arguments, - logLevel, - hasPlugin, - (schemaFiles.takeIf { it.isNotEmpty() } ?: fallbackSchemaFiles), - warningMessageConsumer, - codegenSchemaOptionsFile.get().asFile, - codegenSchemaFile.get().asFile - ) - } - } - } -} - -private interface GenerateCodegenSchemaParameters : WorkParameters { - var codegenSchemaFile: RegularFileProperty - var schemaFiles: List - var fallbackSchemaFiles: List - val codegenSchemaOptionsFile: RegularFileProperty - var hasPlugin: Boolean - var arguments: Map - var logLevel: Int - val apolloBuildService: Property - var classpath: FileCollection -} - diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesBaseTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesBaseTask.kt deleted file mode 100644 index 8ac5f86f4ab..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesBaseTask.kt +++ /dev/null @@ -1,9 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.tasks.OutputDirectory - -interface ApolloGenerateDataBuildersSourcesBaseTask { - @get:OutputDirectory - abstract val dataBuildersOutputDir: DirectoryProperty -} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesTask.kt deleted file mode 100644 index 96a368347a8..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateDataBuildersSourcesTask.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.CodegenSchema -import com.apollographql.apollo.compiler.LayoutFactory -import com.apollographql.apollo.compiler.codegen.SchemaAndOperationsLayout -import com.apollographql.apollo.compiler.toCodegenOptions -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.FileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.MapProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import org.gradle.workers.WorkAction -import org.gradle.workers.WorkParameters - -@CacheableTask -abstract class ApolloGenerateDataBuildersSourcesTask : ApolloTaskWithClasspath(), ApolloGenerateDataBuildersSourcesBaseTask { - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenSchemas: ConfigurableFileCollection - - @get:Input - abstract val downstreamUsedCoordinates: MapProperty>> - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val upstreamMetadata: ConfigurableFileCollection - - @get:InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenOptionsFile: RegularFileProperty - - @TaskAction - fun taskAction() { - val workQueue = getWorkQueue() - - workQueue.submit(GenerateDataBuildersWorkAction::class.java) { - it.codegenSchemas.from(codegenSchemas) - it.codegenOptions.set(codegenOptionsFile) - it.downstreamUsedCoordinates.set(downstreamUsedCoordinates) - it.upstreamMetadata.from(upstreamMetadata) - it.outputDir.set(dataBuildersOutputDir) - it.hasPlugin = hasPlugin.get() - it.arguments = arguments.get() - it.logLevel = logLevel.get().ordinal - it.apolloBuildService.set(apolloBuildService) - it.classpath = classpath - } - } -} - -private abstract class GenerateDataBuildersWorkAction : WorkAction { - override fun execute() { - with(parameters) { - runInIsolation(apolloBuildService.get(), classpath) { - it.reflectiveCall( - "buildDataBuilders", - arguments, - logLevel, - hasPlugin, - codegenSchemas.toInputFiles().isolate(), - upstreamMetadata.toInputFiles().isolate(), - downstreamUsedCoordinates.get(), - codegenOptions.get().asFile, - outputDir.get().asFile, - ) - } - } - } -} - -private interface GenerateDataBuildersSources : WorkParameters { - var hasPlugin: Boolean - val codegenSchemas: ConfigurableFileCollection - val codegenOptions: RegularFileProperty - val downstreamUsedCoordinates: MapProperty>> - val upstreamMetadata: ConfigurableFileCollection - val outputDir: DirectoryProperty - var arguments: Map - var logLevel: Int - val apolloBuildService: Property - var classpath: FileCollection -} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateIrOperationsTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateIrOperationsTask.kt deleted file mode 100644 index 56c0e612964..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateIrOperationsTask.kt +++ /dev/null @@ -1,89 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.FileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import org.gradle.workers.WorkAction -import org.gradle.workers.WorkParameters -import java.io.File -import java.util.function.Consumer - -@CacheableTask -abstract class ApolloGenerateIrOperationsTask : ApolloTaskWithClasspath() { - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenSchemaFiles: ConfigurableFileCollection - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val graphqlFiles: ConfigurableFileCollection - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val upstreamIrFiles: ConfigurableFileCollection - - @get:InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val irOptionsFile: RegularFileProperty - - @get:OutputFile - abstract val irOperationsFile: RegularFileProperty - - @TaskAction - fun taskAction() { - - val workQueue = getWorkQueue() - - workQueue.submit(GenerateIrOperations::class.java) { - it.codegenSchemaFiles = codegenSchemaFiles.isolate() - it.graphqlFiles = graphqlFiles.isolate() - it.upstreamIrFiles = upstreamIrFiles.isolate() - it.irOptionsFile.set(irOptionsFile) - it.irOperationsFile.set(irOperationsFile) - it.arguments = arguments.get() - it.logLevel = logLevel.get().ordinal - it.apolloBuildService.set(apolloBuildService) - it.classpath = classpath - } - } -} - -private abstract class GenerateIrOperations : WorkAction { - override fun execute() { - with(parameters) { - runInIsolation(apolloBuildService.get(), classpath) { - it.reflectiveCall( - "buildIr", - arguments, - logLevel, - graphqlFiles, - codegenSchemaFiles, - upstreamIrFiles, - irOptionsFile.get().asFile, - warningMessageConsumer, - irOperationsFile.get().asFile - ) - } - } - } -} - -private interface GenerateIrOperationsParameters : WorkParameters { - var codegenSchemaFiles: List - var graphqlFiles: List - var upstreamIrFiles: List - val irOptionsFile: RegularFileProperty - val irOperationsFile: RegularFileProperty - var arguments: Map - var logLevel: Int - val apolloBuildService: Property - var classpath: FileCollection -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateOptionsTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateOptionsTask.kt deleted file mode 100644 index 16bbd1e2412..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateOptionsTask.kt +++ /dev/null @@ -1,369 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.CodegenOptions -import com.apollographql.apollo.compiler.CodegenSchemaOptions -import com.apollographql.apollo.compiler.GeneratedMethod -import com.apollographql.apollo.compiler.IrOptions -import com.apollographql.apollo.compiler.JavaNullable -import com.apollographql.apollo.compiler.MODELS_OPERATION_BASED -import com.apollographql.apollo.compiler.MODELS_OPERATION_BASED_WITH_INTERFACES -import com.apollographql.apollo.compiler.MODELS_RESPONSE_BASED -import com.apollographql.apollo.compiler.TargetLanguage -import com.apollographql.apollo.compiler.writeTo -import kotlinx.serialization.Serializable -import kotlinx.serialization.encodeToString -import kotlinx.serialization.json.Json -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.ListProperty -import org.gradle.api.provider.MapProperty -import org.gradle.api.provider.Property -import org.gradle.api.provider.SetProperty -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import java.io.File - -@CacheableTask -abstract class ApolloGenerateOptionsTask : DefaultTask() { - /** - * CodegenSchemaOptions - */ - @get:Input - @get:Optional - abstract val generateKotlinModels: Property - - @get:Input - @get:Optional - abstract val languageVersion: Property - - @get:Input - @get:Optional - abstract val scalarTypeMapping: MapProperty - - @get:Input - @get:Optional - abstract val scalarAdapterMapping: MapProperty - - @get:Input - @get:Optional - abstract val codegenModels: Property - - @get:Input - @get:Optional - abstract val generateDataBuilders: Property - - @get:OutputFile - abstract val codegenSchemaOptionsFile: RegularFileProperty - - /** - * IrOptions - */ - @get:Input - @get:Optional - abstract val addTypename: Property - - @get:Input - @get:Optional - abstract val fieldsOnDisjointTypesMustMerge: Property - - @get:Input - @get:Optional - abstract val decapitalizeFields: Property - - @get:Input - @get:Optional - abstract val flattenModels: Property - - @get:Input - @get:Optional - abstract val warnOnDeprecatedUsages: Property - - @get:Input - @get:Optional - abstract val failOnWarnings: Property - - @get:Input - @get:Optional - abstract val generateOptionalOperationVariables: Property - - @get:Input - @get:Optional - abstract val alwaysGenerateTypesMatching: SetProperty - - @get:OutputFile - abstract val irOptionsFile: RegularFileProperty - - /** - * CommonCodegenOptions - */ - @get:Input - @get:Optional - abstract val packageName: Property - - @get:Input - @get:Optional - abstract val rootPackageName: Property - - @get:Input - @get:Optional - abstract val useSemanticNaming: Property - - @get:Input - @get:Optional - abstract val generateFragmentImplementations: Property - - @get:Input - @get:Optional - abstract val generateMethods: ListProperty - - @get:Input - @get:Optional - abstract val generateQueryDocument: Property - - @get:Input - @get:Optional - abstract val generateSchema: Property - - @get:Input - @get:Optional - abstract val generatedSchemaName: Property - - @get:Input - @get:Optional - abstract val operationManifestFormat: Property - - /** - * JavaCodegenOptions - */ - @get:Input - @get:Optional - abstract val generatePrimitiveTypes: Property - - @get:Input - @get:Optional - abstract val nullableFieldStyle: Property - - @get:Input - @get:Optional - abstract val generateModelBuilders: Property - - @get:Input - @get:Optional - abstract val classesForEnumsMatching: ListProperty - - /** - * KotlinCodegenOptions - */ - @get:Input - @get:Optional - abstract val sealedClassesForEnumsMatching: ListProperty - - @get:Input - @get:Optional - abstract val generateAsInternal: Property - - @get:Input - @get:Optional - abstract val generateInputBuilders: Property - - @get:Input - @get:Optional - abstract val addJvmOverloads: Property - - @get:Input - @get:Optional - abstract val jsExport: Property - - @get:Input - @get:Optional - abstract val requiresOptInAnnotation: Property - - @get:OutputFile - abstract val codegenOptions: RegularFileProperty - - /** - * Gradle model - */ - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val upstreamOtherOptions: ConfigurableFileCollection - - @get:Input - abstract var isJavaPluginApplied: Boolean - - @get:Input - @get:Optional - abstract var kgpVersion: String? - - @get:Input - abstract var isKmp: Boolean - - @get:Input - abstract var generateAllTypes: Boolean - - @get:OutputFile - abstract val otherOptions: RegularFileProperty - - @TaskAction - fun taskAction() { - check( - packageName.isPresent || rootPackageName.isPresent - ) { - """ - |Apollo: specify 'packageName': - |apollo { - | service("service") { - | packageName.set("com.example") - | } - |} - """.trimMargin() - } - - val upstreamOtherOptions = upstreamOtherOptions.firstOrNull()?.toOtherOptions() - val upstreamTargetLanguage = upstreamOtherOptions?.targetLanguage - val targetLanguage = - targetLanguage(generateKotlinModels.orNull, languageVersion.orNull, isJavaPluginApplied, kgpVersion, upstreamTargetLanguage) - val generateFilterNotNull = generateFilterNotNull(targetLanguage, isKmp) - val alwaysGenerateTypesMatching = alwaysGenerateTypesMatching(alwaysGenerateTypesMatching.orNull, generateAllTypes) - val upstreamCodegenModels = upstreamOtherOptions?.codegenModels - val codegenModels = codegenModels(codegenModels.orNull, upstreamCodegenModels) - - CodegenSchemaOptions( - scalarTypeMapping = scalarTypeMapping.getOrElse(emptyMap()), - scalarAdapterMapping = scalarAdapterMapping.getOrElse(emptyMap()), - generateDataBuilders = generateDataBuilders.getOrElse(false), - ).writeTo(codegenSchemaOptionsFile.get().asFile) - - IrOptions( - codegenModels = codegenModels, - addTypename = addTypename.orNull, - fieldsOnDisjointTypesMustMerge = fieldsOnDisjointTypesMustMerge.orNull, - decapitalizeFields = decapitalizeFields.orNull, - flattenModels = flattenModels.orNull, - warnOnDeprecatedUsages = warnOnDeprecatedUsages.orNull, - failOnWarnings = failOnWarnings.orNull, - generateOptionalOperationVariables = generateOptionalOperationVariables.orNull, - alwaysGenerateTypesMatching = alwaysGenerateTypesMatching - ).writeTo(irOptionsFile.get().asFile) - - CodegenOptions( - targetLanguage = targetLanguage, - useSemanticNaming = useSemanticNaming.orNull, - generateFragmentImplementations = generateFragmentImplementations.orNull, - generateMethods = generateMethods.orNull, - generateQueryDocument = generateQueryDocument.orNull, - generateSchema = generateSchema.orNull, - generatedSchemaName = generatedSchemaName.orNull, - operationManifestFormat = operationManifestFormat.orNull, - nullableFieldStyle = nullableFieldStyle.orNull, - generateModelBuilders = generateModelBuilders.orNull, - classesForEnumsMatching = classesForEnumsMatching.orNull, - generatePrimitiveTypes = generatePrimitiveTypes.orNull, - generateAsInternal = generateAsInternal.orNull, - generateFilterNotNull = generateFilterNotNull, - sealedClassesForEnumsMatching = sealedClassesForEnumsMatching.orNull, - addJvmOverloads = addJvmOverloads.orNull, - requiresOptInAnnotation = requiresOptInAnnotation.orNull, - jsExport = jsExport.orNull, - generateInputBuilders = generateInputBuilders.orNull, - decapitalizeFields = decapitalizeFields.orNull, - addDefaultArgumentForInputObjects = true, - addUnknownForEnums = true, - packageName = packageName.orNull, - rootPackageName = rootPackageName.orNull - ).writeTo(codegenOptions.get().asFile) - - OtherOptions(targetLanguage, codegenModels).writeTo(otherOptions.get().asFile) - } - - private fun codegenModels(codegenModels: String?, upstreamCodegenModels: String?): String { - if (codegenModels != null) { - setOf(MODELS_OPERATION_BASED, MODELS_RESPONSE_BASED, MODELS_OPERATION_BASED_WITH_INTERFACES).apply { - check(contains(codegenModels)) { - "Apollo: unknown codegenModels '$codegenModels'. Valid values: $this" - } - } - - check(upstreamCodegenModels == null || codegenModels == upstreamCodegenModels) { - "Apollo: Expected '$upstreamCodegenModels', got '$codegenModels'. Check your codegenModels setting." - } - return codegenModels - } - if (upstreamCodegenModels != null) { - return upstreamCodegenModels - } - - return MODELS_OPERATION_BASED - } -} - -private fun targetLanguage( - generateKotlinModels: Boolean?, - languageVersion: String?, - javaPluginApplied: Boolean, - kgpVersion: String?, - upstreamTargetLanguage: TargetLanguage?, -): TargetLanguage { - return when { - generateKotlinModels != null -> { - if (generateKotlinModels) { - check(kgpVersion != null) { - "Apollo: generateKotlinModels.set(true) requires to apply a Kotlin plugin" - } - val targetLanguage = getKotlinTargetLanguage(kgpVersion, languageVersion) - - check(upstreamTargetLanguage == null || targetLanguage == upstreamTargetLanguage) { - "Apollo: Expected '$upstreamTargetLanguage', got '$targetLanguage'. Check your generateKotlinModels and languageVersion settings." - } - targetLanguage - } else { - check(javaPluginApplied) { - "Apollo: generateKotlinModels.set(false) requires to apply the Java plugin" - } - - check(upstreamTargetLanguage == null || TargetLanguage.JAVA == upstreamTargetLanguage) { - "Apollo: Expected '$upstreamTargetLanguage', got '${TargetLanguage.JAVA}'. Check your generateKotlinModels settings." - } - - TargetLanguage.JAVA - } - } - - upstreamTargetLanguage != null -> { - upstreamTargetLanguage - } - - kgpVersion != null -> { - getKotlinTargetLanguage(kgpVersion, languageVersion) - } - - javaPluginApplied -> { - TargetLanguage.JAVA - } - - else -> { - error("Apollo: No Java or Kotlin plugin found") - } - } -} - -@Serializable -internal class OtherOptions( - val targetLanguage: TargetLanguage, - val codegenModels: String, -) - -internal fun OtherOptions.writeTo(file: File) { - file.writeText(Json.encodeToString(this)) -} - -internal fun File.toOtherOptions(): OtherOptions { - return Json.decodeFromString(readText()) -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesBaseTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesBaseTask.kt deleted file mode 100644 index 3e301587631..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesBaseTask.kt +++ /dev/null @@ -1,26 +0,0 @@ - -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.OutputDirectory -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity - -@CacheableTask -abstract class ApolloGenerateSourcesBaseTask : ApolloTaskWithClasspath() { - @get:InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenOptionsFile: RegularFileProperty - - @get:OutputFile - @get:Optional - abstract val operationManifestFile: RegularFileProperty - - @get:OutputDirectory - abstract val outputDir: DirectoryProperty -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesFromIrTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesFromIrTask.kt deleted file mode 100644 index 1045eeb4e7a..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesFromIrTask.kt +++ /dev/null @@ -1,102 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.FileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.MapProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import org.gradle.workers.WorkAction -import org.gradle.workers.WorkParameters - -@CacheableTask -abstract class ApolloGenerateSourcesFromIrTask : ApolloGenerateSourcesBaseTask() { - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenSchemas: ConfigurableFileCollection - - @get:InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val irOperations: RegularFileProperty - - @get:Input - abstract val downstreamUsedCoordinates: MapProperty>> - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val upstreamMetadata: ConfigurableFileCollection - - @get:OutputFile - @get:Optional - abstract val metadataOutputFile: RegularFileProperty - - @TaskAction - fun taskAction() { - val workQueue = getWorkQueue() - - workQueue.submit(GenerateSourcesFromIr::class.java) { - it.codegenSchemas.from(codegenSchemas) - it.irOperations.set(irOperations) - it.codegenOptions.set(codegenOptionsFile) - it.downstreamUsedCoordinates.set(downstreamUsedCoordinates) - it.upstreamMetadata.from(upstreamMetadata) - it.operationManifestFile.set(operationManifestFile) - it.outputDir.set(outputDir) - it.metadataOutputFile.set(metadataOutputFile) - it.hasPlugin = hasPlugin.get() - it.arguments = arguments.get() - it.logLevel = logLevel.get().ordinal - it.apolloBuildService.set(apolloBuildService) - it.classpath = classpath - } - } -} - -private abstract class GenerateSourcesFromIr : WorkAction { - override fun execute() { - with(parameters) { - runInIsolation(apolloBuildService.get(), classpath) { - it.reflectiveCall( - "buildSourcesFromIr", - arguments, - logLevel, - hasPlugin, - codegenSchemas.toInputFiles().isolate(), - upstreamMetadata.toInputFiles().isolate(), - irOperations.get().asFile, - downstreamUsedCoordinates.get(), - codegenOptions.get().asFile, - operationManifestFile.orNull?.asFile, - outputDir.get().asFile, - metadataOutputFile.orNull?.asFile - ) - } - } - } -} - -private interface GenerateSourcesFromIrParameters : WorkParameters { - var hasPlugin: Boolean - val codegenSchemas: ConfigurableFileCollection - val irOperations: RegularFileProperty - val codegenOptions: RegularFileProperty - val downstreamUsedCoordinates: MapProperty>> - val upstreamMetadata: ConfigurableFileCollection - val operationManifestFile: RegularFileProperty - val outputDir: DirectoryProperty - val metadataOutputFile: RegularFileProperty - var arguments: Map - var logLevel: Int - val apolloBuildService: Property - var classpath: FileCollection -} - diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesTask.kt deleted file mode 100644 index 0ac64c3e5bf..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesTask.kt +++ /dev/null @@ -1,100 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.DirectoryProperty -import org.gradle.api.file.FileCollection -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.InputFiles -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import org.gradle.workers.WorkAction -import org.gradle.workers.WorkParameters - -@CacheableTask -abstract class ApolloGenerateSourcesTask : ApolloGenerateSourcesBaseTask(), ApolloGenerateDataBuildersSourcesBaseTask { - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val schemaFiles: ConfigurableFileCollection - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val fallbackSchemaFiles: ConfigurableFileCollection - - @get:InputFiles - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val graphqlFiles: ConfigurableFileCollection - - @get:org.gradle.api.tasks.InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val codegenSchemaOptionsFile: RegularFileProperty - - @get:org.gradle.api.tasks.InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - abstract val irOptionsFile: RegularFileProperty - - @TaskAction - fun taskAction() { - val workQueue = getWorkQueue() - - workQueue.submit(GenerateSources::class.java) { - it.hasPlugin = hasPlugin.get() - it.graphqlFiles = graphqlFiles.isolate() - it.schemaFiles = schemaFiles.isolate() - it.fallbackSchemaFiles = fallbackSchemaFiles.isolate() - it.codegenSchemaOptions.set(codegenSchemaOptionsFile) - it.irOptions.set(irOptionsFile) - it.codegenOptions.set(codegenOptionsFile) - it.operationManifestFile.set(operationManifestFile) - it.outputDir.set(outputDir) - it.dataBuildersOutputDir.set(dataBuildersOutputDir) - it.arguments = arguments.get() - it.logLevel = logLevel.get().ordinal - it.apolloBuildService.set(apolloBuildService) - it.classpath = classpath - } - } -} - -private abstract class GenerateSources : WorkAction { - override fun execute() { - with(parameters) { - runInIsolation(apolloBuildService.get(), classpath) { - it.reflectiveCall( - "buildSources", - arguments, - logLevel, - hasPlugin, - (schemaFiles.takeIf { it.isNotEmpty() } ?: fallbackSchemaFiles), - graphqlFiles, - codegenSchemaOptions.get().asFile, - codegenOptions.get().asFile, - irOptions.get().asFile, - warningMessageConsumer, - operationManifestFile.orNull?.asFile, - outputDir.get().asFile, - dataBuildersOutputDir.get().asFile, - ) - } - } - } -} - -private interface GenerateSourcesParameters : WorkParameters { - var hasPlugin: Boolean - var graphqlFiles: List - var schemaFiles: List - var fallbackSchemaFiles: List - val codegenSchemaOptions: RegularFileProperty - val codegenOptions: RegularFileProperty - val irOptions: RegularFileProperty - val operationManifestFile: RegularFileProperty - val outputDir: DirectoryProperty - val dataBuildersOutputDir: DirectoryProperty - var arguments: Map - var logLevel: Int - val apolloBuildService: Property - var classpath: FileCollection -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPlugin.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPlugin.kt deleted file mode 100644 index f4995622854..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPlugin.kt +++ /dev/null @@ -1,59 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.APOLLO_VERSION -import com.apollographql.apollo.gradle.api.ApolloExtension -import com.apollographql.apollo.gradle.api.ApolloGradleToolingModel -import org.gradle.api.Plugin -import org.gradle.api.Project -import org.gradle.api.artifacts.ExternalDependency -import org.gradle.tooling.provider.model.ToolingModelBuilder -import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry -import javax.inject.Inject - -open class ApolloPlugin -@Inject -constructor(private val toolingModelRegistry: ToolingModelBuilderRegistry) : Plugin { - override fun apply(project: Project) { - val apolloExtension: DefaultApolloExtension = project.extensions.create(ApolloExtension::class.java, "apollo", DefaultApolloExtension::class.java, project) as DefaultApolloExtension - - project.configureDefaultVersionsResolutionStrategy() - toolingModelRegistry.register( - object : ToolingModelBuilder { - override fun canBuild(modelName: String) = modelName == ApolloGradleToolingModel::class.java.name - - override fun buildAll(modelName: String, project: Project): ApolloGradleToolingModel { - return DefaultApolloGradleToolingModel( - projectName = project.name, - projectPath = project.path, - serviceInfos = apolloExtension.getServiceInfos(project), - telemetryData = getTelemetryData(project, apolloExtension), - ) - } - } - ) - } - - /** - * Allow users to omit the Apollo version in their dependencies - * Inspired by https://github.com/JetBrains/kotlin/blob/70e15b281cb43379068facb82b8e4bcb897a3c4f/libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/internal/KotlinDependenciesManagement.kt#L52 - */ - private fun Project.configureDefaultVersionsResolutionStrategy() { - configurations.configureEach { configuration -> - // Use the API introduced in Gradle 4.4 to modify the dependencies directly before they are resolved: - configuration.withDependencies { dependencySet -> - val pluginVersion = APOLLO_VERSION - dependencySet.filterIsInstance() - .filter { it.group == "com.apollographql.apollo" && it.version.isNullOrEmpty() } - .forEach { it.version { constraint -> constraint.require(pluginVersion) } } - } - } - } - - - companion object { - internal val extraHeaders = mapOf( - "apollographql-client-name" to "apollo-gradle-plugin", - "apollographql-client-version" to APOLLO_VERSION - ) - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPushSchemaTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPushSchemaTask.kt deleted file mode 100644 index 13381d66d71..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloPushSchemaTask.kt +++ /dev/null @@ -1,81 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.gradle.internal.ApolloPlugin.Companion.extraHeaders -import com.apollographql.apollo.tooling.SchemaUploader -import org.gradle.api.DefaultTask -import org.gradle.api.provider.Property -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.TaskAction -import org.gradle.api.tasks.options.Option -import org.gradle.work.DisableCachingByDefault -import java.io.File - -@DisableCachingByDefault(because = "This uploads a file to the internet and we cannot track the internet.") -abstract class ApolloPushSchemaTask : DefaultTask() { - @get:Input - @get:Optional - @get:Option(option = "schema", description = "The schema to push as SDL") - abstract val schema: Property - - @get:Input - @get:Option(option = "key", description = "The Apollo API key. See https://www.apollographql.com/docs/studio/api-keys/ for more information on how to get your API key.") - abstract val key: Property - - @get:Input - @get:Option(option = "graph", description = "The identifier of the Apollo graph used to download the schema.") - abstract val graph: Property - - @get:Input - @get:Option(option = "graphVariant", description = "The variant of the Apollo graph used to download the schema.") - abstract val graphVariant: Property - - @get:Optional - @get:Input - @get:Option(option = "subgraph", description = "The subgraph name. Can be omitted if the graph is a legacy monograph.") - abstract val subgraph: Property - - @get:Optional - @get:Input - @get:Option(option = "revision", description = "The revision name. Can be omitted if the graph is a legacy monograph, must be provided otherwise.") - abstract val revision: Property - - @get:Input - abstract var projectRootDir: String - - @TaskAction - fun taskAction() { - val key = key.get() - var graph = graph.get() - val graphVariant = graphVariant.get() - val schema = schema.orNull - val subgraph = subgraph.orNull - val revision = revision.orNull - - if (key.startsWith("service:")) { - graph = key.split(":")[1] - } - - check(schema != null) { - "please define schema" - } - - check(subgraph == null && revision == null || subgraph != null && revision != null) { - "please define both subgraph and revision or neither" - } - - // Files are relative to the root project. It is not possible in a consistent way to have them relative to the current - // working directory where the gradle command was started - SchemaUploader.uploadSchema( - apolloKey = key, - graph = graph, - variant = graphVariant ?: "current", - sdl = File(projectRootDir).resolve(schema).readText(), - headers = extraHeaders, - subgraph = subgraph, - revision = revision, - ) - - logger.info("Apollo: schema pushed successfully") - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloRegisterOperationsTask.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloRegisterOperationsTask.kt deleted file mode 100644 index c192bd0f6a8..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloRegisterOperationsTask.kt +++ /dev/null @@ -1,106 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.MANIFEST_OPERATION_OUTPUT -import com.apollographql.apollo.compiler.MANIFEST_PERSISTED_QUERY -import com.apollographql.apollo.compiler.toOperationOutput -import com.apollographql.apollo.compiler.toPersistedQueryManifest -import com.apollographql.apollo.tooling.CannotModifyOperationBody -import com.apollographql.apollo.tooling.GraphNotFound -import com.apollographql.apollo.tooling.PermissionError -import com.apollographql.apollo.tooling.PersistedQuery -import com.apollographql.apollo.tooling.PublishOperationsSuccess -import com.apollographql.apollo.tooling.RegisterOperations -import com.apollographql.apollo.tooling.publishOperations -import org.gradle.api.DefaultTask -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.Optional -import org.gradle.api.tasks.PathSensitive -import org.gradle.api.tasks.PathSensitivity -import org.gradle.api.tasks.TaskAction -import org.gradle.work.DisableCachingByDefault - -@DisableCachingByDefault(because = "This uploads a file to the internet and we cannot track the internet.") -abstract class ApolloRegisterOperationsTask: DefaultTask() { - @get:InputFile - @get:PathSensitive(PathSensitivity.RELATIVE) - @get:Optional - abstract val operationOutput: RegularFileProperty - - @get:Input - @get:Optional - abstract val operationManifestFormat: Property - - @get:Input - @get:Optional - abstract val listId: Property - - @get:Input - abstract val key: Property - - @get:Input - abstract val graph: Property - - @get:Input - @get:Optional - abstract val graphVariant: Property - - @TaskAction - fun taskAction() { - if (listId.isPresent) { - check(operationManifestFormat.get() == MANIFEST_PERSISTED_QUERY) { - """Apollo: registering operations to a persisted query list requires operationManifestFormat = "$MANIFEST_PERSISTED_QUERY": - |apollo { - | service("service") { - | operationManifestFormat.set("$MANIFEST_PERSISTED_QUERY") - | } - |} - """.trimMargin() - } - val result = publishOperations( - listId = listId.get(), - persistedQueries = operationOutput.get().asFile.toPersistedQueryManifest().operations.map { - PersistedQuery( - name = it.name, - id = it.id, - body = it.body, - operationType = it.type - ) - }, - apolloKey = key.get(), - graph = graph.get() - ) - - when(result) { - is PublishOperationsSuccess -> { - logger.info("Apollo: persisted query list uploaded successfully") - } - - is CannotModifyOperationBody -> error("Cannot upload persisted query list: cannot modify operation body ('${result.message}')") - GraphNotFound -> error("Cannot upload persisted query list: graph '$graph' not found") - is PermissionError -> error("Cannot upload persisted query list: permission error ('${result.message}')") - } - } else { - logger.warn("Apollo: registering operations without a listId is deprecated") - @Suppress("DEPRECATION_ERROR") - check(operationManifestFormat.get() == MANIFEST_OPERATION_OUTPUT) { - """Apollo: registering legacy operations requires operationManifestFormat = "$MANIFEST_OPERATION_OUTPUT": - |apollo { - | service("service") { - | operationManifestFormat.set("$MANIFEST_OPERATION_OUTPUT") - | } - |} - """.trimMargin() - } - @Suppress("DEPRECATION") - RegisterOperations.registerOperations( - key = key.get() ?: error("key is required to register operations"), - graphID = graph.get() ?: error("graphID is required to register operations"), - graphVariant = graphVariant.get() ?: error("graphVariant is required to register operations"), - operationOutput = operationOutput.get().asFile.toOperationOutput() - ) - } - } -} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloTaskWithClasspath.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloTaskWithClasspath.kt deleted file mode 100644 index 58e43ee5c33..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloTaskWithClasspath.kt +++ /dev/null @@ -1,65 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.DefaultTask -import org.gradle.api.file.ConfigurableFileCollection -import org.gradle.api.file.FileCollection -import org.gradle.api.logging.LogLevel -import org.gradle.api.logging.Logging -import org.gradle.api.provider.MapProperty -import org.gradle.api.provider.Property -import org.gradle.api.tasks.CacheableTask -import org.gradle.api.tasks.Classpath -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.Internal -import org.gradle.workers.WorkQueue -import org.gradle.workers.WorkerExecutor -import java.util.function.Consumer -import javax.inject.Inject - -@CacheableTask -abstract class ApolloTaskWithClasspath: DefaultTask() { - @get:Classpath - abstract val classpath: ConfigurableFileCollection - - @get:Input - abstract val hasPlugin: Property - - @get:Input - abstract val arguments: MapProperty - - @get:Internal - abstract val logLevel: Property - - @Inject - abstract fun getWorkerExecutor(): WorkerExecutor - - // This property provides access to the service instance - @get:Internal - abstract val apolloBuildService: Property - - @Internal - fun getWorkQueue(): WorkQueue { - return getWorkerExecutor().noIsolation() - } - - class Options( - val classpath: FileCollection, - val hasPlugin: Boolean, - val arguments: Map, - val logLevel: LogLevel, - ) -} - -internal fun runInIsolation(buildService: ApolloBuildService, classpath: FileCollection, block: (Any) -> Unit) { - val clazz = buildService.classloader(classpath).loadClass("com.apollographql.apollo.compiler.EntryPoints") - - block(clazz.declaredConstructors.single().newInstance()) -} - -internal val warningMessageConsumer: Consumer = object : Consumer { - private val logger = Logging.getLogger("apollo") - - override fun accept(p0: String) { - logger.lifecycle(p0) - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt deleted file mode 100644 index 97fba818521..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt +++ /dev/null @@ -1,100 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.gradle.api.Service -import org.gradle.api.Project -import org.gradle.api.file.Directory -import org.gradle.api.file.RegularFile -import org.gradle.api.provider.Provider -import java.io.File - -object BuildDirLayout { - internal fun operationManifest(project: Project, service: Service, format: String): File { - return project.layout.buildDirectory.file( - "generated/manifest/apollo/${service.name}/$format.json" - ).get().asFile - } - - internal fun metadata(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/metadata/apollo/${service.name}/metadata.json" - ) - } - - internal fun usedCoordinates(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/usedCoordinates/apollo/${service.name}/usedCoordinates.json" - ) - } - - internal fun ir(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/ir/apollo/${service.name}/ir.json" - ) - } - - internal fun irOptions(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/options/apollo/${service.name}/irOptions.json" - ) - } - - internal fun codegenOptions(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/options/apollo/${service.name}/codegenOptions.json" - ) - } - - internal fun otherOptions(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/options/apollo/${service.name}/otherOptions.json" - ) - } - - internal fun codegenSchemaOptions(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/options/apollo/${service.name}/codegenSchemaOptions.json" - ) - } - internal fun codegenSchema(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/schema/apollo/${service.name}/codegenSchema.json" - ) - } - - internal fun outputDir(project: Project, service: Service): Provider { - return project.layout.buildDirectory.dir( - "generated/source/apollo/${service.name}" - ) - } - - internal fun dataBuildersOutputDir(project: Project, service: Service): Provider { - return project.layout.buildDirectory.dir( - "generated/dataBuildersSource/apollo/${service.name}" - ) - } - - - internal fun kspProcessorJar(project: Project, serviceName: String): Provider { - return project.layout.buildDirectory.file( - "generated/jar/apollo/${serviceName}Processor.jar" - ) - } - - internal fun versionCheck(project: Project): Provider { - return project.layout.buildDirectory.file( - "generated/checks/apollo/versionCheck" - ) - } - - internal fun legacyJsTargetCheck(project: Project): Provider { - return project.layout.buildDirectory.file( - "generated/checks/apollo/legacyJsTargetCheck" - ) - } - - internal fun duplicatesCheck(project: Project, service: Service): Provider { - return project.layout.buildDirectory.file( - "generated/checks/apollo/${service.name}/duplicatesCheck" - ) - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/TaskExtensions.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/TaskExtensions.kt deleted file mode 100644 index 7f66e1bdb86..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/TaskExtensions.kt +++ /dev/null @@ -1,11 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.ApolloCompiler -import org.gradle.api.logging.Logging - -fun logger() = object : ApolloCompiler.Logger { - val logger = Logging.getLogger("apollo") - override fun warning(message: String) { - logger.lifecycle(message) - } -} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/defaults.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/defaults.kt deleted file mode 100644 index e34d036f7d1..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/defaults.kt +++ /dev/null @@ -1,115 +0,0 @@ -@file:Suppress("DEPRECATION") - -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.MANIFEST_NONE -import com.apollographql.apollo.compiler.MANIFEST_OPERATION_OUTPUT -import com.apollographql.apollo.compiler.MANIFEST_PERSISTED_QUERY -import com.apollographql.apollo.compiler.TargetLanguage -import org.gradle.api.file.RegularFileProperty -import org.gradle.api.provider.Provider -import java.io.File - - -/** - * Resolves the operation manifest and formats. - */ -private fun DefaultService.resolveOperationManifest(): Pair { - @Suppress("DEPRECATION_ERROR") - generateOperationOutput.disallowChanges() - @Suppress("DEPRECATION_ERROR") - operationOutputFile.disallowChanges() - operationManifest.disallowChanges() - operationManifestFormat.disallowChanges() - - var format = operationManifestFormat.orNull - if (format == null) { - @Suppress("DEPRECATION_ERROR") - if (generateOperationOutput.orElse(false).get()) { - println("Apollo: using 'generateOperationOutput' is deprecated, please use 'operationManifestFormat.set(\"$MANIFEST_PERSISTED_QUERY\")' instead") - format = MANIFEST_OPERATION_OUTPUT - } - } else { - @Suppress("DEPRECATION_ERROR") - when (format) { - MANIFEST_NONE, - MANIFEST_PERSISTED_QUERY, - -> Unit - MANIFEST_OPERATION_OUTPUT -> { - println("Apollo: using '$MANIFEST_OPERATION_OUTPUT' is deprecated, please use '$MANIFEST_PERSISTED_QUERY' instead") - } - - else -> { - error("Apollo: unknown operation manifest format: $format") - } - } - @Suppress("DEPRECATION_ERROR") - check(!generateOperationOutput.isPresent) { - "Apollo: it is an error to set both `generateOperationOutput` and `operationManifestFormat`. Remove `generateOperationOutput`" - } - } - var userFile = operationManifest.orNull?.asFile - if (userFile == null) { - @Suppress("DEPRECATION_ERROR") - userFile = operationOutputFile.orNull?.asFile - } else { - @Suppress("DEPRECATION_ERROR") - check(!operationOutputFile.isPresent) { - "Apollo: it is an error to set both `operationManifest` and `operationOutputFile`. Remove `operationOutputFile`" - } - } - - if (userFile != null) { - if (format == null) { - @Suppress("DEPRECATION_ERROR") - format = MANIFEST_OPERATION_OUTPUT - } - } else { - userFile = if (format == null || format == MANIFEST_NONE) { - null - } else { - BuildDirLayout.operationManifest(project, this, format) - } - } - - if (format == null) { - format = MANIFEST_NONE - } - return format to userFile -} - -internal fun DefaultService.operationManifestFile(): RegularFileProperty { - return project.provider { - resolveOperationManifest().second - }.let { fileProvider -> - project.objects.fileProperty().fileProvider(fileProvider) - } -} - -internal fun DefaultService.operationManifestFormat(): Provider { - return project.provider { - resolveOperationManifest().first - } -} - -internal fun generateFilterNotNull(targetLanguage: TargetLanguage, isKmp: Boolean): Boolean? { - return if (targetLanguage == TargetLanguage.JAVA) { - null - } else { - isKmp - } -} - -internal fun alwaysGenerateTypesMatching(alwaysGenerateTypesMatching: Set?, generateAllTypes: Boolean): Set { - if (alwaysGenerateTypesMatching != null) { - // The user specified something, use this - return alwaysGenerateTypesMatching - } - - if (generateAllTypes) { - return setOf(".*") - } else { - // get the used coordinates from the downstream dependencies - return emptySet() - } -} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt b/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt deleted file mode 100644 index 571ef9d2387..00000000000 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt +++ /dev/null @@ -1,61 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import com.apollographql.apollo.compiler.InputFile -import org.gradle.api.artifacts.ProjectDependency -import org.gradle.api.file.FileCollection -import java.lang.reflect.InvocationTargetException - - -internal fun FileCollection.toInputFiles(): List { - val inputFiles = mutableListOf() - - asFileTree.visit { - if (it.file.isFile) { - inputFiles.add(InputFile(it.file, it.path)) - } - } - - return inputFiles -} - -/** - * Isolates inputs so we can use them from a separate classloader. - * - * See also https://github.com/gradle/gradle/issues/28147 for why this is needed. - */ -internal fun FileCollection.isolate(): List = toInputFiles().isolate() -internal fun List.isolate(): List = flatMap { listOf(it.normalizedPath, it.file) } - - -internal fun ProjectDependency.getPathCompat(): String { - val method = this::class.java.methods.firstOrNull { - it.name == "getPath" && it.parameters.isEmpty() - } - return if (method != null) { - // Gradle 8.11+ path - // See https://docs.gradle.org/8.11/userguide/upgrading_version_8.html#deprecate_get_dependency_project - method.invoke(this) as String - } else { - dependencyProject.path - } -} - -internal fun Any.reflectiveCall(methodName: String, vararg args: Any?) { - try { - javaClass.declaredMethods.single { it.name == methodName }.invoke(this, *args) - } catch (e: InvocationTargetException) { - /** - * Unwrap the exception so it's displayed in Gradle error messages: - * - * Execution failed for task ':generateServiceApolloSources'. - * > A failure occurred while executing com.apollographql.apollo.gradle.internal.GenerateSources - * > e: operation.graphql: (2, 5): Can't query `foo2` on type `Query` - * ---------------------------------------------------- - * [1]:query GetFoo { - * [2]: foo2 - * [3]:} - * ---------------------------------------------------- - */ - throw e.cause!! - } -} diff --git a/libraries/apollo-gradle-plugin-tasks/README.md b/libraries/apollo-gradle-plugin-tasks/README.md new file mode 100644 index 00000000000..215e1e9ef02 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/README.md @@ -0,0 +1,5 @@ +# Module apollo-gradle-plugin-tasks + +`apollo-gradle-plugin-tasks` contains the task implementations for the Apollo Gradle plugin. + +This module is loaded in a separate classloader to allow compiler plugins and avoid polluting the main build script classpath. This module is an implementation detail of `apollo-gradle-plugin` and should not be depended on directly. diff --git a/libraries/apollo-gradle-plugin-tasks/api/apollo-gradle-plugin-tasks.api b/libraries/apollo-gradle-plugin-tasks/api/apollo-gradle-plugin-tasks.api new file mode 100644 index 00000000000..33a21cbd0e9 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/api/apollo-gradle-plugin-tasks.api @@ -0,0 +1,99 @@ +public final class com/apollographql/apollo/gradle/task/ApolloComputeUsedCoordinatesEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloComputeUsedCoordinatesEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/List;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloComputeUsedCoordinatesEntryPoint$Companion { + public final fun run (Ljava/util/List;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloDownloadSchemaEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloDownloadSchemaEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/io/File;Ljava/lang/Boolean;Ljava/util/Map;Ljava/util/function/BiConsumer;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloDownloadSchemaEntryPoint$Companion { + public final fun run (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/io/File;Ljava/lang/Boolean;Ljava/util/Map;Ljava/util/function/BiConsumer;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateCodegenSchemaEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloGenerateCodegenSchemaEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateCodegenSchemaEntryPoint$Companion { + public final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateDataBuildersSourcesEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloGenerateDataBuildersSourcesEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/io/File;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateDataBuildersSourcesEntryPoint$Companion { + public final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/io/File;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateIrOperationsEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloGenerateIrOperationsEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateIrOperationsEntryPoint$Companion { + public final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateOptionsEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloGenerateOptionsEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/lang/Boolean;Ljava/lang/String;Ljava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/util/List;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/Boolean;Ljava/util/List;Ljava/util/List;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;ZZLjava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateOptionsEntryPoint$Companion { + public final fun run (Ljava/lang/Boolean;Ljava/lang/String;Ljava/util/Map;Ljava/util/Map;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/util/Set;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/util/List;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Boolean;Ljava/lang/String;Ljava/lang/Boolean;Ljava/util/List;Ljava/util/List;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/Boolean;Ljava/lang/String;Ljava/util/List;ZLjava/lang/String;ZZLjava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateOptionsKt { + public static final fun getKotlinTargetLanguage (Ljava/lang/String;Ljava/lang/String;)Lcom/apollographql/apollo/compiler/TargetLanguage; +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateSourcesEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloGenerateSourcesEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateSourcesEntryPoint$Companion { + public final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/util/List;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateSourcesFromIrEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloGenerateSourcesFromIrEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/io/File;Ljava/io/File;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateSourcesFromIrEntryPoint$Companion { + public final fun run (Ljava/util/function/BiConsumer;Ljava/util/Map;ZLjava/util/List;Ljava/io/File;Ljava/io/File;Ljava/util/List;Ljava/io/File;Ljava/io/File;Ljava/io/File;Ljava/io/File;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloRegisterOperationsEntryPoint { + public static final field Companion Lcom/apollographql/apollo/gradle/task/ApolloRegisterOperationsEntryPoint$Companion; + public fun ()V + public static final fun run (Ljava/util/function/BiConsumer;Ljava/io/File;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V +} + +public final class com/apollographql/apollo/gradle/task/ApolloRegisterOperationsEntryPoint$Companion { + public final fun run (Ljava/util/function/BiConsumer;Ljava/io/File;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V +} + +public final class com/apollographql/apollo/gradle/task/UtilsKt { + public static final fun asLogger (Lgratatouille/tasks/GLogger;)Lcom/apollographql/apollo/compiler/ApolloCompiler$Logger; + public static final fun toInputFiles (Ljava/util/List;)Ljava/util/List; +} + diff --git a/libraries/apollo-gradle-plugin-tasks/build.gradle.kts b/libraries/apollo-gradle-plugin-tasks/build.gradle.kts new file mode 100644 index 00000000000..60a662a53ab --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + id("org.jetbrains.kotlin.jvm") + id("com.gradleup.gratatouille.tasks") + id("com.google.devtools.ksp") + id("org.jetbrains.kotlin.plugin.serialization") +} + +apolloLibrary( + jvmTarget = 11, // Gratatouille requires 11 + namespace = "com.apollographql.apollo.gradle.tasks", +) + +dependencies { + implementation(project(":apollo-compiler")) + implementation(project(":apollo-tooling")) + implementation(project(":apollo-ast")) + implementation(libs.asm) + implementation(libs.kotlinx.serialization.json) +} + +gratatouille { + codeGeneration { + classLoaderIsolation() + } +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/gradle.properties b/libraries/apollo-gradle-plugin-tasks/gradle.properties similarity index 100% rename from libraries/apollo-gradle-plugin-external/gradle.properties rename to libraries/apollo-gradle-plugin-tasks/gradle.properties diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloComputeUsedCoordinates.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloComputeUsedCoordinates.kt new file mode 100644 index 00000000000..844e65f9201 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloComputeUsedCoordinates.kt @@ -0,0 +1,22 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.UsedCoordinates +import com.apollographql.apollo.compiler.toIrOperations +import com.apollographql.apollo.compiler.writeTo +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GOutputFile +import gratatouille.tasks.GTask + +@GTask +internal fun apolloComputeUsedCoordinates( + irOperations: GInputFiles, + outputFile: GOutputFile, +) { + val usedCoordinates: UsedCoordinates = irOperations.map { + it.file.toIrOperations().usedCoordinates + }.fold(UsedCoordinates()) { acc, element -> + acc.mergeWith(element) + } + + usedCoordinates.writeTo(outputFile) +} diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloDownloadSchema.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloDownloadSchema.kt new file mode 100644 index 00000000000..1725e1b828b --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloDownloadSchema.kt @@ -0,0 +1,52 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.APOLLO_VERSION +import com.apollographql.apollo.tooling.SchemaDownloader +import gratatouille.tasks.GInternal +import gratatouille.tasks.GLogger +import gratatouille.tasks.GTask +import java.io.File + +/** + * A task to download a schema either from introspection or from the registry. + */ +@GTask(pure = false) +internal fun apolloDownloadSchema( + endpoint: String?, + graph: String?, + key: String?, + graphVariant: String?, + registryUrl: String?, + @GInternal schema: File, + insecure: Boolean?, + headers: Map, + logger: GLogger, +) { + val extraHeaders = mapOf( + "apollographql-client-name" to "apollo-gradle-plugin", + "apollographql-client-version" to APOLLO_VERSION + ) + SchemaDownloader.download( + endpoint = endpoint, + graph = graph, + graphVariant = graphVariant ?: "current", + key = key, + registryUrl = registryUrl ?: "https://api.apollographql.com/graphql", + schema = schema, + insecure = insecure ?: false, + headers = headers.toMap() + extraHeaders, + ) + + logger.lifecycle("Apollo: schema downloaded to ${schema.absolutePath}") +} + +private fun List.toMap(): Map { + return map { + val index = it.indexOf(':') + check(index > 0 && index < it.length - 1) { + "header should be in the form 'Name: Value'" + } + + it.substring(0, index).trim() to it.substring(index + 1, it.length).trim() + }.toMap() +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateCodegenSchema.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateCodegenSchema.kt new file mode 100644 index 00000000000..5d36c24845b --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateCodegenSchema.kt @@ -0,0 +1,41 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.EntryPoints +import gratatouille.tasks.GAny +import gratatouille.tasks.GInputFile +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GLogger +import gratatouille.tasks.GOutputFile +import gratatouille.tasks.GTask + +@GTask +internal fun apolloGenerateCodegenSchema( + logger: GLogger, + arguments: Map, + warnIfNotFound: Boolean, + schemaFiles: GInputFiles, + fallbackSchemaFiles: GInputFiles, + upstreamSchemaFiles: GInputFiles, + codegenSchemaOptionsFile: GInputFile, + codegenSchemaFile: GOutputFile, +) { + if (upstreamSchemaFiles.isNotEmpty()) { + /** + * Output an empty file + */ + codegenSchemaFile.let { + it.delete() + it.createNewFile() + } + return + } + + EntryPoints.buildCodegenSchema( + logger = logger.asLogger(), + arguments = arguments, + warnIfNotFound = warnIfNotFound, + normalizedSchemaFiles = (schemaFiles.takeIf { it.isNotEmpty() } ?: fallbackSchemaFiles).toInputFiles(), + codegenSchemaOptionsFile = codegenSchemaOptionsFile, + codegenSchemaFile = codegenSchemaFile, + ) +} diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateDataBuildersSources.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateDataBuildersSources.kt new file mode 100644 index 00000000000..3151ff43328 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateDataBuildersSources.kt @@ -0,0 +1,34 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.EntryPoints +import gratatouille.tasks.GAny +import gratatouille.tasks.GInputFile +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GLogger +import gratatouille.tasks.GManuallyWired +import gratatouille.tasks.GOutputDirectory +import gratatouille.tasks.GTask + +@GTask +internal fun apolloGenerateDataBuildersSources( + logger: GLogger, + arguments: Map, + warnIfNotFound: Boolean, + codegenSchemas: GInputFiles, + downstreamUsedCoordinates: GInputFile, + upstreamMetadata: GInputFiles, + codegenOptions: GInputFile, + @GManuallyWired + outputDirectory: GOutputDirectory, +) { + EntryPoints.buildDataBuilders( + arguments = arguments, + logger = logger.asLogger(), + warnIfNotFound = warnIfNotFound, + codegenSchemas = codegenSchemas.toInputFiles(), + upstreamMetadatas = upstreamMetadata.toInputFiles(), + downstreamUsedCoordinates = downstreamUsedCoordinates, + codegenOptions = codegenOptions, + outputDirectory = outputDirectory, + ) +} diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateIrOperations.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateIrOperations.kt new file mode 100644 index 00000000000..67894193ecb --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateIrOperations.kt @@ -0,0 +1,32 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.EntryPoints +import gratatouille.tasks.GAny +import gratatouille.tasks.GInputFile +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GLogger +import gratatouille.tasks.GOutputFile +import gratatouille.tasks.GTask + +@GTask +internal fun apolloGenerateIrOperations( + logger: GLogger, + arguments: Map, + warnIfNotFound: Boolean, + codegenSchemas: GInputFiles, + graphqlFiles: GInputFiles, + upstreamIrFiles: GInputFiles, + irOptionsFile: GInputFile, + irOperationsFile: GOutputFile, +) { + EntryPoints.buildIr( + logger = logger.asLogger(), + arguments = arguments, + warnIfNotFound = warnIfNotFound, + graphqlFiles = graphqlFiles.toInputFiles(), + codegenSchemaFiles = codegenSchemas.toInputFiles(), + upstreamIrOperations = upstreamIrFiles.toInputFiles(), + irOptionsFile = irOptionsFile, + irOperationsFile = irOperationsFile, + ) +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateOptions.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateOptions.kt new file mode 100644 index 00000000000..5de26b83c6d --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateOptions.kt @@ -0,0 +1,283 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.CodegenOptions +import com.apollographql.apollo.compiler.CodegenSchemaOptions +import com.apollographql.apollo.compiler.GeneratedMethod +import com.apollographql.apollo.compiler.IrOptions +import com.apollographql.apollo.compiler.JavaNullable +import com.apollographql.apollo.compiler.MANIFEST_NONE +import com.apollographql.apollo.compiler.MANIFEST_OPERATION_OUTPUT +import com.apollographql.apollo.compiler.MANIFEST_PERSISTED_QUERY +import com.apollographql.apollo.compiler.MODELS_OPERATION_BASED +import com.apollographql.apollo.compiler.MODELS_OPERATION_BASED_WITH_INTERFACES +import com.apollographql.apollo.compiler.MODELS_RESPONSE_BASED +import com.apollographql.apollo.compiler.TargetLanguage +import com.apollographql.apollo.compiler.writeTo +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GOutputFile +import gratatouille.tasks.GTask +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json +import java.io.File + +@GTask +internal fun apolloGenerateOptions( + generateKotlinModels: Boolean?, + languageVersion: String?, + scalarTypeMapping: Map?, + scalarAdapterMapping: Map?, + codegenModels: String?, + generateDataBuilders: Boolean?, + addTypename: String?, + fieldsOnDisjointTypesMustMerge: Boolean?, + decapitalizeFields: Boolean?, + flattenModels: Boolean?, + warnOnDeprecatedUsages: Boolean?, + failOnWarnings: Boolean?, + generateOptionalOperationVariables: Boolean?, + alwaysGenerateTypesMatching: Set?, + packageName: String?, + rootPackageName: String?, + useSemanticNaming: Boolean?, + generateFragmentImplementations: Boolean?, + generateMethods: List?, + generateQueryDocument: Boolean?, + generateSchema: Boolean?, + generatedSchemaName: String?, + operationManifestFormat: String?, + // JavaCodegenOptions + generatePrimitiveTypes: Boolean?, + nullableFieldStyle: String?, + generateModelBuilders: Boolean?, + classesForEnumsMatching: List?, + // KotlinCodegenOptions + sealedClassesForEnumsMatching: List?, + generateAsInternal: Boolean?, + generateInputBuilders: Boolean?, + addJvmOverloads: Boolean?, + jsExport: Boolean?, + requiresOptInAnnotation: String?, + + // multi modules + upstreamOtherOptions: GInputFiles, + javaPluginApplied: Boolean, + kgpVersion: String?, + kmp: Boolean, + generateAllTypes: Boolean, + + // outputs + codegenSchemaOptionsFile: GOutputFile, + irOptionsFile: GOutputFile, + codegenOptions: GOutputFile, + otherOptions: GOutputFile, +) { + check( + packageName != null || rootPackageName != null + ) { + """ + |Apollo: specify 'packageName': + |apollo { + | service("service") { + | packageName.set("com.example") + | } + |} + """.trimMargin() + } + + val upstreamOtherOptions = upstreamOtherOptions.firstOrNull()?.file?.toOtherOptions() + val upstreamTargetLanguage = upstreamOtherOptions?.targetLanguage + val targetLanguage = + targetLanguage(generateKotlinModels, languageVersion, javaPluginApplied, kgpVersion, upstreamTargetLanguage) + val generateFilterNotNull = generateFilterNotNull(targetLanguage, kmp) + val alwaysGenerateTypesMatching = + alwaysGenerateTypesMatching(alwaysGenerateTypesMatching, generateAllTypes) + val upstreamCodegenModels = upstreamOtherOptions?.codegenModels + val codegenModels = codegenModels(codegenModels, upstreamCodegenModels) + + CodegenSchemaOptions( + scalarTypeMapping = scalarTypeMapping ?: emptyMap(), + scalarAdapterMapping = scalarAdapterMapping ?: emptyMap(), + generateDataBuilders = generateDataBuilders ?: false, + ).writeTo(codegenSchemaOptionsFile) + + IrOptions( + codegenModels = codegenModels, + addTypename = addTypename, + fieldsOnDisjointTypesMustMerge = fieldsOnDisjointTypesMustMerge, + decapitalizeFields = decapitalizeFields, + flattenModels = flattenModels, + warnOnDeprecatedUsages = warnOnDeprecatedUsages, + failOnWarnings = failOnWarnings, + generateOptionalOperationVariables = generateOptionalOperationVariables, + alwaysGenerateTypesMatching = alwaysGenerateTypesMatching + ).writeTo(irOptionsFile) + + CodegenOptions( + targetLanguage = targetLanguage, + useSemanticNaming = useSemanticNaming, + generateFragmentImplementations = generateFragmentImplementations, + generateMethods = generateMethods?.map { GeneratedMethod.fromName(it) ?: error("Apollo: unknown method type: $it for generateMethods")}, + generateQueryDocument = generateQueryDocument, + generateSchema = generateSchema, + generatedSchemaName = generatedSchemaName, + operationManifestFormat = operationManifestFormat(operationManifestFormat), + nullableFieldStyle = nullableFieldStyle?.let { JavaNullable.fromName(it) }, + generateModelBuilders = generateModelBuilders, + classesForEnumsMatching = classesForEnumsMatching, + generatePrimitiveTypes = generatePrimitiveTypes, + generateAsInternal = generateAsInternal, + generateFilterNotNull = generateFilterNotNull, + sealedClassesForEnumsMatching = sealedClassesForEnumsMatching, + addJvmOverloads = addJvmOverloads, + requiresOptInAnnotation = requiresOptInAnnotation, + jsExport = jsExport, + generateInputBuilders = generateInputBuilders, + decapitalizeFields = decapitalizeFields, + addDefaultArgumentForInputObjects = true, + addUnknownForEnums = true, + packageName = packageName, + rootPackageName = rootPackageName + ).writeTo(codegenOptions) + + OtherOptions(targetLanguage, codegenModels).writeTo(otherOptions) +} + +@Suppress("DEPRECATION_ERROR") +private fun operationManifestFormat(format: String?): String { + if (format == null) { + return MANIFEST_PERSISTED_QUERY + } else { + when (format) { + MANIFEST_PERSISTED_QUERY, + MANIFEST_NONE, + -> return format + MANIFEST_OPERATION_OUTPUT -> { + error("Apollo: using '$MANIFEST_OPERATION_OUTPUT' is deprecated, please use '$MANIFEST_PERSISTED_QUERY' instead") + } + + else -> { + error("Apollo: unknown operation manifest format: $format") + } + } + } +} + +private fun codegenModels(codegenModels: String?, upstreamCodegenModels: String?): String { + if (codegenModels != null) { + setOf(MODELS_OPERATION_BASED, MODELS_RESPONSE_BASED, MODELS_OPERATION_BASED_WITH_INTERFACES).apply { + check(contains(codegenModels)) { + "Apollo: unknown codegenModels '$codegenModels'. Valid values: $this" + } + } + + check(upstreamCodegenModels == null || codegenModels == upstreamCodegenModels) { + "Apollo: Expected '$upstreamCodegenModels', got '$codegenModels'. Check your codegenModels setting." + } + return codegenModels + } + if (upstreamCodegenModels != null) { + return upstreamCodegenModels + } + + return MODELS_OPERATION_BASED +} + +private fun targetLanguage( + generateKotlinModels: Boolean?, + languageVersion: String?, + javaPluginApplied: Boolean, + kgpVersion: String?, + upstreamTargetLanguage: TargetLanguage?, +): TargetLanguage { + return when { + generateKotlinModels != null -> { + if (generateKotlinModels) { + check(kgpVersion != null) { + "Apollo: generateKotlinModels.set(true) requires to apply a Kotlin plugin" + } + val targetLanguage = getKotlinTargetLanguage(kgpVersion, languageVersion) + + check(upstreamTargetLanguage == null || targetLanguage == upstreamTargetLanguage) { + "Apollo: Expected '$upstreamTargetLanguage', got '$targetLanguage'. Check your generateKotlinModels and languageVersion settings." + } + targetLanguage + } else { + check(javaPluginApplied) { + "Apollo: generateKotlinModels.set(false) requires to apply the Java plugin" + } + + check(upstreamTargetLanguage == null || TargetLanguage.JAVA == upstreamTargetLanguage) { + "Apollo: Expected '$upstreamTargetLanguage', got '${TargetLanguage.JAVA}'. Check your generateKotlinModels settings." + } + + TargetLanguage.JAVA + } + } + + upstreamTargetLanguage != null -> { + upstreamTargetLanguage + } + + kgpVersion != null -> { + getKotlinTargetLanguage(kgpVersion, languageVersion) + } + + javaPluginApplied -> { + TargetLanguage.JAVA + } + + else -> { + error("Apollo: No Java or Kotlin plugin found") + } + } +} + +@Serializable +internal class OtherOptions( + val targetLanguage: TargetLanguage, + val codegenModels: String, +) + +internal fun OtherOptions.writeTo(file: File) { + file.writeText(Json.encodeToString(this)) +} + +internal fun File.toOtherOptions(): OtherOptions { + return Json.decodeFromString(readText()) +} + +fun getKotlinTargetLanguage(kgpVersion: String, userSpecified: String?): TargetLanguage { + @Suppress("DEPRECATION_ERROR") + return when (userSpecified) { + "1.5" -> TargetLanguage.KOTLIN_1_5 + "1.9" -> TargetLanguage.KOTLIN_1_9 + null -> { + // User didn't specify a version: default to the Kotlin plugin version + val kotlinPluginVersion = kgpVersion.split("-")[0] + val versionNumbers = kotlinPluginVersion.split(".").map { it.toInt() } + val version = KotlinVersion(versionNumbers[0], versionNumbers[1]) + if (version.isAtLeast(1, 9)) { + TargetLanguage.KOTLIN_1_9 + } else { + TargetLanguage.KOTLIN_1_5 + } + } + + else -> error("Apollo: languageVersion '$userSpecified' is not supported, Supported values: '1.5', '1.9'") + } +} + +internal fun alwaysGenerateTypesMatching(alwaysGenerateTypesMatching: Set?, generateAllTypes: Boolean): Set { + if (alwaysGenerateTypesMatching != null) { + // The user specified something, use this + return alwaysGenerateTypesMatching + } + + if (generateAllTypes) { + return setOf(".*") + } else { + // get the used coordinates from the downstream dependencies + return emptySet() + } +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSources.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSources.kt new file mode 100644 index 00000000000..eea14362576 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSources.kt @@ -0,0 +1,44 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.EntryPoints +import gratatouille.tasks.GAny +import gratatouille.tasks.GInputFile +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GLogger +import gratatouille.tasks.GManuallyWired +import gratatouille.tasks.GOutputDirectory +import gratatouille.tasks.GOutputFile +import gratatouille.tasks.GTask + +@GTask +internal fun apolloGenerateSources( + logger: GLogger, + arguments: Map, + warnIfNotFound: Boolean, + schemas: GInputFiles, + fallbackSchemas: GInputFiles, + executableDocuments: GInputFiles, + codegenSchemaOptions: GInputFile, + codegenOptions: GInputFile, + irOptions: GInputFile, + @GManuallyWired + operationManifest: GOutputFile, + @GManuallyWired + outputDirectory: GOutputDirectory, + @GManuallyWired + dataBuildersOutputDirectory: GOutputDirectory, +) { + EntryPoints.buildSources( + arguments = arguments, + warnIfNotFound = warnIfNotFound, + logger = logger.asLogger(), + schemas = (schemas.takeIf { it.isNotEmpty() } ?: fallbackSchemas).toInputFiles(), + executableDocuments = executableDocuments.toInputFiles(), + codegenSchemaOptions = codegenSchemaOptions, + codegenOptions = codegenOptions, + irOptions = irOptions, + operationManifest = operationManifest, + outputDirectory = outputDirectory, + dataBuildersOutputDirectory = dataBuildersOutputDirectory, + ) +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSourcesFromIr.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSourcesFromIr.kt new file mode 100644 index 00000000000..ebfb914f255 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloGenerateSourcesFromIr.kt @@ -0,0 +1,46 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.EntryPoints +import gratatouille.tasks.GAny +import gratatouille.tasks.GInputFile +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GLogger +import gratatouille.tasks.GManuallyWired +import gratatouille.tasks.GOutputDirectory +import gratatouille.tasks.GOutputFile +import gratatouille.tasks.GTask + + +@GTask +internal fun apolloGenerateSourcesFromIr( + logger: GLogger, + arguments: Map, + warnIfNotFound: Boolean, + codegenSchemas: GInputFiles, + irOperations: GInputFile, + usedCoordinates: GInputFile, + upstreamMetadata: GInputFiles, + codegenOptions: GInputFile, + // outputs + @GManuallyWired + operationManifest: GOutputFile, + @GManuallyWired + outputDirectory: GOutputDirectory, + metadataOutput: GOutputFile, +) { + EntryPoints.buildSourcesFromIr( + logger = logger.asLogger(), + arguments = arguments, + warnIfNotFound = warnIfNotFound, + codegenSchemas = codegenSchemas.toInputFiles(), + irOperations = irOperations, + usedCoordinates = usedCoordinates, + upstreamMetadata = upstreamMetadata.toInputFiles(), + codegenOptions = codegenOptions, + operationManifest = operationManifest, + outputDirectory = outputDirectory, + metadataOutput = metadataOutput, + ) +} + + diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloRegisterOperations.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloRegisterOperations.kt new file mode 100644 index 00000000000..48aa112f3d2 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/apolloRegisterOperations.kt @@ -0,0 +1,81 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.MANIFEST_OPERATION_OUTPUT +import com.apollographql.apollo.compiler.MANIFEST_PERSISTED_QUERY +import com.apollographql.apollo.compiler.toOperationOutput +import com.apollographql.apollo.compiler.toPersistedQueryManifest +import com.apollographql.apollo.tooling.CannotModifyOperationBody +import com.apollographql.apollo.tooling.GraphNotFound +import com.apollographql.apollo.tooling.PermissionError +import com.apollographql.apollo.tooling.PersistedQuery +import com.apollographql.apollo.tooling.PublishOperationsSuccess +import com.apollographql.apollo.tooling.RegisterOperations +import com.apollographql.apollo.tooling.publishOperations +import gratatouille.tasks.GInputFile +import gratatouille.tasks.GLogger +import gratatouille.tasks.GTask + +@GTask(pure = false) +internal fun apolloRegisterOperations( + logger: GLogger, + operationOutput: GInputFile, + operationManifestFormat: String?, + listId: String?, + key: String?, + graph: String?, + graphVariant: String?, +) { + if (listId != null) { + check(operationManifestFormat == MANIFEST_PERSISTED_QUERY) { + """Apollo: registering operations to a persisted query list requires operationManifestFormat = "$MANIFEST_PERSISTED_QUERY": + |apollo { + | service("service") { + | operationManifestFormat.set("$MANIFEST_PERSISTED_QUERY") + | } + |} + """.trimMargin() + } + val result = publishOperations( + listId = listId, + persistedQueries = operationOutput.toPersistedQueryManifest().operations.map { + PersistedQuery( + name = it.name, + id = it.id, + body = it.body, + operationType = it.type + ) + }, + apolloKey = key ?: error("key is required to register operations"), + graph = graph + ) + + when(result) { + is PublishOperationsSuccess -> { + logger.lifecycle("Apollo: persisted query list uploaded successfully") + } + + is CannotModifyOperationBody -> error("Cannot upload persisted query list: cannot modify operation body ('${result.message}')") + GraphNotFound -> error("Cannot upload persisted query list: graph '$graph' not found") + is PermissionError -> error("Cannot upload persisted query list: permission error ('${result.message}')") + } + } else { + logger.warn("Apollo: registering operations without a listId is deprecated") + @Suppress("DEPRECATION_ERROR") + check(operationManifestFormat == MANIFEST_OPERATION_OUTPUT) { + """Apollo: registering legacy operations requires operationManifestFormat = "$MANIFEST_OPERATION_OUTPUT": + |apollo { + | service("service") { + | operationManifestFormat.set("$MANIFEST_OPERATION_OUTPUT") + | } + |} + """.trimMargin() + } + @Suppress("DEPRECATION") + RegisterOperations.registerOperations( + key = key?: error("key is required to register operations"), + graphID = graph ?: error("graphID is required to register operations"), + graphVariant = graphVariant ?: error("graphVariant is required to register operations"), + operationOutput = operationOutput.toOperationOutput() + ) + } +} diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/defaults.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/defaults.kt new file mode 100644 index 00000000000..adf20e8ff38 --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/defaults.kt @@ -0,0 +1,12 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.TargetLanguage + +internal fun generateFilterNotNull(targetLanguage: TargetLanguage, isKmp: Boolean): Boolean? { + return if (targetLanguage == TargetLanguage.JAVA) { + null + } else { + isKmp + } +} + diff --git a/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/utils.kt b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/utils.kt new file mode 100644 index 00000000000..0d9cf6ff7fd --- /dev/null +++ b/libraries/apollo-gradle-plugin-tasks/src/main/kotlin/com/apollographql/apollo/gradle/task/utils.kt @@ -0,0 +1,31 @@ +package com.apollographql.apollo.gradle.task + +import com.apollographql.apollo.compiler.ApolloCompiler +import com.apollographql.apollo.compiler.InputFile +import gratatouille.tasks.GInputFiles +import gratatouille.tasks.GLogger + +fun GInputFiles.toInputFiles(): List = mapNotNull { + if (it.file.isFile) { + InputFile(it.file, it.normalizedPath) + } else { + null + } +} +fun GLogger.asLogger(): ApolloCompiler.Logger = object : ApolloCompiler.Logger { + override fun debug(message: String) { + this@asLogger.debug(message) + } + + override fun info(message: String) { + this@asLogger.lifecycle(message) + } + + override fun warning(message: String) { + this@asLogger.warn(message) + } + + override fun error(message: String) { + this@asLogger.error(message) + } +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin/README.md b/libraries/apollo-gradle-plugin/README.md index 1abca726c6b..892109418f5 100644 --- a/libraries/apollo-gradle-plugin/README.md +++ b/libraries/apollo-gradle-plugin/README.md @@ -2,8 +2,4 @@ `apollo-gradle-plugin` contains the Apollo Gradle plugin. -This module shadows and relocates its runtime dependencies to avoid classpath issues. This can make debugging harder in some cases. - -See `apollo-gradle-plugin-external` for a version of `apollo-gradle-plugin` that does not shadow its dependencies. - See ["Gradle Plugin Configuration"](https://www.apollographql.com/docs/kotlin/advanced/plugin-configuration/) for how to use the Gradle plugin. diff --git a/libraries/apollo-gradle-plugin/api/apollo-gradle-plugin.api b/libraries/apollo-gradle-plugin/api/apollo-gradle-plugin.api index e69de29bb2d..39a247432a3 100644 --- a/libraries/apollo-gradle-plugin/api/apollo-gradle-plugin.api +++ b/libraries/apollo-gradle-plugin/api/apollo-gradle-plugin.api @@ -0,0 +1,243 @@ +public final class com/apollographql/apollo/compiler/OptionsOverlayKt { + public static final field ADD_TYPENAME_ALWAYS Ljava/lang/String; + public static final field ADD_TYPENAME_IF_ABSTRACT Ljava/lang/String; + public static final field ADD_TYPENAME_IF_FRAGMENTS Ljava/lang/String; + public static final field ADD_TYPENAME_IF_POLYMORPHIC Ljava/lang/String; + public static final field MANIFEST_NONE Ljava/lang/String; + public static final field MANIFEST_OPERATION_OUTPUT Ljava/lang/String; + public static final field MANIFEST_PERSISTED_QUERY Ljava/lang/String; + public static final field MODELS_OPERATION_BASED Ljava/lang/String; + public static final field MODELS_OPERATION_BASED_WITH_INTERFACES Ljava/lang/String; + public static final field MODELS_RESPONSE_BASED Ljava/lang/String; +} + +public final class com/apollographql/apollo/gradle/VersionKt { + public static final field APOLLO_VERSION Ljava/lang/String; +} + +public final class com/apollographql/apollo/gradle/api/ApolloDependencies { + public fun (Lorg/gradle/api/artifacts/dsl/DependencyHandler;)V + public final fun getApi ()Lorg/gradle/api/artifacts/Dependency; + public final fun getAst ()Lorg/gradle/api/artifacts/Dependency; + public final fun getMockServer ()Lorg/gradle/api/artifacts/Dependency; + public final fun getNormalizedCache ()Lorg/gradle/api/artifacts/Dependency; + public final fun getNormalizedCacheSqlite ()Lorg/gradle/api/artifacts/Dependency; + public final fun getRuntime ()Lorg/gradle/api/artifacts/Dependency; +} + +public abstract interface class com/apollographql/apollo/gradle/api/ApolloExtension { + public abstract fun createAllAndroidVariantServices (Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/Action;)V + public abstract fun createAllKotlinSourceSetServices (Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/Action;)V + public abstract fun getDeps ()Lcom/apollographql/apollo/gradle/api/ApolloDependencies; + public abstract fun getGenerateSourcesDuringGradleSync ()Lorg/gradle/api/provider/Property; + public abstract fun getLinkSqlite ()Lorg/gradle/api/provider/Property; + public abstract fun service (Ljava/lang/String;Lorg/gradle/api/Action;)V +} + +public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel { + public static final field Companion Lcom/apollographql/apollo/gradle/api/ApolloGradleToolingModel$Companion; + public static final field VERSION_MAJOR I + public abstract fun getProjectName ()Ljava/lang/String; + public abstract fun getProjectPath ()Ljava/lang/String; + public abstract fun getServiceInfos ()Ljava/util/List; + public abstract fun getTelemetryData ()Lcom/apollographql/apollo/gradle/api/ApolloGradleToolingModel$TelemetryData; + public abstract fun getVersionMajor ()I + public abstract fun getVersionMinor ()I +} + +public final class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$Companion { + public static final field VERSION_MAJOR I +} + +public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$ServiceInfo { + public abstract fun getEndpointHeaders ()Ljava/util/Map; + public abstract fun getEndpointUrl ()Ljava/lang/String; + public abstract fun getGraphqlSrcDirs ()Ljava/util/Set; + public abstract fun getName ()Ljava/lang/String; + public abstract fun getSchemaFiles ()Ljava/util/Set; + public abstract fun getUpstreamProjectPaths ()Ljava/util/Set; + public abstract fun getUpstreamProjects ()Ljava/util/Set; + public abstract fun getUseSemanticNaming ()Z +} + +public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$TelemetryData { + public abstract fun getAndroidAgpVersion ()Ljava/lang/String; + public abstract fun getAndroidCompileSdk ()Ljava/lang/String; + public abstract fun getAndroidMinSdk ()Ljava/lang/Integer; + public abstract fun getAndroidTargetSdk ()Ljava/lang/Integer; + public abstract fun getApolloGenerateSourcesDuringGradleSync ()Ljava/lang/Boolean; + public abstract fun getApolloLinkSqlite ()Ljava/lang/Boolean; + public abstract fun getApolloServiceCount ()I + public abstract fun getApolloServiceTelemetryData ()Ljava/util/List; + public abstract fun getGradleVersion ()Ljava/lang/String; +} + +public abstract interface class com/apollographql/apollo/gradle/api/ApolloGradleToolingModel$TelemetryData$ServiceTelemetryData { + public abstract fun getAddJvmOverloads ()Ljava/lang/Boolean; + public abstract fun getAddTypename ()Ljava/lang/String; + public abstract fun getCodegenModels ()Ljava/lang/String; + public abstract fun getDecapitalizeFields ()Ljava/lang/Boolean; + public abstract fun getFailOnWarnings ()Ljava/lang/Boolean; + public abstract fun getFieldsOnDisjointTypesMustMerge ()Ljava/lang/Boolean; + public abstract fun getFlattenModels ()Ljava/lang/Boolean; + public abstract fun getGenerateApolloMetadata ()Ljava/lang/Boolean; + public abstract fun getGenerateAsInternal ()Ljava/lang/Boolean; + public abstract fun getGenerateDataBuilders ()Ljava/lang/Boolean; + public abstract fun getGenerateFragmentImplementations ()Ljava/lang/Boolean; + public abstract fun getGenerateInputBuilders ()Ljava/lang/Boolean; + public abstract fun getGenerateKotlinModels ()Ljava/lang/Boolean; + public abstract fun getGenerateMethods ()Ljava/util/List; + public abstract fun getGenerateModelBuilders ()Ljava/lang/Boolean; + public abstract fun getGenerateOptionalOperationVariables ()Ljava/lang/Boolean; + public abstract fun getGeneratePrimitiveTypes ()Ljava/lang/Boolean; + public abstract fun getGenerateQueryDocument ()Ljava/lang/Boolean; + public abstract fun getGenerateSchema ()Ljava/lang/Boolean; + public abstract fun getJsExport ()Ljava/lang/Boolean; + public abstract fun getLanguageVersion ()Ljava/lang/String; + public abstract fun getNullableFieldStyle ()Ljava/lang/String; + public abstract fun getOperationManifestFormat ()Ljava/lang/String; + public abstract fun getUseSemanticNaming ()Ljava/lang/Boolean; + public abstract fun getUsedOptions ()Ljava/util/Set; + public abstract fun getWarnOnDeprecatedUsages ()Ljava/lang/Boolean; +} + +public abstract interface class com/apollographql/apollo/gradle/api/CompilerPlugin { + public abstract fun argument (Ljava/lang/String;Ljava/lang/Object;)V +} + +public abstract interface class com/apollographql/apollo/gradle/api/Introspection { + public abstract fun getEndpointUrl ()Lorg/gradle/api/provider/Property; + public abstract fun getHeaders ()Lorg/gradle/api/provider/MapProperty; + public abstract fun getSchemaFile ()Lorg/gradle/api/file/RegularFileProperty; + public abstract fun schemaConnection (Lorg/gradle/api/Action;)V +} + +public abstract interface class com/apollographql/apollo/gradle/api/RegisterOperationsConfig { + public abstract fun getGraph ()Lorg/gradle/api/provider/Property; + public abstract fun getGraphVariant ()Lorg/gradle/api/provider/Property; + public abstract fun getKey ()Lorg/gradle/api/provider/Property; + public abstract fun getListId ()Lorg/gradle/api/provider/Property; +} + +public abstract interface class com/apollographql/apollo/gradle/api/Registry { + public abstract fun getGraph ()Lorg/gradle/api/provider/Property; + public abstract fun getGraphVariant ()Lorg/gradle/api/provider/Property; + public abstract fun getKey ()Lorg/gradle/api/provider/Property; + public abstract fun getSchemaFile ()Lorg/gradle/api/file/RegularFileProperty; + public abstract fun schemaConnection (Lorg/gradle/api/Action;)V +} + +public final class com/apollographql/apollo/gradle/api/SchemaConnection { + public fun (Lorg/gradle/api/tasks/TaskProvider;Lorg/gradle/api/provider/Provider;)V + public final fun getDownloadedSchema ()Lorg/gradle/api/provider/Provider; + public final fun getTask ()Lorg/gradle/api/tasks/TaskProvider; +} + +public abstract interface class com/apollographql/apollo/gradle/api/Service { + public abstract fun dataBuildersOutputDirConnection (Lorg/gradle/api/Action;)V + public abstract fun dependsOn (Ljava/lang/Object;)V + public abstract fun dependsOn (Ljava/lang/Object;Z)V + public abstract fun getAddJvmOverloads ()Lorg/gradle/api/provider/Property; + public abstract fun getAddTypename ()Lorg/gradle/api/provider/Property; + public abstract fun getAlwaysGenerateTypesMatching ()Lorg/gradle/api/provider/SetProperty; + public abstract fun getClassesForEnumsMatching ()Lorg/gradle/api/provider/ListProperty; + public abstract fun getCodegenModels ()Lorg/gradle/api/provider/Property; + public abstract fun getDebugDir ()Lorg/gradle/api/file/DirectoryProperty; + public abstract fun getDecapitalizeFields ()Lorg/gradle/api/provider/Property; + public abstract fun getExcludes ()Lorg/gradle/api/provider/ListProperty; + public abstract fun getFailOnWarnings ()Lorg/gradle/api/provider/Property; + public abstract fun getFieldsOnDisjointTypesMustMerge ()Lorg/gradle/api/provider/Property; + public abstract fun getFlattenModels ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateApolloMetadata ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateAsInternal ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateDataBuilders ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateFragmentImplementations ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateInputBuilders ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateKotlinModels ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateMethods ()Lorg/gradle/api/provider/ListProperty; + public abstract fun getGenerateModelBuilders ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateOptionalOperationVariables ()Lorg/gradle/api/provider/Property; + public abstract fun getGeneratePrimitiveTypes ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateQueryDocument ()Lorg/gradle/api/provider/Property; + public abstract fun getGenerateSchema ()Lorg/gradle/api/provider/Property; + public abstract fun getGeneratedSchemaName ()Lorg/gradle/api/provider/Property; + public abstract fun getIncludes ()Lorg/gradle/api/provider/ListProperty; + public abstract fun getJsExport ()Lorg/gradle/api/provider/Property; + public abstract fun getLanguageVersion ()Lorg/gradle/api/provider/Property; + public abstract fun getName ()Ljava/lang/String; + public abstract fun getNullableFieldStyle ()Lorg/gradle/api/provider/Property; + public abstract fun getOperationManifest ()Lorg/gradle/api/file/RegularFileProperty; + public abstract fun getOperationManifestFormat ()Lorg/gradle/api/provider/Property; + public abstract fun getOutputDir ()Lorg/gradle/api/file/DirectoryProperty; + public abstract fun getPackageName ()Lorg/gradle/api/provider/Property; + public abstract fun getRequiresOptInAnnotation ()Lorg/gradle/api/provider/Property; + public abstract fun getSchemaFile ()Lorg/gradle/api/file/RegularFileProperty; + public abstract fun getSchemaFiles ()Lorg/gradle/api/file/ConfigurableFileCollection; + public abstract fun getSealedClassesForEnumsMatching ()Lorg/gradle/api/provider/ListProperty; + public abstract fun getSourceFolder ()Lorg/gradle/api/provider/Property; + public abstract fun getUseSemanticNaming ()Lorg/gradle/api/provider/Property; + public abstract fun getWarnOnDeprecatedUsages ()Lorg/gradle/api/provider/Property; + public abstract fun introspection (Lorg/gradle/api/Action;)V + public abstract fun isADependencyOf (Ljava/lang/Object;)V + public abstract fun mapScalar (Ljava/lang/String;Ljava/lang/String;)V + public abstract fun mapScalar (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V + public abstract fun mapScalarToJavaBoolean (Ljava/lang/String;)V + public abstract fun mapScalarToJavaDouble (Ljava/lang/String;)V + public abstract fun mapScalarToJavaFloat (Ljava/lang/String;)V + public abstract fun mapScalarToJavaInteger (Ljava/lang/String;)V + public abstract fun mapScalarToJavaLong (Ljava/lang/String;)V + public abstract fun mapScalarToJavaObject (Ljava/lang/String;)V + public abstract fun mapScalarToJavaString (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinAny (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinBoolean (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinDouble (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinFloat (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinInt (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinLong (Ljava/lang/String;)V + public abstract fun mapScalarToKotlinString (Ljava/lang/String;)V + public abstract fun mapScalarToUpload (Ljava/lang/String;)V + public abstract fun operationManifestConnection (Lorg/gradle/api/Action;)V + public abstract fun operationOutputConnection (Lorg/gradle/api/Action;)V + public abstract fun outgoingVariantsConnection (Lorg/gradle/api/Action;)V + public abstract fun outputDirConnection (Lorg/gradle/api/Action;)V + public abstract fun packageNamesFromFilePaths (Ljava/lang/String;)V + public static synthetic fun packageNamesFromFilePaths$default (Lcom/apollographql/apollo/gradle/api/Service;Ljava/lang/String;ILjava/lang/Object;)V + public abstract fun plugin (Ljava/lang/Object;)V + public abstract fun plugin (Ljava/lang/Object;Lorg/gradle/api/Action;)V + public abstract fun registerOperations (Lorg/gradle/api/Action;)V + public abstract fun registry (Lorg/gradle/api/Action;)V + public abstract fun srcDir (Ljava/lang/Object;)V +} + +public abstract interface class com/apollographql/apollo/gradle/api/Service$DirectoryConnection { + public abstract fun connectToAllAndroidVariants ()V + public abstract fun connectToAndroidSourceSet (Ljava/lang/String;)V + public abstract fun connectToAndroidVariant (Ljava/lang/Object;)V + public abstract fun connectToJavaSourceSet (Ljava/lang/String;)V + public abstract fun connectToKotlinSourceSet (Ljava/lang/String;)V + public abstract fun getOutputDir ()Lorg/gradle/api/provider/Provider; + public abstract fun getTask ()Lorg/gradle/api/tasks/TaskProvider; +} + +public final class com/apollographql/apollo/gradle/api/Service$OperationManifestConnection { + public fun (Lorg/gradle/api/tasks/TaskProvider;Lorg/gradle/api/provider/Provider;)V + public final fun getManifest ()Lorg/gradle/api/provider/Provider; + public final fun getTask ()Lorg/gradle/api/tasks/TaskProvider; +} + +public final class com/apollographql/apollo/gradle/api/Service$OperationOutputConnection { + public fun (Lorg/gradle/api/tasks/TaskProvider;Lorg/gradle/api/provider/Provider;)V + public final fun getOperationOutputFile ()Lorg/gradle/api/provider/Provider; + public final fun getTask ()Lorg/gradle/api/tasks/TaskProvider; +} + +public abstract interface class com/apollographql/apollo/gradle/api/Service$OutgoingVariantsConnection { + public abstract fun addToSoftwareComponent (Ljava/lang/String;)V + public abstract fun addToSoftwareComponent (Lorg/gradle/api/component/SoftwareComponent;)V + public abstract fun getOutgoingVariants ()Ljava/util/List; +} + +public final class com/apollographql/apollo/gradle/task/ApolloGenerateOptionsTaskKt { + public static synthetic fun registerApolloGenerateOptionsTask$default (Lorg/gradle/api/Project;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lorg/gradle/api/file/FileCollection;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/file/FileCollection;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;Lorg/gradle/api/provider/Provider;IILjava/lang/Object;)Lorg/gradle/api/tasks/TaskProvider; +} + diff --git a/libraries/apollo-gradle-plugin/build.gradle.kts b/libraries/apollo-gradle-plugin/build.gradle.kts index 2cd52d3143a..196fdecb449 100644 --- a/libraries/apollo-gradle-plugin/build.gradle.kts +++ b/libraries/apollo-gradle-plugin/build.gradle.kts @@ -1,36 +1,44 @@ +import org.gradle.kotlin.dsl.javaToolchains import org.jetbrains.kotlin.gradle.dsl.KotlinVersion +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import kotlin.jvm.java plugins { id("org.jetbrains.kotlin.jvm") - id("java-gradle-plugin") - id("com.gradle.plugin-publish") - id("com.gradleup.gr8") + id("com.google.devtools.ksp") + id("com.gradleup.gratatouille.wiring") + id("com.android.lint") } -val jvmTarget = 11 // AGP requires 11 apolloLibrary( - namespace = "com.apollographql.apollo.gradle.relocated", - jvmTarget = jvmTarget, - kotlinCompilerOptions = KotlinCompilerOptions(KotlinVersion.KOTLIN_1_9) + namespace = "com.apollographql.apollo.gradle", + jvmTarget = 11, // To compile against AGP 8.0.0 + kotlinCompilerOptions = KotlinCompilerOptions(KotlinVersion.KOTLIN_1_9) // For better Gradle compatibility ) -// Set to false to skip relocation and save some building time during development -val relocateJar = System.getenv("APOLLO_RELOCATE_JAR")?.toBoolean() ?: true - -val shadowedDependencies = configurations.create("shadowedDependencies") +gratatouille { + codeGeneration() + pluginMarker("com.apollographql.apollo") +} dependencies { - add(shadowedDependencies.name, project(":apollo-gradle-plugin-external")) + gratatouille(project(":apollo-gradle-plugin-tasks")) + compileOnly(libs.gradle.api.min) + compileOnly(libs.kotlin.plugin.min) + compileOnly(libs.android.plugin.min) + + compileOnly(libs.gradle.api.min) + implementation(project(":apollo-annotations")) testImplementation(project(":apollo-ast")) testImplementation(libs.junit) testImplementation(libs.truth) testImplementation(libs.assertj) testImplementation(libs.okhttp.mockwebserver) testImplementation(libs.okhttp.tls) - testImplementation(libs.apollo.execution) testImplementation(libs.apollo.execution.http4k) + testImplementation(gradleTestKit()) testImplementation(platform(libs.http4k.bom.get())) testImplementation(libs.http4k.core) @@ -38,86 +46,7 @@ dependencies { testImplementation(libs.slf4j.nop.get().toString()) { because("jetty uses SL4F") } -} - - -if (relocateJar) { - gr8 { - val shadowedJar = create("default") { - addProgramJarsFrom(shadowedDependencies) - addProgramJarsFrom(tasks.getByName("jar")) - r8Version("887704078a06fc0090e7772c921a30602bf1a49f") - systemClassesToolchain { - languageVersion.set(JavaLanguageVersion.of(jvmTarget)) - } - proguardFile("rules.pro") - registerFilterTransform(listOf(".*/impldep/META-INF/versions/.*")) - } - - removeGradleApiFromApi() - configurations.named("compileOnly").configure { - extendsFrom(shadowedDependencies) - } - configurations.named("testImplementation").configure { - extendsFrom(shadowedDependencies) - } - - replaceOutgoingJar2(shadowedJar) - } -} else { - configurations.named("implementation").configure { - extendsFrom(shadowedDependencies) - } -} - -fun replaceOutgoingJar2(newJar: Any) { - project.configurations.configureEach { - outgoing { - val removed = artifacts.removeIf { - it.name == "apollo-gradle-plugin" && it.type == "jar" && it.classifier.isNullOrEmpty() - } - if (removed) { - artifact(newJar) { - // Pom and maven consumers do not like the `-all` or `-shadowed` classifiers - classifier = "" - } - } - } - } -} - -gradlePlugin { - website.set("https://github.com/apollographql/apollo-kotlin") - vcsUrl.set("https://github.com/apollographql/apollo-kotlin") - - plugins { - create("apolloGradlePlugin") { - id = "com.apollographql.apollo" - displayName = "Apollo Kotlin GraphQL client plugin." - description = "Automatically generates typesafe java and kotlin models from your GraphQL files." - implementationClass = "com.apollographql.apollo.gradle.internal.ApolloPlugin" - tags.set(listOf("graphql", "apollo")) - } - } -} - -/** - * This is so that the plugin marker pom contains a tag - * It was recommended by the Gradle support team. - */ -configure { - publications.configureEach { - if (name == "apolloGradlePluginPluginMarkerMaven") { - this as MavenPublication - pom { - scm { - url.set(findProperty("POM_SCM_URL") as String?) - connection.set(findProperty("POM_SCM_CONNECTION") as String?) - developerConnection.set(findProperty("POM_SCM_DEV_CONNECTION") as String?) - } - } - } - } + lintChecks(libs.androidx.lint.rules) } tasks.register("cleanStaleTestProjects") { @@ -142,7 +71,7 @@ tasks.register("publishDependencies") { dependsOn(":apollo-normalized-cache-api:publishAllPublicationsToPluginTestRepository") dependsOn(":apollo-mpp-utils:publishAllPublicationsToPluginTestRepository") dependsOn(":apollo-compiler:publishAllPublicationsToPluginTestRepository") - dependsOn(":apollo-gradle-plugin-external:publishAllPublicationsToPluginTestRepository") + dependsOn(":apollo-gradle-plugin-tasks:publishAllPublicationsToPluginTestRepository") dependsOn(":apollo-tooling:publishAllPublicationsToPluginTestRepository") } @@ -157,54 +86,60 @@ tasks.withType { // debug = true maxParallelForks = (Runtime.getRuntime().availableProcessors() / 2).takeIf { it > 0 } ?: 1 -} -val allTests = tasks.register("allTests") -tasks.check { - dependsOn(allTests) + val javaToolchains = project.extensions.getByName("javaToolchains") as JavaToolchainService + javaLauncher.set(javaToolchains.launcherFor { + // Run all tests using java 17 + languageVersion.set(JavaLanguageVersion.of(17)) + }) } -fun createTests(javaVersion: Int) { - val sourceSet = sourceSets.create("test-java$javaVersion") +tasks.register("acceptAndroidLicenses") { + val source = rootProject.file("android-licenses/android-sdk-preview-license") + val target = rootProject.file("${System.getenv("ANDROID_HOME")}/licenses/android-sdk-preview-license") + doLast { + source.copyTo(target, overwrite = true) + } +} - configurations[sourceSet.implementationConfigurationName].extendsFrom(configurations.testImplementation.get()) - dependencies.add(sourceSet.implementationConfigurationName, sourceSets.getByName("test").output) - configurations[sourceSet.runtimeOnlyConfigurationName].extendsFrom(configurations.testRuntimeOnly.get()) +tasks.named("test").configure { + dependsOn("acceptAndroidLicenses") +} - val task = tasks.register("testJava$javaVersion") { - description = "Runs integration tests for Java $javaVersion." - group = "verification" - useJUnit() +abstract class GeneratePluginVersion : DefaultTask() { + @get:Input + abstract val version: Property - testClassesDirs = sourceSet.output.classesDirs - classpath = configurations[sourceSet.runtimeClasspathConfigurationName] + sourceSet.output + @get:OutputDirectory + abstract val outputDir: DirectoryProperty - environment("APOLLO_RELOCATE_JAR", System.getenv("APOLLO_RELOCATE_JAR")) - setTestToolchain(project, this, javaVersion) - } + @TaskAction + fun taskAction() { + outputDir.asFile.get().apply { + deleteRecursively() + mkdirs() + } - allTests.configure { - dependsOn(task) + val versionFile = File(outputDir.asFile.get(), "com/apollographql/apollo/gradle/Version.kt") + versionFile.parentFile.mkdirs() + versionFile.writeText("""// Generated file. Do not edit! +package com.apollographql.apollo.gradle +const val APOLLO_VERSION = "${version.get()}" +""" + ) } } -tasks.named("test").configure { - // Disable the default tests, they are empty - enabled = false +val pluginVersionTaskProvider = tasks.register("pluginVersion", GeneratePluginVersion::class.java) { + outputDir.set(project.layout.buildDirectory.dir("generated/kotlin/")) + version.set(project.version.toString()) } -listOf(11, 17).forEach { javaVersion -> - createTests(javaVersion) +configure { + val versionFileProvider = pluginVersionTaskProvider.flatMap { it.outputDir } + sourceSets.getByName("main").kotlin.srcDir(versionFileProvider) } -tasks.register("acceptAndroidLicenses") { - val source = rootProject.file("android-licenses/android-sdk-preview-license") - val target = rootProject.file("${System.getenv("ANDROID_HOME")}/licenses/android-sdk-preview-license") - doLast { - source.copyTo(target, overwrite = true) - } -} - -tasks.named("testJava17").configure { - dependsOn("acceptAndroidLicenses") +tasks.withType(KotlinCompile::class.java) { + dependsOn(pluginVersionTaskProvider) } diff --git a/libraries/apollo-gradle-plugin/rules.pro b/libraries/apollo-gradle-plugin/rules.pro deleted file mode 100644 index 276632ab874..00000000000 --- a/libraries/apollo-gradle-plugin/rules.pro +++ /dev/null @@ -1,54 +0,0 @@ -#noinspection ShrinkerUnresolvedReference - -# Keep kotlin metadata so that the Kotlin compiler knows about top level functions such as -# Line 1: import com.apollographql.apollo.gradle.api.kotlinMultiplatformExtension -# ^ Unresolved reference: kotlinMultiplatformExtension --keep class kotlin.Metadata { *; } --keep class kotlin.Unit { *; } -# Keep the @RequiresOptIn annotation so we get proper warnings in gradle build files --keep class kotlin.RequiresOptIn { *; } - -# We need to keep type arguments (Signature) for Gradle to be able to instantiate abstract models like `Property` -# Else it fails with -# 'Declaration of property alwaysGenerateTypesMatching does not include any type arguments in its property type interface org.gradle.api.provider.SetProperty' --keepattributes Signature,InnerClasses,EnclosingMethod -# Gradle needs the @Inject annotations, the Kotlin compiler needs @RequiresOptIn, etc.. --keepattributes *Annotation* -# For debug --keepattributes SourceFile,LineNumberTable - -# kotlinpoet uses EnumSetOf that makes a reflexive access to "values" -# https://github.com/square/kotlinpoet/blob/9952ddcd5095a1fd09c86b9fb07faa347a4c04f0/kotlinpoet/src/main/java/com/squareup/kotlinpoet/PropertySpec.kt#L102 --keepclassmembers class com.squareup.kotlinpoet.KModifier { - public static **[] values(); -} - -# Keep apollo-annotations for ApolloExperimental --keep class com.apollographql.apollo.annotations.** { *; } -# Keep the plugin API as it's used from build scripts --keep class com.apollographql.apollo.gradle.api.** { *; } --keep interface com.apollographql.apollo.gradle.api.** { *; } -# And also the compiler API as it's used transitively for things like MANIFEST_PERSISTED_QUERY and other constants --keep class com.apollographql.apollo.compiler.** { *; } --keep interface com.apollographql.apollo.compiler.** { *; } --keep enum com.apollographql.apollo.compiler.** { *; } -# Schema is used in a worker: https://github.com/apollographql/apollo-kotlin/blob/198480d8b0b24c01f4d11da0b1e9fa9c97062c5c/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloGenerateSourcesTask.kt#L131 --keep class com.apollographql.apollo.ast.Schema { *; } -# Keep the ApolloPlugin entry point and everything in internal too because we have ApolloPlugin there --keep class com.apollographql.apollo.gradle.internal.** { *; } - -# Keep class names to make debugging easier --dontobfuscate --repackageclasses com.apollographql.apollo.relocated - -# Allow to repackage com.moshi.JsonAdapter.lenient --allowaccessmodification - -# The Gradle API jar and other compileOnly dependencies aren't added to the classpath, ignore the missing symbols -# I tried adding them but they duplicate a lot of the program classes and trigger errors in R8. -# A future version could try to remove the intersection between the compileOnly classpath and the runtime one --dontwarn org.gradle.** --dontwarn org.jetbrains.kotlin.gradle.** --dontwarn com.android.build.gradle.** --dontwarn com.android.builder.** --dontwarn javax.inject.Inject \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/compiler/OptionsOverlay.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/compiler/OptionsOverlay.kt new file mode 100644 index 00000000000..a0e636af936 --- /dev/null +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/compiler/OptionsOverlay.kt @@ -0,0 +1,53 @@ +package com.apollographql.apollo.compiler + +/** + * This file duplicates some of the apollo-compiler symbols to display a meaningful error to users relying + * on them in build scripts. + * + * It will be removed in a future version. + */ +import com.apollographql.apollo.annotations.ApolloDeprecatedSince + + +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("responseBased"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val MODELS_RESPONSE_BASED = "responseBased" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("operationBased"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val MODELS_OPERATION_BASED = "operationBased" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("experimental_operationBasedWithInterfaces"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val MODELS_OPERATION_BASED_WITH_INTERFACES = "experimental_operationBasedWithInterfaces" + +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("ifFragments"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val ADD_TYPENAME_IF_FRAGMENTS = "ifFragments" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("ifPolymorphic"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val ADD_TYPENAME_IF_POLYMORPHIC = "ifPolymorphic" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("ifAbstract"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val ADD_TYPENAME_IF_ABSTRACT = "ifAbstract" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("always"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val ADD_TYPENAME_ALWAYS = "always" + +@Deprecated("Use \"persistedQueryManifest\" instead", replaceWith = ReplaceWith("persistedQueryManifest"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v4_0_1) +@JvmField +val MANIFEST_OPERATION_OUTPUT = "operationOutput" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("persistedQueryManifest"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val MANIFEST_PERSISTED_QUERY = "persistedQueryManifest" +@Deprecated("The apollo-compiler symbols are not available in the Gradle plugin anymore. Use their value directly.", replaceWith = ReplaceWith("none"), level = DeprecationLevel.ERROR) +@ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) +@JvmField +val MANIFEST_NONE = "none" diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloDependencies.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloDependencies.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloDependencies.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloDependencies.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt similarity index 98% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt index eacc5e5ac7d..691e334aca4 100644 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloExtension.kt @@ -1,6 +1,5 @@ package com.apollographql.apollo.gradle.api -import com.apollographql.apollo.annotations.ApolloExperimental import org.gradle.api.Action import org.gradle.api.provider.Property diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloGradleToolingModel.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloGradleToolingModel.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloGradleToolingModel.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/ApolloGradleToolingModel.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/CompilerPlugin.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/CompilerPlugin.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/CompilerPlugin.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/CompilerPlugin.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Introspection.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Introspection.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Introspection.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Introspection.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/RegisterOperationsConfig.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/RegisterOperationsConfig.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/RegisterOperationsConfig.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/RegisterOperationsConfig.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Registry.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Registry.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Registry.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Registry.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt similarity index 93% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt index 06e3bb450b5..e383cc08368 100644 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/api/Service.kt @@ -2,10 +2,8 @@ package com.apollographql.apollo.gradle.api -import com.android.build.gradle.api.BaseVariant import com.apollographql.apollo.annotations.ApolloDeprecatedSince import com.apollographql.apollo.annotations.ApolloExperimental -import com.apollographql.apollo.compiler.MANIFEST_PERSISTED_QUERY import org.gradle.api.Action import org.gradle.api.Task import org.gradle.api.artifacts.Configuration @@ -20,7 +18,6 @@ import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.provider.SetProperty import org.gradle.api.tasks.TaskProvider -import java.io.File /** * A [Service] represents a GraphQL schema and associated queries. @@ -459,45 +456,16 @@ interface Service { * The directory where the generated models are written. It's called [outputDir] but this an "input" parameter for the compiler * If you want a [DirectoryProperty] that carries the task dependency, use [outputDirConnection] */ + @Deprecated("Changing the location of the generated sources is not possible anymore. Use `outputDirConnection` to consume them and potentially copy them to another filesystem location.", level = DeprecationLevel.ERROR) val outputDir: DirectoryProperty - /** - * The directory where the generated data builders are written. It's called [dataBuildersOutputDir] but this an "input" parameter for the compiler - * If you want a [DirectoryProperty] that carries the task dependency, use [dataBuildersOutputDirConnection] - */ - val dataBuildersOutputDir: DirectoryProperty - - /** - * Whether to generate the operationOutput.json - * - * Defaults value: false - */ - @Deprecated("Use operationManifestFormat", ReplaceWith("operationManifestFormat.set(\"$MANIFEST_PERSISTED_QUERY\")"), level = DeprecationLevel.ERROR) - @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v4_0_0) - val generateOperationOutput: Property - /** * The format to output for the operation manifest. Valid values are: * - * - "operationOutput": a manifest that matches the format used by [OperationOutput] - * - "persistedQueryManifest": a manifest format for an upcoming GraphOS feature - * - nothing (Default): by default no manifest is generated - * - * "operationOutput" uses a JSON format like so: - * ```json - * { - * "3f8a446ab7672c1efad3735b6fa86caaeefe7ec47f87fca9b84e71e0d93e6bea": { - * "name": "DroidDetails", - * "source": "query DroidDetails { species(id: \"c3BlY2llczoy\") { id name filmConnection { edges { node { id title } } } } }" - * }, - * "e772cb55495ad5becc0c804ca3de7d5a5f31f145552bc33529f025d6cb0a8ce6": { - * "name": "AllFilms", - * "source": "query AllFilms { allFilms(first: 100) { totalCount films { title releaseDate } } }" - * } - * } - * ``` + * - "persistedQueryManifest": the manifest format for [persisted queries](https://www.apollographql.com/docs/kotlin/advanced/persisted-queries) + * - "none" (Default): no manifest is generated * - * "persistedQueryManifest" uses a format compatible with an upcoming GraphQL feature like so: + * Example of a "persistedQueryManifest": * ```json * { * "format": "apollo-persisted-query-manifest", @@ -528,18 +496,12 @@ interface Service { */ val operationManifestFormat: Property - /** - * The file where the operation output will be written. It's called [operationOutputFile] but this an "input" parameter for the compiler - * If you want a [RegularFileProperty] that carries the task dependency, use [operationManifestConnection] - */ - @Deprecated("Use operationManifest", ReplaceWith("operationManifest"), level = DeprecationLevel.ERROR) - @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v4_0_0) - val operationOutputFile: RegularFileProperty - /** * The file where to write the operation manifest. * If you want a [RegularFileProperty] that carries the task dependency, use [operationManifestConnection]. */ + @Deprecated("Changing the location of the generated manifest is not possible anymore. Use `operationManifestConnection` to consume it and potentially copy it to another filesystem location.", level = DeprecationLevel.ERROR) + @ApolloDeprecatedSince(ApolloDeprecatedSince.Version.v5_0_0) val operationManifest: RegularFileProperty /** diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/AndroidPluginFacade.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/AndroidPluginFacade.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/AndroidPluginFacade.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/AndroidPluginFacade.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloAttributes.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloAttributes.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloAttributes.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloAttributes.kt diff --git a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt new file mode 100644 index 00000000000..bc282fe2612 --- /dev/null +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt @@ -0,0 +1,8 @@ +package com.apollographql.apollo.gradle.internal + +import org.gradle.api.file.FileCollection +import org.gradle.api.services.BuildService +import org.gradle.api.services.BuildServiceParameters +import java.net.URI +import java.net.URLClassLoader + diff --git a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt new file mode 100644 index 00000000000..3e27b4b8bd0 --- /dev/null +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/BuildDirLayout.kt @@ -0,0 +1,33 @@ +package com.apollographql.apollo.gradle.internal + +import com.apollographql.apollo.gradle.api.Service +import org.gradle.api.Project +import org.gradle.api.file.Directory +import org.gradle.api.file.RegularFile +import org.gradle.api.provider.Provider + +object BuildDirLayout { + internal fun operationManifest(project: Project, service: Service): Provider { + return project.layout.buildDirectory.file( + "generated/manifest/apollo/${service.name}/persistedQueryManifest.json" + ) + } + + internal fun outputDir(project: Project, service: Service): Provider { + return project.layout.buildDirectory.dir( + "generated/source/apollo/${service.name}" + ) + } + + internal fun dataBuildersOutputDir(project: Project, service: Service): Provider { + return project.layout.buildDirectory.dir( + "generated/dataBuildersSource/apollo/${service.name}" + ) + } + + internal fun versionCheck(project: Project): Provider { + return project.layout.buildDirectory.file( + "generated/checks/apollo/versionCheck" + ) + } +} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt similarity index 60% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt index 799a9549f74..a70e528b7be 100644 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloExtension.kt @@ -1,16 +1,26 @@ package com.apollographql.apollo.gradle.internal -import com.apollographql.apollo.compiler.APOLLO_VERSION -import com.apollographql.apollo.compiler.GeneratedMethod -import com.apollographql.apollo.compiler.JavaNullable -import com.apollographql.apollo.compiler.UsedCoordinates -import com.apollographql.apollo.compiler.capitalizeFirstLetter -import com.apollographql.apollo.compiler.toIrOperations import com.apollographql.apollo.gradle.api.ApolloDependencies import com.apollographql.apollo.gradle.api.ApolloExtension import com.apollographql.apollo.gradle.api.ApolloGradleToolingModel import com.apollographql.apollo.gradle.api.SchemaConnection import com.apollographql.apollo.gradle.api.Service +import com.apollographql.apollo.gradle.internal.BuildDirLayout.dataBuildersOutputDir +import com.apollographql.apollo.gradle.internal.BuildDirLayout.outputDir +import com.apollographql.apollo.gradle.task.ApolloDownloadSchemaTask +import com.apollographql.apollo.gradle.task.ApolloGenerateDataBuildersSourcesTask +import com.apollographql.apollo.gradle.task.ApolloGenerateSourcesFromIrTask +import com.apollographql.apollo.gradle.task.ApolloGenerateSourcesTask +import com.apollographql.apollo.gradle.task.registerApolloComputeUsedCoordinatesTask +import com.apollographql.apollo.gradle.task.registerApolloDownloadSchemaTask +import com.apollographql.apollo.gradle.task.registerApolloGenerateCodegenSchemaTask +import com.apollographql.apollo.gradle.task.registerApolloGenerateDataBuildersSourcesTask +import com.apollographql.apollo.gradle.task.registerApolloGenerateIrOperationsTask +import com.apollographql.apollo.gradle.task.registerApolloGenerateOptionsTask +import com.apollographql.apollo.gradle.task.registerApolloGenerateSourcesFromIrTask +import com.apollographql.apollo.gradle.task.registerApolloGenerateSourcesTask +import com.apollographql.apollo.gradle.task.registerApolloRegisterOperationsTask +import gratatouille.wiring.capitalizeFirstLetter import org.gradle.api.Action import org.gradle.api.Project import org.gradle.api.Task @@ -23,9 +33,9 @@ import org.gradle.api.attributes.Usage import org.gradle.api.component.AdhocComponentWithVariants import org.gradle.api.component.SoftwareComponent import org.gradle.api.component.SoftwareComponentFactory -import org.gradle.api.file.FileCollection +import org.gradle.api.file.Directory +import org.gradle.api.file.RegularFile import org.gradle.api.file.SourceDirectorySet -import org.gradle.api.logging.LogLevel import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.tasks.TaskProvider @@ -50,7 +60,6 @@ abstract class DefaultApolloExtension( project.components.add(it) } } - private var apolloBuildServiceProvider: Provider internal fun getServiceInfos(project: Project): List = services.map { service -> DefaultServiceInfo( @@ -112,11 +121,13 @@ abstract class DefaultApolloExtension( } else if (service.scalarTypeMapping.isNotEmpty()) { add("mapScalar") } + @Suppress("DEPRECATION_ERROR") if (service.operationManifest.isPresent) add("operationManifest") if (service.generatedSchemaName.isPresent) add("generatedSchemaName") if (service.debugDir.isPresent) add("debugDir") if (service.sealedClassesForEnumsMatching.isPresent) add("sealedClassesForEnumsMatching") if (service.classesForEnumsMatching.isPresent) add("classesForEnumsMatching") + @Suppress("DEPRECATION_ERROR") if (service.outputDir.isPresent) add("outputDir") if (service.alwaysGenerateTypesMatching.isPresent) add("alwaysGenerateTypesMatching") if (service.introspection != null) add("introspection") @@ -150,34 +161,35 @@ abstract class DefaultApolloExtension( } /** - * A simple task to be used from the command line to ease the schema download + * A simple task to be used from the command line to ease the schema download (deprecated) */ - project.tasks.register(ModelNames.downloadApolloSchema(), ApolloDownloadSchemaTask::class.java) { task -> + project.tasks.register(ModelNames.downloadApolloSchema()) { task -> task.group = TASK_GROUP - task.projectRootDir = project.rootDir.absolutePath task.doLast { - it.logger.lifecycle("Apollo: using './gradlew downloadApolloSchema' is deprecated. Please use the Apollo Kotlin cli for one-time downloads or the introspection {} block for Gradle downloads. See https://go.apollo.dev/ak-download-schema.") + error("Apollo: using './gradlew downloadApolloSchema' is deprecated. Please use the Apollo Kotlin cli for one-time downloads or the introspection {} block for Gradle downloads. See https://go.apollo.dev/ak-download-schema.") } } /** - * A simple task to be used from the command line to ease the schema upload + * A simple task to be used from the command line to ease schema conversion */ - project.tasks.register(ModelNames.pushApolloSchema(), ApolloPushSchemaTask::class.java) { task -> + project.tasks.register(ModelNames.convertApolloSchema()) { task -> task.group = TASK_GROUP - task.projectRootDir = project.rootDir.absolutePath + task.doLast { + error("Apollo: using './gradlew convertApolloSchema' is deprecated. Please use the Apollo Kotlin cli for converseions. See https://go.apollo.dev/ak-cli.") + } } /** - * A simple task to be used from the command line to ease schema conversion + * A simple task to be used from the command line to ease the schema upload */ - project.tasks.register(ModelNames.convertApolloSchema(), ApolloConvertSchemaTask::class.java) { task -> + project.tasks.register(ModelNames.pushApolloSchema()) { task -> task.group = TASK_GROUP - task.projectRootDir = project.rootDir.absolutePath + task.doLast { + error("Apollo: using './gradlew pushApolloSchema' is deprecated. Please use rover to push schemas. See https://go.apollo.dev/rover.") + } } - apolloBuildServiceProvider = project.gradle.sharedServices.registerIfAbsent("apollo", ApolloBuildService::class.java) {} - project.afterEvaluate { maybeLinkSqlite() checkForLegacyJsTarget() @@ -199,6 +211,7 @@ abstract class DefaultApolloExtension( // explicit opt-in linkSqlite(project) } + null -> { // default: automatic detection project.configurations.configureEach { it.dependencies.configureEach { @@ -213,7 +226,8 @@ abstract class DefaultApolloExtension( && it.group?.contains("apollo") == true && it.name.contains("normalized-cache-sqlite") && !it.name.contains("jvm") - && !it.name.contains("android")) { + && !it.name.contains("android") + ) { linkSqlite(project) } } @@ -239,7 +253,7 @@ abstract class DefaultApolloExtension( private fun sanityChecks(service: DefaultService) { @Suppress("DEPRECATION_ERROR") - check (!service.sourceFolder.isPresent) { + check(!service.sourceFolder.isPresent) { error("Apollo: using 'sourceFolder' is deprecated, replace with 'srcDir(\"src/${project.mainSourceSet()}/graphql/${service.sourceFolder.get()}\")'") } } @@ -299,7 +313,7 @@ abstract class DefaultApolloExtension( it.inputs.property("allVersions", Callable { val allDeps = ( - getDeps(project.buildscript.configurations) + + getDeps(project.buildscript.configurations) + getDeps(project.configurations) ) allDeps.distinct().sorted() @@ -331,22 +345,24 @@ abstract class DefaultApolloExtension( serviceName: String, apolloUsage: ApolloUsage, direction: ApolloDirection, - extendsFrom: Configuration + extendsFrom: Configuration, ): Configurations { - val consumable = project.configurations.create(ModelNames.configuration(serviceName, direction, apolloUsage, ConfigurationKind.Consumable )) { - it.isCanBeConsumed = true - it.isCanBeResolved = false + val consumable = + project.configurations.create(ModelNames.configuration(serviceName, direction, apolloUsage, ConfigurationKind.Consumable)) { + it.isCanBeConsumed = true + it.isCanBeResolved = false - it.extendsFrom(extendsFrom) - it.attributes(serviceName, apolloUsage, direction) - } - val resolvable = project.configurations.create(ModelNames.configuration(serviceName, direction, apolloUsage, ConfigurationKind.Resolvable )) { - it.isCanBeConsumed = false - it.isCanBeResolved = true + it.extendsFrom(extendsFrom) + it.attributes(serviceName, apolloUsage, direction) + } + val resolvable = + project.configurations.create(ModelNames.configuration(serviceName, direction, apolloUsage, ConfigurationKind.Resolvable)) { + it.isCanBeConsumed = false + it.isCanBeResolved = true - it.extendsFrom(extendsFrom) - it.attributes(serviceName, apolloUsage, direction) - } + it.extendsFrom(extendsFrom) + it.attributes(serviceName, apolloUsage, direction) + } return Configurations( consumable = consumable, @@ -399,24 +415,101 @@ abstract class DefaultApolloExtension( it.isCanBeResolved = true } - compilerConfiguration.dependencies.add(project.dependencies.create("com.apollographql.apollo:apollo-compiler:$APOLLO_VERSION")) service.pluginDependency?.let { compilerConfiguration.dependencies.add(it) } - val classpathOptions = ApolloTaskWithClasspath.Options( - compilerConfiguration, - service.pluginDependency != null, - (service.compilerPlugin as DefaultCompilerPlugin?)?.arguments.orEmpty(), - LogLevel.entries.first { project.logger.isEnabled(it) }, - ) + val warnIfNoPluginFound = service.pluginDependency != null + val pluginArguments = (service.compilerPlugin as DefaultCompilerPlugin?)?.arguments.orEmpty() if (service.languageVersion.orNull == "1.5") { project.logger.lifecycle("Apollo: languageVersion 1.5 is deprecated, please use 1.9 or leave empty") } - val optionsTaskProvider = registerOptionsTask(project, service, otherOptions.resolvable) + val optionsTaskProvider = project.registerApolloGenerateOptionsTask( + taskName = ModelNames.generateApolloOptions(service), + taskGroup = TASK_GROUP, + taskDescription = "Generate Apollo options for service '${service.name}'", + /** + * CodegenSchemaOptions + */ + scalarTypeMapping = project.provider { service.scalarTypeMapping }, + scalarAdapterMapping = project.provider { service.scalarAdapterMapping }, + generateDataBuilders = service.generateDataBuilders, + /** + * IrOptions + */ + codegenModels = service.codegenModels, + addTypename = service.addTypename, + fieldsOnDisjointTypesMustMerge = service.fieldsOnDisjointTypesMustMerge, + decapitalizeFields = service.decapitalizeFields, + flattenModels = service.flattenModels, + warnOnDeprecatedUsages = service.warnOnDeprecatedUsages, + failOnWarnings = service.failOnWarnings, + generateOptionalOperationVariables = service.generateOptionalOperationVariables, + alwaysGenerateTypesMatching = service.alwaysGenerateTypesMatching, + + /** + * CommonCodegenOptions + */ + generateKotlinModels = service.generateKotlinModels, + languageVersion = service.languageVersion, + packageName = service.packageName, + rootPackageName = project.provider { service.rootPackageName }, + useSemanticNaming = service.useSemanticNaming, + generateFragmentImplementations = service.generateFragmentImplementations, + generateMethods = service.generateMethods, + generateQueryDocument = service.generateQueryDocument, + generateSchema = service.generateSchema, + generatedSchemaName = service.generatedSchemaName, + operationManifestFormat = service.operationManifestFormat, + + /** + * JavaCodegenOptions + */ + generateModelBuilders = service.generateModelBuilders, + classesForEnumsMatching = service.classesForEnumsMatching, + generatePrimitiveTypes = service.generatePrimitiveTypes, + nullableFieldStyle = service.nullableFieldStyle, + + /** + * KotlinCodegenOptions + */ + sealedClassesForEnumsMatching = service.sealedClassesForEnumsMatching, + generateAsInternal = service.generateAsInternal, + generateInputBuilders = service.generateInputBuilders, + addJvmOverloads = service.addJvmOverloads, + requiresOptInAnnotation = service.requiresOptInAnnotation, + jsExport = service.jsExport, + + /** + * Gradle model + */ + upstreamOtherOptions = otherOptions.resolvable, + javaPluginApplied = project.provider { project.hasJavaPlugin() }, + kgpVersion = project.provider { project.apolloGetKotlinPluginVersion() }, + kmp = project.provider { project.isKotlinMultiplatform }, + // If there is no downstream dependency, generate everything because we don't know what types are going to be used downstream + generateAllTypes = project.provider { service.isSchemaModule() && service.isMultiModule() && service.downstreamDependencies.isEmpty() }, + ) + if (!service.isMultiModule()) { - sourcesBaseTaskProvider = registerSourcesTask(project, optionsTaskProvider, service, classpathOptions) + sourcesBaseTaskProvider = project.registerApolloGenerateSourcesTask( + taskName = ModelNames.generateApolloSources(service), + taskGroup = TASK_GROUP, + taskDescription = "Generate Apollo models for service '${service.name}'", + extraClasspath = compilerConfiguration, + arguments = project.provider { pluginArguments }, + warnIfNotFound = project.provider { warnIfNoPluginFound }, + schemas = service.schemaFiles(project), + fallbackSchemas = service.fallbackSchemaFiles(project), + irOptions = optionsTaskProvider.flatMap { it.irOptionsFile }, + codegenSchemaOptions = optionsTaskProvider.flatMap { it.codegenSchemaOptionsFile }, + codegenOptions = optionsTaskProvider.flatMap { it.codegenOptions }, + executableDocuments = service.graphqlSourceDirectorySet, + outputDirectory = outputDir(project, service), + operationManifest = BuildDirLayout.operationManifest(project, service), + dataBuildersOutputDirectory = dataBuildersOutputDir(project, service) + ) dataBuildersSourcesBaseTaskProvider = if (service.generateDataBuilders.orElse(false).get()) { // Only register the wiring if we actually generate data builders sourcesBaseTaskProvider @@ -456,12 +549,17 @@ abstract class DefaultApolloExtension( * Tasks */ val codegenSchemaTaskProvider = if (service.isSchemaModule()) { - registerCodegenSchemaTask( - project = project, - service = service, - optionsTaskProvider = optionsTaskProvider, - schemaConsumerConfiguration = codegenSchema.resolvable, - classpathOptions = classpathOptions + project.registerApolloGenerateCodegenSchemaTask( + taskName = ModelNames.generateApolloCodegenSchema(service), + taskGroup = TASK_GROUP, + taskDescription = "Generate Apollo schema for service '${service.name}'", + schemaFiles = service.schemaFiles(project), + fallbackSchemaFiles = service.fallbackSchemaFiles(project), + upstreamSchemaFiles = codegenSchema.resolvable, + codegenSchemaOptionsFile = optionsTaskProvider.flatMap { it.codegenSchemaOptionsFile }, + arguments = project.provider { pluginArguments }, + extraClasspath = compilerConfiguration, + warnIfNotFound = project.provider { warnIfNoPluginFound }, ) } else { check(service.scalarTypeMapping.isEmpty()) { @@ -474,48 +572,66 @@ abstract class DefaultApolloExtension( null } - val irOperationsTaskProvider = registerIrOperationsTask( - project = project, - service = service, - schemaConsumerConfiguration = codegenSchema.resolvable, - schemaTaskProvider = codegenSchemaTaskProvider, - irOptionsTaskProvider = optionsTaskProvider, + val upstreamAndSelfCodegenSchemas = project.files().also { + it.from(codegenSchema.resolvable) + if (codegenSchemaTaskProvider != null) { + it.from(codegenSchemaTaskProvider.flatMap { it.codegenSchemaFile }) + } + } + val irOperationsTaskProvider = project.registerApolloGenerateIrOperationsTask( + taskName = ModelNames.generateApolloIrOperations(service), + taskGroup = TASK_GROUP, + taskDescription = "Generate Apollo IR operations for service '${service.name}'", + extraClasspath = compilerConfiguration, + arguments = project.provider { pluginArguments }, + warnIfNotFound = project.provider { warnIfNoPluginFound }, upstreamIrFiles = upstreamIr.resolvable, - classpathOptions = classpathOptions + codegenSchemas = upstreamAndSelfCodegenSchemas, + graphqlFiles = service.graphqlSourceDirectorySet, + irOptionsFile = optionsTaskProvider.flatMap { it.irOptionsFile }, ) - val sourcesFromIrTaskProvider = registerSourcesFromIrTask( - project = project, - service = service, - schemaConsumerConfiguration = codegenSchema.resolvable, - generateOptionsTaskProvider = optionsTaskProvider, - codegenSchemaTaskProvider = codegenSchemaTaskProvider, - downstreamIrOperations = downstreamIr.resolvable, - irOperationsTaskProvider = irOperationsTaskProvider, - upstreamCodegenMetadata = codegenMetadata.resolvable, - classpathOptions = classpathOptions, + val computeUsedCoordinatesTask = project.registerApolloComputeUsedCoordinatesTask( + taskName = ModelNames.computeUsedCoordinates(service), + taskGroup = TASK_GROUP, + irOperations = downstreamIr.resolvable, + ) + val sourcesFromIrTaskProvider = project.registerApolloGenerateSourcesFromIrTask( + taskName = ModelNames.generateApolloSources(service), + taskGroup = TASK_GROUP, + taskDescription = "Generate Apollo models for service '${service.name}'", + extraClasspath = compilerConfiguration, + arguments = project.provider { pluginArguments }, + warnIfNotFound = project.provider { warnIfNoPluginFound }, + codegenSchemas = upstreamAndSelfCodegenSchemas, + usedCoordinates = computeUsedCoordinatesTask.flatMap { it.outputFile }, + irOperations = irOperationsTaskProvider.flatMap { it.irOperationsFile }, + upstreamMetadata = codegenMetadata.resolvable, + codegenOptions = optionsTaskProvider.flatMap { it.codegenOptions }, + outputDirectory = outputDir(project, service), + operationManifest = BuildDirLayout.operationManifest(project, service) ) sourcesBaseTaskProvider = sourcesFromIrTaskProvider val upstreamAndSelfCodegenMetadata = project.files().apply { from(codegenMetadata.resolvable) - from(sourcesFromIrTaskProvider.flatMap { it.metadataOutputFile }) - } - val downstreamAndSelfIrOperations = project.files().apply { - from(downstreamIr.resolvable) - from(irOperationsTaskProvider.flatMap { it.irOperationsFile }) + from(sourcesFromIrTaskProvider.flatMap { it.metadataOutput }) } + dataBuildersSourcesBaseTaskProvider = if (service.generateDataBuilders.orElse(false).get()) { - registerDataBuilderSourcesTask( - project = project, - service = service, - schemaConsumerConfiguration = codegenSchema.resolvable, - generateOptionsTaskProvider = optionsTaskProvider, - codegenSchemaTaskProvider = codegenSchemaTaskProvider, - downstreamAndSelfIrOperations = downstreamAndSelfIrOperations, - upstreamAndSelfCodegenMetadata = upstreamAndSelfCodegenMetadata, - classpathOptions = classpathOptions, + project.registerApolloGenerateDataBuildersSourcesTask( + taskName = ModelNames.generateDataBuildersApolloSources(service), + taskGroup = TASK_GROUP, + taskDescription = "Generate Apollo data builders for service '${service.name}'", + extraClasspath = compilerConfiguration, + arguments = project.provider { pluginArguments }, + warnIfNotFound = project.provider { warnIfNoPluginFound }, + codegenSchemas = upstreamAndSelfCodegenSchemas, + downstreamUsedCoordinates = computeUsedCoordinatesTask.flatMap { it.outputFile }, + upstreamMetadata = upstreamAndSelfCodegenMetadata, + codegenOptions = optionsTaskProvider.flatMap { it.codegenOptions }, + outputDirectory = dataBuildersOutputDir(project, service) ) } else { null @@ -536,7 +652,7 @@ abstract class DefaultApolloExtension( it.add(downstreamIr.consumable.name, irOperationsTaskProvider.flatMap { it.irOperationsFile }) { it.classifier = "ir-${service.name}" } - it.add(codegenMetadata.consumable.name, sourcesFromIrTaskProvider.flatMap { it.metadataOutputFile }) { + it.add(codegenMetadata.consumable.name, sourcesFromIrTaskProvider.flatMap { it.metadataOutput }) { it.classifier = "codegen-metadata-${service.name}" } } @@ -555,11 +671,11 @@ abstract class DefaultApolloExtension( } override fun addToSoftwareComponent(softwareComponent: SoftwareComponent) { - check (softwareComponent is AdhocComponentWithVariants) { + check(softwareComponent is AdhocComponentWithVariants) { "Software component '$softwareComponent' is not an instance of AdhocComponentWithVariants" } outgoingVariants.forEach { - softwareComponent.addVariantsFromConfiguration(it) { } + softwareComponent.addVariantsFromConfiguration(it) { } } } @@ -583,20 +699,29 @@ abstract class DefaultApolloExtension( val operationOutputConnection = Service.OperationOutputConnection( task = sourcesBaseTaskProvider, - operationOutputFile = sourcesBaseTaskProvider.flatMap { (it as ApolloGenerateSourcesBaseTask).operationManifestFile } + operationOutputFile = sourcesBaseTaskProvider.flatMap { it.operationManifest() } ) + @Suppress("DEPRECATION_ERROR") + check(!service.outputDir.isPresent) { + "Apollo: changing the location of the generated sources is not possible anymore. Use `outputDirConnection` to consume them and potentially copy them to another filesystem location." + } val directoryConnection = DefaultDirectoryConnection( project = project, task = sourcesBaseTaskProvider, - outputDir = sourcesBaseTaskProvider.flatMap { (it as ApolloGenerateSourcesBaseTask).outputDir }, - hardCodedOutputDir = BuildDirLayout.outputDir(project, service) + outputDir = sourcesBaseTaskProvider.flatMap { it.outputDirectory() }, + hardCodedOutputDir = outputDir(project, service) ) if (project.hasKotlinPlugin()) { checkKotlinPluginVersion(project) } + + @Suppress("DEPRECATION_ERROR") + check(!service.operationManifest.isPresent) { + "Apollo: changing the location of the generated manifest is not possible anymore. Use `operationManifestConnection` to consume it and potentially copy it to another filesystem location." + } check(service.operationOutputAction == null || service.operationManifestAction == null) { "Apollo: it is an error to set both operationOutputAction and operationManifestAction. Remove operationOutputAction" } @@ -611,7 +736,19 @@ abstract class DefaultApolloExtension( ) ) } - maybeRegisterRegisterOperationsTasks(project, service, operationOutputConnection) + val registerOperationsConfig = service.registerOperationsConfig + if (registerOperationsConfig != null) { + project.registerApolloRegisterOperationsTask( + taskName = ModelNames.registerApolloOperations(service), + taskGroup = TASK_GROUP, + operationOutput = operationOutputConnection.operationOutputFile, + operationManifestFormat = service.operationManifestFormat, + listId = registerOperationsConfig.listId, + graphVariant = registerOperationsConfig.graphVariant, + key = registerOperationsConfig.key, + graph = registerOperationsConfig.graph, + ) + } if (service.outputDirAction == null) { service.outputDirAction = defaultOutputDirAction @@ -627,10 +764,9 @@ abstract class DefaultApolloExtension( project = project, task = dataBuildersSourcesBaseTaskProvider, outputDir = dataBuildersSourcesBaseTaskProvider.flatMap { - it as ApolloGenerateDataBuildersSourcesBaseTask - it.dataBuildersOutputDir + it.dataBuildersOutputDirectory() }, - hardCodedOutputDir = BuildDirLayout.dataBuildersOutputDir(project, service) + hardCodedOutputDir = dataBuildersOutputDir(project, service) ) if (service.dataBuildersOutputDirAction == null) { @@ -652,227 +788,6 @@ abstract class DefaultApolloExtension( service.registered = true } - private fun registerSourcesFromIrTask( - project: Project, - service: DefaultService, - schemaConsumerConfiguration: Configuration, - codegenSchemaTaskProvider: TaskProvider?, - generateOptionsTaskProvider: TaskProvider, - downstreamIrOperations: FileCollection, - irOperationsTaskProvider: TaskProvider, - upstreamCodegenMetadata: Configuration, - classpathOptions: ApolloTaskWithClasspath.Options, - ): TaskProvider { - return project.tasks.register(ModelNames.generateApolloSources(service), ApolloGenerateSourcesFromIrTask::class.java) { task -> - task.group = TASK_GROUP - task.description = "Generate Apollo models for service '${service.name}'" - - configureBaseCodegenTask(project, task, generateOptionsTaskProvider, service, classpathOptions) - - task.codegenSchemas.from(schemaConsumerConfiguration) - if (codegenSchemaTaskProvider != null) { - task.codegenSchemas.from(codegenSchemaTaskProvider.flatMap { it.codegenSchemaFile }) - } - task.irOperations.set(irOperationsTaskProvider.flatMap { it.irOperationsFile }) - task.upstreamMetadata.from(upstreamCodegenMetadata) - task.downstreamUsedCoordinates.set(downstreamIrOperations.elements.map { - it.map { it.asFile.toIrOperations() }.fold(UsedCoordinates()) { acc, element -> - acc.mergeWith(element.usedCoordinates) - }.asMap() - }) - task.downstreamUsedCoordinates.finalizeValueOnRead() - - task.metadataOutputFile.set(BuildDirLayout.metadata(project, service)) - } - } - - private fun registerDataBuilderSourcesTask( - project: Project, - service: DefaultService, - schemaConsumerConfiguration: Configuration, - codegenSchemaTaskProvider: TaskProvider?, - generateOptionsTaskProvider: TaskProvider, - downstreamAndSelfIrOperations: FileCollection, - upstreamAndSelfCodegenMetadata: FileCollection, - classpathOptions: ApolloTaskWithClasspath.Options, - ): TaskProvider { - return project.tasks.register(ModelNames.generateDataBuildersApolloSources(service), ApolloGenerateDataBuildersSourcesTask::class.java) { task -> - task.group = TASK_GROUP - task.description = "Generate Apollo data builders for service '${service.name}'" - - configureTaskWithClassPath(task, classpathOptions) - - task.codegenOptionsFile.set(generateOptionsTaskProvider.flatMap { it.codegenOptions }) - - task.dataBuildersOutputDir.set(service.dataBuildersOutputDir.orElse(BuildDirLayout.dataBuildersOutputDir(project, service))) - - task.codegenSchemas.from(schemaConsumerConfiguration) - if (codegenSchemaTaskProvider != null) { - task.codegenSchemas.from(codegenSchemaTaskProvider.flatMap { it.codegenSchemaFile }) - } - task.upstreamMetadata.from(upstreamAndSelfCodegenMetadata) - task.downstreamUsedCoordinates.set(downstreamAndSelfIrOperations.elements.map { - it.map { it.asFile.toIrOperations() }.fold(UsedCoordinates()) { acc, element -> - acc.mergeWith(element.usedCoordinates) - } - .asMap() - }) - task.downstreamUsedCoordinates.finalizeValueOnRead() - } - } - - private fun registerOptionsTask( - project: Project, - service: DefaultService, - upstreamOtherOptions: FileCollection, - ): TaskProvider { - return project.tasks.register(ModelNames.generateApolloOptions(service), ApolloGenerateOptionsTask::class.java) { task -> - task.group = TASK_GROUP - task.description = "Generate Apollo options for service '${service.name}'" - - /** - * CodegenSchemaOptions - */ - task.scalarTypeMapping.set(service.scalarTypeMapping) - task.scalarAdapterMapping.set(service.scalarAdapterMapping) - task.generateDataBuilders.set(service.generateDataBuilders) - - task.codegenSchemaOptionsFile.set(BuildDirLayout.codegenSchemaOptions(project, service)) - - /** - * IrOptions - */ - task.codegenModels.set(service.codegenModels) - task.addTypename.set(service.addTypename) - task.fieldsOnDisjointTypesMustMerge.set(service.fieldsOnDisjointTypesMustMerge) - task.decapitalizeFields.set(service.decapitalizeFields) - task.flattenModels.set(service.flattenModels) - task.warnOnDeprecatedUsages.set(service.warnOnDeprecatedUsages) - task.failOnWarnings.set(service.failOnWarnings) - task.generateOptionalOperationVariables.set(service.generateOptionalOperationVariables) - task.alwaysGenerateTypesMatching.set(service.alwaysGenerateTypesMatching) - - task.irOptionsFile.set(BuildDirLayout.irOptions(project, service)) - - /** - * CommonCodegenOptions - */ - task.generateKotlinModels.set(service.generateKotlinModels) - task.languageVersion.set(service.languageVersion) - task.packageName.set(service.packageName) - task.rootPackageName.set(service.rootPackageName) - task.useSemanticNaming.set(service.useSemanticNaming) - task.generateFragmentImplementations.set(service.generateFragmentImplementations) - task.generateMethods.set(service.generateMethods.map { list -> - list.map { - GeneratedMethod.fromName(it) ?: error("Apollo: unknown method type: $it for generateMethods") - } - }) - task.generateQueryDocument.set(service.generateQueryDocument) - task.generateSchema.set(service.generateSchema) - task.generatedSchemaName.set(service.generatedSchemaName) - task.operationManifestFormat.set(service.operationManifestFormat()) - - /** - * JavaCodegenOptions - */ - task.generateModelBuilders.set(service.generateModelBuilders) - task.classesForEnumsMatching.set(service.classesForEnumsMatching) - task.generatePrimitiveTypes.set(service.generatePrimitiveTypes) - task.nullableFieldStyle.set(service.nullableFieldStyle.orNull?.let { JavaNullable.fromName(it) }) - - /** - * KotlinCodegenOptions - */ - task.sealedClassesForEnumsMatching.set(service.sealedClassesForEnumsMatching) - task.generateAsInternal.set(service.generateAsInternal) - task.generateInputBuilders.set(service.generateInputBuilders) - task.addJvmOverloads.set(service.addJvmOverloads) - task.requiresOptInAnnotation.set(service.requiresOptInAnnotation) - task.jsExport.set(service.jsExport) - - task.codegenOptions.set(BuildDirLayout.codegenOptions(project, service)) - - /** - * Gradle model - */ - task.upstreamOtherOptions.from(upstreamOtherOptions) - task.isJavaPluginApplied = project.hasJavaPlugin() - task.kgpVersion = project.apolloGetKotlinPluginVersion() - task.isKmp = project.isKotlinMultiplatform - // If there is no downstream dependency, generate everything because we don't know what types are going to be used downstream - task.generateAllTypes = service.isSchemaModule() && service.isMultiModule() && service.downstreamDependencies.isEmpty() - - task.otherOptions.set(BuildDirLayout.otherOptions(project, service)) - } - } - - private fun registerIrOperationsTask( - project: Project, - service: DefaultService, - schemaConsumerConfiguration: Configuration, - schemaTaskProvider: TaskProvider?, - irOptionsTaskProvider: TaskProvider, - upstreamIrFiles: Configuration, - classpathOptions: ApolloTaskWithClasspath.Options, - ): TaskProvider { - return project.tasks.register(ModelNames.generateApolloIrOperations(service), ApolloGenerateIrOperationsTask::class.java) { task -> - task.group = TASK_GROUP - task.description = "Generate Apollo IR operations for service '${service.name}'" - - configureTaskWithClassPath(task, classpathOptions) - task.codegenSchemaFiles.from(schemaConsumerConfiguration) - if (schemaTaskProvider != null) { - task.codegenSchemaFiles.from(schemaTaskProvider.flatMap { it.codegenSchemaFile }) - } - task.graphqlFiles.from(service.graphqlSourceDirectorySet) - task.upstreamIrFiles.from(upstreamIrFiles) - task.irOptionsFile.set(irOptionsTaskProvider.flatMap { it.irOptionsFile }) - - task.irOperationsFile.set(BuildDirLayout.ir(project, service)) - } - } - - private fun registerCodegenSchemaTask( - project: Project, - service: DefaultService, - optionsTaskProvider: TaskProvider, - schemaConsumerConfiguration: Configuration, - classpathOptions: ApolloTaskWithClasspath.Options, - ): TaskProvider { - return project.tasks.register(ModelNames.generateApolloCodegenSchema(service), ApolloGenerateCodegenSchemaTask::class.java) { task -> - task.group = TASK_GROUP - task.description = "Generate Apollo schema for service '${service.name}'" - - configureTaskWithClassPath(task, classpathOptions) - task.schemaFiles.from(service.schemaFiles(project)) - task.fallbackSchemaFiles.from(service.fallbackSchemaFiles(project)) - task.upstreamSchemaFiles.from(schemaConsumerConfiguration) - task.codegenSchemaOptionsFile.set(optionsTaskProvider.flatMap { it.codegenSchemaOptionsFile }) - task.codegenSchemaFile.set(BuildDirLayout.codegenSchema(project, service)) - } - } - - private fun maybeRegisterRegisterOperationsTasks( - project: Project, - service: DefaultService, - operationOutputConnection: Service.OperationOutputConnection, - ) { - val registerOperationsConfig = service.registerOperationsConfig - if (registerOperationsConfig != null) { - project.tasks.register(ModelNames.registerApolloOperations(service), ApolloRegisterOperationsTask::class.java) { task -> - task.group = TASK_GROUP - - task.operationManifestFormat.set(service.operationManifestFormat()) - task.listId.set(registerOperationsConfig.listId) - task.graph.set(registerOperationsConfig.graph) - task.graphVariant.set(registerOperationsConfig.graphVariant) - task.key.set(registerOperationsConfig.key) - task.operationOutput.set(operationOutputConnection.operationOutputFile) - } - } - } - /** * The default wiring. */ @@ -920,79 +835,41 @@ abstract class DefaultApolloExtension( } } - private fun configureTaskWithClassPath( - task: ApolloTaskWithClasspath, - classpathOptions: ApolloTaskWithClasspath.Options - ) { - task.hasPlugin.set(classpathOptions.hasPlugin) - task.classpath.from(classpathOptions.classpath) - task.arguments.set(classpathOptions.arguments) - task.logLevel.set(classpathOptions.logLevel) - task.apolloBuildService.set(apolloBuildServiceProvider) - task.usesService(apolloBuildServiceProvider) - } - - private fun configureBaseCodegenTask( - project: Project, - task: ApolloGenerateSourcesBaseTask, - generateOptionsTask: TaskProvider, - service: DefaultService, - classpathOptions: ApolloTaskWithClasspath.Options, - ) { - configureTaskWithClassPath(task, classpathOptions) - - task.codegenOptionsFile.set(generateOptionsTask.flatMap { it.codegenOptions }) - - task.outputDir.set(service.outputDir.orElse(BuildDirLayout.outputDir(project, service))) - task.operationManifestFile.set(service.operationManifestFile()) - } - - private fun registerSourcesTask( - project: Project, - optionsTaskProvider: TaskProvider, - service: DefaultService, - classpathOptions: ApolloTaskWithClasspath.Options, - ): TaskProvider { - return project.tasks.register(ModelNames.generateApolloSources(service), ApolloGenerateSourcesTask::class.java) { task -> - task.group = TASK_GROUP - task.description = "Generate Apollo models for service '${service.name}'" - - configureBaseCodegenTask(project, task, optionsTaskProvider, service, classpathOptions) - - task.graphqlFiles.from(service.graphqlSourceDirectorySet) - task.schemaFiles.from(service.schemaFiles(project)) - task.fallbackSchemaFiles.from(service.fallbackSchemaFiles(project)) - task.codegenSchemaOptionsFile.set(optionsTaskProvider.map { it.codegenSchemaOptionsFile.get() }) - task.irOptionsFile.set(optionsTaskProvider.map { it.irOptionsFile.get() }) - task.dataBuildersOutputDir.set(service.dataBuildersOutputDir.orElse(BuildDirLayout.dataBuildersOutputDir(project, service))) - } - } - private fun registerDownloadSchemaTasks(service: DefaultService) { val introspection = service.introspection var taskProvider: TaskProvider? = null var connection: Action? = null if (introspection != null) { - taskProvider = project.tasks.register(ModelNames.downloadApolloSchemaIntrospection(service), ApolloDownloadSchemaTask::class.java) { task -> - - task.group = TASK_GROUP - task.outputFile.set(service.guessSchemaFile(project, introspection.schemaFile)) - task.endpoint.set(introspection.endpointUrl) - task.header = introspection.headers.get().map { "${it.key}: ${it.value}" } - } + taskProvider = project.registerApolloDownloadSchemaTask( + taskName = ModelNames.downloadApolloSchemaIntrospection(service), + taskGroup = TASK_GROUP, + schema = project.provider { service.guessSchemaFile(project, introspection.schemaFile) }, + endpoint = introspection.endpointUrl, + headers = introspection.headers, + graph = project.provider { null }, + key = project.provider { null }, + graphVariant = project.provider { null }, + registryUrl = project.provider { null }, + insecure = project.provider { false } + ) connection = introspection.schemaConnection } val registry = service.registry if (registry != null) { - taskProvider = project.tasks.register(ModelNames.downloadApolloSchemaRegistry(service), ApolloDownloadSchemaTask::class.java) { task -> + taskProvider = project.registerApolloDownloadSchemaTask( + taskName = ModelNames.downloadApolloSchemaIntrospection(service), + taskGroup = TASK_GROUP, + schema = project.provider { service.guessSchemaFile(project, registry.schemaFile) }, + endpoint = project.provider { null }, + headers = project.objects.mapProperty(String::class.java, String::class.java), + graph = registry.graph, + key = registry.key, + graphVariant = registry.graphVariant, + registryUrl = project.provider { null }, + insecure = project.provider { false } + ) - task.group = TASK_GROUP - task.outputFile.set(service.guessSchemaFile(project, registry.schemaFile)) - task.graph.set(registry.graph) - task.key.set(registry.key) - task.graphVariant.set(registry.graphVariant) - } connection = registry.schemaConnection } if (connection != null && taskProvider != null) { @@ -1000,7 +877,7 @@ abstract class DefaultApolloExtension( SchemaConnection( taskProvider, taskProvider.flatMap { downloadSchemaTask -> - downloadSchemaTask.outputFile + project.layout.file(downloadSchemaTask.schema) } ) ) @@ -1056,6 +933,7 @@ abstract class DefaultApolloExtension( companion object { private const val TASK_GROUP = "apollo" + // Keep in sync gradle-api-min const val MIN_GRADLE_VERSION = "8.0" @@ -1096,3 +974,26 @@ abstract class DefaultApolloExtension( } +private fun Task.outputDirectory(): Provider { + return when (this) { + is ApolloGenerateSourcesTask -> this.outputDirectory + is ApolloGenerateSourcesFromIrTask -> this.outputDirectory + else -> error("Unexpected task $this") + } +} + +private fun Task.operationManifest(): Provider { + return when (this) { + is ApolloGenerateSourcesTask -> this.operationManifest + is ApolloGenerateSourcesFromIrTask -> this.operationManifest + else -> error("Unexpected task $this") + } +} + +private fun Task.dataBuildersOutputDirectory(): Provider { + return when (this) { + is ApolloGenerateSourcesTask -> this.dataBuildersOutputDirectory + is ApolloGenerateDataBuildersSourcesTask -> this.outputDirectory + else -> error("Unexpected task $this") + } +} \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloGradleToolingModel.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloGradleToolingModel.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloGradleToolingModel.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultApolloGradleToolingModel.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultCompilerPlugin.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultCompilerPlugin.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultCompilerPlugin.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultCompilerPlugin.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultDirectoryConnection.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultDirectoryConnection.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultDirectoryConnection.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultDirectoryConnection.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultIntrospection.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultIntrospection.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultIntrospection.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultIntrospection.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegisterOperationsConfig.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegisterOperationsConfig.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegisterOperationsConfig.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegisterOperationsConfig.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegistry.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegistry.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegistry.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultRegistry.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultService.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultService.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultService.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/DefaultService.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt similarity index 70% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt index 019c2f117df..84bd3b822a1 100644 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/KotlinPluginFacade.kt @@ -1,9 +1,8 @@ package com.apollographql.apollo.gradle.internal -import com.apollographql.apollo.compiler.TargetLanguage -import com.apollographql.apollo.compiler.capitalizeFirstLetter import com.apollographql.apollo.gradle.api.Service import com.apollographql.apollo.gradle.internal.DefaultApolloExtension.Companion.hasKotlinPlugin +import gratatouille.wiring.capitalizeFirstLetter import org.gradle.api.Action import org.gradle.api.Project import org.jetbrains.kotlin.gradle.plugin.getKotlinPluginVersion @@ -14,26 +13,7 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget * For a non-Kotlin project, this class will never be loaded so that no runtime * exception is thrown */ -fun getKotlinTargetLanguage(kgpVersion: String, userSpecified: String?): TargetLanguage { - @Suppress("DEPRECATION_ERROR") - return when (userSpecified) { - "1.5" -> TargetLanguage.KOTLIN_1_5 - "1.9" -> TargetLanguage.KOTLIN_1_9 - null -> { - // User didn't specify a version: default to the Kotlin plugin version - val kotlinPluginVersion = kgpVersion.split("-")[0] - val versionNumbers = kotlinPluginVersion.split(".").map { it.toInt() } - val version = KotlinVersion(versionNumbers[0], versionNumbers[1]) - if (version.isAtLeast(1, 9)) { - TargetLanguage.KOTLIN_1_9 - } else { - TargetLanguage.KOTLIN_1_5 - } - } - else -> error("Apollo: languageVersion '$userSpecified' is not supported, Supported values: '1.5', '1.9'") - } -} fun Project.apolloGetKotlinPluginVersion(): String? { if (!project.hasKotlinPlugin()) { @@ -87,7 +67,7 @@ fun createAllKotlinSourceSetServices( apolloExtension.service(name) { service -> action.execute(service) service.srcDir("src/${kotlinSourceSet.name}/graphql/$sourceFolder") - (service as DefaultService).outputDirAction = Action { connection -> + (service as DefaultService).outputDirAction = Action { connection -> kotlinSourceSet.kotlin.srcDir(connection.outputDir) } } diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt similarity index 93% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt index 969083ec7ee..adc2ab6045f 100644 --- a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ModelNames.kt @@ -1,8 +1,7 @@ package com.apollographql.apollo.gradle.internal -import com.apollographql.apollo.annotations.ApolloDeprecatedSince -import com.apollographql.apollo.compiler.capitalizeFirstLetter import com.apollographql.apollo.gradle.api.Service +import gratatouille.wiring.capitalizeFirstLetter internal object ModelNames { private fun camelCase(vararg elements: String): String { @@ -20,6 +19,7 @@ internal object ModelNames { fun generateApolloSources(service: Service) = camelCase("generate", service.name, "ApolloSources") fun generateDataBuildersApolloSources(service: Service) = camelCase("generate", service.name, "DataBuildersApolloSources") fun generateApolloCodegenSchema(service: Service) = camelCase("generate", service.name, "ApolloCodegenSchema") + fun computeUsedCoordinates(service: DefaultService)= camelCase("compute", service.name, "ApolloUsedCoordinates") fun generateApolloIrOperations(service: Service) = camelCase("generate", service.name, "ApolloIrOperations") fun generateApolloOptions(service: Service) = camelCase("generate", service.name, "ApolloOptions") fun downloadApolloSchema() = camelCase("downloadApolloSchema") diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/Telemetry.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/Telemetry.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/Telemetry.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/Telemetry.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/androidProject.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/androidProject.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/androidProject.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/androidProject.kt diff --git a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/apolloPlugin.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/apolloPlugin.kt new file mode 100644 index 00000000000..fe112cbcfb4 --- /dev/null +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/apolloPlugin.kt @@ -0,0 +1,52 @@ +package com.apollographql.apollo.gradle.internal + +import com.apollographql.apollo.gradle.APOLLO_VERSION +import com.apollographql.apollo.gradle.api.ApolloExtension +import com.apollographql.apollo.gradle.api.ApolloGradleToolingModel +import gratatouille.wiring.GPlugin +import org.gradle.api.Project +import org.gradle.api.artifacts.ExternalDependency +import org.gradle.tooling.provider.model.ToolingModelBuilder +import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry +import javax.inject.Inject + + +@GPlugin(id = "com.apollographql.apollo") +fun apolloPlugin(project: Project) { + val apolloExtension: DefaultApolloExtension = project.extensions.create(ApolloExtension::class.java, "apollo", DefaultApolloExtension::class.java, project) as DefaultApolloExtension + + project.configureDefaultVersionsResolutionStrategy() + + project.objects.newInstance(ToolingRegistryRef::class.java).toolingModelRegistry.register( + object : ToolingModelBuilder { + override fun canBuild(modelName: String) = modelName == ApolloGradleToolingModel::class.java.name + + override fun buildAll(modelName: String, project: Project): ApolloGradleToolingModel { + return DefaultApolloGradleToolingModel( + projectName = project.name, + projectPath = project.path, + serviceInfos = apolloExtension.getServiceInfos(project), + telemetryData = getTelemetryData(project, apolloExtension), + ) + } + } + ) +} + +abstract class ToolingRegistryRef @Inject constructor(val toolingModelRegistry: ToolingModelBuilderRegistry) + +/** + * Allow users to omit the Apollo version in their dependencies + * Inspired by https://github.com/JetBrains/kotlin/blob/70e15b281cb43379068facb82b8e4bcb897a3c4f/libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/internal/KotlinDependenciesManagement.kt#L52 + */ +private fun Project.configureDefaultVersionsResolutionStrategy() { + configurations.configureEach { configuration -> + // Use the API introduced in Gradle 4.4 to modify the dependencies directly before they are resolved: + configuration.withDependencies { dependencySet -> + val pluginVersion = APOLLO_VERSION + dependencySet.filterIsInstance() + .filter { it.group == "com.apollographql.apollo" && it.version.isNullOrEmpty() } + .forEach { it.version { constraint -> constraint.require(pluginVersion) } } + } + } +} diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/javaProject.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/javaProject.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/javaProject.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/javaProject.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/kotlinProject.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/kotlinProject.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/kotlinProject.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/kotlinProject.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/normalization.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/normalization.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/normalization.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/normalization.kt diff --git a/libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/project.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/project.kt similarity index 100% rename from libraries/apollo-gradle-plugin-external/src/main/kotlin/com/apollographql/apollo/gradle/internal/project.kt rename to libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/project.kt diff --git a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt new file mode 100644 index 00000000000..37996e8dd36 --- /dev/null +++ b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/utils.kt @@ -0,0 +1,16 @@ +package com.apollographql.apollo.gradle.internal + +import org.gradle.api.artifacts.ProjectDependency + +internal fun ProjectDependency.getPathCompat(): String { + val method = this::class.java.methods.firstOrNull { + it.name == "getPath" && it.parameters.isEmpty() + } + return if (method != null) { + // Gradle 8.11+ path + // See https://docs.gradle.org/8.11/userguide/upgrading_version_8.html#deprecate_get_dependency_project + method.invoke(this) as String + } else { + dependencyProject.path + } +} diff --git a/libraries/apollo-gradle-plugin/src/test-java11/README.md b/libraries/apollo-gradle-plugin/src/test-java11/README.md deleted file mode 100644 index 1f8f6d19429..00000000000 --- a/libraries/apollo-gradle-plugin/src/test-java11/README.md +++ /dev/null @@ -1 +0,0 @@ -Tests run with JDK 11 for compatibility with older Gradle versions \ No newline at end of file diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ConvertSchemaTests.kt b/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ConvertSchemaTests.kt deleted file mode 100644 index ed23f806069..00000000000 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ConvertSchemaTests.kt +++ /dev/null @@ -1,103 +0,0 @@ -package test - -import com.apollographql.apollo.ast.introspection.normalize -import com.apollographql.apollo.ast.introspection.toIntrospectionSchema -import org.gradle.testkit.runner.TaskOutcome -import org.junit.Assert -import org.junit.Test -import util.TestUtils -import java.io.File -import org.assertj.core.api.Assertions.assertThat as assertjThat - -class ConvertSchemaTests { - @Test - fun `convert from SDL to Json works`() { - TestUtils.withTestProject("convertSchema") { dir -> - val from = "schemas/schema.sdl" - val to = "schema.json" - val result = TestUtils.executeTask("convertApolloSchema", - dir, - "--from", - from, - "--to", - to - ) - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":convertApolloSchema")!!.outcome) - - /** - * The conversion might change the order of the types - */ - val schema1 = File(dir, to).toIntrospectionSchema().normalize() - val schema2 = File(dir, "schemas/schema.json").toIntrospectionSchema().normalize() - assertjThat(schema1) - .usingRecursiveComparison() - .isEqualTo(schema2) - } - } - - @Test - fun `convert is never up-to-date`() { - TestUtils.withTestProject("convertSchema") { dir -> - val from = File(dir, "schemas/schema.sdl") - val to = File(dir, "schema.json") - var result = TestUtils.executeTask("convertApolloSchema", - dir, - "--from", - from.absolutePath, - "--to", - to.absolutePath - ) - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":convertApolloSchema")!!.outcome) - result = TestUtils.executeTask("convertApolloSchema", - dir, - "--from", - from.absolutePath, - "--to", - to.absolutePath - ) - // even if inputs are the same, - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":convertApolloSchema")!!.outcome) - } - } - - @Test - fun `convert from Json to SDL works`() { - TestUtils.withTestProject("convertSchema") { dir -> - val from = File(dir, "schemas/schema.json") - val to = File(dir, "schema.sdl") - val result = TestUtils.executeTask("convertApolloSchema", - dir, - "--from", - from.absolutePath, - "--to", - to.absolutePath - ) - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":convertApolloSchema")!!.outcome) - assertjThat(to.readText()) - .isEqualTo(File(dir, "schemas/schema.sdl").readText()) - } - } - - @Test - fun `convert from october-2015 JSON to SDL works`() { - TestUtils.withTestProject("convertSchema") { dir -> - // schema-october-2015.json doesn't have: - // - `__Directive.locations` (introduced in the April2016 spec) - // - `__Directive.isRepeatable` (introduced in the October2021 spec) - // - `__InputField.isDeprecated` and `__InputField.deprecatedReason` (introduced after the October2021 spec) - val from = File(dir, "schemas/schema-october-2015-spec.json") - val to = File(dir, "schema.sdl") - val result = TestUtils.executeTask("convertApolloSchema", - dir, - "--from", - from.absolutePath, - "--to", - to.absolutePath - ) - Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":convertApolloSchema")!!.outcome) - assertjThat(to.readText()) - .isEqualTo(File(dir, "schemas/schema-october-2015-spec.sdl").readText()) - } - } - -} diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/Agp8_2Test.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/Agp8_2Test.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/Agp8_2Test.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/Agp8_2Test.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/AndroidProjectTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/AndroidProjectTests.kt similarity index 89% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/AndroidProjectTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/AndroidProjectTests.kt index 0e51867890c..d2a6df8e66f 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/AndroidProjectTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/AndroidProjectTests.kt @@ -6,7 +6,7 @@ import util.TestUtils import util.TestUtils.executeTaskAndAssertSuccess import util.TestUtils.withProject import util.TestUtils.withTestProject -import util.generatedChild +import util.generatedSource import org.gradle.testkit.runner.TaskOutcome import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue @@ -32,9 +32,9 @@ class AndroidProjectTests { assertEquals(TaskOutcome.SUCCESS, result.task(":build")!!.outcome) // Java classes generated successfully - assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/FilmsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").isFile) } } @@ -54,9 +54,9 @@ class AndroidProjectTests { assertEquals(TaskOutcome.SUCCESS, result.task(":build")!!.outcome) // Java classes generated successfully - assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/FilmsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").isFile) assertTrue(File(dir, "build/outputs/apk/debug/testProject-debug.apk").isFile) } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ConfigurationCacheTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/ConfigurationCacheTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ConfigurationCacheTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/ConfigurationCacheTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/DeprecationTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/DeprecationTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/DeprecationTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/DeprecationTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/DownloadSchemaTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/DownloadSchemaTests.kt similarity index 75% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/DownloadSchemaTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/DownloadSchemaTests.kt index a3c527ba90c..2e554575ebe 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/DownloadSchemaTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/DownloadSchemaTests.kt @@ -222,66 +222,6 @@ class DownloadSchemaTests { } } - @Test - fun `manually downloading a schema is working`() { - - TestUtils.withSimpleProject(apolloConfiguration = "") { dir -> - mockServer.enqueue(MockResponse().setBody(preIntrospectionResponse)) - mockServer.enqueue(MockResponse().setBody(schemaString1)) - - // Tests can run from any working directory. - // They used to run in `apollo-gradle-plugin` but with Gradle 6.7, they now run in something like - // /private/var/folders/zh/xlpqxsfn7vx_dhjswsgsps6h0000gp/T/.gradle-test-kit-martin/test-kit-daemon/6.7/ - // We'll use absolute path as arguments for the check to succeed later on - val schema = File("build/testProject/schema.json") - - TestUtils.executeGradle(dir, "downloadApolloSchema", - "--schema=${schema.absolutePath}", - "--endpoint=${mockServer.url("/")}" - ) - - Assert.assertEquals(schemaString1, schema.readText()) - } - } - - @Test - fun `manually downloading a schema from self signed endpoint is working`() { - TestUtils.withSimpleProject(apolloConfiguration = "") { dir -> - mockServer.enqueue(MockResponse().setBody(preIntrospectionResponse)) - mockServer.enqueue(MockResponse().setBody(schemaString1)) - - val selfSignedCertificate = HeldCertificate.Builder().build() - val certs = HandshakeCertificates.Builder().heldCertificate(selfSignedCertificate).build() - mockServer.useHttps(certs.sslSocketFactory(), tunnelProxy = false) - - val schema = File("build/testProject/schema.json") - - TestUtils.executeGradle(dir, "downloadApolloSchema", - "--schema=${schema.absolutePath}", - "--endpoint=${mockServer.url("/")}", - "--insecure" - ) - - Assert.assertEquals(schemaString1, schema.readText()) - } - } - - @Test - fun `manually downloading a schema when 2-step mode fails is working`() { - TestUtils.withSimpleProject(apolloConfiguration = "") { dir -> - mockServer.enqueue(MockResponse().setBody(preIntrospectionResponse)) - mockServer.enqueue(MockResponse().setBody(schemaStringError)) - mockServer.enqueue(MockResponse().setBody(schemaString1)) - val schema = File("build/testProject/schema.json") - TestUtils.executeGradle(dir, "downloadApolloSchema", - "--schema=${schema.absolutePath}", - "--endpoint=${mockServer.url("/")}", - ) - - Assert.assertEquals(schemaString1, schema.readText()) - } - } - @Test fun `download a schema from a real server is working`() { val executableSchema = ExecutableSchema.Builder() diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/GradleBuildCacheTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleBuildCacheTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/GradleBuildCacheTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleBuildCacheTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/GradleToolingTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleToolingTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/GradleToolingTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleToolingTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java11/kotlin/com/apollographql/apollo/gradle/test/GradleVersionTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleVersionTests.kt similarity index 94% rename from libraries/apollo-gradle-plugin/src/test-java11/kotlin/com/apollographql/apollo/gradle/test/GradleVersionTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleVersionTests.kt index f3ee8a73e29..e3fd78a39b1 100644 --- a/libraries/apollo-gradle-plugin/src/test-java11/kotlin/com/apollographql/apollo/gradle/test/GradleVersionTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/GradleVersionTests.kt @@ -1,6 +1,6 @@ -package com.apollographql.apollo.gradle.test +package test -import com.apollographql.apollo.compiler.APOLLO_VERSION +import com.apollographql.apollo.gradle.APOLLO_VERSION import com.apollographql.apollo.gradle.internal.DefaultApolloExtension.Companion.MIN_GRADLE_VERSION import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/GroovyTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/GroovyTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/GroovyTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/GroovyTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/JavaOnly.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/JavaOnly.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/JavaOnly.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/JavaOnly.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinDSLTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinDSLTests.kt similarity index 91% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinDSLTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinDSLTests.kt index 57f9eb6df7f..5e773f159d5 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinDSLTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinDSLTests.kt @@ -1,7 +1,7 @@ package test import util.TestUtils -import util.generatedChild +import util.generatedSource import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome import org.gradle.testkit.runner.UnexpectedBuildFailure @@ -34,7 +34,7 @@ class KotlinDSLTests { fun `parameters do not throw`() { val apolloConfiguration = """ apollo { - service("starwars") { + service("service") { useSemanticNaming.set(false) mapScalar("DateTime", "java.util.Date") srcDir("src/main/graphql/com/example") @@ -52,7 +52,7 @@ class KotlinDSLTests { ) { dir -> val result = TestUtils.executeTask("generateApolloSources", dir) assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) - Assert.assertTrue(dir.generatedChild("starwars/com/starwars/DroidDetails.kt").isFile) + Assert.assertTrue(dir.generatedSource("com/starwars/DroidDetails.kt").isFile) } } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinJVMProjectTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinJVMProjectTests.kt similarity index 93% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinJVMProjectTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinJVMProjectTests.kt index a5d041129a1..59a97b88e7c 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinJVMProjectTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinJVMProjectTests.kt @@ -2,7 +2,7 @@ package test import util.TestUtils import util.TestUtils.withSimpleProject -import util.generatedChild +import util.generatedSource import util.replaceInText import org.gradle.testkit.runner.TaskOutcome import org.junit.Assert @@ -42,7 +42,7 @@ class KotlinJVMProjectTests { Assert.assertTrue(File(dir, "build/classes/kotlin/main/com/example/DroidDetailsQuery.class").isFile) Assert.assertTrue(File(dir, "build/classes/kotlin/main/com/example/Main.class").isFile) - Assert.assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) + Assert.assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) Assert.assertTrue(File(dir, "build/libs/testProject.jar").isFile) } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinMultiplatformProjectTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinMultiplatformProjectTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinMultiplatformProjectTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinMultiplatformProjectTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinPluginVersionTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinPluginVersionTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/KotlinPluginVersionTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/KotlinPluginVersionTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/LanguageVersionTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/LanguageVersionTests.kt similarity index 91% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/LanguageVersionTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/LanguageVersionTests.kt index 36e050d975c..21cd15fcf14 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/LanguageVersionTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/LanguageVersionTests.kt @@ -4,9 +4,11 @@ import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome import org.gradle.testkit.runner.UnexpectedBuildFailure import org.junit.Assert +import org.junit.Assert.assertTrue import org.junit.Test import util.TestUtils import util.disableIsolatedProjects +import util.generatedSource import java.io.File import kotlin.test.assertEquals @@ -48,20 +50,22 @@ class LanguageVersionTests { @Test fun `compiling with 1_9 features generates entries in enums`() { withProject(apolloLanguageVersion = "1.9", graphqlPath = "githunt") { dir -> + TestUtils.executeGradleWithVersion(dir, "8.10", ":generateApolloSources").apply { assertEquals(TaskOutcome.SUCCESS, task(":generateApolloSources")!!.outcome) } - Assert.assertTrue(File(dir, "build/generated/source/apollo/service/com/example/type/FeedType.kt").readText().contains("entries.find")) + assertTrue(dir.generatedSource("com/example/type/FeedType.kt").readText().contains("entries.find")) } } @Test fun `compiling with 1_5 features generates values in enums`() { withProject(apolloLanguageVersion = "1.5", graphqlPath = "githunt") { dir -> + TestUtils.executeGradleWithVersion(dir, "8.10", ":generateApolloSources").apply { assertEquals(TaskOutcome.SUCCESS, task(":generateApolloSources")!!.outcome) } - Assert.assertTrue(File(dir, "build/generated/source/apollo/service/com/example/type/FeedType.kt").readText().contains("values().find")) + assertTrue(dir.generatedSource("com/example/type/FeedType.kt").readText().contains("values().find")) } } @@ -105,7 +109,7 @@ class LanguageVersionTests { configure { service("service") { packageNamesFromFilePaths() - codegenModels.set(com.apollographql.apollo.compiler.MODELS_RESPONSE_BASED) + codegenModels.set("responseBased") ${if (apolloLanguageVersion == null) "" else "languageVersion.set(\"$apolloLanguageVersion\")"} } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/LazyTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/LazyTests.kt similarity index 100% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/LazyTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/LazyTests.kt diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/MultiModulesTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/MultiModulesTests.kt similarity index 97% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/MultiModulesTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/MultiModulesTests.kt index d49b9c9d3f1..b8263ef145f 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/MultiModulesTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/MultiModulesTests.kt @@ -7,8 +7,10 @@ import org.junit.Assert import org.junit.Test import util.TestUtils import util.disableIsolatedProjects +import util.generatedSource import util.replaceInText import java.io.File +import kotlin.test.assertTrue internal fun testProjectWithIsolatedProjectsWorkaround(name: String, block: (File) -> Unit) { @@ -106,8 +108,8 @@ class MultiModulesTests { testProjectWithIsolatedProjectsWorkaround("multi-modules-custom-scalar") { dir -> TestUtils.executeTaskAndAssertSuccess(":leaf:assemble", dir) // Date and GeoPoint is generated in the root module - Assert.assertTrue(File(dir, "root/build/generated/source/apollo/service/com/library/type/Date.kt").exists()) - Assert.assertTrue(File(dir, "root/build/generated/source/apollo/service/com/library/type/GeoPoint.kt").exists()) + assertTrue(dir.resolve("root").generatedSource("com/library/type/Date.kt").isFile) + assertTrue(dir.resolve("root").generatedSource("com/library/type/GeoPoint.kt").isFile) // Leaf metadata doesn't contain Date Assert.assertTrue(dir.walk().filter { it.isFile && it.name == "Data.kt" }.toList().isEmpty()) } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/MultiServicesTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/MultiServicesTests.kt similarity index 83% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/MultiServicesTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/MultiServicesTests.kt index fbc6673819e..f3e8290f7e6 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/MultiServicesTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/MultiServicesTests.kt @@ -3,7 +3,7 @@ package test import util.TestUtils import util.TestUtils.withProject -import util.generatedChild +import util.generatedSource import org.gradle.testkit.runner.UnexpectedBuildFailure import org.hamcrest.CoreMatchers.containsString import org.hamcrest.MatcherAssert @@ -83,11 +83,11 @@ class MultiServicesTests { withMultipleServicesProject(apolloConfiguration) { dir -> TestUtils.executeTask("build", dir) - assertTrue(dir.generatedChild("starwars/starwars/DroidDetailsQuery.kt").isFile) - assertTrue(dir.generatedChild("starwars/starwars/FilmsQuery.kt").isFile) - assertTrue(dir.generatedChild("starwars/starwars/fragment/SpeciesInformation.kt").isFile) - assertTrue(dir.generatedChild("githunt/githunt/FeedQuery.kt").isFile) - assertTrue(dir.generatedChild("githunt/githunt/fragment/RepositoryFragment.kt").isFile) + assertTrue(dir.generatedSource("starwars/DroidDetailsQuery.kt", "starwars").isFile) + assertTrue(dir.generatedSource("starwars/FilmsQuery.kt", "starwars").isFile) + assertTrue(dir.generatedSource("starwars/fragment/SpeciesInformation.kt", "starwars").isFile) + assertTrue(dir.generatedSource("githunt/FeedQuery.kt", "githunt").isFile) + assertTrue(dir.generatedSource("githunt/fragment/RepositoryFragment.kt", "githunt").isFile) } } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/OperationIdGeneratorTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/OperationIdGeneratorTests.kt similarity index 83% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/OperationIdGeneratorTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/OperationIdGeneratorTests.kt index 6a8d244fcfc..57e84029901 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/OperationIdGeneratorTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/OperationIdGeneratorTests.kt @@ -6,7 +6,7 @@ import org.junit.Assert import org.junit.Test import util.TestUtils import util.TestUtils.withTestProject -import util.generatedChild +import util.generatedSource import util.replaceInText import java.io.File @@ -20,7 +20,7 @@ class OperationIdGeneratorTests { val appDir = dir.resolve("app") Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":app:generateServiceApolloSources")!!.outcome) - Truth.assertThat(appDir.generatedChild("service/com/example/GreetingQuery.kt").readText()) + Truth.assertThat(appDir.generatedSource("com/example/GreetingQuery.kt").readText()) .contains("OPERATION_ID: String = \"GreetingCustomId\"") // Change the implementation of the operation ID generator and check again @@ -30,7 +30,7 @@ class OperationIdGeneratorTests { Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":app:generateServiceApolloSources")!!.outcome) - Truth.assertThat(appDir.generatedChild("service/com/example/GreetingQuery.kt").readText()) + Truth.assertThat(appDir.generatedSource("com/example/GreetingQuery.kt").readText()) .contains("anotherCustomId") } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/RegisterOperationsTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/RegisterOperationsTests.kt similarity index 80% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/RegisterOperationsTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/RegisterOperationsTests.kt index c7f44b836fc..4ea99132a95 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/RegisterOperationsTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/RegisterOperationsTests.kt @@ -7,13 +7,13 @@ import org.junit.Test class RegisterOperationsTests { @Test - fun `operation output is parsed correctly`() { + fun `simpleTest`() { TestUtils.withTestProject("register-operations") { dir -> try { TestUtils.executeTask("registerServiceApolloOperations", dir) } catch (e: UnexpectedBuildFailure) { // because there's no API key, this test will fail but that'll at least verify that we reach that point - Truth.assertThat(e.message).contains("Cannot push operations") + Truth.assertThat(e.message).contains("Cannot upload persisted query list") } } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/SchemaResolutionTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/SchemaResolutionTests.kt similarity index 92% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/SchemaResolutionTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/SchemaResolutionTests.kt index 7806bdfe095..736e9971200 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/SchemaResolutionTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/SchemaResolutionTests.kt @@ -4,7 +4,7 @@ package test import util.TestUtils import util.TestUtils.executeTask import util.TestUtils.withProject -import util.generatedChild +import util.generatedSource import com.google.common.truth.Truth.assertThat import org.gradle.testkit.runner.UnexpectedBuildFailure import org.junit.Assert.assertTrue @@ -18,7 +18,7 @@ class SchemaResolutionTests { fun `when SDL schema assert implicitly resolved and generates classes`() { val apolloConfiguration = """ apollo { - service("api") { + service("service") { packageNamesFromFilePaths() } } @@ -40,7 +40,7 @@ class SchemaResolutionTests { executeTask("generateApolloSources", projectDir) - assertTrue(projectDir.generatedChild("api/FeedRepositoryQuery.kt").isFile) + assertTrue(projectDir.generatedSource("FeedRepositoryQuery.kt").isFile) } } @@ -48,7 +48,7 @@ class SchemaResolutionTests { fun `when SDL schema set explicitly assert generates classes`() { val apolloConfiguration = """ apollo { - service("api") { + service("service") { packageNamesFromFilePaths() schemaFiles.from(file("src/main/graphql/schema.sdl")) } @@ -69,7 +69,7 @@ class SchemaResolutionTests { executeTask("generateApolloSources", projectDir) - assertTrue(projectDir.generatedChild("api/FeedRepositoryQuery.kt").isFile) + assertTrue(projectDir.generatedSource("FeedRepositoryQuery.kt").isFile) } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ServiceTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/ServiceTests.kt similarity index 77% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ServiceTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/ServiceTests.kt index 7f1de49eb73..9360655d7f0 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/ServiceTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/ServiceTests.kt @@ -4,7 +4,7 @@ import util.TestUtils import util.TestUtils.fixturesDirectory import util.TestUtils.withSimpleProject import util.TestUtils.withTestProject -import util.generatedChild +import util.generatedSource import util.replaceInText import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome @@ -30,7 +30,7 @@ class ServiceTests { } """.trimIndent()) { dir -> TestUtils.executeTask("generateApolloSources", dir) - TestUtils.assertFileContains(dir, "service/com/example/type/DateTime.kt", "\"java.util.Date\"") + TestUtils.assertFileContains(dir, "com/example/type/DateTime.kt", "\"java.util.Date\"") } } @@ -53,22 +53,6 @@ class ServiceTests { } } - - @Test - fun canConfigureOutputDir() { - withSimpleProject(""" - apollo { - service("service") { - packageNamesFromFilePaths() - outputDir.set(file("build/apollo")) - } - } - """.trimIndent()) { dir -> - TestUtils.executeTask("generateApolloSources", dir) - assertTrue(File(dir, "build/apollo/com/example/type/DateTime.kt").exists()) - } - } - @Test fun `useSemanticNaming defaults to true`() { withSimpleProject(""" @@ -79,7 +63,7 @@ class ServiceTests { } """.trimIndent()) { dir -> TestUtils.executeTask("generateApolloSources", dir) - TestUtils.assertFileContains(dir, "service/com/example/DroidDetailsQuery.kt", "class DroidDetailsQuery") + TestUtils.assertFileContains(dir, "com/example/DroidDetailsQuery.kt", "class DroidDetailsQuery") } } @@ -94,7 +78,7 @@ class ServiceTests { } """.trimIndent()) { dir -> TestUtils.executeTask("generateApolloSources", dir) - TestUtils.assertFileContains(dir, "service/com/example/DroidDetails.kt", "class DroidDetails") + TestUtils.assertFileContains(dir, "com/example/DroidDetails.kt", "class DroidDetails") } } @@ -108,9 +92,9 @@ class ServiceTests { } """.trimIndent()) { dir -> TestUtils.executeTask("generateApolloSources", dir) - assertTrue(dir.generatedChild("service/com/starwars/DroidDetailsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/starwars/type/DateTime.kt").isFile) - assertTrue(dir.generatedChild("service/com/starwars/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("com/starwars/DroidDetailsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/starwars/type/DateTime.kt").isFile) + assertTrue(dir.generatedSource("com/starwars/fragment/SpeciesInformation.kt").isFile) } } @@ -119,14 +103,14 @@ class ServiceTests { val schema = File(System.getProperty("user.dir"), "testFiles/starwars/schema.json") withSimpleProject(""" apollo { - service("starwars") { + service("service") { schemaFiles.from(file("${schema.absolutePath}")) packageName.set("com.example") } } """.trimIndent()) { dir -> TestUtils.executeTask("generateApolloSources", dir) - TestUtils.assertFileContains(dir, "starwars/com/example/DroidDetailsQuery.kt", "class DroidDetailsQuery") + TestUtils.assertFileContains(dir, "com/example/DroidDetailsQuery.kt", "class DroidDetailsQuery") } } @@ -146,7 +130,7 @@ class ServiceTests { TestUtils.executeTask("generateApolloSources", dir) - assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) } } @@ -241,12 +225,12 @@ class ServiceTests { } @Test - fun `operationOutput uses same id as the query`() { + fun `persistedQueryManifest uses same id as the query`() { withSimpleProject(""" apollo { service("service") { packageNamesFromFilePaths() - generateOperationOutput.set(true) + operationManifestFormat.set("persistedQueryManifest") } } """.trimIndent()) { dir -> @@ -254,24 +238,24 @@ class ServiceTests { assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) val expectedOperationId = "292319c237e71c9dfec7a7d7f993e9c91bd81361a786f251840e105f4b6c9145" - val operationOutput = File(dir, "build/generated/manifest/apollo/service/operationOutput.json") + val operationOutput = File(dir, "build/generated/manifest/apollo/service/persistedQueryManifest.json") Truth.assertThat(operationOutput.readText()).contains(expectedOperationId) - val queryJavaFile = dir.generatedChild("service/com/example/DroidDetailsQuery.kt") + val queryJavaFile = dir.generatedSource("com/example/DroidDetailsQuery.kt") Truth.assertThat(queryJavaFile.readText()).contains(expectedOperationId) } } @Test - fun `operationOutputFile carries task dependencies`() { + fun `operationManifest carries task dependencies`() { withSimpleProject(""" apollo { service("service") { - generateOperationOutput.set(true) + operationManifestFormat.set("persistedQueryManifest") packageNamesFromFilePaths() - operationOutputConnection { + operationManifestConnection { tasks.register("customTaskService") { - inputs.file(operationOutputFile) + inputs.file(manifest) } } } @@ -296,7 +280,7 @@ class ServiceTests { TestUtils.executeTask("generateApolloSources", dir) - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").isFile) } } @@ -313,7 +297,7 @@ class ServiceTests { TestUtils.executeTask("generateApolloSources", dir) - assertTrue(dir.generatedChild("service/example/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("example/fragment/SpeciesInformation.kt").isFile) } } @@ -322,7 +306,7 @@ class ServiceTests { withTestProject("testSourceSet") { dir -> TestUtils.executeTask("build", dir) - assertTrue(dir.generatedChild("service/com/example/GreetingQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/GreetingQuery.kt").isFile) assertTrue(File(dir, "build/libs/testSourceSet.jar").isFile) } } @@ -349,14 +333,14 @@ class ServiceTests { TestUtils.executeTask("build", dir) - assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) - Truth.assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText()).contains("internal class") + assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) + Truth.assertThat(dir.generatedSource("com/example/DroidDetailsQuery.kt").readText()).contains("internal class") - assertTrue(dir.generatedChild("service/com/example/type/DateTime.kt").isFile) - Truth.assertThat(dir.generatedChild("service/com/example/type/DateTime.kt").readText()).contains("internal class DateTime") + assertTrue(dir.generatedSource("com/example/type/DateTime.kt").isFile) + Truth.assertThat(dir.generatedSource("com/example/type/DateTime.kt").readText()).contains("internal class DateTime") - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) - Truth.assertThat(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").readText()).contains("internal data class") + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").isFile) + Truth.assertThat(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").readText()).contains("internal data class") } } @@ -364,7 +348,7 @@ class ServiceTests { fun `when generateFragmentImplementations is not set, it defaults to false`() { withSimpleProject { dir -> TestUtils.executeTask("generateApolloSources", dir) - assertFalse(dir.generatedChild("service/com/example/fragment/SpeciesInformationImpl.kt").exists()) + assertFalse(dir.generatedSource("com/example/fragment/SpeciesInformationImpl.kt").exists()) } } @@ -379,7 +363,7 @@ class ServiceTests { } """.trimIndent()) { dir -> TestUtils.executeTask("generateApolloSources", dir) - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformationImpl.kt").isFile) + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformationImpl.kt").isFile) } } } diff --git a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/UpToDateTests.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/test/UpToDateTests.kt similarity index 77% rename from libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/UpToDateTests.kt rename to libraries/apollo-gradle-plugin/src/test/kotlin/test/UpToDateTests.kt index 5ddb2452233..cac8e4ddea5 100644 --- a/libraries/apollo-gradle-plugin/src/test-java17/kotlin/test/UpToDateTests.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/test/UpToDateTests.kt @@ -3,7 +3,7 @@ package test import util.TestUtils import util.TestUtils.withSimpleProject -import util.generatedChild +import util.generatedSource import util.replaceInText import com.google.common.truth.Truth import org.gradle.testkit.runner.TaskOutcome @@ -28,9 +28,9 @@ class UpToDateTests { assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) // Java classes generated successfully - assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/FilmsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").isFile) } private fun `nothing changed, task up to date`(dir: File) { @@ -39,9 +39,9 @@ class UpToDateTests { assertEquals(TaskOutcome.UP_TO_DATE, result.task(":generateApolloSources")!!.outcome) // Java classes generated successfully - assertTrue(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/FilmsQuery.kt").isFile) - assertTrue(dir.generatedChild("service/com/example/fragment/SpeciesInformation.kt").isFile) + assertTrue(dir.generatedSource("com/example/DroidDetailsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/FilmsQuery.kt").isFile) + assertTrue(dir.generatedSource("com/example/fragment/SpeciesInformation.kt").isFile) } private fun `adding a custom scalar to the build script re-generates the CustomScalars`(dir: File) { @@ -56,7 +56,7 @@ class UpToDateTests { // and the task should run again assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) - TestUtils.assertFileContains(dir, "service/com/example/type/DateTime.kt", "\"java.util.Date\"") + TestUtils.assertFileContains(dir, "com/example/type/DateTime.kt", "\"java.util.Date\"") File(dir, "build.gradle").replaceInText("mapScalar(\"DateTime\", \"java.util.Date\")", "") } @@ -67,14 +67,14 @@ class UpToDateTests { var result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) - Truth.assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText()).contains("classification") + Truth.assertThat(dir.generatedSource("com/example/DroidDetailsQuery.kt").readText()).contains("classification") File(dir, "src/main/graphql/com/example/DroidDetails.graphql").replaceInText("classification", "") result = TestUtils.executeTask("generateApolloSources", dir, "-i") assertEquals(TaskOutcome.SUCCESS, result.task(":generateApolloSources")!!.outcome) - Truth.assertThat(dir.generatedChild("service/com/example/DroidDetailsQuery.kt").readText()).doesNotContain("classification") + Truth.assertThat(dir.generatedSource("com/example/DroidDetailsQuery.kt").readText()).doesNotContain("classification") } } diff --git a/libraries/apollo-gradle-plugin/src/test/kotlin/util/TestUtils.kt b/libraries/apollo-gradle-plugin/src/test/kotlin/util/TestUtils.kt index 0b47e0df37b..550e06a117a 100644 --- a/libraries/apollo-gradle-plugin/src/test/kotlin/util/TestUtils.kt +++ b/libraries/apollo-gradle-plugin/src/test/kotlin/util/TestUtils.kt @@ -198,7 +198,7 @@ object TestUtils { } fun assertFileContains(projectDir: File, path: String, content: String) { - val text = projectDir.generatedChild(path).readText() + val text = projectDir.generatedSource(path).readText() Truth.assertThat(text).contains(content) } @@ -210,7 +210,7 @@ object TestUtils { } } -fun File.generatedChild(path: String) = File(this, "build/generated/source/apollo/$path") +fun File.generatedSource(path: String, serviceName: String = "service") = File(this, "build/generated/source/apollo/${serviceName}").resolve(path) fun File.replaceInText(oldValue: String, newValue: String) { val text = readText() diff --git a/libraries/apollo-gradle-plugin/testProjects/gradle-min-version/build.gradle.kts b/libraries/apollo-gradle-plugin/testProjects/gradle-min-version/build.gradle.kts index 3d7834eaa14..c488bee0c3d 100644 --- a/libraries/apollo-gradle-plugin/testProjects/gradle-min-version/build.gradle.kts +++ b/libraries/apollo-gradle-plugin/testProjects/gradle-min-version/build.gradle.kts @@ -22,6 +22,7 @@ repositories { url = uri("../../../../build/localMaven") } mavenCentral() + // Uncomment this one to use the Kotlin "dev" repository // maven("https://redirector.kotlinlang.org/maven/dev/") } diff --git a/libraries/apollo-gradle-plugin/testProjects/register-operations/build.gradle.kts b/libraries/apollo-gradle-plugin/testProjects/register-operations/build.gradle.kts index 126d713aafb..717871ab81d 100644 --- a/libraries/apollo-gradle-plugin/testProjects/register-operations/build.gradle.kts +++ b/libraries/apollo-gradle-plugin/testProjects/register-operations/build.gradle.kts @@ -11,9 +11,10 @@ dependencies { apollo { service("service") { packageName.set("com.example") - operationManifestFormat.set("operationOutput") + operationManifestFormat.set("persistedQueryManifest") registerOperations { key.set("unused") + listId.set("unused") graph.set("unused") graphVariant.set("current") } diff --git a/settings.gradle.kts b/settings.gradle.kts index 259b6e6d43e..84d75879b4d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,4 +38,3 @@ dependencyResolutionManagement { apply(from = "./gradle/repositories.gradle.kts") apply(from = "./gradle/ge.gradle") - diff --git a/tests/build.gradle.kts b/tests/build.gradle.kts index cf85aaad970..57b1ce3465b 100644 --- a/tests/build.gradle.kts +++ b/tests/build.gradle.kts @@ -2,6 +2,11 @@ plugins { id("build.logic") apply false } +buildscript { + dependencies { + classpath("com.apollographql.apollo:apollo-gradle-plugin") + } +} val ciBuild = tasks.register("ciBuild") { description = """Execute the 'build' task in subprojects and the `termination:run` task too""" subprojects { diff --git a/tests/compiler-plugins/app/build.gradle.kts b/tests/compiler-plugins/app/build.gradle.kts index b3b7454e7df..f06d38e1f54 100644 --- a/tests/compiler-plugins/app/build.gradle.kts +++ b/tests/compiler-plugins/app/build.gradle.kts @@ -1,7 +1,6 @@ @file:OptIn(ApolloExperimental::class) import com.apollographql.apollo.annotations.ApolloExperimental -import com.apollographql.apollo.compiler.MODELS_RESPONSE_BASED plugins { id("org.jetbrains.kotlin.jvm") @@ -45,7 +44,7 @@ apollo { srcDir("src/main/graphql/default") } "customflatten" -> { - codegenModels.set(MODELS_RESPONSE_BASED) + codegenModels.set("responseBased") srcDir(dir.resolve("src/main/graphql")) } else -> { diff --git a/tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/TestPlugin.kt b/tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/DefaultToNullPlugin.kt similarity index 97% rename from tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/TestPlugin.kt rename to tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/DefaultToNullPlugin.kt index 878d937e9be..80bf940fe40 100644 --- a/tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/TestPlugin.kt +++ b/tests/compiler-plugins/default-null-values/src/main/kotlin/hooks/DefaultToNullPlugin.kt @@ -8,7 +8,7 @@ import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.TypeSpec -class TestPlugin: ApolloCompilerPlugin { +class DefaultToNullPlugin: ApolloCompilerPlugin { override fun beforeCompilationStep( environment: ApolloCompilerPluginEnvironment, registry: ApolloCompilerRegistry, diff --git a/tests/compiler-plugins/default-null-values/src/main/resources/META-INF/services/com.apollographql.apollo.compiler.ApolloCompilerPlugin b/tests/compiler-plugins/default-null-values/src/main/resources/META-INF/services/com.apollographql.apollo.compiler.ApolloCompilerPlugin index f9d9be73fdf..fbb2ee566e1 100644 --- a/tests/compiler-plugins/default-null-values/src/main/resources/META-INF/services/com.apollographql.apollo.compiler.ApolloCompilerPlugin +++ b/tests/compiler-plugins/default-null-values/src/main/resources/META-INF/services/com.apollographql.apollo.compiler.ApolloCompilerPlugin @@ -1 +1 @@ -hooks.TestPlugin \ No newline at end of file +hooks.DefaultToNullPlugin diff --git a/tests/compiler-plugins/schema-codegen/src/main/kotlin/schema/TestPlugin.kt b/tests/compiler-plugins/schema-codegen/src/main/kotlin/schema/TestPlugin.kt index 1ff33120567..f1fcc4df99c 100644 --- a/tests/compiler-plugins/schema-codegen/src/main/kotlin/schema/TestPlugin.kt +++ b/tests/compiler-plugins/schema-codegen/src/main/kotlin/schema/TestPlugin.kt @@ -6,9 +6,9 @@ import com.apollographql.apollo.ast.ForeignSchema import com.apollographql.apollo.ast.GQLIntValue import com.apollographql.apollo.ast.GQLTypeDefinition import com.apollographql.apollo.ast.parseAsGQLDocument +import com.apollographql.apollo.compiler.ApolloCompiler import com.apollographql.apollo.compiler.ApolloCompilerPlugin import com.apollographql.apollo.compiler.ApolloCompilerPluginEnvironment -import com.apollographql.apollo.compiler.ApolloCompilerPluginLogger import com.apollographql.apollo.compiler.ApolloCompilerPluginProvider import com.apollographql.apollo.compiler.ApolloCompilerRegistry import com.squareup.kotlinpoet.ClassName @@ -18,12 +18,8 @@ import okio.buffer import okio.source class TestPlugin( - logger: ApolloCompilerPluginLogger, + logger: ApolloCompiler.Logger, ) : ApolloCompilerPlugin { - init { - logger.info("TestPlugin") - } - override fun beforeCompilationStep( environment: ApolloCompilerPluginEnvironment, registry: ApolloCompilerRegistry, diff --git a/tests/gradle.properties b/tests/gradle.properties index 85b1ed4d4b9..747cecc93ee 100644 --- a/tests/gradle.properties +++ b/tests/gradle.properties @@ -16,3 +16,6 @@ ksp.allow.all.target.configuration=false # https://kotlinlang.slack.com/archives/C0B8L3U69/p1740063113894839 kotlin.js.yarn=false + +# https://github.com/gradle/gradle/issues/31278 +kotlin.internal.collectFUSMetrics=false \ No newline at end of file diff --git a/tests/integration-tests/build.gradle.kts b/tests/integration-tests/build.gradle.kts index 9f0befe249a..ed1b409061d 100644 --- a/tests/integration-tests/build.gradle.kts +++ b/tests/integration-tests/build.gradle.kts @@ -1,5 +1,3 @@ -import com.apollographql.apollo.compiler.MANIFEST_PERSISTED_QUERY - plugins { id("org.jetbrains.kotlin.multiplatform") id("com.apollographql.apollo") @@ -54,7 +52,7 @@ fun configureApollo(generateKotlinModels: Boolean) { service("${it.name}-$extra") { when (it.name) { "httpcache" -> { - operationManifestFormat.set(MANIFEST_PERSISTED_QUERY) + operationManifestFormat.set("persistedQueryManifest") if (generateKotlinModels) { mapScalarToKotlinString("Date") } else { diff --git a/tests/integration-tests/src/jvmTest/kotlin/test/OperationOutputTest.kt b/tests/integration-tests/src/jvmTest/kotlin/test/OperationOutputTest.kt deleted file mode 100644 index b4af71064a4..00000000000 --- a/tests/integration-tests/src/jvmTest/kotlin/test/OperationOutputTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -package test - -import com.apollographql.apollo.integration.httpcache.AllFilmsQuery -import com.apollographql.apollo.testing.HostFileSystem -import com.apollographql.apollo.testing.pathToUtf8 -import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.jsonArray -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -import okio.Path.Companion.toPath -import okio.buffer -import org.junit.Test -import kotlin.test.assertEquals - -/** - * These tests read the operationOutput.json generated during compilation and compare it to the generated models - * - * This makes sure minification is the same between operationOutput.json and the models - * - * This is a JVM only test because we need to assume "http-kotlin" for the service name - * where the file will be generated. Apple code shouldn't be much different in all cases - */ -class OperationOutputTest { - @Test - fun operationOutputMatchesTheModels() { - @Suppress("DEPRECATION") val operationOutput = pathToUtf8("integration-tests/build/generated/manifest/apollo/httpcache-kotlin/persistedQueryManifest.json") - val source = Json.parseToJsonElement(operationOutput).jsonObject - .getValue("operations") - .jsonArray - .filterIsInstance() - .single { element -> - element.get("name")!!.jsonPrimitive.content == "AllFilms" - } - .get("body")!! - .jsonPrimitive - .content - - assertEquals(AllFilmsQuery().document(), source) - } -} \ No newline at end of file diff --git a/tests/platform-api/build.gradle.kts b/tests/platform-api/build.gradle.kts index 24a163f0517..f141f72fd6d 100644 --- a/tests/platform-api/build.gradle.kts +++ b/tests/platform-api/build.gradle.kts @@ -1,5 +1,4 @@ import com.android.build.gradle.internal.tasks.factory.dependsOn -import com.apollographql.apollo.gradle.internal.ApolloPushSchemaTask plugins { id("org.jetbrains.kotlin.jvm") @@ -42,22 +41,12 @@ apollo { } if (apiKey != null) { - tasks.named("pushApolloSchema") { - key.set(apiKey) - graph.set("Apollo-Kotlin-CI-tests") - subgraph.set("subgraph1") - schema.set("platform-api/src/main/graphql/schema.graphqls") - revision.set("1") - graphVariant.set("current") - } - tasks.named("generateServiceApolloSources").dependsOn("downloadServiceApolloSchemaFromRegistry") tasks.register("platformApiTests") { description = "Execute Platform API tests" dependsOn("registerServiceApolloOperations") dependsOn("downloadServiceApolloSchemaFromRegistry") - dependsOn("pushApolloSchema") dependsOn("test") } } diff --git a/tests/schema-transform/app/build.gradle.kts b/tests/schema-transform/app/build.gradle.kts index b801ecc62ba..140bf8048d1 100644 --- a/tests/schema-transform/app/build.gradle.kts +++ b/tests/schema-transform/app/build.gradle.kts @@ -1,7 +1,6 @@ @file:OptIn(ApolloExperimental::class) import com.apollographql.apollo.annotations.ApolloExperimental -import com.apollographql.apollo.compiler.MODELS_RESPONSE_BASED plugins { id("org.jetbrains.kotlin.jvm") From 35fe9085ad17ad6cd41f03e43533f4f5ee95c4c8 Mon Sep 17 00:00:00 2001 From: Martin Bonnin Date: Fri, 13 Jun 2025 16:03:12 +0200 Subject: [PATCH 2/2] remove unused file --- .../apollo/gradle/internal/ApolloBuildService.kt | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt diff --git a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt b/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt deleted file mode 100644 index bc282fe2612..00000000000 --- a/libraries/apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo/gradle/internal/ApolloBuildService.kt +++ /dev/null @@ -1,8 +0,0 @@ -package com.apollographql.apollo.gradle.internal - -import org.gradle.api.file.FileCollection -import org.gradle.api.services.BuildService -import org.gradle.api.services.BuildServiceParameters -import java.net.URI -import java.net.URLClassLoader -