diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..79487c2 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,26 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +indent_style = space +trim_trailing_whitespace = true + +[*.{kt,kts}] +max_line_length=140 + +[*.kt] +ij_kotlin_name_count_to_use_star_import = 99 +ij_kotlin_name_count_to_use_star_import_for_members = 99 + +ktlint_standard_import-ordering = disabled +ktlint_standard_filename = disabled + +[*.kts] +ktlint_gradle-kotlin-dsl_gradle-kotlin-dsl-blank-lines = disabled +ktlint_gradle-kotlin-dsl_gradle-kotlin-dsl-imports = disabled +ktlint_gradle-kotlin-dsl_visibility-modifiers-own-lin = disabled + +[*.bat] +end_of_line = crlf diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..9af0acf --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: + - package-ecosystem: "gradle" + directory: "/" + schedule: + interval: "weekly" + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..0b3ac44 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,55 @@ +name: CI + +on: + push: + pull_request: + +permissions: + contents: read + actions: read + checks: write + +jobs: + gradle-build: + runs-on: ubuntu-latest + steps: + - name: Checkout project sources + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-java@v4 + with: + distribution: zulu + java-version: 21 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v3 + + - name: Run build with Gradle Wrapper + run: ./gradlew build + + - name: Test Report + uses: dorny/test-reporter@v1 + if: success() || failure() # run this step even if previous step failed + with: + name: Test reports + path: build/test-results/**/TEST-*.xml + reporter: java-junit + + auto-merge-dependabot: + name: 🤖 Auto merge dependabot PR + timeout-minutes: 10 + needs: [ gradle-build ] + if: ${{ github.actor == 'dependabot[bot]' }} + runs-on: ubuntu-latest + permissions: + pull-requests: write + contents: write + steps: + - name: 🤖 Merge PR from dependabot + uses: fastify/github-action-merge-dependabot@v3.10.1 + with: + github-token: ${{secrets.GITHUB_TOKEN}} + target: minor + merge-method: squash diff --git a/.github/workflows/dependency-submission.yml b/.github/workflows/dependency-submission.yml new file mode 100644 index 0000000..0966857 --- /dev/null +++ b/.github/workflows/dependency-submission.yml @@ -0,0 +1,22 @@ +name: Dependency Submission + +on: [ push ] + +permissions: + contents: write + +jobs: + dependency-submission: + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v4 + + - name: Setup Java + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-version: 21 + + - name: Generate and submit dependency graph + uses: gradle/actions/dependency-submission@v3 diff --git a/.github/workflows/wrapper-validation.yml b/.github/workflows/wrapper-validation.yml new file mode 100644 index 0000000..2e581e6 --- /dev/null +++ b/.github/workflows/wrapper-validation.yml @@ -0,0 +1,10 @@ +name: "Validate Gradle Wrapper" +on: [push, pull_request] + +jobs: + validation: + name: "Validation" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: gradle/actions/wrapper-validation@v3 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1f93dfc --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +.idea diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..0a87bf7 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,18 @@ +repos: + - repo: https://github.com/jguttman94/pre-commit-gradle + rev: v0.3.0 + hooks: + - id: gradle-spotless + args: [ --wrapper, --output ] + - id: gradle-task + name: gradle spotless [buildSrc] + args: [ --wrapper, -p buildSrc, spotlessApply] + + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-case-conflict + - id: check-json + - id: check-xml + - id: check-yaml + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c723398 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 red green coding + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f1a2468 --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +Kotlin single module project blueprint +====================================== + +Buildtool +* Gradle (Kotlin DSL) + +Basic dependencies +* Kotlin JVM +* Kotlin Logging +* slf4j + logback + +Testing +* Kotest +* mockk + +## pre-commit hooks + +Dependencies: https://pre-commit.com/#installation + +* Install git hook: https://pre-commit.com/#3-install-the-git-hook-scripts +```bash +pre-commit install +``` +* Test hook: +```bash +pre-commit run --all-files +``` diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..c0af8b4 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,42 @@ +plugins { + id("module-conventions") + + id("com.google.devtools.ksp") version "1.9.23-1.0.20" + + kotlin("plugin.serialization") version "1.9.23" + + // https://foso.github.io/Ktorfit/ + id("de.jensklingenberg.ktorfit") version "1.13.0" +} + +dependencies { + implementation(platform("io.arrow-kt:arrow-stack:1.2.4")) + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3") + + implementation("io.arrow-kt:arrow-core") + implementation("io.arrow-kt:arrow-fx-coroutines") + implementation("io.arrow-kt:arrow-optics") + implementation("io.arrow-kt:arrow-exact:0.1.0") + ksp("io.arrow-kt:arrow-optics-ksp-plugin:1.2.4") + + val ktorfitVersion = "1.13.0" + + ksp("de.jensklingenberg.ktorfit:ktorfit-ksp:$ktorfitVersion") + + implementation("de.jensklingenberg.ktorfit:ktorfit-lib:$ktorfitVersion") + + testImplementation("io.kotest.extensions:kotest-assertions-arrow:1.4.0") + + implementation(platform("io.ktor:ktor-bom:2.3.10")) + + testImplementation("io.ktor:ktor-client-content-negotiation") + testImplementation("io.ktor:ktor-serialization-kotlinx-json") + + testImplementation("io.ktor:ktor-client-logging") +} + +spotless { + kotlin { + targetExclude("build/generated/**") + } +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 0000000..df61aa1 --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,32 @@ +plugins { + `kotlin-dsl` + id("com.diffplug.spotless") version libs.versions.gradleSpotlessPlugin.get() +} + +repositories { + gradlePluginPortal() +} + +dependencies { + val kotlinVersion = libs.versions.kotlin.get() + val testLoggerPluginVersion = libs.versions.gradleTestLoggerPlugin.get() + val spotlessVersion = libs.versions.gradleSpotlessPlugin.get() + + implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") + implementation("com.adarshr:gradle-test-logger-plugin:$testLoggerPluginVersion") + implementation("com.diffplug.spotless:spotless-plugin-gradle:$spotlessVersion") + + // workaround to be able to use the version catalog inside of gradle convention plugins + implementation(files(libs.javaClass.superclass.protectionDomain.codeSource.location)) +} + +configure { + // ratchetFrom("origin/main") + + kotlin { + ktlint() + } + kotlinGradle { + ktlint() + } +} diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts new file mode 100644 index 0000000..b5a0fab --- /dev/null +++ b/buildSrc/settings.gradle.kts @@ -0,0 +1,7 @@ +dependencyResolutionManagement { + versionCatalogs { + create("libs") { + from(files("../gradle/libs.versions.toml")) + } + } +} diff --git a/buildSrc/src/main/kotlin/kotlin-conventions.gradle.kts b/buildSrc/src/main/kotlin/kotlin-conventions.gradle.kts new file mode 100644 index 0000000..9e63b6d --- /dev/null +++ b/buildSrc/src/main/kotlin/kotlin-conventions.gradle.kts @@ -0,0 +1,53 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.gradle.accessors.dm.LibrariesForLibs + +plugins { + id("org.jetbrains.kotlin.jvm") +} + +repositories { + mavenCentral() +} + +val libs = the() + +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(libs.versions.java.get())) + } +} + +dependencies { + constraints { + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + } + + // Align versions of all Kotlin components + implementation(platform("org.jetbrains.kotlin:kotlin-bom")) + + // Use the Kotlin JDK 8 standard library. + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") +} + +val isIdea = providers.systemProperty("idea.version").isPresent + +tasks.withType(KotlinCompile::class.java).configureEach { + kotlinOptions { + // don't fail the build when running tests in idea! + allWarningsAsErrors = !isIdea + + incremental = true + freeCompilerArgs = listOf("-Xjsr305=strict", "-Xcontext-receivers") + + if (isIdea) { + freeCompilerArgs += "-Xdebug" + } + + jvmTarget = libs.versions.java.get() + } +} + +tasks.withType { + sourceCompatibility = libs.versions.java.get() + targetCompatibility = libs.versions.java.get() +} diff --git a/buildSrc/src/main/kotlin/module-conventions.gradle.kts b/buildSrc/src/main/kotlin/module-conventions.gradle.kts new file mode 100644 index 0000000..c006148 --- /dev/null +++ b/buildSrc/src/main/kotlin/module-conventions.gradle.kts @@ -0,0 +1,63 @@ +import org.gradle.accessors.dm.LibrariesForLibs + +plugins { + id("kotlin-conventions") + id("com.adarshr.test-logger") + id("com.diffplug.spotless") +} + +val libs = the() + +dependencies { + implementation(libs.kotlinLogging) + + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.bundles.kotest) + testImplementation(libs.mockk.core) + + runtimeOnly(libs.bundles.logback) + runtimeOnly(libs.bundles.slf4j) +} + +val isIdea = providers.systemProperty("idea.version") +testlogger { + // idea can't handle ANSI output + setTheme(if (isIdea.isPresent) "plain" else "mocha") + showFullStackTraces = false + + showStandardStreams = true + showPassedStandardStreams = false + showSkippedStandardStreams = false + showFailedStandardStreams = true + + showPassed = true + showSkipped = false + showFailed = true +} + +configurations { + all { + exclude(module = "log4j") + exclude(module = "mockito-core") + exclude(module = "junit") + exclude(module = "commons-logging") + } +} + +tasks.withType().configureEach { + useJUnitPlatform() +} + +configure { + // ratchetFrom("origin/main") + + kotlin { + ktlint() + } + kotlinGradle { + ktlint() + } + java { + googleJavaFormat().aosp() + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..d39edd1 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.caching=true +org.gradle.configuration-cache=true +org.gradle.parallel=true diff --git a/gradle/gng.cfg b/gradle/gng.cfg new file mode 100644 index 0000000..adc8690 --- /dev/null +++ b/gradle/gng.cfg @@ -0,0 +1,12 @@ +# Configuration file of gng +# 1. key/value pair is separated using '=' +# 2. Line starts with '#' will be ignored. +# 3. Empty line is ignored +# 4. Variable Substitution based on envsubst. 'envsubst' is from GNU gettext utilities. +# Please visit https://command-not-found.com/envsubst to find out how to install it +# 5. 'envsubst' is strongly recommended. But it is not mandatory. You can still configure 'gng' using plain values. + +# https://github.com/ddimtirov/gwo-agent +#gwo_agent_jar=~/.gradle/gwo-agent.jar +#GRADLE_OPTS=-javaagent:${gwo_agent_jar}=distributionUrl~=@https://services.gradle.org/distributions@https://mymirror/gradle/@ + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..b6cd2ae --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,45 @@ +[versions] + +java = "21" +kotlin = "1.9.23" + +slf4j = "2.0.13" +logback = "1.5.6" + +junit = "5.10.2" +kotest = "5.8.1" +mockk = "1.13.10" + +ktlint = "0.50.0" + +gradleTestLoggerPlugin = "4.0.0" +gradleSpotlessPlugin = "6.25.0" + +[libraries] + +# Logging +kotlinLogging = "io.github.microutils:kotlin-logging-jvm:3.0.5" + +slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +slf4j-jul = { module = "org.slf4j:jul-to-slf4j", version.ref = "slf4j" } +slf4j-jcl = { module = "org.slf4j:jcl-over-slf4j", version.ref = "slf4j" } + +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } +logback-core = { module = "ch.qos.logback:logback-core", version.ref = "logback" } + +# Testing +junit-bom = { module = "org.junit:junit-bom", version.ref="junit" } + +kotest-runner = { module = "io.kotest:kotest-runner-junit5", version.ref = "kotest" } +kotest-assertions = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" } +kotest-datatest = { module = "io.kotest:kotest-framework-datatest", version.ref = "kotest" } +kotest-property = { module = "io.kotest:kotest-property", version.ref = "kotest" } +kotest-json = { module = "io.kotest:kotest-assertions-json", version.ref = "kotest"} + +mockk-core = { module = "io.mockk:mockk", version.ref = "mockk" } + +[bundles] + +kotest = ["kotest-runner", "kotest-assertions", "kotest-datatest", "kotest-json", "kotest-property"] +logback = ["logback-classic", "logback-core"] +slf4j = ["slf4j-jul", "slf4j-jcl", "slf4j-api"] diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..dca0c92 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "arrow-ktor" diff --git a/src/main/kotlin/arrow/ArrowEitherConverterFactory.kt b/src/main/kotlin/arrow/ArrowEitherConverterFactory.kt new file mode 100644 index 0000000..a780d1b --- /dev/null +++ b/src/main/kotlin/arrow/ArrowEitherConverterFactory.kt @@ -0,0 +1,69 @@ +package arrow + +import arrow.core.Either +import arrow.core.Either.Left +import arrow.core.left +import arrow.core.right +import de.jensklingenberg.ktorfit.Ktorfit +import de.jensklingenberg.ktorfit.converter.Converter +import de.jensklingenberg.ktorfit.converter.KtorfitResult +import de.jensklingenberg.ktorfit.internal.TypeData +import io.ktor.client.call.body +import io.ktor.client.statement.HttpResponse +import kotlinx.coroutines.runBlocking + +class ArrowEitherConverterFactory : Converter.Factory { + override fun suspendResponseConverter( + typeData: TypeData, + ktorfit: Ktorfit, + ): Converter.SuspendResponseConverter>? { + if (typeData.typeInfo.type == Either::class) { + return object : Converter.SuspendResponseConverter> { + override suspend fun convert(result: KtorfitResult): Either = + result.fold(::Left) { + readBody(it, typeData) + } + + @Deprecated("deprecated in interface") + override suspend fun convert(response: HttpResponse): Either { + throw AssertionError("required by the interface but shouldn't be used directly!") + } + } + } + return null + } + + private suspend fun readBody( + httpResponse: HttpResponse, + typeData: TypeData, + ): Either = + try { + httpResponse.body>(typeData.typeArgs[1].typeInfo).right() + } catch (ex: Exception) { + ex.left() + } + + override fun responseConverter( + typeData: TypeData, + ktorfit: Ktorfit, + ): Converter.ResponseConverter>? { + if (typeData.typeInfo.type == Either::class) { + return object : Converter.ResponseConverter> { + override fun convert(getResponse: suspend () -> HttpResponse): Either = + runBlocking { + readBody(getResponse(), typeData) + } + } + } + return null + } +} + +internal inline fun KtorfitResult.fold( + onFailure: (Throwable) -> T, + onSuccess: (HttpResponse) -> T, +): T = + when (this) { + is KtorfitResult.Failure -> onFailure(throwable) + is KtorfitResult.Success -> onSuccess(this.response) + } diff --git a/src/main/kotlin/demo/ExampleApi.kt b/src/main/kotlin/demo/ExampleApi.kt new file mode 100644 index 0000000..1509267 --- /dev/null +++ b/src/main/kotlin/demo/ExampleApi.kt @@ -0,0 +1,29 @@ +package demo + +import arrow.core.Either +import de.jensklingenberg.ktorfit.http.GET +import io.ktor.client.statement.HttpResponse +import kotlinx.serialization.Serializable + +interface ExampleApi { + @GET("people/1/") + suspend fun getPerson(): String + + @GET("people/1/") + suspend fun getPersonJson(): PersonResponse + + @GET("people/1/") + suspend fun getPersonArrow(): Either + + @GET("people/1/") + fun getPersonArrow2(): Either + + @GET("people/a/") + suspend fun getPersonArrowFailing(): Either + + @GET("people/1/") + suspend fun getPersonKtor(): Either +} + +@Serializable +data class PersonResponse(val name: String, val birth_year: String, val films: List) diff --git a/src/test/kotlin/demo/ExampleApiSpec.kt b/src/test/kotlin/demo/ExampleApiSpec.kt new file mode 100644 index 0000000..a9cf5fe --- /dev/null +++ b/src/test/kotlin/demo/ExampleApiSpec.kt @@ -0,0 +1,212 @@ +package demo + +import arrow.ArrowEitherConverterFactory +import de.jensklingenberg.ktorfit.Ktorfit +import io.kotest.assertions.arrow.core.shouldBeLeft +import io.kotest.assertions.arrow.core.shouldBeRight +import io.kotest.core.spec.style.StringSpec +import io.kotest.matchers.collections.shouldNotBeEmpty +import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.types.shouldBeInstanceOf +import io.ktor.client.HttpClient +import io.ktor.client.plugins.ClientRequestException +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.plugins.logging.LogLevel +import io.ktor.client.plugins.logging.Logger +import io.ktor.client.plugins.logging.Logging +import io.ktor.http.HttpStatusCode +import io.ktor.serialization.JsonConvertException +import io.ktor.serialization.kotlinx.json.json +import kotlinx.serialization.json.Json + +class ExampleApiSpec : StringSpec({ + + "suspend GET -> String" { + val exampleApi = buildApiClient() + + exampleApi.getPerson() shouldContain "Luke Skywalker" + } + + "suspend GET -> KotlinX Serializable" { + val ktorClient = + HttpClient { + install(ContentNegotiation) { + json( + Json { + isLenient = true + ignoreUnknownKeys = true + }, + ) + } + } + + val exampleApi = + buildApiClient { + it.httpClient(ktorClient) + } + + exampleApi.getPersonJson().let { + it.name shouldBe "Luke Skywalker" + it.birth_year shouldBe "19BBY" + it.films.shouldNotBeEmpty() + } + } + + "suspend GET -> Either" { + + val ktorClient = + HttpClient { + install(ContentNegotiation) { + json( + Json { + isLenient = true + ignoreUnknownKeys = true + }, + ) + } + } + + val exampleApi = + buildApiClient { + it.httpClient(ktorClient) + .converterFactories(ArrowEitherConverterFactory()) + } + + exampleApi.getPersonArrow().shouldBeRight() + .let { + it.name shouldBe "Luke Skywalker" + it.birth_year shouldBe "19BBY" + it.films.shouldNotBeEmpty() + } + } + + "GET -> Either" { + val ktorClient = + HttpClient { + install(ContentNegotiation) { + json( + Json { + isLenient = true + ignoreUnknownKeys = true + }, + ) + } + } + + val exampleApi = + buildApiClient { + it.httpClient(ktorClient) + .converterFactories(ArrowEitherConverterFactory()) + } + + exampleApi.getPersonArrow2().shouldBeRight() + .let { + it.name shouldBe "Luke Skywalker" + it.birth_year shouldBe "19BBY" + it.films.shouldNotBeEmpty() + } + } + + "suspend GET -> Either" { + val ktorClient = + HttpClient { + install(ContentNegotiation) { + json( + Json { + isLenient = true + ignoreUnknownKeys = true + }, + ) + } + } + + val exampleApi = + buildApiClient { + it.httpClient(ktorClient) + .converterFactories(ArrowEitherConverterFactory()) + } + + exampleApi.getPersonKtor() + .shouldBeRight().let { + it.status shouldBe HttpStatusCode.OK + } + } + + "Either.Left contains HTTP error" { + val ktorClient = + HttpClient { + + expectSuccess = true + + install(ContentNegotiation) { + json( + Json { + isLenient = true + ignoreUnknownKeys = true + }, + ) + } + + install(Logging) { + level = LogLevel.ALL + + logger = + object : Logger { + override fun log(message: String) { + println(message) + } + } + } + } + + val exampleApi = + buildApiClient { + it.httpClient(ktorClient) + .converterFactories(ArrowEitherConverterFactory()) + } + + exampleApi.getPersonArrowFailing() + .shouldBeLeft() + .let { + it.shouldBeInstanceOf() + + it.response.status shouldBe HttpStatusCode.NotFound + } + } + + "Either.Left contains Serialization Error" { + val ktorClient = + HttpClient { + install(ContentNegotiation) { + json( + Json { + isLenient = true + ignoreUnknownKeys = true + }, + ) + } + } + + val exampleApi = + buildApiClient { + it.httpClient(ktorClient) + .converterFactories(ArrowEitherConverterFactory()) + } + + exampleApi.getPersonArrowFailing() + .shouldBeLeft() + .let { + it.shouldBeInstanceOf() + } + } +}) + +private fun buildApiClient(customizer: (Ktorfit.Builder) -> Unit = {}): ExampleApi { + val ktorfit = + Ktorfit.Builder().baseUrl("https://swapi.dev/api/") + .also(customizer) + .build() + + return ktorfit.create() +} diff --git a/src/test/resources/kotest.properties b/src/test/resources/kotest.properties new file mode 100644 index 0000000..57b6c3b --- /dev/null +++ b/src/test/resources/kotest.properties @@ -0,0 +1 @@ +kotest.framework.classpath.scanning.config.disable=true diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 0000000..a8d671a --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,19 @@ + + + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + +