├── sample
├── settings.gradle
├── gradle.properties
├── src
│ └── main
│ │ └── kgql
│ │ └── com
│ │ └── codingfeline
│ │ └── kgql
│ │ └── sample
│ │ └── viewer.graphql
└── build.gradle
├── kgql-gradle-plugin
├── src
│ ├── test
│ │ ├── kotlin-mpp
│ │ │ ├── settings.gradle
│ │ │ ├── src
│ │ │ │ ├── main
│ │ │ │ │ └── kgql
│ │ │ │ │ │ └── com
│ │ │ │ │ │ └── sample
│ │ │ │ │ │ ├── Viewer.gql
│ │ │ │ │ │ ├── User.gql
│ │ │ │ │ │ └── QueryWithParam.graphql
│ │ │ │ └── commonMain
│ │ │ │ │ └── kotlin
│ │ │ │ │ └── com
│ │ │ │ │ └── sample
│ │ │ │ │ └── data
│ │ │ │ │ └── UserProfile.kt
│ │ │ └── build.gradle
│ │ ├── no-kotlin
│ │ │ ├── settings.gradle
│ │ │ └── build.gradle
│ │ ├── library-project
│ │ │ ├── settings.gradle
│ │ │ ├── src
│ │ │ │ └── main
│ │ │ │ │ └── AndroidManifest.xml
│ │ │ └── build.gradle
│ │ ├── no-kotlin-android
│ │ │ ├── settings.gradle
│ │ │ └── build.gradle
│ │ ├── kotlin-mpp-android-ios
│ │ │ ├── settings.gradle
│ │ │ ├── src
│ │ │ │ ├── main
│ │ │ │ │ └── kgql
│ │ │ │ │ │ └── com
│ │ │ │ │ │ └── sample
│ │ │ │ │ │ ├── Viewer.gql
│ │ │ │ │ │ ├── User.gql
│ │ │ │ │ │ └── QueryWithParam.gql
│ │ │ │ ├── commonMain
│ │ │ │ │ └── kotlin
│ │ │ │ │ │ └── com
│ │ │ │ │ │ └── sample
│ │ │ │ │ │ └── data
│ │ │ │ │ │ └── UserProfile.kt
│ │ │ │ └── androidMain
│ │ │ │ │ └── AndroidManifest.xml
│ │ │ ├── gradle.properties
│ │ │ └── build.gradle
│ │ ├── kotlin-mpp-no-serialization
│ │ │ ├── settings.gradle
│ │ │ └── build.gradle
│ │ ├── kotlin
│ │ │ └── com
│ │ │ │ └── codingfeline
│ │ │ │ └── kgql
│ │ │ │ └── gradle
│ │ │ │ ├── IosTest.kt
│ │ │ │ ├── AndroidTestUtil.kt
│ │ │ │ └── KgqlPluginTest.kt
│ │ └── settings.gradle
│ └── main
│ │ └── kotlin
│ │ └── com
│ │ └── codingfeline
│ │ └── kgql
│ │ └── gradle
│ │ ├── KgqlExtension.kt
│ │ ├── android
│ │ └── PackageName.kt
│ │ ├── KgqlTask.kt
│ │ ├── KgqlConfig.kt
│ │ ├── KgqlPlugin.kt
│ │ └── kotlin
│ │ └── SourceRoots.kt
├── gradle.properties
└── build.gradle
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── maven-publish.gradle
└── libs.versions.toml
├── release.sh
├── kgql-compiler
├── gradle.properties
├── src
│ ├── main
│ │ └── kotlin
│ │ │ └── com
│ │ │ └── codingfeline
│ │ │ └── kgql
│ │ │ └── compiler
│ │ │ ├── KgqlException.kt
│ │ │ ├── KgqlFileType.kt
│ │ │ ├── Constants.kt
│ │ │ ├── KgqlFile.kt
│ │ │ ├── KgqlCustomTypeMapper.kt
│ │ │ ├── generator
│ │ │ ├── DocumentWrapperGenerator.kt
│ │ │ ├── KgqlCompiler.kt
│ │ │ ├── VariablesWrapperGenerator.kt
│ │ │ ├── RequestBodyGenerator.kt
│ │ │ └── OperationWrapperGenerator.kt
│ │ │ └── KgqlEnvironment.kt
│ └── test
│ │ └── kotlin
│ │ └── com
│ │ └── codingfeline
│ │ └── kgql
│ │ └── compiler
│ │ └── DocumentWrapperTest.kt
└── build.gradle
├── kgql-core
├── gradle.properties
├── src
│ └── commonMain
│ │ └── kotlin
│ │ └── com
│ │ └── codingfeline
│ │ └── kgql
│ │ └── core
│ │ ├── KgqlRequestBody.kt
│ │ └── KgqlResponse.kt
└── build.gradle
├── .idea
└── codeStyles
│ ├── codeStyleConfig.xml
│ └── Project.xml
├── settings.gradle
├── test-util
├── build.gradle
└── src
│ └── main
│ └── kotlin
│ └── com
│ └── codingfeline
│ └── kgql
│ └── test
│ └── util
│ ├── TestEnvironment.kt
│ └── FixtureCompiler.kt
├── .github
├── FUNDING.yml
└── workflows
│ ├── pullrequest.yml
│ └── release.yml
├── gradle.properties
├── .gitignore
├── RELEASING.md
├── gradlew.bat
├── CHANGELOG.md
├── README.md
├── gradlew
└── LICENSE
/sample/settings.gradle:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp/settings.gradle:
--------------------------------------------------------------------------------
1 | apply from: "../settings.gradle"
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/no-kotlin/settings.gradle:
--------------------------------------------------------------------------------
1 | apply from: "../settings.gradle"
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/library-project/settings.gradle:
--------------------------------------------------------------------------------
1 | apply from: "../settings.gradle"
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/no-kotlin-android/settings.gradle:
--------------------------------------------------------------------------------
1 | apply from: "../settings.gradle"
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/settings.gradle:
--------------------------------------------------------------------------------
1 | apply from: "../settings.gradle"
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-no-serialization/settings.gradle:
--------------------------------------------------------------------------------
1 | apply from: "../settings.gradle"
--------------------------------------------------------------------------------
/sample/gradle.properties:
--------------------------------------------------------------------------------
1 | org.gradle.jvmargs=-Xmx3g -XX:MaxPermSize=2048m -XX:+CMSClassUnloadingEnabled
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/yshrsmz/kgql/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/library-project/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/sample/src/main/kgql/com/codingfeline/kgql/sample/viewer.graphql:
--------------------------------------------------------------------------------
1 | query {
2 | viewer {
3 | login
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp/src/main/kgql/com/sample/Viewer.gql:
--------------------------------------------------------------------------------
1 | query {
2 | viewer {
3 | login
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/release.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ./gradlew clean build publish :kgql-gradle-plugin:publishPlugins --no-daemon --no-parallel
4 |
--------------------------------------------------------------------------------
/kgql-compiler/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=compiler
2 | POM_NAME=Kgql Compiler
3 | POM_DESCRIPTION=Kgql Compiler
4 | POM_PACKAGING=jar
5 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/src/main/kgql/com/sample/Viewer.gql:
--------------------------------------------------------------------------------
1 | query {
2 | viewer {
3 | login
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin/com/codingfeline/kgql/gradle/IosTest.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle
2 |
3 | interface IosTest {
4 | }
5 |
--------------------------------------------------------------------------------
/kgql-core/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=core
2 | POM_NAME=Kgql Multiplatform Runtime (Experimental)
3 | POM_DESCRIPTION=Multiplatform runtime library to support generated code
4 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/KgqlException.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | class KgqlException(message: String) : IllegalStateException(message)
4 |
--------------------------------------------------------------------------------
/gradle/maven-publish.gradle:
--------------------------------------------------------------------------------
1 | publishing {
2 | repositories {
3 | maven {
4 | name = "testMaven"
5 | url = "${rootProject.buildDir}/localMaven"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/gradle.properties:
--------------------------------------------------------------------------------
1 | POM_ARTIFACT_ID=gradle-plugin
2 | POM_NAME=Kgql Gradle Plugin
3 | POM_DESCRIPTION=Gradle plugin for generating Kotlin interfaces for GraphQL document files
4 | POM_PACKAGING=jar
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp/src/commonMain/kotlin/com/sample/data/UserProfile.kt:
--------------------------------------------------------------------------------
1 | package com.sample.data
2 |
3 | import kotlinx.serialization.Serializable
4 |
5 | @Serializable
6 | class UserProfile
7 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/settings.gradle:
--------------------------------------------------------------------------------
1 | dependencyResolutionManagement {
2 | versionCatalogs {
3 | libs {
4 | from(files("../../../gradle/libs.versions.toml"))
5 | }
6 | }
7 | }
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 | #
3 | # Android
4 | android.useAndroidX=true
5 | android.enableJetifier=true
6 | #android.enableUnitTestBinaryResources=true
7 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/src/commonMain/kotlin/com/sample/data/UserProfile.kt:
--------------------------------------------------------------------------------
1 | package com.sample.data
2 |
3 | import kotlinx.serialization.Serializable
4 |
5 | @Serializable
6 | class UserProfile
7 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/KgqlFileType.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | object KgqlFileType {
4 | val EXTENSIONS = arrayOf("gql", "graphql")
5 | const val FOLDER_NAME = "kgql"
6 | }
7 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/src/androidMain/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp/src/main/kgql/com/sample/User.gql:
--------------------------------------------------------------------------------
1 | query User($login: String!) {
2 | user(login: $login) {
3 | id
4 | login
5 | bio
6 | avatarUrl
7 | company
8 | createdAt
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/Constants.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | typealias GraphQLCustomTypeName = String
4 | typealias GraphQLCustomTypeFQName = String
5 |
6 | typealias Logger = (String) -> Unit
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/src/main/kgql/com/sample/User.gql:
--------------------------------------------------------------------------------
1 | query User($login: String!) {
2 | user(login: $login) {
3 | id
4 | login
5 | bio
6 | avatarUrl
7 | company
8 | createdAt
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/KgqlFile.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | import java.io.File
4 |
5 | data class KgqlFile(
6 | val packageName: String,
7 | val outputDirectory: File,
8 | val source: File
9 | )
10 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/no-kotlin/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.codingfeline.kgql'
3 | }
4 |
5 | repositories {
6 | maven {
7 | url "file://${projectDir.absolutePath}/../../../../build/localMaven"
8 | }
9 | mavenCentral()
10 | google()
11 | jcenter()
12 | }
13 |
--------------------------------------------------------------------------------
/kgql-core/src/commonMain/kotlin/com/codingfeline/kgql/core/KgqlRequestBody.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.core
2 |
3 | /**
4 | * Root interface for GraphQL request body
5 | */
6 | public interface KgqlRequestBody {
7 | public val operationName: String?
8 | public val query: String
9 | public val variables: T?
10 | }
11 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-no-serialization/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'kotlin-multiplatform'
3 | id 'com.codingfeline.kgql'
4 | }
5 |
6 | repositories {
7 | maven {
8 | url "file://${projectDir.absolutePath}/../../../../build/localMaven"
9 | }
10 | mavenCentral()
11 | google()
12 | jcenter()
13 | }
14 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | mavenCentral()
4 | google()
5 | gradlePluginPortal()
6 | }
7 | }
8 |
9 | include ':kgql-core'
10 | include ':kgql-compiler'
11 | include ':kgql-gradle-plugin'
12 | include ':test-util'
13 |
14 | rootProject.name = 'kgql'
15 |
16 | //enableFeaturePreview('STABLE_PUBLISHING')
17 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/no-kotlin-android/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'com.codingfeline.kgql'
4 | }
5 |
6 | repositories {
7 | maven {
8 | url "file://${projectDir.absolutePath}/../../../../build/localMaven"
9 | }
10 | mavenCentral()
11 | google()
12 | }
13 |
14 | android {
15 | compileSdkVersion versions.compileSdk
16 |
17 | lintOptions {
18 | textReport true
19 | }
20 | }
21 |
22 | kgql {
23 | schemaOutputDirectory = file('src/main/kgql/documents')
24 | }
25 |
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/library-project/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.library'
3 | id 'com.codingfeline.kgql'
4 | id 'org.jetbrains.kotlin.android'
5 | id 'kotlinx-serialization'
6 | }
7 |
8 | repositories {
9 | maven {
10 | url "file://${projectDir.absolutePath}/../../../../build/localMaven"
11 | }
12 | mavenCentral()
13 | google()
14 | jcenter()
15 | }
16 |
17 | android {
18 | namespace = "com.example.kgql"
19 | compileSdkVersion libs.versions.compileSdk.get() as int
20 |
21 | lintOptions {
22 | textReport true
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp/src/main/kgql/com/sample/QueryWithParam.graphql:
--------------------------------------------------------------------------------
1 | query User(
2 | $login: String!,
3 | $name: Int,
4 | $id: String = "",
5 | $company: String = null,
6 | $foo: Float,
7 | $logins: [String]) {
8 | user(login: $login) {
9 | id
10 | login
11 | bio
12 | avatarUrl
13 | company
14 | createdAt
15 | }
16 | }
17 |
18 | mutation withArbitraryType($user: UserProfile) {
19 | user(login: $login) {
20 | id
21 | login
22 | bio
23 | avatarUrl
24 | company
25 | createdAt
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/src/main/kgql/com/sample/QueryWithParam.gql:
--------------------------------------------------------------------------------
1 | query User(
2 | $id: ID!,
3 | $login: String!,
4 | $name: Int,
5 | $idstr: String = "",
6 | $company: String = null,
7 | $foo: Float,
8 | $logins: [String]) {
9 | user(login: $login) {
10 | id
11 | login
12 | bio
13 | avatarUrl
14 | company
15 | createdAt
16 | }
17 | }
18 |
19 | mutation withArbitraryType($user: UserProfile) {
20 | user(login: $login) {
21 | id
22 | login
23 | bio
24 | avatarUrl
25 | company
26 | createdAt
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/main/kotlin/com/codingfeline/kgql/gradle/KgqlExtension.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle
2 |
3 | import org.gradle.api.Project
4 | import org.gradle.api.file.FileCollection
5 |
6 | open class KgqlExtension {
7 | internal lateinit var project: Project
8 |
9 | var packageName: String? = null
10 | var sourceSet: FileCollection? = null
11 | var typeMapper: MutableMap? = null
12 |
13 | internal fun toConfig(): KgqlConfig {
14 | return KgqlConfig(
15 | project = project,
16 | packageName = packageName,
17 | sourceSet = sourceSet,
18 | typeMapper = typeMapper
19 | )
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/test-util/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'org.jetbrains.kotlin.jvm'
2 | apply plugin: 'kotlin'
3 |
4 | targetCompatibility = JavaVersion.VERSION_1_8
5 | sourceCompatibility = JavaVersion.VERSION_1_8
6 |
7 | dependencies {
8 | implementation project(':kgql-compiler')
9 |
10 | implementation libs.junit
11 | }
12 |
13 | compileKotlin {
14 | kotlinOptions.jvmTarget = "1.8"
15 | }
16 | compileTestKotlin {
17 | kotlinOptions.jvmTarget = "1.8"
18 | }
19 |
20 | // work around for https://youtrack.jetbrains.com/issue/KT-27059
21 | configurations.all {
22 | resolutionStrategy.dependencySubstitution {
23 | substitute module("${project.property("GROUP")}:core-jvm:${project.property("VERSION_NAME")}") with project(':kgql-core')
24 | }
25 | }
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: yshrsmz # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/main/kotlin/com/codingfeline/kgql/gradle/android/PackageName.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle.android
2 |
3 | import com.android.build.gradle.BaseExtension
4 | import org.gradle.api.GradleException
5 | import org.gradle.api.Project
6 |
7 | internal fun Project.packageName(): String {
8 | val androidExtensions = extensions.getByType(BaseExtension::class.java)
9 | return androidExtensions.namespace ?: throw GradleException(
10 | """
11 | |SqlDelight requires a package name to be set. This can be done via the android namespace:
12 | |
13 | |android {
14 | | namespace "com.sample.mygraphql"
15 | |}
16 | |
17 | |or the kgql configuration:
18 | |
19 | |kgql {
20 | | packageName = "com.sample.mygraphql"
21 | |}
22 | """.trimMargin()
23 | )
24 | }
25 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 | kotlin.js.compiler=both
3 | kotlin.mpp.stability.nowarn=true
4 | #
5 | GROUP=com.codingfeline.kgql
6 | VERSION_NAME=0.11.0
7 | #
8 | POM_URL=https://github.com/yshrsmz/kgql/
9 | POM_SCM_URL=https://github.com/yshrsmz/kgql/
10 | POM_SCM_CONNECTION=scm:git:git://github.com/yshrsmz/kgql.git
11 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/yshrsmz/kgql.git
12 | #
13 | POM_LICENCE_NAME=The Apache Software License, Version 2.0
14 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt
15 | POM_LICENCE_DIST=repo
16 | #
17 | POM_DEVELOPER_ID=yshrsmz
18 | POM_DEVELOPER_NAME=Yasuhiro Shimizu
19 | POM_DEVELOPER_URL=https://github.com/yshrsmz
20 | #
21 | SONATYPE_HOST=DEFAULT
22 | #
23 | org.gradle.jvmargs=-Xmx3g -XX:MaxPermSize=2048m -XX:+CMSClassUnloadingEnabled
24 | ## This a workaround for https://github.com/gradle/gradle/issues/11412
25 | systemProp.org.gradle.internal.publish.checksums.insecure=true
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Built application files
2 | *.apk
3 | *.ap_
4 |
5 | # Files for the ART/Dalvik VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # Generated files
12 | bin/
13 | gen/
14 | out/
15 | generated
16 |
17 | # Gradle files
18 | .gradle/
19 | build/
20 |
21 | # Local configuration file (sdk path, etc)
22 | local.properties
23 |
24 | # Proguard folder generated by Eclipse
25 | proguard/
26 |
27 | # Log Files
28 | *.log
29 |
30 | # Android Studio Navigation editor temp files
31 | .navigation/
32 |
33 | # Android Studio captures folder
34 | captures/
35 |
36 | # Android Studio
37 | *.iml
38 | *.iws
39 | *.ipr
40 | .idea/*
41 |
42 | # Keystore files
43 | *.jks
44 |
45 | # Eclipse project files
46 | .classpath
47 | .project
48 |
49 | ## Playgrounds
50 | timeline.xctimeline
51 | playground.xcworkspace
52 |
53 | #Because ugh
54 | .DS_Store
55 |
56 | secret.properties
57 |
58 | kotlin-js-store/
59 | !.idea/codeStyles/
60 | .envrc
61 | *-sec.asc
--------------------------------------------------------------------------------
/kgql-core/src/commonMain/kotlin/com/codingfeline/kgql/core/KgqlResponse.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.core
2 |
3 | import kotlinx.serialization.SerialName
4 | import kotlinx.serialization.Serializable
5 |
6 | /**
7 | * Root interface for GraphQL response
8 | */
9 | public interface KgqlResponse {
10 | public val data: T?
11 | public val errors: List?
12 | }
13 |
14 | /**
15 | * GraphQL error
16 | */
17 | @Serializable
18 | public data class KgqlError(
19 | @SerialName("message") val message: String,
20 | @SerialName("locations") val locations: List = emptyList(),
21 | @SerialName("description") val description: String,
22 | @SerialName("validationErrorType") val validationErrorType: String,
23 | @SerialName("queryPath") val queryPath: List = emptyList()
24 | )
25 |
26 | @Serializable
27 | public data class KgqlErrorLocation(
28 | @SerialName("line") val line: Int,
29 | @SerialName("column") val column: Int
30 | )
31 |
--------------------------------------------------------------------------------
/RELEASING.md:
--------------------------------------------------------------------------------
1 | RELEASING
2 | ===
3 |
4 | These environment variables should be available:
5 |
6 | ```
7 | export ORG_GRADLE_PROJECT_mavenCentralUsername=
8 | export ORG_GRADLE_PROJECT_mavenCentralPassword=
9 | export ORG_GRADLE_PROJECT_signingInMemoryKey=
10 | export ORG_GRADLE_PROJECT_signingInMemoryKeyPassword=
11 | export ORG_GRADLE_PROJECT_gradle.publish.key=
12 | export ORG_GRADLE_PROJECT_gradle.publish.secret=
13 | ```
14 |
15 | 1. Change the version in `gradle.properties` to a non-SNAPSHOT version
16 | 2. Update `CHANGELOG.md`
17 | 3. Update `README.md` with the new version
18 | 4. `git commit -am "Prepare for release vX.Y.Z."` (where X.Y.Z is the new version)
19 | 5. `sh ./release.sh`
20 | 6. Visit [oss.sonatype.org](https://oss.sonatype.org/#stagingRepositories) and promote the artifact.
21 | 7. Visit [Gradle Plugin Portal](https://plugins.gradle.org/) and promote the plugin.
22 | 8. `git tag -a vX.Y.Z -m "Version X.Y.Z"` (where X.Y.Z is the new version)
23 | 9. Change the version in `gradle.properties` to a new SNAPSHOT version
24 | 10. `git commit -am "Prepare for next development iteration"`
25 |
--------------------------------------------------------------------------------
/.github/workflows/pullrequest.yml:
--------------------------------------------------------------------------------
1 | name: Run Tests upon PullRequest
2 | on:
3 | pull_request:
4 | branches:
5 | - master
6 |
7 | jobs:
8 | build:
9 | name: Run Test Cases
10 | runs-on: macos-latest
11 | steps:
12 | - name: Checkout
13 | uses: actions/checkout@v2
14 |
15 | - uses: actions/cache@v1
16 | with:
17 | path: ~/.gradle/caches
18 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}-${{ hashFiles('**/libs.versions.toml') }}
19 | restore-keys: |
20 | ${{ runner.os }}-gradle-
21 | - name: Set up JDK 11
22 | uses: actions/setup-java@v2
23 | with:
24 | distribution: 'temurin'
25 | java-version: '11'
26 |
27 | - name: Execute test cases
28 | env:
29 | ORG_GRADLE_PROJECT_RELEASE_SIGNING_ENABLED: false
30 | run: ./gradlew test
31 |
32 | - name: Upload test results
33 | if: failure()
34 | uses: actions/upload-artifact@v2
35 | with:
36 | name: test-reports
37 | path: ./*/build/reports/tests/
38 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'org.jetbrains.kotlin.multiplatform'
3 | id 'kotlinx-serialization'
4 | id 'com.codingfeline.kgql'
5 | }
6 |
7 | repositories {
8 | maven {
9 | url "file://${projectDir.absolutePath}/../../../../build/localMaven"
10 | }
11 | mavenCentral()
12 | jcenter()
13 | }
14 |
15 | kgql {
16 | packageName = "com.sample"
17 | typeMapper = [
18 | "UserProfile": "com.sample.data.UserProfile"
19 | ]
20 | }
21 |
22 | kotlin {
23 | jvm()
24 | js(IR) {
25 | browser()
26 | nodejs()
27 | }
28 | ios() {
29 | binaries {
30 | framework()
31 | }
32 | }
33 |
34 | sourceSets {
35 | commonMain {
36 | dependencies {
37 | implementation libs.kotlin.serialization.json
38 | }
39 | }
40 | jvmMain {
41 | dependencies {
42 | }
43 | }
44 | jsMain {
45 | dependencies {
46 | }
47 | }
48 | iosMain {
49 | dependencies {
50 | }
51 | }
52 | iosTest {}
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/test-util/src/main/kotlin/com/codingfeline/kgql/test/util/TestEnvironment.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.test.util
2 |
3 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeFQName
4 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeName
5 | import com.codingfeline.kgql.compiler.KgqlEnvironment
6 | import java.io.File
7 | import java.nio.file.Files
8 | import java.nio.file.Path
9 | import java.nio.file.attribute.BasicFileAttributes
10 | import java.util.function.BiPredicate
11 | import java.util.stream.Collectors
12 |
13 | internal class TestEnvironment(private val outputDirectory: File = File("output")) {
14 |
15 | fun build(
16 | root: String,
17 | typeMap: Map = emptyMap()
18 | ): KgqlEnvironment {
19 | val files =
20 | Files.find(
21 | File(root).toPath(),
22 | Int.MAX_VALUE,
23 | BiPredicate { t: Path, _: BasicFileAttributes -> t.toString().endsWith(".gql") })
24 | .map { it.toFile() }
25 | .collect(Collectors.toList())
26 | return KgqlEnvironment(files, "com.example", outputDirectory, typeMap)
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/kgql-core/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.kotlin.multiplatform)
3 | alias(libs.plugins.kotlin.serialization)
4 | alias(libs.plugins.mavenPublish)
5 | alias(libs.plugins.dokka)
6 | }
7 |
8 | archivesBaseName = 'kgql-core'
9 |
10 | kotlin {
11 | jvm()
12 | js(IR) {
13 | browser()
14 | nodejs()
15 | }
16 | ios()
17 | iosSimulatorArm64()
18 |
19 | explicitApi()
20 |
21 | sourceSets {
22 | commonMain {
23 | dependencies {
24 | api libs.kotlin.serialization.json
25 | }
26 | }
27 | commonTest {
28 | dependencies {
29 | implementation libs.kotlin.test.common
30 | implementation libs.kotlin.test.annotations
31 | }
32 | }
33 | jvmMain {}
34 | jvmTest {}
35 | jsMain {}
36 | jsTest {}
37 | iosMain {}
38 | iosTest {}
39 | iosSimulatorArm64Main.dependsOn(iosMain)
40 | iosSimulatorArm64Test.dependsOn(iosTest)
41 | }
42 | }
43 |
44 | // TODO work around for https://youtrack.jetbrains.com/issue/KT-27170
45 | configurations {
46 | compileClasspath
47 | }
48 |
49 | apply from: "$rootDir/gradle/maven-publish.gradle"
50 |
--------------------------------------------------------------------------------
/kgql-compiler/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.kotlin.jvm)
3 | alias(libs.plugins.mavenPublish)
4 | alias(libs.plugins.dokka)
5 | }
6 |
7 | sourceSets {
8 | main.java.srcDir "gen"
9 | }
10 |
11 | dependencies {
12 | implementation project(':kgql-core')
13 | implementation libs.kotlin.serialization.json
14 |
15 | implementation libs.graphql
16 |
17 | implementation libs.kotlinPoet
18 |
19 | testImplementation libs.junit
20 | testImplementation libs.truth
21 | testImplementation project(':test-util')
22 | }
23 |
24 | task pluginVersion {
25 | def outputDir = file("gen")
26 |
27 | inputs.property 'version', version
28 | outputs.dir outputDir
29 |
30 | doLast {
31 | def versionFile = file("$outputDir/com/codingfeline/kgql/Version.kt")
32 | versionFile.parentFile.mkdirs()
33 | versionFile.text = """// Generated file. Do not edit!
34 | package com.codingfeline.kgql
35 |
36 | val VERSION = "${project.version}"
37 | """
38 | }
39 | }
40 |
41 | afterEvaluate {
42 | tasks.named('compileKotlin').configure { dependsOn('pluginVersion') }
43 | tasks.named('dokkaHtml').configure { dependsOn('pluginVersion') }
44 | tasks.named('javaSourcesJar').configure { dependsOn('pluginVersion') }
45 | }
46 |
47 | compileKotlin {
48 | kotlinOptions.jvmTarget = "1.8"
49 | }
50 | compileTestKotlin {
51 | kotlinOptions.jvmTarget = "1.8"
52 | }
53 |
54 | apply from: "$rootDir/gradle/maven-publish.gradle"
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin/com/codingfeline/kgql/gradle/AndroidTestUtil.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2016 Square, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.codingfeline.kgql.gradle
17 |
18 | import java.io.File
19 | import java.util.Properties
20 |
21 | internal fun androidHome(): String {
22 | val env = System.getenv("ANDROID_HOME")
23 | if (env != null) {
24 | return env
25 | }
26 | val localProp = File(File(System.getProperty("user.dir")).parentFile, "local.properties")
27 | if (localProp.exists()) {
28 | val prop = Properties()
29 | localProp.inputStream().use {
30 | prop.load(it)
31 | }
32 | val sdkHome = prop.getProperty("sdk.dir")
33 | if (sdkHome != null) {
34 | return sdkHome
35 | }
36 | }
37 | throw IllegalStateException(
38 | "Missing 'ANDROID_HOME' environment variable or local.properties with 'sdk.dir'")
39 | }
40 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin-mpp-android-ios/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'org.jetbrains.kotlin.multiplatform'
3 | id 'com.android.library'
4 | id 'kotlinx-serialization'
5 | id 'com.codingfeline.kgql'
6 | }
7 |
8 | repositories {
9 | maven {
10 | url "file://${projectDir.absolutePath}/../../../../build/localMaven"
11 | }
12 | mavenCentral()
13 | google()
14 | jcenter()
15 | // maven { url 'https://dl.bintray.com/kotlin/kotlinx' }
16 | }
17 |
18 | android {
19 | compileSdkVersion libs.versions.compileSdk.get() as int
20 |
21 | lintOptions {
22 | textReport true
23 | }
24 |
25 | sourceSets {
26 | main {
27 | manifest.srcFile 'src/androidMain/AndroidManifest.xml'
28 | }
29 | }
30 | }
31 |
32 | kgql {
33 | packageName = "com.sample"
34 | typeMapper = [
35 | "UserProfile": "com.sample.data.UserProfile"
36 | ]
37 | }
38 |
39 | kotlin {
40 |
41 | android()
42 | js(IR) {
43 | browser()
44 | nodejs()
45 | }
46 | ios()
47 | sourceSets {
48 | commonMain {
49 | dependencies {
50 | implementation libs.kotlin.serialization.json
51 | }
52 | }
53 | androidMain {
54 | dependencies {
55 | }
56 | }
57 | jsMain {
58 | dependencies {
59 | }
60 | }
61 | iosMain {
62 | dependencies {
63 | }
64 | }
65 | iosTest {}
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Publish a release
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 | workflow_dispatch:
8 |
9 | jobs:
10 | macos-build:
11 | runs-on: macos-latest
12 |
13 | steps:
14 | - name: Checkout the repo
15 | uses: actions/checkout@v2
16 |
17 | - name: Set up JDK 11
18 | uses: actions/setup-java@v2
19 | with:
20 | distribution: 'temurin'
21 | java-version: '11'
22 |
23 | - name: Publish the artifacts to Maven Central
24 | env:
25 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }}
26 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }}
27 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_PRIVATE_KEY }}
28 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PRIVATE_KEY_PASSWORD }}
29 | run: ./gradlew clean build publishAllPublicationsToMavenCentralRepository -PRELEASE_SIGNING_ENABLED=true --no-daemon --no-parallel
30 |
31 | - name: Publish the plugin to Gradle Plugin portal
32 | env:
33 | ORG_GRADLE_PROJECT_gradle.publish.key: ${{ secrets.GRADLE_PUBLISH_KEY }}
34 | ORG_GRADLE_PROJECT_gradle.publish.secret: ${{ secrets.GRADLE_PUBLISH_SECRET }}
35 | run: ./gradlew publishPlugins --no-daemon --no-parallel
36 |
37 | env:
38 | GRADLE_OPTS: -Dorg.gradle.configureondemand=true -Dorg.gradle.parallel=false -Dkotlin.incremental=false -Dorg.gradle.jvmargs="-Xmx3g -XX:MaxPermSize=2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8"
39 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/main/kotlin/com/codingfeline/kgql/gradle/KgqlTask.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle
2 |
3 | import com.codingfeline.kgql.VERSION
4 | import com.codingfeline.kgql.compiler.KgqlEnvironment
5 | import com.codingfeline.kgql.compiler.KgqlEnvironment.CompilationStatus.Failure
6 | import com.codingfeline.kgql.compiler.KgqlException
7 | import org.gradle.api.logging.LogLevel
8 | import org.gradle.api.tasks.Input
9 | import org.gradle.api.tasks.OutputDirectory
10 | import org.gradle.api.tasks.SourceTask
11 | import org.gradle.api.tasks.TaskAction
12 | import java.io.File
13 |
14 | open class KgqlTask : SourceTask() {
15 | @Suppress("unused")
16 | @Input
17 | val pluginVersion = VERSION
18 |
19 | @get:OutputDirectory
20 | lateinit var outputDirectory: File
21 |
22 | @Input
23 | lateinit var sourceFolders: Iterable
24 |
25 | @Input
26 | lateinit var packageName: String
27 |
28 | @Input
29 | lateinit var typeMap: MutableMap
30 |
31 | @TaskAction
32 | fun generateKgqlFiles() {
33 | outputDirectory.deleteRecursively()
34 | outputDirectory.mkdirs()
35 |
36 | val environment = KgqlEnvironment(
37 | sourceFiles = source.toList(),
38 | packageName = packageName,
39 | outputDirectory = outputDirectory,
40 | typeMap = typeMap
41 | )
42 |
43 | val generationStatus = environment.generateKgqlFiles { info -> logger.log(LogLevel.INFO, info) }
44 |
45 | when (generationStatus) {
46 | is Failure -> {
47 | logger.log(LogLevel.ERROR, "")
48 | generationStatus.errors.forEach { logger.log(LogLevel.ERROR, it) }
49 | throw KgqlException("Generation failed; see the generator error output for details.")
50 | }
51 | KgqlEnvironment.CompilationStatus.Success -> {
52 | // no-op
53 | }
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | compileSdk = "33"
3 | kotlin = "1.7.10"
4 | dokka = "1.7.10"
5 | agp = "7.2.2"
6 |
7 | [libraries]
8 | kotlin-plugin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" }
9 | kotlin-plugin-serialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" }
10 | kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin" }
11 | kotlin-nativeUtils = { module = "org.jetbrains.kotlin:kotlin-native-utils", version.ref = "kotlin" }
12 | kotlin-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version = "1.4.0" }
13 | kotlin-test-common = { module = "org.jetbrains.kotlin:kotlin-test-common", version.ref = "kotlin" }
14 | kotlin-test-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
15 | kotlin-test-annotations = { module = "org.jetbrains.kotlin:kotlin-test-annotations-common", version.ref = "kotlin" }
16 | kotlinPoet = { module = "com.squareup:kotlinpoet", version = "1.12.0" }
17 | junit = { module = "junit:junit", version = "4.13.2" }
18 | truth = { module = "com.google.truth:truth", version = "1.1.3" }
19 |
20 | android-plugin = { module = "com.android.tools.build:gradle", version.ref = "agp" }
21 | graphql = { module = "com.graphql-java:graphql-java", version = "19.2" }
22 |
23 | [plugins]
24 | kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
25 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
26 | kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
27 | dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" }
28 | android-library = { id = "com.android.library", version.ref = "agp" }
29 | versions = { id = "com.github.ben-manes.versions", version = "0.42.0" }
30 | pluginPublish = { id = "com.gradle.plugin-publish", version = "0.21.0" }
31 | mavenPublish = { id = "com.vanniktech.maven.publish", version = "0.21.0" }
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/main/kotlin/com/codingfeline/kgql/gradle/KgqlConfig.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle
2 |
3 | import com.codingfeline.kgql.compiler.KgqlFileType
4 | import com.codingfeline.kgql.gradle.kotlin.sources
5 | import org.gradle.api.Project
6 | import org.gradle.api.file.FileCollection
7 | import java.io.File
8 |
9 | class KgqlConfig(
10 | val project: Project,
11 | var packageName: String? = null,
12 | var sourceSet: FileCollection? = null,
13 | var typeMapper: MutableMap? = null
14 | ) {
15 | private val generatedSourceDirectory
16 | get() = File(project.buildDir, "generated/kgql")
17 |
18 | private val sources by lazy { sources() }
19 |
20 | internal fun registerTask() {
21 |
22 | val packageName = requireNotNull(packageName) { "property packageName must be provided" }
23 | val sourceSet = sourceSet ?: project.files("src/main/kgql")
24 | val typeMap = typeMapper ?: mutableMapOf()
25 |
26 | sources.forEach { source ->
27 | // println(source)
28 | // Add source dependency on the generated code.
29 |
30 | val task = project.tasks.register(
31 | "generate${source.name.capitalize()}KgqlInterface",
32 | KgqlTask::class.java
33 | ) {
34 | it.packageName = packageName
35 | it.sourceFolders = sourceSet.files
36 | it.outputDirectory = generatedSourceDirectory
37 | it.typeMap = typeMap
38 | it.source(sourceSet)
39 | it.include(KgqlFileType.EXTENSIONS.map { ext -> listOf("**", "*.$ext").joinToString(File.separator) })
40 | it.group = KgqlPlugin.GROUP
41 | it.description = "Generate Kotlin interface for .gql/.graphql files"
42 | }
43 |
44 | project.tasks.named("generateKgqlInterface").configure { it.dependsOn(task) }
45 |
46 | source.sourceDirectorySet.srcDirs(task.map { it.outputDirectory })
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/KgqlCustomTypeMapper.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | import com.squareup.kotlinpoet.ANY
4 | import com.squareup.kotlinpoet.ClassName
5 | import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.plusParameter
6 | import com.squareup.kotlinpoet.TypeName
7 | import com.squareup.kotlinpoet.asTypeName
8 | import graphql.language.ListType
9 | import graphql.language.NonNullType
10 | import graphql.language.Type
11 |
12 | class KgqlCustomTypeMapper(
13 | private val typeMap: Map
14 | ) {
15 | fun get(type: Type<*>): TypeName {
16 | return when (type) {
17 | is NonNullType -> get(type.type).copy(nullable = false)
18 | is ListType -> ClassName("kotlin.collections", "List")
19 | .plusParameter(get(type.type)).copy(nullable = true)
20 | else -> {
21 | when ((type as graphql.language.TypeName).name) {
22 | // GraphQL embedded type
23 | "ID" -> String::class.asTypeName()
24 | "String" -> String::class.asTypeName()
25 | "Int" -> Int::class.asTypeName()
26 | "Float" -> Float::class.asTypeName()
27 | "Boolean" -> Boolean::class.asTypeName()
28 | else -> mapCustomType(type)
29 | }.copy(nullable = true)
30 | }
31 | }
32 | }
33 |
34 | private fun mapCustomType(type: graphql.language.TypeName): TypeName {
35 | return typeMap[type.name]?.let { fqName ->
36 | val parts = fqName.split('.')
37 | ClassName(parts.dropLast(1).joinToString("."), parts.last())
38 | } ?: ANY
39 | }
40 |
41 | fun isCustomType(type: TypeName): Boolean {
42 | return typeMap.values.contains(type.copy(nullable = false, annotations = emptyList()).toString())
43 | }
44 |
45 | fun hasCustomType(gqlTypeName: String): Boolean {
46 | return typeMap.containsKey(gqlTypeName)
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/generator/DocumentWrapperGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler.generator
2 |
3 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeFQName
4 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeName
5 | import com.codingfeline.kgql.compiler.KgqlCustomTypeMapper
6 | import com.codingfeline.kgql.compiler.KgqlFile
7 | import com.codingfeline.kgql.compiler.Logger
8 | import com.squareup.kotlinpoet.KModifier
9 | import com.squareup.kotlinpoet.PropertySpec
10 | import com.squareup.kotlinpoet.TypeSpec
11 | import graphql.language.OperationDefinition
12 | import graphql.parser.Parser
13 |
14 | class DocumentWrapperGenerator(
15 | private val sourceFile: KgqlFile,
16 | typeMap: Map
17 | ) {
18 |
19 | private val rawDocument = sourceFile.source.readText()
20 | private val document = Parser().parseDocument(rawDocument)
21 | private val typeMapper = KgqlCustomTypeMapper(typeMap)
22 |
23 | private val className = "${sourceFile.source.nameWithoutExtension.capitalize()}Document"
24 |
25 | fun generateType(logger: Logger): TypeSpec {
26 | logger("Generating $className...")
27 |
28 | val objectType = TypeSpec.objectBuilder(className)
29 | .addModifiers(KModifier.INTERNAL)
30 |
31 | val fqName = "${sourceFile.packageName}.$className"
32 |
33 | // add raw document property
34 | val documentProp = PropertySpec.builder("document", String::class)
35 | .addModifiers(KModifier.PRIVATE)
36 | .initializer("%S", rawDocument)
37 | .build()
38 |
39 | objectType.addProperty(documentProp)
40 |
41 | val operationWrapperGenerator = OperationWrapperGenerator(documentProp, typeMapper, fqName)
42 | val operations = document.definitions.filterIsInstance()
43 | .map { operationWrapperGenerator.generateObject(it) }
44 |
45 | objectType.addTypes(operations)
46 |
47 | return objectType.build()
48 | }
49 | }
50 |
51 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | alias(libs.plugins.kotlin.jvm)
3 | id("java-gradle-plugin")
4 | alias(libs.plugins.mavenPublish)
5 | alias(libs.plugins.dokka)
6 | alias(libs.plugins.pluginPublish)
7 | }
8 |
9 | sourceCompatibility = JavaVersion.VERSION_1_8
10 | targetCompatibility = JavaVersion.VERSION_1_8
11 |
12 | pluginBundle {
13 | website = POM_URL
14 | vcsUrl = 'https://github.com/yshrsmz/kgql.git'
15 | tags = ['GraphQL', 'Kotlin', 'Kotlin Multiplatform']
16 | }
17 |
18 | gradlePlugin {
19 | plugins {
20 | kgql {
21 | id = "com.codingfeline.kgql"
22 | displayName = POM_NAME
23 | description = POM_DESCRIPTION
24 | implementationClass = "com.codingfeline.kgql.gradle.KgqlPlugin"
25 | }
26 | }
27 | }
28 |
29 | dependencies {
30 | implementation project(':kgql-compiler')
31 |
32 | implementation libs.kotlin.nativeUtils
33 | implementation libs.kotlin.plugin
34 | implementation libs.kotlin.plugin.serialization
35 | implementation libs.android.plugin
36 |
37 | compileOnly gradleApi()
38 |
39 | testImplementation libs.junit
40 | testImplementation libs.truth
41 | }
42 |
43 | compileKotlin {
44 | kotlinOptions.jvmTarget = "1.8"
45 | }
46 | compileTestKotlin {
47 | kotlinOptions.jvmTarget = "1.8"
48 | }
49 |
50 | tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile) {
51 | kotlinOptions.jvmTarget = "1.8"
52 | }
53 |
54 | test {
55 | def os = System.getenv("TRAVIS_OS_NAME")
56 | dependsOn(
57 | ":kgql-core:publishAllPublicationsToTestMavenRepository",
58 | ":kgql-compiler:publishAllPublicationsToTestMavenRepository",
59 | )
60 | }
61 |
62 | // work around for https://youtrack.jetbrains.com/issue/KT-27059
63 | configurations.all {
64 | resolutionStrategy.dependencySubstitution {
65 | substitute module("${project.property("GROUP")}:core-jvm:${project.property("VERSION_NAME")}") with project(':kgql-core')
66 | }
67 | }
68 |
69 | apply from: "$rootDir/gradle/maven-publish.gradle"
70 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/generator/KgqlCompiler.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler.generator
2 |
3 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeFQName
4 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeName
5 | import com.codingfeline.kgql.compiler.KgqlFile
6 | import com.codingfeline.kgql.compiler.Logger
7 | import com.squareup.kotlinpoet.AnnotationSpec
8 | import com.squareup.kotlinpoet.FileSpec
9 | import kotlinx.serialization.SerialName
10 | import java.io.Closeable
11 |
12 | private typealias FileAppender = (fileName: String) -> Appendable
13 |
14 | object KgqlCompiler {
15 |
16 | fun compile(
17 | file: KgqlFile,
18 | typeMap: Map,
19 | output: FileAppender,
20 | logger: Logger
21 | ) {
22 | writeDocumentWrapperFile(file, typeMap, output, logger)
23 | }
24 |
25 | private fun writeDocumentWrapperFile(
26 | sourceFile: KgqlFile,
27 | typeMap: Map,
28 | output: FileAppender,
29 | logger: Logger
30 | ) {
31 | val packageName = sourceFile.packageName
32 | val outputDirectory = "${sourceFile.outputDirectory.absolutePath}/${packageName.replace(".", "/")}"
33 | val documentWrapperType = DocumentWrapperGenerator(sourceFile, typeMap).generateType(logger)
34 | FileSpec.builder(sourceFile.packageName, sourceFile.source.nameWithoutExtension)
35 | .apply {
36 | addType(documentWrapperType)
37 | }
38 | .build()
39 | .writeToAndClose(output("$outputDirectory/${documentWrapperType.name}.kt"))
40 | }
41 |
42 | private fun FileSpec.writeToAndClose(appendable: Appendable) {
43 | writeTo(appendable)
44 | if (appendable is Closeable) appendable.close()
45 | }
46 | }
47 |
48 | fun generateSerialName(name: String): AnnotationSpec {
49 | return AnnotationSpec.builder(SerialName::class)
50 | .addMember("value = %S", name)
51 | .build()
52 | }
53 |
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/KgqlEnvironment.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | import com.codingfeline.kgql.compiler.generator.KgqlCompiler
4 | import java.io.File
5 |
6 | class KgqlEnvironment(
7 | /**
8 | * The GraphQL source files for this environment
9 | */
10 | private val sourceFiles: List,
11 | /**
12 | * The package name to be used for generated KgqlDocuments class.
13 | */
14 | private val packageName: String? = null,
15 | /**
16 | * An output directory to place the generated class files
17 | */
18 | private val outputDirectory: File? = null,
19 | private val typeMap: Map
20 | ) {
21 |
22 | sealed class CompilationStatus {
23 | object Success : CompilationStatus()
24 | class Failure(val errors: List) : CompilationStatus()
25 | }
26 |
27 | fun generateKgqlFiles(logger: Logger): CompilationStatus {
28 | val errors = ArrayList()
29 |
30 | val writer = writer@{ fileName: String ->
31 | val file = File(fileName)
32 | if (!file.exists()) {
33 | file.parentFile.mkdirs()
34 | file.createNewFile()
35 | }
36 | return@writer file.writer()
37 | }
38 |
39 | forEachSourceFile { file ->
40 | try {
41 | KgqlCompiler.compile(file, typeMap, writer, logger)
42 | } catch (e: Throwable) {
43 | e.message?.let { errors.add(it) }
44 | }
45 | }
46 |
47 | return if (errors.isEmpty()) {
48 | CompilationStatus.Success
49 | } else {
50 | CompilationStatus.Failure(errors)
51 | }
52 | }
53 |
54 | fun forEachSourceFile(action: (file: KgqlFile) -> Unit) {
55 | sourceFiles.forEach { file ->
56 | val kgqlFile = KgqlFile(
57 | packageName = packageName!!,
58 | outputDirectory = outputDirectory!!,
59 | source = file
60 | )
61 | action(kgqlFile)
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/sample/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | maven { url "file://${projectDir.absolutePath}/../build/localMaven" }
4 | mavenCentral()
5 | google()
6 | gradlePluginPortal()
7 | // mavenLocal()
8 | }
9 | dependencies {
10 | classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21'
11 | classpath 'org.jetbrains.kotlin:kotlin-serialization:1.5.21'
12 | classpath 'com.codingfeline.kgql:gradle-plugin:+'
13 | }
14 | }
15 |
16 | apply plugin: 'kotlin-multiplatform'
17 | apply plugin: 'kotlinx-serialization'
18 | apply plugin: 'com.codingfeline.kgql'
19 |
20 | repositories {
21 | maven { url "file://${projectDir.absolutePath}/../build/localMaven" }
22 | mavenCentral()
23 | google()
24 | // mavenLocal()
25 | }
26 |
27 | kotlin {
28 | jvm()
29 | js(IR) {
30 | browser()
31 | nodejs()
32 | }
33 | ios {
34 | binaries {
35 | framework()
36 | }
37 | }
38 |
39 | sourceSets {
40 | commonMain {
41 | dependencies {
42 | implementation kotlin('stdlib-common')
43 | implementation "org.jetbrains.kotlinx:kotlinx-serialization-core:1.2.2"
44 | }
45 | }
46 | jvmMain {
47 | dependencies {
48 | }
49 | }
50 | jsMain {
51 | dependencies {
52 | }
53 | }
54 | iosMain {
55 | dependencies {
56 | }
57 | }
58 | }
59 | }
60 |
61 | kgql {
62 | packageName = "com.codingfeline.kgql.sample"
63 | sourceSet = files("src/main/kgql")
64 | }
65 |
66 | // Workaround for https://youtrack.jetbrains.com/issue/KT-36721.
67 | // Put this snippet into your root buildscript.
68 | allprojects {
69 | pluginManager.withPlugin("kotlin-multiplatform") {
70 | def uniqueName = "${project.group}.${project.name}".toString()
71 |
72 | project.kotlin.targets.withType(org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget.class) {
73 | compilations["main"].kotlinOptions.freeCompilerArgs += ["-module-name", uniqueName]
74 | }
75 | }
76 | }
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/generator/VariablesWrapperGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler.generator
2 |
3 | import com.codingfeline.kgql.compiler.KgqlCustomTypeMapper
4 | import com.codingfeline.kgql.core.KgqlRequestBody
5 | import com.squareup.kotlinpoet.FunSpec
6 | import com.squareup.kotlinpoet.KModifier
7 | import com.squareup.kotlinpoet.ParameterSpec
8 | import com.squareup.kotlinpoet.PropertySpec
9 | import com.squareup.kotlinpoet.TypeSpec
10 | import graphql.language.VariableDefinition
11 | import kotlinx.serialization.Serializable
12 |
13 | class VariableWrapperGenerator(
14 | val variables: List,
15 | val typeMapper: KgqlCustomTypeMapper
16 | ) {
17 |
18 | fun generateType(): TypeSpec {
19 | val classSpec = TypeSpec.classBuilder("Variables")
20 | .addModifiers(KModifier.DATA)
21 | .addAnnotation(Serializable::class)
22 | .primaryConstructor(generateConstructor(variables))
23 | .addProperties(generateProperties(variables))
24 |
25 | return classSpec.build()
26 | }
27 |
28 | private fun generateConstructor(variables: List): FunSpec {
29 | return FunSpec.constructorBuilder()
30 | .addParameters(variables.map {
31 | val type = typeMapper.get(it.type)
32 | val spec = ParameterSpec.builder(it.name, type)
33 | .addAnnotation(generateSerialName(it.name))
34 |
35 | if (type.isNullable) {
36 | spec.defaultValue("null")
37 | }
38 |
39 | spec.build()
40 | })
41 | .build()
42 | }
43 |
44 | private fun generateProperties(variables: List): List {
45 | return variables.map {
46 | val type = typeMapper.get(it.type)
47 | val spec = PropertySpec.builder(it.name, type)
48 | .initializer(it.name)
49 |
50 | spec.build()
51 | }
52 | }
53 | }
54 |
55 | data class Request(
56 | override val variables: String?
57 | ) : KgqlRequestBody {
58 | override val operationName: String? = null
59 | override val query: String = ""
60 | }
61 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if %ERRORLEVEL% equ 0 goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if %ERRORLEVEL% equ 0 goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | set EXIT_CODE=%ERRORLEVEL%
84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
86 | exit /b %EXIT_CODE%
87 |
88 | :mainEnd
89 | if "%OS%"=="Windows_NT" endlocal
90 |
91 | :omega
92 |
--------------------------------------------------------------------------------
/test-util/src/main/kotlin/com/codingfeline/kgql/test/util/FixtureCompiler.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.test.util
2 |
3 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeName
4 | import com.codingfeline.kgql.compiler.GraphQLCustomTypeFQName
5 | import com.codingfeline.kgql.compiler.KgqlFile
6 | import com.codingfeline.kgql.compiler.Logger
7 | import com.codingfeline.kgql.compiler.generator.KgqlCompiler
8 | import org.junit.rules.TemporaryFolder
9 | import java.io.File
10 | import java.io.FilenameFilter
11 |
12 | private typealias CompilationMethod = (KgqlFile, Map, (String) -> Appendable, (String) -> Unit) -> Unit
13 |
14 | object FixtureCompiler {
15 |
16 | fun compileGql(
17 | gql: String,
18 | temporaryFolder: TemporaryFolder,
19 | compilationMethod: CompilationMethod = KgqlCompiler::compile,
20 | typeMap: Map = emptyMap(),
21 | fileName: String = "Test.gql"
22 | ): CompilationResult {
23 | writeGql(gql, temporaryFolder, fileName)
24 | return compileFixture(temporaryFolder.fixtureRoot().path, compilationMethod, typeMap)
25 | }
26 |
27 | fun writeGql(
28 | gql: String,
29 | temporaryFolder: TemporaryFolder,
30 | fileName: String
31 | ): File {
32 | val srcRootDir = temporaryFolder.fixtureRoot().apply { mkdirs() }
33 | val fixtureSrcDir = File(srcRootDir, "com/example").apply { mkdirs() }
34 | return File(fixtureSrcDir, fileName).apply {
35 | createNewFile()
36 | writeText(gql)
37 | }
38 | }
39 |
40 | fun compileFixture(
41 | fixtureRoot: String,
42 | compilationMethod: CompilationMethod,
43 | typeMap: Map = emptyMap(),
44 | writer: ((String) -> Appendable)? = null,
45 | outputDirectory: File = File(fixtureRoot, "output")
46 | ): CompilationResult {
47 | val compilerOutput = mutableMapOf()
48 | val errors = mutableListOf()
49 | val sourceFiles = StringBuilder()
50 | val parser = TestEnvironment(outputDirectory)
51 | val fixtureRootDir = File(fixtureRoot)
52 |
53 | if (!fixtureRootDir.exists()) {
54 | throw IllegalArgumentException("$fixtureRoot does not exist")
55 | }
56 |
57 | val environment = parser.build(fixtureRootDir.path)
58 | val fileWriter = writer ?: fileWriter@{ fileName: String ->
59 | val builder = StringBuilder()
60 | compilerOutput += File(fileName) to builder
61 | return@fileWriter builder
62 | }
63 |
64 | val logger: Logger = {}
65 |
66 | var file: KgqlFile? = null
67 |
68 | environment.forEachSourceFile {
69 | compilationMethod(it, typeMap, fileWriter, logger)
70 | file = it
71 | }
72 |
73 | return CompilationResult(outputDirectory, compilerOutput, errors, sourceFiles.toString(), file!!)
74 | }
75 |
76 | data class CompilationResult(
77 | val outputDirectory: File,
78 | val compilerOutput: Map,
79 | val errors: List,
80 | val sourceFiles: String,
81 | val compiledFile: KgqlFile
82 | )
83 | }
84 |
85 | fun TemporaryFolder.fixtureRoot() = File(root, "src/test/test-fixture")
86 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/main/kotlin/com/codingfeline/kgql/gradle/KgqlPlugin.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle
2 |
3 | import com.codingfeline.kgql.VERSION
4 | import com.codingfeline.kgql.gradle.android.packageName
5 | import org.gradle.api.Plugin
6 | import org.gradle.api.Project
7 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
8 | import org.jetbrains.kotlin.gradle.plugin.sources.DefaultKotlinSourceSet
9 | import java.util.concurrent.atomic.AtomicBoolean
10 |
11 | open class KgqlPlugin : Plugin {
12 | private val android = AtomicBoolean(false)
13 | private val kotlin = AtomicBoolean(false)
14 | private val serialization = AtomicBoolean(false)
15 |
16 | private lateinit var extension: KgqlExtension
17 |
18 | override fun apply(project: Project) {
19 | extension = project.extensions.create("kgql", KgqlExtension::class.java)
20 | extension.project = project
21 |
22 | val androidPluginHandler = { _: Plugin<*> ->
23 | android.set(true)
24 | project.afterEvaluate { project.setupKgqlTask(afterAndroid = true) }
25 | }
26 |
27 | project.plugins.withId("com.android.application", androidPluginHandler)
28 | project.plugins.withId("com.android.library", androidPluginHandler)
29 | project.plugins.withId("com.android.instantapp", androidPluginHandler)
30 | project.plugins.withId("com.android.feature", androidPluginHandler)
31 | project.plugins.withId("com.android.dynamic-feature", androidPluginHandler)
32 |
33 | val kotlinPluginHandler = { _: Plugin<*> -> kotlin.set(true) }
34 | project.plugins.withId("org.jetbrains.kotlin.multiplatform", kotlinPluginHandler)
35 | project.plugins.withId("org.jetbrains.kotlin.android", kotlinPluginHandler)
36 | project.plugins.withId("org.jetbrains.kotlin.jvm", kotlinPluginHandler)
37 | project.plugins.withId("kotlin2js", kotlinPluginHandler)
38 |
39 | val serializationPluginHandler = { _: Plugin<*> -> serialization.set(true) }
40 | project.plugins.withId("org.jetbrains.kotlin.plugin.serialization", serializationPluginHandler)
41 |
42 | project.afterEvaluate { project.setupKgqlTask(afterAndroid = false) }
43 | }
44 |
45 | private fun Project.setupKgqlTask(afterAndroid: Boolean) {
46 | if (android.get() && !afterAndroid) return
47 |
48 | check(kotlin.get()) {
49 | "Kgql Gradle Plugin applied in " +
50 | "project '${project.path}' but no supported Kotlin plugin was found"
51 | }
52 |
53 | check(serialization.get()) {
54 | "Kgql Gradle Plugin applied in " +
55 | "project '${project.path}' but no kotlinx-serialization plugin was found"
56 | }
57 |
58 | val isMultiplatform = project.plugins.hasPlugin("org.jetbrains.kotlin.multiplatform")
59 |
60 | // Add the runtime dependency
61 | if (isMultiplatform) {
62 | val sourceSets = project.extensions
63 | .getByType(KotlinMultiplatformExtension::class.java).sourceSets
64 | val sourceSet = (sourceSets.getByName("commonMain") as DefaultKotlinSourceSet)
65 | project.configurations.getByName(sourceSet.apiConfigurationName).dependencies
66 | .add(project.dependencies.create("com.codingfeline.kgql:core:$VERSION"))
67 | } else {
68 | project.configurations.getByName("api").dependencies
69 | .add(project.dependencies.create("com.codingfeline.kgql:core-jvm:$VERSION"))
70 | }
71 |
72 | extension.run {
73 | val config: KgqlConfig = toConfig()
74 | if (config.packageName == null && android.get() && !isMultiplatform) {
75 | config.packageName = project.packageName()
76 | }
77 |
78 | project.tasks.register("generateKgqlInterface") {
79 | it.group = GROUP
80 | it.description = "Aggregation task which runs every interface generation task for every given source"
81 | }
82 | config.registerTask()
83 | }
84 | }
85 |
86 | companion object {
87 | const val GROUP = "kgql"
88 | }
89 | }
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/generator/RequestBodyGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler.generator
2 |
3 | import com.codingfeline.kgql.core.KgqlRequestBody
4 | import com.squareup.kotlinpoet.ClassName
5 | import com.squareup.kotlinpoet.FunSpec
6 | import com.squareup.kotlinpoet.KModifier
7 | import com.squareup.kotlinpoet.ParameterSpec
8 | import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.plusParameter
9 | import com.squareup.kotlinpoet.PropertySpec
10 | import com.squareup.kotlinpoet.TypeName
11 | import com.squareup.kotlinpoet.TypeSpec
12 | import com.squareup.kotlinpoet.asTypeName
13 | import kotlinx.serialization.Serializable
14 |
15 | class RequestBodyGenerator(
16 | val operationNameProp: PropertySpec,
17 | val parentDocumentFqName: String,
18 | val parentObjectName: String,
19 | val variablesSpec: TypeSpec?,
20 | val documentProp: PropertySpec
21 | ) {
22 |
23 | fun generateType(): TypeSpec {
24 | val variablesType = variablesSpec.typeNameOrUnit()
25 | val spec = TypeSpec.classBuilder("Request")
26 | .addModifiers(KModifier.DATA)
27 | .addAnnotation(Serializable::class)
28 | .addSuperinterface(
29 | KgqlRequestBody::class.asTypeName().plusParameter(variablesType)
30 | )
31 |
32 | val constructorSpec = FunSpec.constructorBuilder()
33 |
34 | val variablesParameterSpec = ParameterSpec
35 | .builder(
36 | "variables",
37 | variablesType.copy(nullable = true)
38 | )
39 | .addAnnotation(generateSerialName("variables"))
40 |
41 | if (variablesSpec == null) {
42 | variablesParameterSpec.defaultValue("null")
43 | }
44 |
45 | constructorSpec
46 | .addParameter(variablesParameterSpec.build())
47 | .addParameter(
48 | ParameterSpec
49 | .builder(
50 | "operationName",
51 | String::class.asTypeName().copy(nullable = true),
52 | )
53 | .addAnnotation(generateSerialName("operationName"))
54 | .defaultValue(
55 | "%L.%N",
56 | parentObjectName,
57 | operationNameProp
58 | )
59 | .build()
60 | )
61 | .addParameter(
62 | ParameterSpec
63 | .builder(
64 | "query",
65 | String::class,
66 | )
67 | .defaultValue(documentProp.name)
68 | .addAnnotation(generateSerialName("query"))
69 | .build()
70 | )
71 |
72 | spec.primaryConstructor(constructorSpec.build())
73 |
74 | spec
75 | .addProperty(
76 | PropertySpec
77 | .builder(
78 | "operationName",
79 | String::class.asTypeName().copy(nullable = true),
80 | KModifier.OVERRIDE
81 | )
82 | .initializer("operationName")
83 | .build()
84 | )
85 | .addProperty(
86 | PropertySpec
87 | .builder("query", String::class, KModifier.OVERRIDE)
88 | .initializer("query")
89 | .build()
90 | )
91 | .addProperty(
92 | PropertySpec
93 | .builder("variables", variablesType.copy(nullable = true), KModifier.OVERRIDE)
94 | .initializer("variables")
95 | .build()
96 | )
97 |
98 | return spec.build()
99 | }
100 |
101 | private fun TypeSpec?.typeNameOrUnit(): TypeName {
102 | return if (this == null) {
103 | Unit::class.asTypeName()
104 | } else {
105 | ClassName.bestGuess("$parentDocumentFqName.$parentObjectName.$name")
106 | }
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/main/kotlin/com/codingfeline/kgql/gradle/kotlin/SourceRoots.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle.kotlin
2 |
3 | import com.android.build.gradle.AppExtension
4 | import com.android.build.gradle.BaseExtension
5 | import com.android.build.gradle.LibraryExtension
6 | import com.android.build.gradle.api.BaseVariant
7 | import com.codingfeline.kgql.gradle.KgqlConfig
8 | import org.gradle.api.DomainObjectSet
9 | import org.gradle.api.Project
10 | import org.gradle.api.file.SourceDirectorySet
11 | import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
12 | import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension
13 | import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType
14 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinJvmAndroidCompilation
15 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinMetadataTarget
16 | import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
17 | import org.jetbrains.kotlin.konan.target.KonanTarget
18 |
19 | internal fun KgqlConfig.sources(): List {
20 | // Multiplatform Project
21 | project.extensions.findByType(KotlinMultiplatformExtension::class.java)?.let {
22 | return it.sources(project)
23 | }
24 |
25 | // Android project
26 | project.extensions.findByName("android")?.let {
27 | return (it as BaseExtension).sources(project)
28 | }
29 |
30 | // Kotlin project
31 | val sourceSets = (project.extensions.getByName("kotlin") as KotlinProjectExtension).sourceSets
32 | return listOf(
33 | Source(
34 | type = KotlinPlatformType.jvm,
35 | name = "main",
36 | sourceSets = listOf("main"),
37 | sourceDirectorySet = sourceSets.getByName("main").kotlin
38 | )
39 | )
40 | }
41 |
42 | private fun KotlinMultiplatformExtension.sources(project: Project): List {
43 | val target = targets.single { it is KotlinMetadataTarget }
44 | return target.compilations.mapNotNull { compilation ->
45 | if (compilation.name.endsWith(suffix = "Test", ignoreCase = true)) {
46 | return@mapNotNull null
47 | }
48 |
49 | if (compilation.defaultSourceSet.dependsOn.isNotEmpty()) {
50 | // skip non-commonMain compilation
51 | // commonMain has no dependent SourceSet
52 | return@mapNotNull null
53 | }
54 |
55 | val targetName = if (target is KotlinMetadataTarget) "common" else target.name
56 | Source(
57 | type = target.platformType,
58 | konanTarget = (target as? KotlinNativeTarget)?.konanTarget,
59 | name = "${targetName}${compilation.name.capitalize()}",
60 | variantName = (compilation as? KotlinJvmAndroidCompilation)?.name,
61 | sourceDirectorySet = compilation.defaultSourceSet.kotlin,
62 | sourceSets = compilation.allKotlinSourceSets.map { it.name }
63 | )
64 | }
65 | .distinct()
66 | }
67 |
68 | private fun BaseExtension.sources(project: Project): List {
69 |
70 | val variants: DomainObjectSet = when (this) {
71 | is AppExtension -> applicationVariants
72 | is LibraryExtension -> libraryVariants
73 | else -> throw IllegalStateException("Unknown Android plugin $this")
74 | }
75 |
76 | val kotlinSourceSets = (project.extensions.getByName("kotlin") as KotlinProjectExtension).sourceSets
77 | val sourceSets = sourceSets
78 | .associate { sourceSet ->
79 | sourceSet.name to kotlinSourceSets.getByName(sourceSet.name).kotlin
80 | }
81 |
82 | return variants.map { variant ->
83 | Source(
84 | type = KotlinPlatformType.androidJvm,
85 | name = variant.name,
86 | variantName = variant.name,
87 | sourceDirectorySet = sourceSets[variant.name]
88 | ?: throw IllegalStateException("Couldn't find ${variant.name} in $sourceSets"),
89 | sourceSets = variant.sourceSets.map { it.name }
90 | )
91 | }
92 | }
93 |
94 |
95 | internal data class Source(
96 | val type: KotlinPlatformType,
97 | val konanTarget: KonanTarget? = null,
98 | val sourceDirectorySet: SourceDirectorySet,
99 | val name: String,
100 | val variantName: String? = null,
101 | val sourceSets: List
102 | ) {
103 | fun closestMatch(sources: Collection): Source? {
104 | var matches = sources.filter {
105 | type == it.type || (type == KotlinPlatformType.androidJvm && it.type == KotlinPlatformType.jvm)
106 | }
107 | if (matches.size <= 1) return matches.singleOrNull()
108 |
109 | // Multiplatform native matched or android variants matched
110 | matches = matches.filter {
111 | konanTarget == it.konanTarget && variantName == it.variantName
112 | }
113 | return matches.singleOrNull()
114 | }
115 | }
--------------------------------------------------------------------------------
/kgql-compiler/src/main/kotlin/com/codingfeline/kgql/compiler/generator/OperationWrapperGenerator.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler.generator
2 |
3 | import com.codingfeline.kgql.compiler.KgqlCustomTypeMapper
4 | import com.squareup.kotlinpoet.ClassName
5 | import com.squareup.kotlinpoet.FunSpec
6 | import com.squareup.kotlinpoet.KModifier
7 | import com.squareup.kotlinpoet.ParameterSpec
8 | import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.plusParameter
9 | import com.squareup.kotlinpoet.PropertySpec
10 | import com.squareup.kotlinpoet.TypeName
11 | import com.squareup.kotlinpoet.TypeSpec
12 | import com.squareup.kotlinpoet.asTypeName
13 | import graphql.language.OperationDefinition
14 | import kotlinx.serialization.KSerializer
15 |
16 | private const val PARAM_VARIABLES_NAME = "variables"
17 |
18 | class OperationWrapperGenerator(
19 | private val documentProp: PropertySpec,
20 | private val typeMapper: KgqlCustomTypeMapper,
21 | private val parentFQName: String
22 | ) {
23 |
24 | fun generateObject(operation: OperationDefinition): TypeSpec {
25 | val name = "${(operation.name ?: "").capitalize()}${operation.operation.name.toLowerCase().capitalize()}"
26 | val hasVariables = operation.variableDefinitions.isNotEmpty()
27 | var variableSpec: TypeSpec? = null
28 |
29 | val objectSpec = TypeSpec.objectBuilder(name = name)
30 |
31 | val operationNamePropSpec = PropertySpec.builder(
32 | "operationName",
33 | String::class.asTypeName().copy(nullable = true)
34 | )
35 | .addModifiers(KModifier.PUBLIC)
36 | .initializer("%S", operation.name)
37 | .build()
38 |
39 | objectSpec.addProperty(operationNamePropSpec)
40 |
41 | if (hasVariables) {
42 | variableSpec = VariableWrapperGenerator(operation.variableDefinitions, typeMapper).generateType()
43 | objectSpec.addType(variableSpec)
44 | }
45 |
46 | val requestBodySpec =
47 | RequestBodyGenerator(
48 | operationNameProp = operationNamePropSpec,
49 | parentDocumentFqName = parentFQName,
50 | parentObjectName = name,
51 | variablesSpec = variableSpec,
52 | documentProp = documentProp
53 | ).generateType()
54 | objectSpec.addType(requestBodySpec)
55 |
56 | val operationFunSpec = generateOperationFunction(
57 | parentObjectName = name,
58 | variablesSpec = variableSpec,
59 | requestBodySpec = requestBodySpec
60 | )
61 | objectSpec.addFunction(operationFunSpec)
62 | objectSpec.addFunction(generateSerializerFunction(requestBodySpec, name))
63 |
64 | return objectSpec.build()
65 | }
66 |
67 | private fun generateParameterSpecFromVariable(variables: TypeName): ParameterSpec {
68 | return ParameterSpec.builder(
69 | name = PARAM_VARIABLES_NAME,
70 | type = variables
71 | )
72 | .build()
73 | }
74 |
75 | private fun generateOperationFunction(
76 | parentObjectName: String,
77 | variablesSpec: TypeSpec?,
78 | requestBodySpec: TypeSpec
79 | ): FunSpec {
80 | val variablesType: TypeName = variablesSpec.typeNameOrUnit(parentObjectName)
81 |
82 | val spec = FunSpec.builder("requestBody")
83 | .returns(requestBodySpec.typeNameOrUnit(parentObjectName))
84 |
85 | if (variablesSpec != null) {
86 | spec.addParameter(generateParameterSpecFromVariable(variablesType))
87 | }
88 |
89 | if (variablesSpec != null) {
90 | spec.addStatement(
91 | "return %N(variables = variables)",
92 | requestBodySpec
93 | )
94 | } else {
95 | spec.addStatement(
96 | "return %N()",
97 | requestBodySpec
98 | )
99 | }
100 |
101 | spec.addKdoc(
102 | """
103 | |Create an instance of [%N] which then you can encode to JSON string
104 | """.trimMargin(), requestBodySpec
105 | )
106 |
107 | return spec.build()
108 | }
109 |
110 | private fun generateSerializerFunction(requestBodySpec: TypeSpec, parentObjectName: String): FunSpec {
111 | val spec = FunSpec.builder("serializer")
112 | .returns(KSerializer::class.asTypeName().plusParameter(requestBodySpec.typeNameOrUnit(parentObjectName)))
113 |
114 | spec.addStatement("return Request.serializer()")
115 |
116 | return spec.build()
117 | }
118 |
119 | private fun TypeSpec?.typeNameOrUnit(parentObjectName: String): TypeName {
120 | return if (this == null) {
121 | Unit::class.asTypeName()
122 | } else {
123 | ClassName.bestGuess("$parentFQName.$parentObjectName.${name}")
124 | }
125 | }
126 | }
127 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Change Log
2 | ===
3 |
4 | Badges: `[UPDATED]`, `[FIXED]`, `[ADDED]`, `[DEPRECATED]`, `[REMOVED]`, `[BREAKING]`
5 |
6 | Version 0.11.0 *(2022/09/09)*
7 | ---
8 |
9 | * `[UPDATED]`: Kotlin 1.7.10
10 | * `[UPDATED]`: Gradle wrapper 7.5.1
11 | * `[UPDATED]`: Android Gradle Plugin 7.2.2
12 | * `[UPDATED]`: Android compile sdK 33
13 | * `[UPDATED]`: kotlinx.serialization 1.4.0
14 | * `[UPDATED]`: graphql-java 19.2
15 | * `[ADDED]`: iosSimulatorArm64 support
16 |
17 | Version 0.10.1 *(2022/05/16)*
18 | ---
19 |
20 | * `[FIXED]`: revert graphql-java version to 17.3, to fix incompatibility with Android Gradle Plugin
21 |
22 | Version 0.10.0 *(2022/05/16)*
23 | ---
24 |
25 | * `[UPDATED]`: Kotlin 1.6.21
26 | * `[UPDATED]`: Gradle wrapper 7.4.2
27 | * `[UPDATED]`: Android Gradle Plugin 7.1.3
28 | * `[UPDATED]`: Android compileSdk 31
29 | * `[UPDATED]`: graphql-java 18.1
30 |
31 | Version 0.9.0 *(2022/02/02)*
32 | ---
33 |
34 | * `[UPDATED]`: Kotlin 1.6.10
35 | * `[UPDATED]`: GradLe wrapper 7.2
36 | * `[UPDATED]`: kotlinx.serialization 1.3.2
37 | * `[ADDED]`: HMPP support
38 |
39 | Version 0.8.2 *(2021/09/10)*
40 | ---
41 |
42 | * `[FIXED]`: Set source compatibility to Java 8
43 |
44 | Version 0.8.1 *(2021/09/10)*
45 | ---
46 |
47 | * `[FIXED]`: Duplicate content roots warning
48 |
49 | Version 0.8.0 *(2021/09/09)*
50 | ---
51 |
52 | * `[ADDED]`: expose `operationName` from Query object
53 | * `[UPDATED]`: propagate task dependency by source set dependency
54 |
55 | Version 0.7.0 *(2021/08/05)*
56 | ---
57 |
58 | * `[UPDATED]`: Kotlin 1.5.21
59 | * `[UPDATED]`: Android Gradle Plugin 4.2.2
60 | * `[UPDATED]`: kotlinx.serialization 1.2.2
61 | * `[UPDATED]`: gradle wrapper 7.0.2
62 | * `[BREAKING]`: `requestBody` function now returns Request instance. You should encode it on your own
63 |
64 | Version 0.6.0 *(2021-06-11)*
65 | ---
66 |
67 | * `[UPDATED]`: Kotlin 1.5.10
68 | * `[UPDATED]`: kotlinx.serialization 1.2.1
69 | * `[UPDATED]`: gradle wrapper 6.9
70 |
71 | Version 0.5.6 *(2021-05-06)*
72 | ---
73 |
74 | * `[UPDATED]`: Kotlin 1.4.32
75 | * `[UPDATED]`: kotlinx.serialization 1.1.0
76 | * `[UPDATED]`: gradle wrapper 7.0
77 |
78 | Version 0.5.5 *(2020-12-01)*
79 | ---
80 |
81 | * `[UPDATED]`: Kotlin 1.4.20
82 | * `[UPDATED]`: kotlinx.serialization 1.0.1
83 | * `[UPDATED]`: gradle wrapper 6.7.1
84 | * `[ADDED]`: enabled explicit api
85 |
86 | Version 0.5.4 *(2020-10-01)*
87 | ---
88 |
89 | * `[UPDATED]`: rewrite plugin
90 | * `[UPDATED]`: Kotlin 1.4.10
91 | * `[UPDATED]`: kotlinx.serialization 1.0.0-RC2
92 |
93 | Version 0.5.3 *(2020-08-25)*
94 | ---
95 |
96 | * `[UPDATED]`: Kotlin 1.4.0
97 | * `[UPDATED]`: Android Gradle Plugin 4.0.1
98 | * `[UPDATED]`: Gradle 6.6
99 | * `[REMOVED]`: iosArm32 is gone again
100 | * `[BREAKING]`: New JS IR backend
101 |
102 | Version 0.5.2 *(2020-04-13)*
103 | ---
104 |
105 | * `[UPDATED]`: Android Gradle Plugin 3.6.2
106 | * `[UPDATED]`: Project Gradle Version is now 6.3
107 | * `[UPDATED]`: Use maven-publish plugin to publish jvm artifacts
108 | * `[ADDED]`: iosArm32 artifact is back
109 | * `[FIXED]`: Remove unnecessary `@UnstableDefault` annotation.
110 |
111 | Version 0.5.1 *(2020-04-01)*
112 | ---
113 |
114 | * `[UPDATED]`: Kotlin 1.3.71
115 | * `[UPDATED]`: kotlinx.serialization 0.20.0
116 | * `[UPDATED]`: Android Gradle Plugin 3.6.1
117 | * `[UPDATED]`: Gradle 5.6.4
118 | * `[BREAKING]`: drop support for iosArm32
119 | * `[BREAKING]`: `requestBody` method now requires `Json` instance, due to the changes in kotlinx.serialization
120 |
121 | Version 0.4.2 *(2019-12-07)*
122 | ---
123 |
124 | * `[UPDATED]`: Kotlin 1.3.61
125 |
126 | Version 0.4.0 *(2019-09-02)*
127 | ---
128 |
129 | * `[UPDATED]`: Kotlin 1.3.50
130 | * `[UPDATED]`: kotlinx.serialization 0.12.0
131 | * `[UPDATED]`: Android Gradle Plugin 3.5.0
132 | * `[UPDATED]`: Android target SDK version 29
133 | * `[UPDATED]`: Gradle 5.6.1
134 | * `[ADDED]`: `KgqlError` now provides other GraphQL error fields.
135 |
136 | Version 0.3.2 *(2019-08-13)*
137 | ---
138 |
139 | * `[FIXED]`: ID type is converted to Any [#27](https://github.com/yshrsmz/kgql/issues/27)
140 |
141 | Version 0.3.1 *(2019-07-12)*
142 | ---
143 |
144 | * `[UPDATED]`: Kotlin 1.3.41
145 | * `[UPDATED]`: kotlinx.serialization 0.11.1
146 | * `[UPDATED]`: graphql-java 13.0
147 | * `[UPDATED]`: Android Gradle Plugin 3.4.2
148 | * `[ADDED]`: Support `.graphql` file extension
149 | * `[ADDED]`: Add UnstableDefault annotation
150 | * `[ADDED]`: `requestBody` method now optionally take `kotlinx.serialization.json.Json` instance to customize
151 | serialization behavior
152 |
153 | Version 0.2.2 *(2019-04-18)*
154 | ---
155 |
156 | * `[UPDATED]`: Kotlin 1.3.30
157 | * `[UPDATED]`: kotlinx.serialization 0.11.0
158 | * `[UPDATED]`: Android Gradle Plugin 3.4.0
159 | * `[UPDATED]`: graphql-java 12.0
160 |
161 | Version 0.2.1 *(2019-02-12)*
162 | ---
163 |
164 | * `[ADDED]`: Support iOS Arm32
165 | * `[UPDATED]`: Kotlin 1.3.21
166 | * `[UPDATED]`: Android Gradle Plugin 3.3.1
167 |
168 | Version 0.2.0 *(2019-02-06)*
169 | ---
170 |
171 | * `[UPDATED]`: Rewrite Plugin in Kotlin ([#15](https://github.com/yshrsmz/kgql/issues/15))
172 | * `[UPDATED]`: Applying plugin in Android project now automatically add `core-jvm` dependency.
173 |
174 | Version 0.1.1 *(2019-02-05)*
175 | ---
176 |
177 | * `[UPDATED]`: Replace `println` with `Logger`
178 |
179 | Version 0.1.0 *(2019-01-28)*
180 | ---
181 |
182 | * `[BREAKING]`: Generated Document Objects are now `internal` by
183 | default ([#13](https://github.com/yshrsmz/kgql/issues/13))
184 | * `[FIXED]`: Fix generated file's output directory not correct.
185 | * `[UPDATED]`: Kotlin 1.3.20 ([#14](https://github.com/yshrsmz/kgql/issues/14))
186 | * `[UPDATED]`: Gradle 5.1.1 ([#14](https://github.com/yshrsmz/kgql/issues/14)) and __5.1.x or later__ is required.
187 | * `[UPDATED]`: Android Gradle Plugin 3.3.0
188 |
189 | Version 0.0.7 *(2019-01-22)*
190 | ---
191 |
192 | * `[ADDED]`: Use `kotlinx.serialization.SerialName` annotation ([#11](https://github.com/yshrsmz/kgql/issues/11))
193 | * `[FIXED]`: Android compilation task now depends on `generateKgqlInterface` task properly in Kotlin multiplatform
194 | project ([#12](https://github.com/yshrsmz/kgql/issues/12))
195 | * `[FIXED]`: Gradle Plugin now depends on antlr4 to avoid dependency conflict with Android DataBinding
196 |
197 | Version 0.0.6 *(2019-01-21)*
198 | ---
199 |
200 | * `[BREAKING]`: Create dedicated object for each operation in a
201 | document ([#3](https://github.com/yshrsmz/kgql/issues/3))
202 | * `[BREAKING]`: Change KgqlRequestBody & KgqlResponse to interface ([#8](https://github.com/yshrsmz/kgql/issues/8))
203 | * `[ADDED]`: Change suffix of generate classes to Document, from DocumentWrapper
204 | * `[FIXED]`: Downgrade to Kotlin 1.3.11 ([#8](https://github.com/yshrsmz/kgql/issues/8))
205 |
206 | Version 0.0.5 *(2019-01-15)*
207 | ---
208 |
209 | * `[ADDED]`: Release via `gradle-mvn-mpp-push.gradle`
210 |
211 | Version 0.0.4 *(2019-01-14)*
212 | ---
213 |
214 | * `[FIXED]`: Fix dependency resolution
215 |
216 | Version 0.0.3 *(2019-01-14)*
217 | ---
218 |
219 | * Initial preview release
220 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | kgql
2 | ===
3 |
4 | [](https://maven-badges.herokuapp.com/maven-central/com.codingfeline.kgql/gradle-plugin)
5 |
6 | GraphQL Document wrapper generator for Kotlin Multiplatform Project.
7 | Currently, available for JVM/Android/iOS
8 |
9 | ## core
10 |
11 | kgql core classes
12 |
13 | ## kgql-gradle-plugin
14 |
15 | kgql Gradle Plugin generates wrapper classes for provided GraphQL document files.
16 |
17 | ### Setup
18 |
19 | kgql requires Gradle __7.0 or later__
20 |
21 | Supported GraphQL file extension: `.gql` or `.graphql`
22 |
23 | #### For Android Project
24 |
25 | ```gradle
26 | buildscript {
27 | repositories {
28 | mavenCentral()
29 | google()
30 | jcenter()
31 | }
32 | dependencies {
33 | classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'
34 | classpath 'org.jetbrains.kotlin:kotlin-serialization:1.3.2'
35 | classpath 'com.codingfeline.kgql:gradle-plugin:0.9.0'
36 | }
37 | }
38 |
39 | apply plugin: 'com.android.application'
40 | apply plugin: 'kotlin-android'
41 | apply plugin: 'kotlinx-serialization'
42 | apply plugin: 'com.codingfeline.kgql'
43 |
44 | repositories {
45 | mavenCentral()
46 | }
47 |
48 | kgql {
49 | packageName = "com.sample"
50 | sourceSet = files("src/main/kgql")
51 | typeMapper = [
52 | // mapper for non-scalar type
53 | "UserProfile": "com.sample.data.UserProfile"
54 | ]
55 | }
56 | ```
57 |
58 | #### For Kotlin Multiplatform Project
59 |
60 | ```gradle
61 | buildscript {
62 | repositories {
63 | mavenCentral()
64 | google()
65 | jcenter()
66 | }
67 | dependencies {
68 | classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10'
69 | classpath 'org.jetbrains.kotlin:kotlin-serialization:1.3.2'
70 | classpath 'com.codingfeline.kgql:gradle-plugin:0.9.0'
71 | }
72 | }
73 |
74 | apply plugin: 'kotlin-multiplatform'
75 | apply plugin: 'kotlinx-serialization'
76 | apply plugin: 'com.codingfeline.kgql'
77 |
78 | repositories {
79 | mavenCentral()
80 | }
81 |
82 | kotlin {
83 | // kotlin configurations...
84 | }
85 |
86 | kgql {
87 | packageName = "com.sample"
88 | sourceSet = files("src/main/kgql")
89 | typeMapper = [
90 | // mapper for non-scalar type
91 | "UserProfile": "com.sample.data.UserProfile"
92 | ]
93 | }
94 | ```
95 |
96 | #### How to generate wrapper classes
97 |
98 | When you apply kgql plugin, `generateKgqlInterface` task is added to the project. Manually executing it is one way, but
99 | the task is integrated into project's build task, so it will be generated upon each build.
100 |
101 | ## [WIP]kgql-ktor
102 |
103 | ktor extensions for kgql
104 |
105 | ## How it works
106 |
107 | ```
108 | # viewer.gql
109 | query {
110 | viewer {
111 | login
112 | }
113 | }
114 | ```
115 |
116 | Below code will be generated from above GraphQL document file(viewer.gql).
117 |
118 | ```kotlin
119 | package com.sample
120 |
121 | import com.codingfeline.kgql.core.KgqlRequestBody
122 | import kotlin.String
123 | import kotlin.Unit
124 | import kotlinx.serialization.KSerializer
125 | import kotlinx.serialization.Optional
126 | import kotlinx.serialization.SerialName
127 | import kotlinx.serialization.Serializable
128 |
129 | object ViewerDocument {
130 | private val document: String = """
131 | |query {
132 | | viewer {
133 | | login
134 | | }
135 | |}
136 | |""".trimMargin()
137 |
138 | object Query {
139 | /**
140 | * Create an instance of [Request] which then you can encode to JSON string
141 | */
142 | fun requestBody(): Request = Request()
143 |
144 | fun serializer(): KSerializer = Request.serializer()
145 |
146 | @Serializable
147 | data class Request(
148 | @SerialName(value = "variables") @Optional override val variables: Unit? = null,
149 | @Optional @SerialName(value = "operationName") override val operationName: String? =
150 | null,
151 | @SerialName(value = "query") override val query: String = document
152 | ) : KgqlRequestBody
153 | }
154 | }
155 | ```
156 |
157 | As you can see, generated code utilizes data class's default value. So in order to properly serialize, you need to
158 | set `encodeDefaults` to true in your `kotlinx.serialization.json.Json` instance.
159 |
160 | You can use this code with Ktor or any other HttpClient.
161 |
162 | Example usage with Ktor is below
163 |
164 | ```kotlin
165 | package com.sample
166 |
167 | import com.codingfeline.kgql.core.KgqlResponse
168 | import com.codingfeline.kgql.core.KgqlError
169 | import com.sample.ViewerDocument
170 | import io.ktor.client.HttpClient
171 | import io.ktor.client.features.json.JsonFeature
172 | import io.ktor.client.request.headers
173 | import io.ktor.client.request.post
174 | import io.ktor.http.ContentType
175 | import io.ktor.http.content.TextContent
176 | import io.ktor.http.Url
177 | import kotlinx.serialization.json.JSON
178 | import kotlinx.serialization.Serializable
179 |
180 | const val TOKEN = "YOUR_GITHUB_TOKEN"
181 |
182 | @Serializable
183 | data class ViewerWrapper(
184 | val viewer: Viewer
185 | )
186 |
187 | @Serializable
188 | data class Viewer(
189 | val login: String
190 | )
191 |
192 | @Serializable
193 | data class ViewerResponse(
194 | override val data: ViewerWrapper?,
195 | override val errors: List?
196 | ) : KgqlResponse
197 |
198 |
199 | class GitHubApi {
200 |
201 | private val json = Json {
202 | // encodeDefaults must be set to true
203 | encodeDefaults = true
204 | }
205 |
206 | private val client = HttpClient {
207 | install(JsonFeature) {
208 | this.serializer = KotlinxSerializer(json = json)
209 | }
210 | }
211 |
212 | suspend fun fetchLogin(): Viewer? {
213 |
214 | val body = json.encodeToString(ViewerDocument.Query.serializer(), ViewerDocument.Query.requestBody())
215 | val response = client.post(url = Url("https://api.github.com/graphql")) {
216 | body = TextContent(text = body, contentType = ContentType.Application.Json)
217 |
218 | headers {
219 | append("Authorization", "bearer $TOKEN")
220 | }
221 | }
222 |
223 | val res = JSON.parse(ViewerResponse.serializer(), response)
224 |
225 | return res.data?.viewer
226 | }
227 | }
228 |
229 | ```
230 |
231 | ## Try out the sample
232 |
233 | Have a look at `./sample` directory.
234 |
235 | ```
236 | # Try out the samples.
237 | # BuildKonfig will be generated in ./sample/build/kgql
238 | $ ./gradlew -p sample generateKgqlInterface
239 | ```
240 |
241 | ### Try sample with snapshot
242 |
243 | ```
244 | # Try out the samples.
245 | # BuildKonfig will be generated in ./sample/build/kgql
246 | $ ./gradlew clean build installArchives
247 | $ ./gradlew -p sample generateKgqlInterface
248 | ```
249 |
250 | ## Credits
251 |
252 | This library is highly inspired by [squareup/sqldelight](https://github.com/squareup/sqldelight) and the gradle plugin
253 | and basic idea is heavily based on it. Thanks for this.
254 |
--------------------------------------------------------------------------------
/kgql-gradle-plugin/src/test/kotlin/com/codingfeline/kgql/gradle/KgqlPluginTest.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.gradle
2 |
3 | import com.google.common.truth.Truth.assertThat
4 | import org.gradle.testkit.runner.GradleRunner
5 | import org.junit.Test
6 | import org.junit.experimental.categories.Category
7 | import java.io.File
8 |
9 | class KgqlPluginTest {
10 |
11 | @Test
12 | fun `Applying the plugin without Kotlin applied throws`() {
13 | val fixtureRoot = File("src/test/no-kotlin")
14 |
15 | val runner = GradleRunner.create()
16 | .withProjectDir(fixtureRoot)
17 | .withPluginClasspath()
18 |
19 | val result = runner.withArguments("build", "--stacktrace")
20 | .buildAndFail()
21 |
22 | assertThat(result.output).contains("Kgql Gradle Plugin applied in project ':' but no supported Kotlin plugin was found")
23 | }
24 |
25 | @Test
26 | fun `Applying the plugin without kotlinx-serialization applied throws`() {
27 | val fixtureRoot = File("src/test/kotlin-mpp-no-serialization")
28 |
29 | val runner = GradleRunner.create()
30 | .withProjectDir(fixtureRoot)
31 | .withPluginClasspath()
32 |
33 | val result = runner.withArguments("build", "--stacktrace")
34 | .buildAndFail()
35 |
36 | assertThat(result.output).contains("Kgql Gradle Plugin applied in project ':' but no kotlinx-serialization plugin was found")
37 | }
38 |
39 | @Test
40 | fun `Applying the plugin without Kotlin applied throws for Android`() {
41 | val fixtureRoot = File("src/test/no-kotlin-android")
42 | val runner = GradleRunner.create()
43 | .withProjectDir(fixtureRoot)
44 | .withPluginClasspath()
45 |
46 | val result = runner
47 | .withArguments("build", "--stacktrace")
48 | .buildAndFail()
49 | assertThat(result.output)
50 | .contains("Kgql Gradle Plugin applied in project ':' but no supported Kotlin plugin was found")
51 | }
52 |
53 | @Test
54 | fun `Applying the android plugin works fine for library projects`() {
55 | val androidHome = androidHome()
56 | val fixtureRoot = File("src/test/library-project")
57 | File(fixtureRoot, "local.properties").writeText("sdk.dir=$androidHome\n")
58 |
59 | val runner = GradleRunner.create()
60 | .withProjectDir(fixtureRoot)
61 | .withPluginClasspath()
62 |
63 | val result = runner
64 | .withArguments("clean", "generateDebugKgqlInterface", "--stacktrace")
65 | .build()
66 | assertThat(result.output).contains("BUILD SUCCESSFUL")
67 |
68 | // Assert the plugin added the common dependency
69 | val dependenciesResult = runner
70 | .withArguments("dependencies", "--stacktrace")
71 | .build()
72 | assertThat(dependenciesResult.output).contains("com.codingfeline.kgql:core-jvm")
73 | }
74 |
75 | @Test
76 | fun `Applying the plugin works fine for multiplatform projects`() {
77 | val fixtureRoot = File("src/test/kotlin-mpp")
78 | val runner = GradleRunner.create()
79 | .withProjectDir(fixtureRoot)
80 | .withPluginClasspath()
81 |
82 | val result = runner
83 | .withArguments("clean", "generateKgqlInterface", "--stacktrace", "--info")
84 | .build()
85 | assertThat(result.output).contains("BUILD SUCCESSFUL")
86 |
87 | // Assert the plugin added the common dependency
88 | val dependenciesResult = runner
89 | .withArguments("dependencies", "--stacktrace")
90 | .build()
91 | assertThat(dependenciesResult.output).contains("com.codingfeline.kgql:core")
92 | }
93 |
94 | @Test
95 | fun `The generate task is a dependency of multiplatform js target`() {
96 | val fixtureRoot = File("src/test/kotlin-mpp")
97 | val runner = GradleRunner.create()
98 | .withProjectDir(fixtureRoot)
99 | .withPluginClasspath()
100 |
101 | val buildDir = File(fixtureRoot, "build/generated/kgql")
102 |
103 | buildDir.delete()
104 | val result = runner
105 | .withArguments("clean", "compileKotlinJs", "--stacktrace")
106 | .build()
107 | assertThat(result.output).contains("generateCommonMainKgqlInterface")
108 | assertThat(buildDir.exists()).isTrue()
109 | }
110 |
111 | @Test
112 | fun `The generate task is a dependency of multiplatform jvm target`() {
113 | val fixtureRoot = File("src/test/kotlin-mpp")
114 | val runner = GradleRunner.create()
115 | .withProjectDir(fixtureRoot)
116 | .withPluginClasspath()
117 |
118 | val buildDir = File(fixtureRoot, "build/generated/kgql")
119 | buildDir.delete()
120 |
121 | val result = runner
122 | .withArguments("clean", "compileKotlinJvm", "--stacktrace")
123 | .build()
124 | assertThat(result.output).contains("generateCommonMainKgqlInterface")
125 | assertThat(buildDir.exists()).isTrue()
126 | }
127 |
128 | @Test
129 | fun `The generate task is a dependency of multiplatform android target`() {
130 | val fixtureRoot = File("src/test/kotlin-mpp-android-ios")
131 | val runner = GradleRunner.create()
132 | .withProjectDir(fixtureRoot)
133 | .withPluginClasspath()
134 |
135 | val buildDir = File(fixtureRoot, "build/generated/kgql")
136 | buildDir.delete()
137 |
138 | val result = runner
139 | .withArguments("clean", "compileDebugKotlinAndroid", "--stacktrace", "--info")
140 | .build()
141 | assertThat(result.output).contains("BUILD SUCCESSFUL")
142 | assertThat(result.output).contains("generateCommonMainKgqlInterface")
143 | }
144 |
145 | @Test
146 | @Category(IosTest::class)
147 | fun `The generate task is a dependency of multiplatform ios target - Arm64`() {
148 | val fixtureRoot = File("src/test/kotlin-mpp")
149 | val runner = GradleRunner.create()
150 | .withProjectDir(fixtureRoot)
151 | .withPluginClasspath()
152 |
153 | val buildDir = File(fixtureRoot, "build/generated/kgql")
154 |
155 | buildDir.delete()
156 | val result = runner
157 | .withArguments("clean", "linkDebugFrameworkIosArm64", "--stacktrace")
158 | .build()
159 |
160 | assertThat(result.output).contains("generateCommonMainKgqlInterface")
161 | assertThat(buildDir.exists()).isTrue()
162 | }
163 |
164 | @Test
165 | @Category(IosTest::class)
166 | fun `The generate task is a dependency of multiplatform ios target - X64`() {
167 | val fixtureRoot = File("src/test/kotlin-mpp")
168 | val runner = GradleRunner.create()
169 | .withProjectDir(fixtureRoot)
170 | .withPluginClasspath()
171 |
172 | val buildDir = File(fixtureRoot, "build/generated/kgql")
173 |
174 | buildDir.delete()
175 | val result = runner
176 | .withArguments("clean", "linkDebugFrameworkIosX64", "--stacktrace")
177 | .build()
178 |
179 | assertThat(result.output).contains("generateCommonMainKgqlInterface")
180 | assertThat(buildDir.exists()).isTrue()
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Stop when "xargs" is not available.
209 | if ! command -v xargs >/dev/null 2>&1
210 | then
211 | die "xargs is not available"
212 | fi
213 |
214 | # Use "xargs" to parse quoted args.
215 | #
216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
217 | #
218 | # In Bash we could simply go:
219 | #
220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
221 | # set -- "${ARGS[@]}" "$@"
222 | #
223 | # but POSIX shell has neither arrays nor command substitution, so instead we
224 | # post-process each arg (as a line of input to sed) to backslash-escape any
225 | # character that might be a shell metacharacter, then use eval to reverse
226 | # that process (while maintaining the separation between arguments), and wrap
227 | # the whole thing up as a single "set" statement.
228 | #
229 | # This will of course break if any of these variables contains a newline or
230 | # an unmatched quote.
231 | #
232 |
233 | eval "set -- $(
234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
235 | xargs -n1 |
236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
237 | tr '\n' ' '
238 | )" '"$@"'
239 |
240 | exec "$JAVACMD" "$@"
241 |
--------------------------------------------------------------------------------
/kgql-compiler/src/test/kotlin/com/codingfeline/kgql/compiler/DocumentWrapperTest.kt:
--------------------------------------------------------------------------------
1 | package com.codingfeline.kgql.compiler
2 |
3 | import com.codingfeline.kgql.test.util.FixtureCompiler
4 | import com.google.common.truth.Truth.assertThat
5 | import org.junit.Rule
6 | import org.junit.Test
7 | import org.junit.rules.TemporaryFolder
8 | import java.io.File
9 |
10 | class DocumentWrapperTest {
11 | @get:Rule
12 | val tempFolder = TemporaryFolder()
13 |
14 | @Test
15 | fun `documentWrapper create an object for an operation in a document`() {
16 | val result = FixtureCompiler.compileGql(
17 | """
18 | |query {
19 | | viewer {
20 | | login
21 | | }
22 | |}
23 | |""".trimMargin(),
24 | tempFolder
25 | )
26 |
27 | assertThat(result.errors).isEmpty()
28 |
29 | val documentWrapperFile = result.compilerOutput[File(result.outputDirectory, "com/example/TestDocument.kt")]
30 | assertThat(documentWrapperFile).isNotNull()
31 | assertThat(documentWrapperFile.toString()).isEqualTo(
32 | """
33 | |package com.example
34 | |
35 | |import com.codingfeline.kgql.core.KgqlRequestBody
36 | |import kotlin.String
37 | |import kotlin.Unit
38 | |import kotlinx.serialization.KSerializer
39 | |import kotlinx.serialization.SerialName
40 | |import kotlinx.serialization.Serializable
41 | |
42 | |internal object TestDocument {
43 | | private val document: String = ""${'"'}
44 | | |query {
45 | | | viewer {
46 | | | login
47 | | | }
48 | | |}
49 | | |""${'"'}.trimMargin()
50 | |
51 | | public object Query {
52 | | public val operationName: String? = null
53 | |
54 | | /**
55 | | * Create an instance of [Request] which then you can encode to JSON string
56 | | */
57 | | public fun requestBody(): Request = Request()
58 | |
59 | | public fun serializer(): KSerializer = Request.serializer()
60 | |
61 | | @Serializable
62 | | public data class Request(
63 | | @SerialName(value = "variables")
64 | | public override val variables: Unit? = null,
65 | | @SerialName(value = "operationName")
66 | | public override val operationName: String? = Query.operationName,
67 | | @SerialName(value = "query")
68 | | public override val query: String = document,
69 | | ) : KgqlRequestBody
70 | | }
71 | |}
72 | |
73 | """.trimMargin()
74 | )
75 | }
76 |
77 |
78 | @Test
79 | fun `documentWrapper create objects for each operations in a document`() {
80 | val result = FixtureCompiler.compileGql(
81 | """
82 | |query CodeOfConduct {
83 | | codesOfConduct {
84 | | body
85 | | key
86 | | name
87 | | }
88 | |}
89 | |
90 | |query Test{
91 | | viewer {
92 | | login
93 | | }
94 | |}
95 | """.trimMargin(),
96 | tempFolder
97 | )
98 |
99 | assertThat(result.errors).isEmpty()
100 | val documentWrapperFile = result.compilerOutput[File(result.outputDirectory, "com/example/TestDocument.kt")]
101 | assertThat(documentWrapperFile).isNotNull()
102 | assertThat(documentWrapperFile.toString()).isEqualTo(
103 | """
104 | |package com.example
105 | |
106 | |import com.codingfeline.kgql.core.KgqlRequestBody
107 | |import kotlin.String
108 | |import kotlin.Unit
109 | |import kotlinx.serialization.KSerializer
110 | |import kotlinx.serialization.SerialName
111 | |import kotlinx.serialization.Serializable
112 | |
113 | |internal object TestDocument {
114 | | private val document: String = ""${'"'}
115 | | |query CodeOfConduct {
116 | | | codesOfConduct {
117 | | | body
118 | | | key
119 | | | name
120 | | | }
121 | | |}
122 | | |
123 | | |query Test{
124 | | | viewer {
125 | | | login
126 | | | }
127 | | |}
128 | | ""${'"'}.trimMargin()
129 | |
130 | | public object CodeOfConductQuery {
131 | | public val operationName: String? = "CodeOfConduct"
132 | |
133 | | /**
134 | | * Create an instance of [Request] which then you can encode to JSON string
135 | | */
136 | | public fun requestBody(): Request = Request()
137 | |
138 | | public fun serializer(): KSerializer = Request.serializer()
139 | |
140 | | @Serializable
141 | | public data class Request(
142 | | @SerialName(value = "variables")
143 | | public override val variables: Unit? = null,
144 | | @SerialName(value = "operationName")
145 | | public override val operationName: String? = CodeOfConductQuery.operationName,
146 | | @SerialName(value = "query")
147 | | public override val query: String = document,
148 | | ) : KgqlRequestBody
149 | | }
150 | |
151 | | public object TestQuery {
152 | | public val operationName: String? = "Test"
153 | |
154 | | /**
155 | | * Create an instance of [Request] which then you can encode to JSON string
156 | | */
157 | | public fun requestBody(): Request = Request()
158 | |
159 | | public fun serializer(): KSerializer = Request.serializer()
160 | |
161 | | @Serializable
162 | | public data class Request(
163 | | @SerialName(value = "variables")
164 | | public override val variables: Unit? = null,
165 | | @SerialName(value = "operationName")
166 | | public override val operationName: String? = TestQuery.operationName,
167 | | @SerialName(value = "query")
168 | | public override val query: String = document,
169 | | ) : KgqlRequestBody
170 | | }
171 | |}
172 | |
173 | """.trimMargin()
174 | )
175 | }
176 |
177 | @Test
178 | fun `documentWrapper creates Variables class if an operation has parameters`() {
179 | val result = FixtureCompiler.compileGql(
180 | """
181 | |query WithVariables(${"$"}login: String!) {
182 | | user(login: ${'$'}login) {
183 | | id
184 | | login
185 | | bio
186 | | avatarUrl
187 | | company
188 | | createdAt
189 | | }
190 | |}
191 | """.trimMargin(),
192 | tempFolder
193 | )
194 |
195 | assertThat(result.errors).isEmpty()
196 |
197 | val documentWrapperFile = result.compilerOutput[File(result.outputDirectory, "com/example/TestDocument.kt")]
198 | assertThat(documentWrapperFile).isNotNull()
199 | assertThat(documentWrapperFile.toString()).isEqualTo(
200 | """
201 | |package com.example
202 | |
203 | |import com.codingfeline.kgql.core.KgqlRequestBody
204 | |import kotlin.String
205 | |import kotlinx.serialization.KSerializer
206 | |import kotlinx.serialization.SerialName
207 | |import kotlinx.serialization.Serializable
208 | |
209 | |internal object TestDocument {
210 | | private val document: String = ""${'"'}
211 | | |query WithVariables(${"$" + "{'$'}"}login: String!) {
212 | | | user(login: ${"$" + "{'$'}"}login) {
213 | | | id
214 | | | login
215 | | | bio
216 | | | avatarUrl
217 | | | company
218 | | | createdAt
219 | | | }
220 | | |}
221 | | ""${'"'}.trimMargin()
222 | |
223 | | public object WithVariablesQuery {
224 | | public val operationName: String? = "WithVariables"
225 | |
226 | | /**
227 | | * Create an instance of [Request] which then you can encode to JSON string
228 | | */
229 | | public fun requestBody(variables: Variables): Request = Request(variables = variables)
230 | |
231 | | public fun serializer(): KSerializer = Request.serializer()
232 | |
233 | | @Serializable
234 | | public data class Variables(
235 | | @SerialName(value = "login")
236 | | public val login: String,
237 | | )
238 | |
239 | | @Serializable
240 | | public data class Request(
241 | | @SerialName(value = "variables")
242 | | public override val variables: Variables?,
243 | | @SerialName(value = "operationName")
244 | | public override val operationName: String? = WithVariablesQuery.operationName,
245 | | @SerialName(value = "query")
246 | | public override val query: String = document,
247 | | ) : KgqlRequestBody
248 | | }
249 | |}
250 | |
251 | """.trimMargin()
252 | )
253 | }
254 | }
255 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------