diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 372aba2f..6cd3d9b6 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -27,7 +27,7 @@ jobs: uses: actions/setup-java@v3.1.1 with: # The Java version to set up. Takes a whole or semver Java version. See examples of supported syntax in README file - java-version: 8 + java-version: 17 # Java distribution. See the list of supported distributions in README file distribution: zulu diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 91e0e0ec..8b64154b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -30,7 +30,7 @@ jobs: uses: actions/setup-java@v3.1.1 with: # The Java version to set up. Takes a whole or semver Java version. See examples of supported syntax in README file - java-version: 8 + java-version: 17 # Java distribution. See the list of supported distributions in README file distribution: zulu @@ -59,7 +59,7 @@ jobs: uses: actions/setup-java@v3.1.1 with: # The Java version to set up. Takes a whole or semver Java version. See examples of supported syntax in README file - java-version: 8 + java-version: 17 # Java distribution. See the list of supported distributions in README file distribution: zulu diff --git a/README.md b/README.md index cebc35b5..bf3ffacd 100755 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ implementation 'com.sealwu.jsontokotlin:library:3.7.4' ### Overview This is a very cool tool for Kotlin developers, it can convert a JSON string to Kotlin `data class`. The tool could not only recognize the primitive types but also auto create complex types. It's easily accessible, we provide shortcut keymap `ALT + K` for Windows and `Option + K` for Mac, have a try and you'll fall in love with it! JsonToKotlinClass just makes programming more enjoyable, enjoy coding! -[![image](https://user-images.githubusercontent.com/9211902/124459608-e1ff5b00-ddc0-11eb-959a-d7bce50d9233.png)](https://www.youtube.com/watch?v=lSBvHOIDAjc) +[![image](https://user-images.githubusercontent.com/9211902/124459608-e1ff5b00-ddc0-11eb-959a-d7bce50d9233.png)](https://www.youtube.com/watch?v=1Qmo-CY_OdE&t=68s) ### Easy Use ![alt text](https://plugins.jetbrains.com/files/9960/screenshot_18032.png) diff --git a/api/.gitignore b/api/.gitignore deleted file mode 100644 index a065d366..00000000 --- a/api/.gitignore +++ /dev/null @@ -1,34 +0,0 @@ -HELP.md -.gradle -build/ -!gradle/wrapper/gradle-wrapper.jar -!**/src/main/** -!**/src/test/** - -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache - -### IntelliJ IDEA ### -.idea -*.iws -*.iml -*.ipr -out/ - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ - -### VS Code ### -.vscode/ - -application.properties \ No newline at end of file diff --git a/api/build.gradle b/api/build.gradle deleted file mode 100644 index bb35d4e7..00000000 --- a/api/build.gradle +++ /dev/null @@ -1,36 +0,0 @@ -buildscript { - ext.kotlin_version = '1.3.71' // Required for Kotlin integration - ext.spring_boot_version = '2.1.0.RELEASE' - repositories { - jcenter() - } - dependencies { - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // Required for Kotlin integration - classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" - // See https://kotlinlang.org/docs/reference/compiler-plugins.html#spring-support - classpath "org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version" - } -} - -apply plugin: 'kotlin' // Required for Kotlin integration -apply plugin: "kotlin-spring" // https://kotlinlang.org/docs/reference/compiler-plugins.html#spring-support -apply plugin: 'org.springframework.boot' -apply plugin: 'io.spring.dependency-management' - -repositories { - jcenter() -} - -dependencies { - compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration - compile "org.springframework.boot:spring-boot-starter-web" - compile "org.springframework.boot:spring-boot-starter-data-jpa" - compile "org.springframework.boot:spring-boot-starter-data-rest" - compile "com.fasterxml.jackson.module:jackson-module-kotlin" - compile "org.jetbrains.kotlin:kotlin-reflect" - compile "io.springfox:springfox-swagger2:2.9.2" - compile "io.springfox:springfox-swagger-ui:2.9.2" - compile files("libs/JsonToKotlinClassLibrary-3.5.1-alpha01.jar") - runtimeOnly("mysql:mysql-connector-java") - testCompile('org.springframework.boot:spring-boot-starter-test') -} \ No newline at end of file diff --git a/api/gradle/wrapper/gradle-wrapper.jar b/api/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e708b1c0..00000000 Binary files a/api/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/api/gradle/wrapper/gradle-wrapper.properties b/api/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 2a563242..00000000 --- a/api/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/api/gradlew b/api/gradlew deleted file mode 100755 index 4f906e0c..00000000 --- a/api/gradlew +++ /dev/null @@ -1,185 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or 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 UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# 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 - ;; - 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" - which java >/dev/null 2>&1 || 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 - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=`expr $i + 1` - done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -exec "$JAVACMD" "$@" diff --git a/api/gradlew.bat b/api/gradlew.bat deleted file mode 100644 index ac1b06f9..00000000 --- a/api/gradlew.bat +++ /dev/null @@ -1,89 +0,0 @@ -@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=. -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%" == "0" goto execute - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -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%"=="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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/api/json_to_kotlin.sql b/api/json_to_kotlin.sql deleted file mode 100644 index 97b1e873..00000000 --- a/api/json_to_kotlin.sql +++ /dev/null @@ -1,81 +0,0 @@ --- phpMyAdmin SQL Dump --- version 4.5.4.1deb2ubuntu2.1 --- http://www.phpmyadmin.net --- --- Host: localhost --- Generation Time: Mar 19, 2020 at 09:32 PM --- Server version: 5.7.29-0ubuntu0.16.04.1 --- PHP Version: 7.0.33-0ubuntu0.16.04.12 -DROP DATABASE IF EXISTS `json_to_kotlin`; -CREATE DATABASE `json_to_kotlin`; -USE `json_to_kotlin`; - -SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; -SET time_zone = "+00:00"; - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8mb4 */; - --- --- Database: `json_to_kotlin` --- - --- -------------------------------------------------------- - --- --- Table structure for table `hits` --- - -CREATE TABLE `hits` ( - `id` int(11) NOT NULL, - `client` enum('PLUG_IN','WEB','API') NOT NULL, - `class_name` text NOT NULL, - `annotation_lib` enum('NONE','NONE_CC','GSON','FAST_JSON','JACKSON','MOSHI','LOGAN_SQUARE','MOSHI_CODE_GEN','SERIALIZABLE','CUSTOM') NOT NULL, - `class_suffix` text DEFAULT NULL, - `default_value_strategy` enum('AVOID_NULL','ALLOW_NULL','NONE') NOT NULL, - `indent` int(11) NOT NULL, - `is_comments_enabled` tinyint(1) NOT NULL, - `is_create_annotation_only_when_needed_enabled` tinyint(1) NOT NULL, - `is_enable_var_properties` tinyint(1) NOT NULL, - `is_force_init_default_value_with_origin_json_value_enabled` tinyint(1) NOT NULL, - `is_force_primitive_type_non_nullable_enabled` tinyint(1) NOT NULL, - `is_inner_class_model_enabled` tinyint(1) NOT NULL, - `is_keep_annotation_on_class_androidx_enabled` tinyint(1) NOT NULL, - `is_keep_annotation_on_class_enabled` tinyint(1) NOT NULL, - `is_map_type_enabled` tinyint(1) NOT NULL, - `is_order_by_alphabetic_enabled` tinyint(1) NOT NULL, - `is_parcelable_support_enabled` tinyint(1) NOT NULL, - `is_property_and_annotation_in_same_line_enabled` tinyint(1) NOT NULL, - `package_name` text, - `parent_class_template` text, - `property_prefix` text, - `property_suffix` text, - `property_type_strategy` enum('NOT_NULLABLE','NULLABLE','AUTO_DETERMINE_NULLABLE_OR_NOT') NOT NULL, - `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP -) ENGINE=InnoDB DEFAULT CHARSET=latin1; - --- --- Indexes for dumped tables --- - --- --- Indexes for table `hits` --- -ALTER TABLE `hits` - ADD PRIMARY KEY (`id`); - --- --- AUTO_INCREMENT for dumped tables --- - --- --- AUTO_INCREMENT for table `hits` --- -ALTER TABLE `hits` - MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/api/libs/JsonToKotlinClassLibrary-3.5.1-alpha01.jar b/api/libs/JsonToKotlinClassLibrary-3.5.1-alpha01.jar deleted file mode 100644 index 311d8849..00000000 Binary files a/api/libs/JsonToKotlinClassLibrary-3.5.1-alpha01.jar and /dev/null differ diff --git a/api/settings.gradle.kts b/api/settings.gradle.kts deleted file mode 100644 index 4cbbd8ec..00000000 --- a/api/settings.gradle.kts +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "jsontokotlinclass" diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/JsonToKotlinClassApplication.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/JsonToKotlinClassApplication.kt deleted file mode 100644 index 4ccfa1cf..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/JsonToKotlinClassApplication.kt +++ /dev/null @@ -1,11 +0,0 @@ -package wu.seal.jsontokotlinclass.server - -import org.springframework.boot.SpringApplication -import org.springframework.boot.autoconfigure.SpringBootApplication - -@SpringBootApplication -class JsonToKotlinClassApplication - -fun main(args: Array) { - SpringApplication.run(JsonToKotlinClassApplication::class.java, *args) -} diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/AddHitController.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/AddHitController.kt deleted file mode 100644 index 4134deb4..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/AddHitController.kt +++ /dev/null @@ -1,56 +0,0 @@ -package wu.seal.jsontokotlinclass.server.controllers - -import io.swagger.annotations.ApiOperation -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.web.bind.annotation.PostMapping -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.ResponseBody -import org.springframework.web.bind.annotation.RestController -import wu.seal.jsontokotlinclass.server.data.entities.Hit -import wu.seal.jsontokotlinclass.server.data.repos.HitsRepo -import wu.seal.jsontokotlinclass.server.models.routes.addhit.AddHitRequest -import wu.seal.jsontokotlinclass.server.models.routes.addhit.AddHitResponse -import wu.seal.jsontokotlinclass.server.utils.toHit - -@RestController -class AddHitController { - - companion object { - private fun verifyClient(client: String) { - val isValidClient = when (client) { - Hit.CLIENT_API, - Hit.CLIENT_PLUG_IN, - Hit.CLIENT_WEB -> true - else -> false - } - - require(isValidClient) { "Invalid client `$client`" } - } - } - - @Autowired - lateinit var hitsRepo: HitsRepo - - @ApiOperation( - "To add new analytics event" - ) - @PostMapping("/add_hit") - @ResponseBody - fun addHit(@RequestBody addHitRequest: AddHitRequest): AddHitResponse { - - println("Hit!") - - verifyClient(addHitRequest.client) - hitsRepo.save( - addHitRequest.generateMeta.toHit(addHitRequest.client) - ) - return AddHitResponse( - null, - false, - -1, - "Added" - ) - } - - -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/GenerateController.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/GenerateController.kt deleted file mode 100644 index bb98bae9..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/controllers/GenerateController.kt +++ /dev/null @@ -1,136 +0,0 @@ -package wu.seal.jsontokotlinclass.server.controllers - -import io.swagger.annotations.Api -import io.swagger.annotations.ApiOperation -import org.springframework.beans.factory.annotation.Autowired -import org.springframework.web.bind.annotation.PostMapping -import org.springframework.web.bind.annotation.RequestBody -import org.springframework.web.bind.annotation.ResponseBody -import org.springframework.web.bind.annotation.RestController -import wu.seal.jsontokotlin.DefaultValueStrategy -import wu.seal.jsontokotlin.PropertyTypeStrategy -import wu.seal.jsontokotlin.TargetJsonConverter -import wu.seal.jsontokotlin.library.JsonToKotlinBuilder -import wu.seal.jsontokotlinclass.server.data.entities.Hit -import wu.seal.jsontokotlinclass.server.data.repos.HitsRepo -import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateRequest -import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateResponse -import wu.seal.jsontokotlinclass.server.utils.toHit - -@Api(description = "To generate Kotlin source code") -@RestController -class GenerateController { - - @Autowired - var hitsRepo: HitsRepo? = null - - @ApiOperation("To generate Kotlin source code from given input") - @PostMapping("/generate") - @ResponseBody - fun generate(@RequestBody request: GenerateRequest): GenerateResponse { - - val builder = JsonToKotlinBuilder() - - // Integrating REST request params with builder class - if (request.annotationLib != null) { - builder.setAnnotationLib(TargetJsonConverter.valueOf(request.annotationLib)) - } - - if (request.classSuffix != null) { - builder.setClassSuffix(request.classSuffix) - } - - if (request.defaultValueStrategy != null) { - builder.setDefaultValueStrategy(DefaultValueStrategy.valueOf(request.defaultValueStrategy)) - } - - if (request.indent != null) { - builder.setIndent(request.indent) - } - - if (request.commentsEnabled != null) { - builder.enableComments(request.commentsEnabled) - } - - if (request.createAnnotationOnlyWhenNeededEnabled != null) { - builder.enableCreateAnnotationOnlyWhenNeeded(request.createAnnotationOnlyWhenNeededEnabled) - } - - if (request.enableVarProperties != null) { - builder.enableVarProperties(request.enableVarProperties) - } - - if (request.forceInitDefaultValueWithOriginJsonValueEnabled != null) { - builder.enableForceInitDefaultValueWithOriginJsonValue(request.forceInitDefaultValueWithOriginJsonValueEnabled) - } - - if (request.forcePrimitiveTypeNonNullableEnabled != null) { - builder.enableForcePrimitiveTypeNonNullable(request.forcePrimitiveTypeNonNullableEnabled) - } - - if (request.innerClassModelEnabled != null) { - builder.enableInnerClassModel(request.innerClassModelEnabled) - } - - if (request.keepAnnotationOnClassAndroidXEnabled != null) { - builder.enableKeepAnnotationOnClassAndroidX(request.keepAnnotationOnClassAndroidXEnabled) - } - - if (request.keepAnnotationOnClassEnabled != null) { - builder.enableKeepAnnotationOnClass(request.keepAnnotationOnClassEnabled) - } - - if (request.mapTypeEnabled != null) { - builder.enableMapType(request.mapTypeEnabled) - } - - if (request.orderByAlphabeticEnabled != null) { - builder.enableOrderByAlphabetic(request.orderByAlphabeticEnabled) - } - - if (request.parcelableSupportEnabled != null) { - builder.enableParcelableSupport(request.parcelableSupportEnabled) - } - - if (request.propertyAndAnnotationInSameLineEnabled != null) { - builder.enableAnnotationAndPropertyInSameLine(request.propertyAndAnnotationInSameLineEnabled) - } - - if (request.packageName != null) { - builder.setPackageName(request.packageName) - } - - if (request.parentClassTemplate != null) { - builder.setParentClassTemplate(request.parentClassTemplate) - } - - if (request.propertyPrefix != null) { - builder.setPropertyPrefix(request.propertyPrefix) - } - - if (request.propertySuffix != null) { - builder.setPropertySuffix(request.propertyPrefix) - } - - if (request.propertyTypeStrategy != null) { - builder.setPropertyTypeStrategy(PropertyTypeStrategy.valueOf(request.propertyTypeStrategy)) - } - - if (hitsRepo != null) { - // Setting - val hit = request.toHit(Hit.CLIENT_API) - - - // Setting default values - hitsRepo!!.save(hit) - } - - val json = builder.build(request.json, request.className) - return GenerateResponse( - GenerateResponse.Data(json), - false, - -1, - "OK" - ) - } -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/data/entities/Hit.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/data/entities/Hit.kt deleted file mode 100644 index 21e793fb..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/data/entities/Hit.kt +++ /dev/null @@ -1,64 +0,0 @@ -package wu.seal.jsontokotlinclass.server.data.entities - -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.GenerationType -import javax.persistence.Id - -@Entity(name = "hits") -class Hit { - - companion object { - const val CLIENT_PLUG_IN = "PLUG_IN" - const val CLIENT_WEB = "WEB" - const val CLIENT_API = "API" - - const val A_LIB_NONE = "NONE" - const val A_LIB_NONE_CC = "NONE_CC" - const val A_LIB_GSON = "GSON" - const val A_LIB_FAST_JSON = "FAST_JSON" - const val A_LIB_JACKSON = "JACKSON" - const val A_LIB_MOSHI = "MOSHI" - const val A_LIB_LOGAN_SQUARE = "LOGAN_SQUARE" - const val A_LIB_MOSHI_CODE_GEN = "MOSHI_CODE_GEN" - const val A_LIB_SERIALIZABLE = "SERIALIZABLE" - const val A_LIB_CUSTOM = "CUSTOM" - - const val DVS_AVOID_NULL = "AVOID_NULL" - const val DVS_ALLOW_NULL = "ALLOW_NULL" - const val DVS_NONE = "NONE" - - const val PTS_NOT_NULLABLE = "NOT_NULLABLE" - const val PTS_NULLABLE = "NULLABLE" - const val PTS_AUTO_DETERMINE_NULLABLE_OR_NOT = "AUTO_DETERMINE_NULLABLE_OR_NOT" - } - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - var id: Long? = null - - lateinit var client: String - lateinit var className: String - lateinit var annotationLib: String - lateinit var defaultValueStrategy: String - lateinit var propertyTypeStrategy: String - var indent: Int? = null - var isCommentsEnabled: Boolean? = null - var isCreateAnnotationOnlyWhenNeededEnabled: Boolean? = null - var isEnableVarProperties: Boolean? = null - var isForceInitDefaultValueWithOriginJsonValueEnabled: Boolean? = null - var isForcePrimitiveTypeNonNullableEnabled: Boolean? = null - var isInnerClassModelEnabled: Boolean? = null - var isKeepAnnotationOnClassAndroidxEnabled: Boolean? = null - var isKeepAnnotationOnClassEnabled: Boolean? = null - var isMapTypeEnabled: Boolean? = null - var isOrderByAlphabeticEnabled: Boolean? = null - var isParcelableSupportEnabled: Boolean? = null - var isPropertyAndAnnotationInSameLineEnabled: Boolean? = null - - var packageName: String? = null - var parentClassTemplate: String? = null - var propertyPrefix: String? = null - var propertySuffix: String? = null - var classSuffix: String? = null -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/data/repos/HitsRepo.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/data/repos/HitsRepo.kt deleted file mode 100644 index 1237b01e..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/data/repos/HitsRepo.kt +++ /dev/null @@ -1,7 +0,0 @@ -package wu.seal.jsontokotlinclass.server.data.repos - -import org.springframework.data.repository.CrudRepository -import wu.seal.jsontokotlinclass.server.data.entities.Hit - -interface HitsRepo : CrudRepository { -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/exceptions/Exceptions.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/exceptions/Exceptions.kt deleted file mode 100644 index ee5dcde0..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/exceptions/Exceptions.kt +++ /dev/null @@ -1,8 +0,0 @@ -package wu.seal.jsontokotlinclass.server.exceptions - -open class BaseJsonToKotlinException(message: String, val errorCode: Int) : RuntimeException(message) { - companion object { - const val ERROR_CODE_INVALID_JSON_INPUT: Int = 1 - } -} - diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/exceptions/GlobalExceptionHandler.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/exceptions/GlobalExceptionHandler.kt deleted file mode 100644 index 96f846cd..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/exceptions/GlobalExceptionHandler.kt +++ /dev/null @@ -1,25 +0,0 @@ -package wu.seal.jsontokotlinclass.server.exceptions - -import org.springframework.core.Ordered -import org.springframework.core.annotation.Order -import org.springframework.web.bind.annotation.ControllerAdvice -import org.springframework.web.bind.annotation.ExceptionHandler -import org.springframework.web.bind.annotation.ResponseBody -import wu.seal.jsontokotlinclass.server.models.routes.base.BaseResponse - -@Order(Ordered.HIGHEST_PRECEDENCE) -@ControllerAdvice -class GlobalExceptionHandler { - - @ExceptionHandler(BaseJsonToKotlinException::class) - @ResponseBody - fun handleException(e: BaseJsonToKotlinException): BaseResponse { - return BaseResponse(null, true, e.errorCode, e.message!!) - } - - @ExceptionHandler(Exception::class) - @ResponseBody - fun handleBadHttpRequest(e: Exception): BaseResponse { - return BaseResponse(null, true, 1000, e.message!!) - } -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/addhit/AddHitRequest.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/addhit/AddHitRequest.kt deleted file mode 100644 index bb3c3ef9..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/addhit/AddHitRequest.kt +++ /dev/null @@ -1,107 +0,0 @@ -package wu.seal.jsontokotlinclass.server.models.routes.addhit - -import com.fasterxml.jackson.annotation.JsonProperty -import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateRequest - -class AddHitRequest( - @JsonProperty("client") - val client: String, - @JsonProperty("generate_meta") - val generateMeta: GenerateMeta -) { - - class GenerateMeta( - @JsonProperty("json") - json: String, - - @JsonProperty("class_name") - className: String, - - @JsonProperty("annotation_lib") - annotationLib: String, - - @JsonProperty("default_value_strategy") - defaultValueStrategy: String, - - @JsonProperty("property_type_strategy") - propertyTypeStrategy: String, - - @JsonProperty("indent") - indent: Int, - - @JsonProperty("is_comments_enabled") - commentsEnabled: Boolean, - - @JsonProperty("is_create_annotation_only_when_needed_enabled") - createAnnotationOnlyWhenNeededEnabled: Boolean, - - @JsonProperty("is_enable_var_properties") - enableVarProperties: Boolean, - - @JsonProperty("is_force_init_default_ue_with_origin_json_ue_enabled") - forceInitDefaultValueWithOriginJsonValueEnabled: Boolean, - - @JsonProperty("is_force_primitive_type_non_nullable_enabled") - forcePrimitiveTypeNonNullableEnabled: Boolean, - - @JsonProperty("is_inner_class_model_enabled") - innerClassModelEnabled: Boolean, - - @JsonProperty("is_keep_annotation_on_class_androidx_enabled") - keepAnnotationOnClassAndroidXEnabled: Boolean, - - @JsonProperty("is_keep_annotation_on_class_enabled") - keepAnnotationOnClassEnabled: Boolean, - - @JsonProperty("is_map_type_enabled") - mapTypeEnabled: Boolean, - - @JsonProperty("is_order_by_alphabetic_enabled") - orderByAlphabeticEnabled: Boolean, - - @JsonProperty("is_parcelable_support_enabled") - parcelableSupportEnabled: Boolean, - - @JsonProperty("is_property_and_annotation_in_same_line_enabled") - propertyAndAnnotationInSameLineEnabled: Boolean, - - @JsonProperty("package_name") - packageName: String?, - - @JsonProperty("parent_class_template") - parentClassTemplate: String?, - - @JsonProperty("property_prefix") - propertyPrefix: String?, - - @JsonProperty("class_suffix") - classSuffix: String?, - - @JsonProperty("property_suffix") - propertySuffix: String? - ) : GenerateRequest( - json, - className, - annotationLib, - defaultValueStrategy, - propertyTypeStrategy, - indent, - commentsEnabled, - createAnnotationOnlyWhenNeededEnabled, - enableVarProperties, - forceInitDefaultValueWithOriginJsonValueEnabled, - forcePrimitiveTypeNonNullableEnabled, - innerClassModelEnabled, - keepAnnotationOnClassAndroidXEnabled, - keepAnnotationOnClassEnabled, - mapTypeEnabled, - orderByAlphabeticEnabled, - parcelableSupportEnabled, - propertyAndAnnotationInSameLineEnabled, - packageName, - parentClassTemplate, - propertyPrefix, - classSuffix, - propertySuffix - ) -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/addhit/AddHitResponse.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/addhit/AddHitResponse.kt deleted file mode 100644 index 78fbb54c..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/addhit/AddHitResponse.kt +++ /dev/null @@ -1,6 +0,0 @@ -package wu.seal.jsontokotlinclass.server.models.routes.addhit - -import wu.seal.jsontokotlinclass.server.models.routes.base.BaseResponse - -class AddHitResponse(data: Void?, error: Boolean, errorCode: Int, message: String) : BaseResponse(data, error, errorCode, message) { -} \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/base/BaseResponse.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/base/BaseResponse.kt deleted file mode 100644 index 8af81c14..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/base/BaseResponse.kt +++ /dev/null @@ -1,14 +0,0 @@ -package wu.seal.jsontokotlinclass.server.models.routes.base - -import com.fasterxml.jackson.annotation.JsonProperty - -open class BaseResponse( - @field:JsonProperty("data") - val `data`: T?, - @field:JsonProperty("error") - val error: Boolean, // false - @field:JsonProperty("error_code") - val errorCode: Int, // 123 - @field:JsonProperty("message") - val message: String // Generated -) \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/generate/GenerateRequest.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/generate/GenerateRequest.kt deleted file mode 100644 index 1af0ab20..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/generate/GenerateRequest.kt +++ /dev/null @@ -1,118 +0,0 @@ -package wu.seal.jsontokotlinclass.server.models.routes.generate - -import com.fasterxml.jackson.annotation.JsonProperty -import io.swagger.annotations.ApiModelProperty - -open class GenerateRequest( - - @ApiModelProperty( - value = "JSON text" - ) - @JsonProperty("json") - val json: String, - - @ApiModelProperty( - value = "Output class name", - example = "Person" - ) - @JsonProperty("class_name") - val className: String, - - @ApiModelProperty( - value = "Annotation library to be used. Default 'None'", - allowableValues = "None, NoneWithCamelCase, Gson, FastJson, Jackson, MoShi, LoganSquare, MoshiCodeGen, Serializable, Custom" - ) - @JsonProperty("annotation_lib") - val annotationLib: String?, // MOSHI_CODE_GEN - - @ApiModelProperty( - value = "Default value strategy. Default 'None'", - allowableValues = "None, AvoidNull, AllowNull" - ) - @JsonProperty("default_value_strategy") - val defaultValueStrategy: String? = null, // AVOID_NULL - - - @ApiModelProperty( - value = "To set if the properties can be null or not. Default 'AutoDeterMineNullableOrNot'", - allowableValues = "Nullable, NotNullable, AutoDeterMineNullableOrNot" - ) - @JsonProperty("property_type_strategy") - val propertyTypeStrategy: String? = null, // AUTO_DETERMINE_NULLABLE_OR_NOT - - - @ApiModelProperty( - value = "To set indent in output kotlin code. Default '4'" - ) - @JsonProperty("indent") - val indent: Int? = null, // 4 - - @ApiModelProperty( - value = "If true, sample data will be appended as a comment to the property declaration line. Default 'false'" - ) - @JsonProperty("is_comments_enabled") - val commentsEnabled: Boolean? = null, // true - - @ApiModelProperty( - value = "If true, annotation will be only created if key and variable are different. Default 'false'" - ) - @JsonProperty("is_create_annotation_only_when_needed_enabled") - val createAnnotationOnlyWhenNeededEnabled: Boolean? = null, // true - - @ApiModelProperty( - value = "If true, all properties will be 'var'. Default 'false'" - ) - @JsonProperty("is_enable_var_properties") - val enableVarProperties: Boolean? = null, // false - - @ApiModelProperty( - value = "If true, property will be initialized with original value. Default 'fasle'" - ) - @JsonProperty("is_force_init_default_value_with_origin_json_value_enabled") - val forceInitDefaultValueWithOriginJsonValueEnabled: Boolean? = null, // true - - @JsonProperty("is_force_primitive_type_non_nullable_enabled") - val forcePrimitiveTypeNonNullableEnabled: Boolean? = null, // true - - @ApiModelProperty( - value = "If enabled, classes will be nested with in it's parent class. Default 'false'" - ) - @JsonProperty("is_inner_class_model_enabled") - val innerClassModelEnabled: Boolean? = null, // false - - @JsonProperty("is_keep_annotation_on_class_androidx_enabled") - val keepAnnotationOnClassAndroidXEnabled: Boolean? = null, // true - - @JsonProperty("is_keep_annotation_on_class_enabled") - val keepAnnotationOnClassEnabled: Boolean? = null, // true - - @JsonProperty("is_map_type_enabled") - val mapTypeEnabled: Boolean? = null, // true - - @ApiModelProperty( - value = "If enabled properties will be ordered in alphabetic order. Default 'false'" - ) - @JsonProperty("is_order_by_alphabetic_enabled") - val orderByAlphabeticEnabled: Boolean? = null, // true - - @JsonProperty("is_parcelable_support_enabled") - val parcelableSupportEnabled: Boolean? = null, // true - - @JsonProperty("is_property_and_annotation_in_same_line_enabled") - val propertyAndAnnotationInSameLineEnabled: Boolean? = null, // true - - @JsonProperty("package_name") - val packageName: String? = null, // com.my.package.name - - @JsonProperty("parent_class_template") - val parentClassTemplate: String? = null, // android.os.Parcelable - - @JsonProperty("property_prefix") - val propertyPrefix: String? = null, // MY_PREFIX - - @JsonProperty("class_suffix") - val classSuffix: String? = null, // MY_CLASS_SUFFIX - - @JsonProperty("property_suffix") - val propertySuffix: String? = null // MY_SUFFIX -) \ No newline at end of file diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/generate/GenerateResponse.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/generate/GenerateResponse.kt deleted file mode 100644 index c6bbf19e..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/models/routes/generate/GenerateResponse.kt +++ /dev/null @@ -1,14 +0,0 @@ -package wu.seal.jsontokotlinclass.server.models.routes.generate - -import com.fasterxml.jackson.annotation.JsonProperty -import wu.seal.jsontokotlinclass.server.models.routes.base.BaseResponse - - -class GenerateResponse(data: Data, error: Boolean, errorCode: Int, message: String) : - BaseResponse(data, error, errorCode, message) { - data class Data( - @field:JsonProperty("code") - val code: String // The code goes here - ) -} - diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/utils/HitUtils.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/utils/HitUtils.kt deleted file mode 100644 index d6c7cb5c..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/utils/HitUtils.kt +++ /dev/null @@ -1,112 +0,0 @@ -package wu.seal.jsontokotlinclass.server.utils - -import extensions.chen.biao.KeepAnnotationSupport -import extensions.jose.han.ParcelableAnnotationSupport -import extensions.ted.zeng.PropertyAnnotationLineSupport -import extensions.wu.seal.ForceInitDefaultValueWithOriginJsonValueSupport -import extensions.wu.seal.KeepAnnotationSupportForAndroidX -import extensions.xu.rui.PrimitiveTypeNonNullableSupport -import wu.seal.jsontokotlin.DefaultValueStrategy -import wu.seal.jsontokotlin.PropertyTypeStrategy -import wu.seal.jsontokotlin.TargetJsonConverter -import wu.seal.jsontokotlin.test.TestConfig -import wu.seal.jsontokotlinclass.server.data.entities.Hit -import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateRequest - - -fun GenerateRequest.toHit( - client: String -): Hit { - /** - * TODO: Variable name length must be reduced - */ - val hit = Hit() - hit.client = client - hit.className = className - hit.annotationLib = parseAnnotationLib(annotationLib) - hit.defaultValueStrategy = parseDefaultValueStrategy(defaultValueStrategy) - hit.propertyTypeStrategy = parsePropertyTypeStrategy(propertyTypeStrategy) - hit.indent = indent - ?: TestConfig.indent - hit.isCommentsEnabled = commentsEnabled - ?: !TestConfig.isCommentOff - hit.isCreateAnnotationOnlyWhenNeededEnabled = createAnnotationOnlyWhenNeededEnabled - ?: TestConfig.enableMinimalAnnotation - hit.isEnableVarProperties = enableVarProperties - ?: TestConfig.isPropertiesVar - - hit.isForceInitDefaultValueWithOriginJsonValueEnabled = forceInitDefaultValueWithOriginJsonValueEnabled - ?: ForceInitDefaultValueWithOriginJsonValueSupport.getTestHelper().getConfig( - ForceInitDefaultValueWithOriginJsonValueSupport.configKey - ).toBoolean() - - hit.isForcePrimitiveTypeNonNullableEnabled = forcePrimitiveTypeNonNullableEnabled - ?: PrimitiveTypeNonNullableSupport.getTestHelper().getConfig( - PrimitiveTypeNonNullableSupport.configKey - ).toBoolean() - hit.isInnerClassModelEnabled = innerClassModelEnabled - ?: TestConfig.isNestedClassModel - hit.isKeepAnnotationOnClassAndroidxEnabled = keepAnnotationOnClassAndroidXEnabled - ?: KeepAnnotationSupportForAndroidX.getTestHelper().getConfig( - KeepAnnotationSupportForAndroidX.configKey - ).toBoolean() - - hit.isKeepAnnotationOnClassEnabled = keepAnnotationOnClassEnabled - ?: KeepAnnotationSupport.getTestHelper().getConfig( - KeepAnnotationSupport.configKey - ).toBoolean() - - hit.isMapTypeEnabled = mapTypeEnabled - ?: TestConfig.enableMapType - hit.isOrderByAlphabeticEnabled = orderByAlphabeticEnabled - ?: TestConfig.isOrderByAlphabetical - hit.isParcelableSupportEnabled = parcelableSupportEnabled - ?: ParcelableAnnotationSupport.getTestHelper().getConfig( - ParcelableAnnotationSupport.configKey - ).toBoolean() - hit.isPropertyAndAnnotationInSameLineEnabled = propertyAndAnnotationInSameLineEnabled - ?: PropertyAnnotationLineSupport.getTestHelper().getConfig( - PropertyAnnotationLineSupport.configKey - ).toBoolean() - - hit.packageName = packageName - hit.parentClassTemplate = parentClassTemplate - hit.propertyPrefix = propertyPrefix - hit.propertySuffix = propertySuffix - hit.classSuffix = classSuffix - return hit -} - -fun parsePropertyTypeStrategy(propertyTypeStrategy: String?): String { - return when (propertyTypeStrategy ?: TestConfig.propertyTypeStrategy.name) { - PropertyTypeStrategy.Nullable.name -> Hit.PTS_NULLABLE - PropertyTypeStrategy.NotNullable.name -> Hit.PTS_NOT_NULLABLE - PropertyTypeStrategy.AutoDeterMineNullableOrNot.name -> Hit.PTS_AUTO_DETERMINE_NULLABLE_OR_NOT - else -> throw IllegalArgumentException("Undefined property ") - } -} - -fun parseDefaultValueStrategy(defaultValueStrategy: String?): String { - return when (defaultValueStrategy ?: TestConfig.defaultValueStrategy.name) { - DefaultValueStrategy.None.name -> Hit.DVS_NONE - DefaultValueStrategy.AvoidNull.name -> Hit.DVS_AVOID_NULL - DefaultValueStrategy.AllowNull.name -> Hit.DVS_ALLOW_NULL - else -> throw IllegalArgumentException("Undefined DVS : $defaultValueStrategy") - } -} - -fun parseAnnotationLib(annotationLib: String?): String { - return when (annotationLib ?: TestConfig.targetJsonConvertLib.name) { - TargetJsonConverter.None.name -> Hit.A_LIB_NONE - TargetJsonConverter.NoneWithCamelCase.name -> Hit.A_LIB_NONE_CC - TargetJsonConverter.Gson.name -> Hit.A_LIB_GSON - TargetJsonConverter.FastJson.name -> Hit.A_LIB_FAST_JSON - TargetJsonConverter.Jackson.name -> Hit.A_LIB_JACKSON - TargetJsonConverter.MoShi.name -> Hit.A_LIB_MOSHI - TargetJsonConverter.LoganSquare.name -> Hit.A_LIB_LOGAN_SQUARE - TargetJsonConverter.MoshiCodeGen.name -> Hit.A_LIB_MOSHI_CODE_GEN - TargetJsonConverter.Serializable.name -> Hit.A_LIB_SERIALIZABLE - TargetJsonConverter.Custom.name -> Hit.A_LIB_CUSTOM - else -> throw IllegalArgumentException("Undefined annotation library $annotationLib") - } -} diff --git a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/utils/SwaggerConfiguration.kt b/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/utils/SwaggerConfiguration.kt deleted file mode 100644 index ac9de860..00000000 --- a/api/src/main/kotlin/wu/seal/jsontokotlinclass/server/utils/SwaggerConfiguration.kt +++ /dev/null @@ -1,32 +0,0 @@ -package wu.seal.jsontokotlinclass.server.utils - -import org.springframework.context.annotation.Bean -import org.springframework.context.annotation.Configuration -import springfox.documentation.builders.ApiInfoBuilder -import springfox.documentation.builders.PathSelectors -import springfox.documentation.builders.RequestHandlerSelectors -import springfox.documentation.spi.DocumentationType -import springfox.documentation.spring.web.plugins.Docket -import springfox.documentation.swagger2.annotations.EnableSwagger2 - -@Configuration -@EnableSwagger2 -class SwaggerConfiguration { - @Bean - open fun api(): Docket { - - val apiInfo = ApiInfoBuilder() - .title("JsonToKotlin Api") - .description("This is a simple API to access J2K services online.") - .build() - - return Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo) - .select() - .apis(RequestHandlerSelectors.basePackage("wu.seal.jsontokotlinclass.server")) - .paths(PathSelectors.any()) - .build() - } - - -} \ No newline at end of file diff --git a/api/src/test/kotlin/wu/seal/jsontokotlinclass/server/GenerateControllerTest.kt b/api/src/test/kotlin/wu/seal/jsontokotlinclass/server/GenerateControllerTest.kt deleted file mode 100644 index c67eba9a..00000000 --- a/api/src/test/kotlin/wu/seal/jsontokotlinclass/server/GenerateControllerTest.kt +++ /dev/null @@ -1,134 +0,0 @@ -package wu.seal.jsontokotlinclass.server - -import com.fasterxml.jackson.databind.ObjectMapper -import org.junit.Assert.assertEquals -import org.junit.Before -import org.junit.Test -import org.springframework.http.MediaType -import org.springframework.test.web.servlet.MockMvc -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post -import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content -import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status -import org.springframework.test.web.servlet.setup.MockMvcBuilders -import wu.seal.jsontokotlin.PropertyTypeStrategy -import wu.seal.jsontokotlinclass.server.controllers.GenerateController -import wu.seal.jsontokotlinclass.server.models.routes.generate.GenerateRequest -import wu.seal.jsontokotlin.DefaultValueStrategy as DefaultValueStrategy1 -import wu.seal.jsontokotlin.TargetJsonConverter as TargetJsonConverter1 - -class GenerateControllerTest { - - lateinit var mockMvc: MockMvc - lateinit var objectMapper: ObjectMapper - - @Before - fun setup() { - this.mockMvc = MockMvcBuilders.standaloneSetup( - GenerateController() - ).build() - - this.objectMapper = ObjectMapper() - } - - @Test - fun simpleTest() { - - val request = GenerateRequest( - """ - {"name":"theapache64"} - """.trimIndent(), - className = "Person", - annotationLib = TargetJsonConverter1.MoShi.name, - defaultValueStrategy = DefaultValueStrategy1.AvoidNull.name, - propertyTypeStrategy = PropertyTypeStrategy.Nullable.name, - indent = 8, - commentsEnabled = true, - createAnnotationOnlyWhenNeededEnabled = false, - enableVarProperties = true, - forceInitDefaultValueWithOriginJsonValueEnabled = false, - forcePrimitiveTypeNonNullableEnabled = true, - innerClassModelEnabled = true, - keepAnnotationOnClassAndroidXEnabled = false, - keepAnnotationOnClassEnabled = true, - mapTypeEnabled = true, - orderByAlphabeticEnabled = true, - parcelableSupportEnabled = false, - propertyAndAnnotationInSameLineEnabled = false, - classSuffix = null, - packageName = null, - parentClassTemplate = null, - propertyPrefix = null, - propertySuffix = null - ) - - val requestJson = objectMapper.writeValueAsString(request) - mockMvc.perform(post("/generate").content(requestJson).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk) - .andExpect(content().string("{\"data\":{\"code\":\"data class Person(\\n val name: String\\n)\"},\"error\":false,\"error_code\":-1,\"message\":\"OK\"}")) - .andExpect(content().contentType("application/json;charset=UTF-8")) - } - - @Test - fun complexTest() { - val controller = GenerateController() - val request = GenerateRequest( - """ - { - "glossary":{ - "title":"example glossary", - "GlossDiv":{ - "title":"S", - "GlossList":{ - "GlossEntry":{ - "ID":"SGML", - "SortAs":"SGML", - "GlossTerm":"Standard Generalized Markup Language", - "Acronym":"SGML", - "Abbrev":"ISO 8879:1986", - "GlossDef":{ - "para":"A meta-markup language, used to create markup languages such as DocBook.", - "GlossSeeAlso":[ - "GML", - "XML" - ] - }, - "GlossSee":"markup" - } - } - } - } - } - """.trimIndent(), - className = "Example", - annotationLib = TargetJsonConverter1.MoShi.name, - defaultValueStrategy = DefaultValueStrategy1.AvoidNull.name, - propertyTypeStrategy = PropertyTypeStrategy.Nullable.name, - indent = 8, - commentsEnabled = true, - createAnnotationOnlyWhenNeededEnabled = false, - enableVarProperties = true, - forceInitDefaultValueWithOriginJsonValueEnabled = false, - forcePrimitiveTypeNonNullableEnabled = true, - innerClassModelEnabled = true, - keepAnnotationOnClassAndroidXEnabled = false, - keepAnnotationOnClassEnabled = true, - mapTypeEnabled = true, - orderByAlphabeticEnabled = true, - parcelableSupportEnabled = false, - propertyAndAnnotationInSameLineEnabled = false, - classSuffix = "MyClassSuffix", - packageName = "com.my.package.name", - parentClassTemplate = null, - propertyPrefix = "prop_prefix_", - propertySuffix = "_prop_suffix" - ) - - val response = controller.generate(request) - val actualOutput = ObjectMapper().writeValueAsString(response) - println(actualOutput) - val expectedOutput = """ - {"data":{"code":"package com.my.package.name\n\n\nimport com.squareup.moshi.Json\nimport android.support.annotation.Keep\n\n@Keep\ndata class ExampleMyClassSuffix(\n @Json(name = \"glossary\")\n var prop_prefix_GlossaryProp_prefix_: GlossaryMyClassSuffix? = GlossaryMyClassSuffix()\n) {\n @Keep\n data class GlossaryMyClassSuffix(\n @Json(name = \"GlossDiv\")\n var prop_prefix_GlossDivProp_prefix_: GlossDivMyClassSuffix? = GlossDivMyClassSuffix(),\n @Json(name = \"title\")\n var prop_prefix_TitleProp_prefix_: String? = \"\" // example glossary\n ) {\n @Keep\n data class GlossDivMyClassSuffix(\n @Json(name = \"GlossList\")\n var prop_prefix_GlossListProp_prefix_: GlossListMyClassSuffix? = GlossListMyClassSuffix(),\n @Json(name = \"title\")\n var prop_prefix_TitleProp_prefix_: String? = \"\" // S\n ) {\n @Keep\n data class GlossListMyClassSuffix(\n @Json(name = \"GlossEntry\")\n var prop_prefix_GlossEntryProp_prefix_: GlossEntryMyClassSuffix? = GlossEntryMyClassSuffix()\n ) {\n @Keep\n data class GlossEntryMyClassSuffix(\n @Json(name = \"Abbrev\")\n var prop_prefix_AbbrevProp_prefix_: String? = \"\", // ISO 8879:1986\n @Json(name = \"Acronym\")\n var prop_prefix_AcronymProp_prefix_: String? = \"\", // SGML\n @Json(name = \"GlossDef\")\n var prop_prefix_GlossDefProp_prefix_: GlossDefMyClassSuffix? = GlossDefMyClassSuffix(),\n @Json(name = \"GlossSee\")\n var prop_prefix_GlossSeeProp_prefix_: String? = \"\", // markup\n @Json(name = \"GlossTerm\")\n var prop_prefix_GlossTermProp_prefix_: String? = \"\", // Standard Generalized Markup Language\n @Json(name = \"ID\")\n var prop_prefix_IDProp_prefix_: String? = \"\", // SGML\n @Json(name = \"SortAs\")\n var prop_prefix_SortAsProp_prefix_: String? = \"\" // SGML\n ) {\n @Keep\n data class GlossDefMyClassSuffix(\n @Json(name = \"GlossSeeAlso\")\n var prop_prefix_GlossSeeAlsoProp_prefix_: List? = listOf(),\n @Json(name = \"para\")\n var prop_prefix_ParaProp_prefix_: String? = \"\" // A meta-markup language, used to create markup languages such as DocBook.\n )\n }\n }\n }\n }\n}"},"error":false,"error_code":-1,"message":"OK"} - """.trimIndent() - assertEquals(expectedOutput, actualOutput) - } -} \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index cda8db86..016bf233 100755 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,7 @@ import org.hildan.github.changelog.builder.DEFAULT_TIMEZONE import org.hildan.github.changelog.builder.SectionDefinition -import org.jetbrains.changelog.closure import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import java.util.concurrent.TimeUnit buildscript { repositories { @@ -11,27 +11,168 @@ buildscript { } plugins { - id("org.jetbrains.intellij") version "0.7.3" - kotlin("jvm") version "1.5.20" - id("org.jetbrains.changelog") version "1.1.1" + id("org.jetbrains.intellij") version "1.13.3" + kotlin("jvm") version "1.8.20" id("org.hildan.github.changelog") version "1.6.0" + java } group = "wu.seal" -version = System.getenv("TAG") ?: "Unreleased" +// Determine version based on Git tags or environment variable +version = System.getenv("TAG") ?: run { + // Execute git command to check if current commit has a tag + val gitTagCommand = "git describe --exact-match --tags HEAD".execute() + val gitLatestTagCommand = "git describe --tags --abbrev=0".execute() + + if (gitTagCommand.exitValue() == 0) { + // Current commit is exactly at a tag - use the tag name + gitTagCommand.text.trim() + } else { + // Current commit is not at a tag - use "Unreleased" + "Unreleased" + } +} intellij { - version = "2020.1" - pluginName = "JsonToKotlinClass" + version.set("2023.3.5") + type.set("IU") + pluginName.set("JsonToKotlinClass") +} + +// Add a function to convert Markdown to HTML for our specific changelog format +fun formatChangelogToHtml(markdown: String): String { + // Extract the version information + val versionPattern = """## \[(.*?)\](?:\((.*?)\))?(?: \((.*?)\))?""".toRegex() + val versionMatch = versionPattern.find(markdown) + + var html = "

Version ${versionMatch?.groupValues?.get(1) ?: "Latest"}

" + + // Add release date if available + if (versionMatch != null && versionMatch.groupValues.size > 3 && versionMatch.groupValues[3].isNotEmpty()) { + html += "

Released: ${versionMatch.groupValues[3]}

" + } + + // Add link to commits if available + val commitsPattern = """\[View commits\]\((.*?)\)""".toRegex() + val commitsMatch = commitsPattern.find(markdown) + if (commitsMatch != null) { + html += "

View commits

" + } + + // Process each section (Bugfix, Enhancement, Features) + val sections = listOf("Bugfix", "Enhancement", "Features") + + for (section in sections) { + val sectionPattern = """(?:\*\*$section\*\*)(.*?)(?:\*\*|$)""".toRegex(RegexOption.DOT_MATCHES_ALL) + val sectionMatch = sectionPattern.find(markdown) + + if (sectionMatch != null) { + html += "

$section

    " + + // Extract list items (lines starting with "- ") + val content = sectionMatch.groupValues[1] + val lines = content.split("\n") + + var currentItem = "" + + for (line in lines) { + val trimmed = line.trim() + if (trimmed.startsWith("-")) { + // If we have accumulated an item before, add it + if (currentItem.isNotEmpty()) { + var itemText = currentItem.trim() + + // Convert Markdown links to HTML links + val linkPattern = """\[(.*?)\]\((.*?)\)""".toRegex() + itemText = itemText.replace(linkPattern) { matchResult -> + val text = matchResult.groupValues[1] + val url = matchResult.groupValues[2] + "$text" + } + + // Convert escaped characters + itemText = itemText.replace("\\[", "[").replace("\\]", "]").replace("\\(", "(").replace("\\)", ")") + + html += "
  • $itemText
  • " + } + + // Start a new item with the current line (minus the leading dash) + currentItem = trimmed.substring(1).trim() + } else if (trimmed.isNotEmpty() && currentItem.isNotEmpty()) { + // Continue accumulating the current item with additional line + currentItem += " " + trimmed + } + } + + // Don't forget to add the last item if there is one + if (currentItem.isNotEmpty()) { + var itemText = currentItem.trim() + + // Convert Markdown links to HTML links + val linkPattern = """\[(.*?)\]\((.*?)\)""".toRegex() + itemText = itemText.replace(linkPattern) { matchResult -> + val text = matchResult.groupValues[1] + val url = matchResult.groupValues[2] + "$text" + } + + // Convert escaped characters + itemText = itemText.replace("\\[", "[").replace("\\]", "]").replace("\\(", "(").replace("\\)", ")") + + html += "
  • $itemText
  • " + } + + html += "
" + } + } + + // Add a link to the full changelog + html += "

View full changelog

" + + return html } + +// Update the patchPluginXml task to use our improved HTML conversion tasks.patchPluginXml { - untilBuild("") - changeNotes(closure { - changelogForIDEPlugin.getLatest().toHTML() - }) + untilBuild.set("") + // Extract appropriate version's changes and convert to HTML + changeNotes.set( + try { + val changelogFile = File("${project.projectDir}/doc/CHANGELOG.md") + val changelogText = changelogFile.readText() + val currentVersion = project.version.toString() + val isReleaseVersion = currentVersion != "Unreleased" + + // First find the section that matches our current version + val sectionHeader = if (isReleaseVersion) "## [$currentVersion]" else "## [Unreleased]" + val sectionStart = changelogText.indexOf(sectionHeader) + + val markdownNotes = if (sectionStart != -1) { + // Find the start of the next section + val nextSectionStart = changelogText.indexOf("## ", sectionStart + sectionHeader.length) + + // Extract just this version's section + if (nextSectionStart != -1) { + changelogText.substring(sectionStart, nextSectionStart).trim() + } else { + // This is the only/last section + changelogText.substring(sectionStart).trim() + } + } else { + // Section not found - show just a simple message + if (isReleaseVersion) "## [$currentVersion] (2023-09-01)" else "## [Unreleased]" + } + + // Convert to HTML using our improved function + formatChangelogToHtml(markdownNotes) + } catch (e: Exception) { + "

See GitHub for changelog

" + } + ) } + tasks.publishPlugin { - token(System.getenv("token")) - channels(System.getProperty("channels", "")) + token.set(System.getenv("token") ?: "") + channels.set(listOf(System.getProperty("channels", ""))) } repositories { @@ -40,24 +181,29 @@ repositories { } dependencies { - implementation("org.jetbrains.kotlin:kotlin-stdlib:1.5.30") + // Mark Kotlin stdlib as "compileOnly" to avoid duplication with the version provided by the IntelliJ Platform + compileOnly(kotlin("stdlib")) testImplementation("com.winterbe:expekt:0.5.0") { exclude(group = "org.jetbrains.kotlin") } } -buildScan { - termsOfServiceUrl = "https://gradle.com/terms-of-service" - termsOfServiceAgree = "yes" +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 } -tasks.getByPath("publishPlugin").dependsOn("generateChangelog") -changelogForIDEPlugin { - version = project.version.toString() - path = "${project.projectDir}/doc/CHANGELOG.md" - unreleasedTerm = "Unreleased" - itemPrefix = "**" +tasks.withType(KotlinCompile::class.java).configureEach { + kotlinOptions { + jvmTarget = "17" + } } + +tasks.buildSearchableOptions { + enabled = false +} + +// Add back the GitHub changelog configuration changelog { githubUser = "wuseal" githubRepository = rootProject.name @@ -65,40 +211,86 @@ changelog { title = "Change Log" showUnreleased = true unreleasedVersionTitle = "Unreleased" - if (!System.getenv("TAG").isNullOrEmpty()) { - println("TAG is ${System.getenv("TAG")}, Set future version to $version") - futureVersionTag = version.toString() + + val currentVersion = project.version.toString() + if (currentVersion != "Unreleased" && !System.getenv("TAG").isNullOrEmpty()) { + println("TAG is ${System.getenv("TAG")}, Set future version to $currentVersion") + futureVersionTag = currentVersion } + sections = listOf( SectionDefinition("Features", "feature request"), SectionDefinition("Bugfix", listOf("bug", "bug fix")), SectionDefinition("Enhancement", "enhancement") - ) // no custom sections by default, but default sections are prepended + ) includeLabels = listOf("feature request", "bug", "bug fix", "enhancement") excludeLabels = listOf("duplicate", "invalid", "question", "wontfix") sinceTag = "V3.0.0" - skipTags = listOf( - - ) + skipTags = listOf() useMilestoneAsTag = true timezone = DEFAULT_TIMEZONE outputFile = file("${projectDir}/doc/CHANGELOG.md") } +// Custom task to generate GitHub release notes task("createGithubReleaseNotes") { doLast { val githubReleaseNoteFile = file("./githubReleaseNote.md") - val content = "**" + file("${projectDir}/doc/CHANGELOG.md").readText() - .substringAfter("**").substringBefore("##").trim() + val content = try { + "**" + file("${projectDir}/doc/CHANGELOG.md").readText() + .substringAfter("**").substringBefore("##").trim() + } catch (e: Exception) { + "No changelog available" + } githubReleaseNoteFile.writeText(content) } } -tasks.withType(KotlinCompile::class.java).configureEach { - kotlinOptions { - jvmTarget = "1.8" // Set the JVM target to match the bytecode you are inlining + +// Create a custom task to ensure the changelog is generated before building the plugin +tasks.register("ensureChangelogGenerated") { + doLast { + // Get the current version + val currentVersion = project.version.toString() + val isReleaseVersion = currentVersion != "Unreleased" + + if (!file("${projectDir}/doc/CHANGELOG.md").exists() || gradle.startParameter.taskNames.contains("generateChangelog")) { + // If the file doesn't exist or a regeneration is explicitly requested, generate it + tasks.named("generateChangelog").get().actions.forEach { it.execute(tasks.named("generateChangelog").get()) } + } + + // If we're building an "Unreleased" version and have changes since the last tag, + // make sure the Unreleased section exists in the changelog + if (!isReleaseVersion) { + val changelogFile = file("${projectDir}/doc/CHANGELOG.md") + val changelogContent = if (changelogFile.exists()) changelogFile.readText() else "" + + if (!changelogContent.contains("## [Unreleased]")) { + // If there's no Unreleased section, add it at the top of the changelog + val updatedContent = "# Change Log\n\n## [Unreleased]\n\n" + + (if (changelogContent.contains("# Change Log")) + changelogContent.substringAfter("# Change Log").trim() + else changelogContent.trim()) + changelogFile.writeText(updatedContent) + } + } } } -tasks.buildSearchableOptions { - enabled = false -} \ No newline at end of file + +tasks.getByName("buildPlugin").dependsOn("ensureChangelogGenerated") + +// Extension function to execute shell commands +fun String.execute(): Process { + val parts = this.split("\\s".toRegex()) + val process = ProcessBuilder(*parts.toTypedArray()) + .redirectOutput(ProcessBuilder.Redirect.PIPE) + .redirectError(ProcessBuilder.Redirect.PIPE) + .start() + + process.waitFor(10, TimeUnit.SECONDS) + return process +} + +// Extension property to get process output as text +val Process.text: String + get() = inputStream.bufferedReader().readText().trim() diff --git a/doc/CHANGELOG.md b/doc/CHANGELOG.md index 11f0c08b..96d4b3fe 100644 --- a/doc/CHANGELOG.md +++ b/doc/CHANGELOG.md @@ -1,6 +1,25 @@ # Change Log -## [3.7.5] (2024-09-12) +## [Unreleased] + +## [3.7.7](https://github.com/wuseal/JsonToKotlinClass/tree/3.7.7) (2025-04-19) +[View commits](https://github.com/wuseal/JsonToKotlinClass/compare/3.7.6...3.7.7) + +**Bugfix** + +- Fix bug in file duplicate name handling logic [\#447](https://github.com/wuseal/JsonToKotlinClass/pull/447) ([@wuseal](https://github.com/wuseal)) +- Fix JSON Schema reference resolution: kotlin.NotImplementedError: Cannot resolve ref path: \#/$defs/CreditTransferTransaction39 [\#446](https://github.com/wuseal/JsonToKotlinClass/pull/446) ([@wuseal](https://github.com/wuseal)) +- Plugin does not work on Android Studio Meerkat | 2024.3.1 Canary 1 [\#440](https://github.com/wuseal/JsonToKotlinClass/issues/440) + +## [3.7.6](https://github.com/wuseal/JsonToKotlinClass/tree/3.7.6) (2024-12-03) +[View commits](https://github.com/wuseal/JsonToKotlinClass/compare/3.7.5...3.7.6) + +**Bugfix** + +- \[fix\] runtime error exception when run in IntelliJ IDEA 2024.3 and also Android Studio Meerkat [\#443](https://github.com/wuseal/JsonToKotlinClass/pull/443) ([@wuseal](https://github.com/wuseal)) + +## [3.7.5](https://github.com/wuseal/JsonToKotlinClass/tree/3.7.5) (2024-08-31) +[View commits](https://github.com/wuseal/JsonToKotlinClass/compare/3.7.4...3.7.5) **Bugfix** @@ -260,5 +279,4 @@ - JSON input from file [\#76](https://github.com/wuseal/JsonToKotlinClass/issues/76) ## [V3.0.0](https://github.com/wuseal/JsonToKotlinClass/tree/V3.0.0) (2019-01-18) -[View commits](https://github.com/wuseal/JsonToKotlinClass/compare/V3.0-EAP-2...V3.0.0) - +[View commits](https://github.com/wuseal/JsonToKotlinClass/compare/V3.0-EAP-2...V3.0.0) \ No newline at end of file diff --git a/gradle-changelog-plugin-main/.gitignore b/gradle-changelog-plugin-main/.gitignore deleted file mode 100644 index e0d53d80..00000000 --- a/gradle-changelog-plugin-main/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.gradle -.idea -build diff --git a/gradle-changelog-plugin-main/CHANGELOG.md b/gradle-changelog-plugin-main/CHANGELOG.md deleted file mode 100644 index a8c426d6..00000000 --- a/gradle-changelog-plugin-main/CHANGELOG.md +++ /dev/null @@ -1,147 +0,0 @@ -# Gradle Changelog Plugin - -## [Unreleased] -### Added - -### Changed - -### Deprecated - -### Removed - -### Fixed - -### Security -## [1.1.2] -### Changed -- Remove `shadowJar` - -### Fixed -- Don't create groups for the new Unreleased section if empty array is provided - -## [1.1.1] -### Changed -- Require `changelog.version` to be provided explicitly - -### Fixed -- `unspecified` version when patching the changelog - -## [1.0.1] -### Fixed -- Provide `project.version` to the extension using conventions - -## [1.0.0] -### Added -- Support for the [Configuration cache](https://docs.gradle.org/6.8.1/userguide/configuration_cache.html) - -### Changed -- `header` closure has the delegate explicitly set to the extension's context -- Upgrade Gradle Wrapper to `6.6` -- Upgrade `org.jetbrains.kotlin.jvm` to `1.4.21` -- Upgrade `io.gitlab.arturbosch.detekt` to `1.15.0` -- Upgrade `com.github.johnrengelman.shadow` to `6.1.0` - -## [0.6.2] -### Changed -- Smart processing of `headerParserRegex` property - -## [0.6.1] -### Changed -- Renamed `hasVersion` method to `has` -- Better error handling in `patchChangelog` task - -## [0.6.0] -### Added -- `headerParserRegex` extension property for setting custom regex used to extract version from the header string - -### Changed -- Project dependencies upgrade -- Apply ktlint and detekt rules to the code - -## [0.5.0] -### Added -- `header` extension property for setting new header text -- `date` helper method -- `Helper Methods` section in README - -### Removed -- `headerFormat` and `headerArguments` in favor of `header` property - -## [0.4.0] -### Added -- `initializeChangelog` task for creating new changelog file -- `getAll` extension method for fetching all changelog items -- `groups` extension property for defining the groups created with the Unreleased section -- `ktlint` integration - -### Changed -- Move tasks to the `changelog` Gradle group - -## [0.3.3] -### Added -- `patchEmpty` extension property -- Better error handling for the header parser -- GitHub Actions integration with itself - -### Fixed -- Possibility to write date besides versions #5 - -### Changed -- `unreleasedTerm` default value set from `Unreleased` to `[Unreleased]` - -## [0.3.2] -### Added -- `markdownToHTML` method in `extensions.kt` file -- `markdownToPlainText` method in `extensions.kt` file - -## [0.3.1] -### Added -- `--unreleased` flag for the `getChangelog` task - -## [0.3.0] -### Added -- Allow maintaining changelog without change note types (Added, Fixed) -- Customising the header by the `patchChangelog` task with `headerArguments` extension's property -- Customising the change notes splitting with the `itemPrefix` extension's property -- More tests - -### Changed -- `format` extension property renamed to `headerFormat` - -### Fixed -- Avoid parsing the unreleased header -- Invalid change notes splitting - -## [0.2.0] -### Added -- Tests for Plugin, Extension and Tasks -- `getHeader() : String` in `Changelog.Item` -- `withFilter(filter: ((String) -> Boolean)?)` in `Changelog.Item` -- `getLatest()` helper method -- `hasVersion(version: String)` helper method - -### Changed -- Extract `closure` to `extensions.kt` separated file -- Code enhancements - -## [0.1.5] -### Changed -- `changelog.get` and `changelog.getLatest` return `Changelog.Item` -- `noHeader` flag in `Changelog.Item` methods changed to builder pattern -- `Changelog.Item#asHTML` renamed to `Changelog.Item#toHTML` -- `Changelog.Item#asText` renamed to `Changelog.Item#toText` - -## [0.1.4] -### Fixed -- Remove `org.jetbrains:markdown` dependency from the POM file - -## [0.1.3] -### Fixed -- Bundle `org.jetbrains:markdown` dependency with `shadowJar` - -## [0.1.0] -### Added -- Initial release -- `get`/`getUnreleased` helper methods -- `changelog` extension configuration -- `getChangelog`/`patchChangelog` tasks diff --git a/gradle-changelog-plugin-main/CODE_OF_CONDUCT.md b/gradle-changelog-plugin-main/CODE_OF_CONDUCT.md deleted file mode 100644 index 85ed20db..00000000 --- a/gradle-changelog-plugin-main/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct - -This project and the corresponding community is governed by the [JetBrains Open Source and Community Code of Conduct](https://confluence.jetbrains.com/display/ALL/JetBrains+Open+Source+and+Community+Code+of+Conduct). Please make sure you read it. - diff --git a/gradle-changelog-plugin-main/LICENSE b/gradle-changelog-plugin-main/LICENSE deleted file mode 100644 index 9e385b9d..00000000 --- a/gradle-changelog-plugin-main/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2000-2020 JetBrains s.r.o. - - 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 - - http://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. diff --git a/gradle-changelog-plugin-main/README.md b/gradle-changelog-plugin-main/README.md deleted file mode 100644 index 384eb49e..00000000 --- a/gradle-changelog-plugin-main/README.md +++ /dev/null @@ -1,402 +0,0 @@ -# Gradle Changelog Plugin - -[![official JetBrains project](https://jb.gg/badges/official.svg)][jb:confluence-on-gh] -[![Twitter Follow](https://img.shields.io/twitter/follow/JBPlatform?style=flat)][jb:twitter] -[![Gradle Plugin][gradle-plugin-shield]][gradle-plugin] -[![Build](https://github.com/JetBrains/gradle-changelog-plugin/workflows/Build/badge.svg)][gh:build] -[![Slack](https://img.shields.io/badge/Slack-%23gradle--changelog--plugin-blue)][jb:slack] - -**This project requires Gradle 6.6 or newer** - -> **TIP:** Upgrade Gradle Wrapper with `./gradlew wrapper --gradle-version 6.8.2` - -A Gradle plugin that provides tasks and helper methods to simplify working with a changelog that is managed in the [keep a changelog][keep-a-changelog] style. - -## Table of contents - -- [Usage](#usage) -- [Configuration](#configuration) -- [Tasks](#tasks) - - [`initializeChangelog`](#initializechangelog) - - [`getChangelog`](#getchangelog) -- [Extension Methods](#extension-methods) - - [`get`](#get) - - [`getUnreleased`](#getunreleased) - - [`getLatest`](#getlatest) - - [`getAll`](#getall) - - [`has`](#has) -- [`Changelog.Item`](#changelogitem) -- [Gradle Closure in Kotlin DSL](#gradle-closure-in-kotlin-dsl) -- [Helper Methods](#helper-methods) -- [Usage Examples](#usage-examples) -- [Contributing](#contributing) - - -## Usage - -Kotlin: -```kotlin -import org.jetbrains.changelog.closure -import org.jetbrains.changelog.date - -plugins { - id("org.jetbrains.changelog") version "1.1.1" -} - -tasks { - // ... - - patchPluginXml { - changeNotes(closure { changelog.getUnreleased().toHTML() }) - } -} - -changelog { - version = "1.0.0" - path = "${project.projectDir}/CHANGELOG.md" - header = closure { "[$version] - ${date()}" } - itemPrefix = "-" - keepUnreleasedSection = true - unreleasedTerm = "[Unreleased]" - groups = listOf("Added", "Changed", "Deprecated", "Removed", "Fixed", "Security") -} -``` - -Groovy: -```groovy -import org.jetbrains.changelog.ExtensionsKt - -plugins { - id 'org.jetbrains.changelog' version '1.1.1' -} - -apply plugin: 'org.jetbrains.changelog' - -intellij { - // ... - - patchPluginXml { - changeNotes({ changelog.getUnreleased().toHTML() }) - } -} - -changelog { - version = "1.0.0" - path = "${project.projectDir}/CHANGELOG.md" - header = { "[$version] - ${ExtensionsKt.date()}" } - headerParserRegex = ~/\d+\.\d+/ - itemPrefix = "-" - keepUnreleasedSection = true - unreleasedTerm = "[Unreleased]" - groups = ["Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"] -} -``` - -> **Note:** `closure` is a wrapper for the `KotlinClosure0` class and can be used directly as following: -> ```kotlin -> import org.gradle.kotlin.dsl.KotlinClosure0 -> -> changeNotes(KotlinClosure0({ changelog.getUnreleased() })) -> ``` - - -## Configuration - -Plugin can be configured with the following properties set in the `changelog {}` closure: - -| Property | Description | Default value | -| ----------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------- | -| **`version`** | **Required.** Current project's version. | | -| `groups` | List of groups created with a new Unreleased section. | `["Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"]` | -| `header` | Closure that returns current header value. | `{ "[$version]" }` | -| `headerParserRegex` | `Regex`/`Pattern`/`String` used to extract version from the header string. | `null`, fallbacks to [`Changelog#semVerRegex`][semver-regex] | -| `itemPrefix` | Single item's prefix, allows to customise the bullet sign. | `"-"` | -| `keepUnreleasedSection` | Add Unreleased empty section after patching. | `true` | -| `patchEmpty` | Patches changelog even if no release note is provided. | `true` | -| `path` | Path to the changelog file. | `"${project.projectDir}/CHANGELOG.md"` | -| `unreleasedTerm` | Unreleased section text. | `"[Unreleased]"` | - -> **Note:** `header` closure has the delegate explicitly set to the extension's context for the sake of the [Configuration cache][configuration-cache] support. - -## Tasks - -The plugin introduces the following tasks: - -| Task | Description | -| --------------------- | ----------------------------------------------------------------------------------------------------------------------- | -| `getChangelog` | Retrieves changelog for the specified version. | -| `initializeChangelog` | Creates new changelog file with Unreleased section and empty groups. | -| `patchChangelog` | Updates the unreleased section to the given version. Requires *unreleased* section to be present in the changelog file. | - -### `initializeChangelog` - -#### Examples - -```bash -$ ./gradlew initializeChangelog -$ cat CHANGELOG.md - -## [Unreleased] -### Added -- Example item - -### Changed - -### Deprecated - -### Removed - -### Fixed - -### Security -``` - -### `getChangelog` - -#### Options - -| Option | Description | -| --------------- | -------------------------------------------------- | -| `--no-header` | Skips the first version header line in the output. | -| `--unreleased` | Returns Unreleased change notes. | - -#### Examples - -```bash -$ ./gradlew getChangelog --console=plain -q --no-header - -### Added -- Initial project scaffold -- GitHub Actions to automate testing and deployment -- Kotlin support -``` - - -## Extension Methods - -All the methods are available via the `changelog` extension and allow for reading the changelog file within the Gradle tasks to provide the latest (or specific) change notes. - -> **Note:** Following methods depend on the `changelog` extension, which is set in the *Configuration* -> [build phase][build-phases]. To make it running properly, it's required to place the configuration before the fist -> usage of such a method. Alternatively, you can pass the Gradle closure to the task, which will postpone the method -> invocation. - -### `get` - -The method returns a `Changelog.Item` object for the specified version. -Throws `MissingVersionException` if the version is not available. - -It is possible to specify the *unreleased* section with setting the `${changelog.unreleasedTerm}` value. - - -#### Parameters - -| Parameter | Type | Description | Default value | -| ----------- | --------- | -------------------- | ---------------------- | -| `version` | `String` | Change note version. | `${changelog.version}` | - -#### Examples - -Kotlin: -```kotlin -tasks { - patchPluginXml { - changeNotes(closure { changelog.get("1.0.0").toHTML() }) - } -} -``` - -Groovy: -```groovy -tasks { - patchPluginXml { - changeNotes({ changelog.get("1.0.0").toHTML() }) - } -} -``` - -### `getUnreleased` - -The method returns a `Changelog.Item` object for the *unreleased* version. - -#### Examples - -Kotlin: -```kotlin -tasks { - patchPluginXml { - changeNotes(closure { changelog.getUnreleased().toHTML() }) - } -} -``` - -Groovy: -```groovy -tasks { - patchPluginXml { - changeNotes({ changelog.getUnreleased().toHTML() }) - } -} -``` - -### `getLatest` - -The method returns the latest `Changelog.Item` object (first on the list). - -#### Examples - -Kotlin: -```kotlin -tasks { - patchPluginXml { - changeNotes(closure { changelog.getLatest().toHTML() }) - } -} -``` - -Groovy: -```groovy -tasks { - patchPluginXml { - changeNotes({ changelog.getLatest().toHTML() }) - } -} -``` - -### `getAll` - -The method returns all available `Changelog.Item` objects. - -#### Examples - -Kotlin: -```kotlin -extension.getAll().values.map { it.toText() } -``` - -Groovy: -```groovy -extension.getAll().values().each { it.toText() } -``` - -### `has` - -The method checks if the given version exists in the changelog. - -#### Examples - -Kotlin: -```kotlin -tasks { - patchPluginXml { - closure { changelog.has("1.0.0") } - } -} -``` - -Groovy: -```groovy -tasks { - patchPluginXml { - { changelog.has("1.0.0") } - } -} -``` - -## `Changelog.Item` - -Methods described in the above section return `Changelog.Item` object, which is a representation of the single changelog section for the specific version. - -It provides a couple of properties and methods that allow altering the output form of the change notes: - -### Properties - -| Name | Type | Description | -| --------- | --------- | ----------------------- | -| `version` | `String` | Change note version. | - -### Methods - -| Name | Description | Returned type | -| ------------------- | ------------------------------ | ------------- | -| `noHeader()` | Excludes header part. | `this` | -| `noHeader(Boolean)` | Includes/excludes header part. | `this` | -| `getHeader()` | Returns header text. | `String` | -| `toText()` | Generates Markdown output. | `String` | -| `toPlainText()` | Generates Plain Text output. | `String` | -| `toString()` | Generates Markdown output. | `String` | -| `toHTML()` | Generates HTML output. | `String` | - -## Gradle Closure in Kotlin DSL - -To produce Gradle-specific closure in Kotlin DSL, required by some third-party plugins, like [gradle-intellij-plugin][gh:gradle-intellij-plugin] it is required to wrap the Kotlin Unit with `KotlinClosure0` class: - -```kotlin -KotlinClosure0({ changelog.get("1.0.0") }) -``` - -There is also a *neater* method available: - -```kotlin -import org.jetbrains.changelog.closure - -closure { changelog.get("1.0.0") } -``` - -## Helper Methods - -| Name | Description | Returned type | -| -------------------------------------- | -------------------------------------------------------------- | ------------- | -| `closure(function: () -> T)` | Produces Gradle-specific Closure for Kotlin DSL. | `Closure` | -| `date(pattern: String = "yyyy-MM-dd")` | Shorthand for retrieving the current date in the given format. | `String` | -| `markdownToHTML(input: String)` | Converts given Markdown content to HTML output. | `String` | -| `markdownToPlainText(input: String)` | Converts given Markdown content to Plain Text output. | `String` | - -> **Note:** To use package-level Kotlin functions in Groovy, you need to import the containing file as a class: -> ```groovy -> import org.jetbrains.changelog.ExtensionsKt -> -> changelog { -> header = { "[$version] - ${ExtensionsKt.date('yyyy-MM-dd')}" } -> } -> ``` - -## Usage Examples - -- [Unity Support for ReSharper and Rider](https://github.com/JetBrains/resharper-unity) -- [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template) -- [Package Search](https://plugins.jetbrains.com/plugin/12507-package-search) - -## Contributing - -### Integration tests - -To perform integration tests with an existing project, bind the `gradle-changelog-plugin` sources in the Gradle settings file: - -`settings.gradle`: -``` -rootProject.name = "IntelliJ Platform Plugin Template" - -includeBuild '/Users/hsz/Projects/JetBrains/gradle-changelog-plugin' -``` - -`settings.gradle.kts`: -``` -rootProject.name = "IntelliJ Platform Plugin Template" - -includeBuild("/Users/hsz/Projects/JetBrains/gradle-changelog-plugin") -``` - -[gh:build]: https://github.com/JetBrains/gradle-changelog-plugin/actions?query=workflow%3ABuild -[gh:gradle-intellij-plugin]: https://github.com/JetBrains/gradle-intellij-plugin - -[jb:confluence-on-gh]: https://confluence.jetbrains.com/display/ALL/JetBrains+on+GitHub -[jb:slack]: https://plugins.jetbrains.com/slack -[jb:twitter]: https://twitter.com/JBPlatform - -[build-phases]: https://docs.gradle.org/current/userguide/build_lifecycle.html#sec:build_phases -[configuration-cache]: https://docs.gradle.org/6.8.2/userguide/configuration_cache.html -[keep-a-changelog]: https://keepachangelog.com/en/1.0.0 -[gradle-plugin-shield]: https://img.shields.io/maven-metadata/v.svg?label=Gradle%20Plugin&color=blue&metadataUrl=https://plugins.gradle.org/m2/org/jetbrains/intellij/plugins/gradle-changelog-plugin/maven-metadata.xml -[gradle-plugin]: https://plugins.gradle.org/plugin/org.jetbrains.changelog -[semver-regex]: https://github.com/JetBrains/gradle-changelog-plugin/blob/main/src/main/kotlin/org/jetbrains/changelog/Changelog.kt#L23 diff --git a/gradle-changelog-plugin-main/build.gradle.kts b/gradle-changelog-plugin-main/build.gradle.kts deleted file mode 100644 index bbd0e2df..00000000 --- a/gradle-changelog-plugin-main/build.gradle.kts +++ /dev/null @@ -1,74 +0,0 @@ -import io.gitlab.arturbosch.detekt.Detekt -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile - -plugins { - id("java-gradle-plugin") - id("maven-publish") - id("org.jetbrains.changelog") version "1.1.2" - id("org.jetbrains.kotlin.jvm") version "1.5.0" - id("com.gradle.plugin-publish") version "0.14.0" - id("io.gitlab.arturbosch.detekt") version "1.16.0" - id("org.jlleitschuh.gradle.ktlint") version "10.0.0" - id("com.github.breadmoirai.github-release") version "2.2.12" -} - -description = "Gradle Changelog Plugin" -group = "org.jetbrains.intellij.plugins" -version = "1.1.2" - -repositories { - mavenCentral() - jcenter() -} - -dependencies { - implementation(kotlin("stdlib-jdk8")) - implementation("org.jetbrains:markdown:0.2.3") - detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.16.0") - testImplementation(kotlin("test")) - testImplementation(kotlin("test-junit")) -} - -gradlePlugin { - plugins.create("changelog") { - id = "org.jetbrains.changelog" - implementationClass = "org.jetbrains.changelog.ChangelogPlugin" - displayName = "Gradle Changelog Plugin" - description = "Provides tasks and helper methods for handling changelog in the Project." - } -} - -pluginBundle { - website = "https://github.com/JetBrains/${project.name}" - vcsUrl = "https://github.com/JetBrains/${project.name}.git" - description = "Gradle Changelog Plugin" - tags = listOf("changelog", "jetbrains") -} - -changelog { - version = "${project.version}" -} - -detekt { - config.from(file("detekt.yml")) - buildUponDefaultConfig = true - parallel = true - - reports { - html.enabled = false - xml.enabled = false - txt.enabled = false - } -} - -tasks { - listOf("compileKotlin", "compileTestKotlin").forEach { - getByName(it) { - kotlinOptions.jvmTarget = "1.8" - } - } - - withType().configureEach { - jvmTarget = JavaVersion.VERSION_1_8.toString() - } -} diff --git a/gradle-changelog-plugin-main/detekt.yml b/gradle-changelog-plugin-main/detekt.yml deleted file mode 100644 index 1a418171..00000000 --- a/gradle-changelog-plugin-main/detekt.yml +++ /dev/null @@ -1,3 +0,0 @@ -formatting: - Indentation: - active: true diff --git a/gradle-changelog-plugin-main/gradle.properties b/gradle-changelog-plugin-main/gradle.properties deleted file mode 100644 index e69de29b..00000000 diff --git a/gradle-changelog-plugin-main/gradle/wrapper/gradle-wrapper.jar b/gradle-changelog-plugin-main/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 5c2d1cf0..00000000 Binary files a/gradle-changelog-plugin-main/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle-changelog-plugin-main/gradle/wrapper/gradle-wrapper.properties b/gradle-changelog-plugin-main/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index bca17f36..00000000 --- a/gradle-changelog-plugin-main/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,5 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.6-all.zip -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradle-changelog-plugin-main/gradlew b/gradle-changelog-plugin-main/gradlew deleted file mode 100755 index b0d6d0ab..00000000 --- a/gradle-changelog-plugin-main/gradlew +++ /dev/null @@ -1,188 +0,0 @@ -#!/usr/bin/env sh - -# -# Copyright 2015 the original author or 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 -# -# http://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 UN*X -## -############################################################################## - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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"' - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn () { - echo "$*" -} - -die () { - echo - echo "$*" - echo - exit 1 -} - -# 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 - ;; - 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" - which java >/dev/null 2>&1 || 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 - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi - -exec "$JAVACMD" "$@" diff --git a/gradle-changelog-plugin-main/gradlew.bat b/gradle-changelog-plugin-main/gradlew.bat deleted file mode 100644 index 9991c503..00000000 --- a/gradle-changelog-plugin-main/gradlew.bat +++ /dev/null @@ -1,100 +0,0 @@ -@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 http://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=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@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%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - -: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 %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/gradle-changelog-plugin-main/settings.gradle.kts b/gradle-changelog-plugin-main/settings.gradle.kts deleted file mode 100644 index 3527590d..00000000 --- a/gradle-changelog-plugin-main/settings.gradle.kts +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = "gradle-changelog-plugin" diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/Changelog.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/Changelog.kt deleted file mode 100644 index 540a59d1..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/Changelog.kt +++ /dev/null @@ -1,130 +0,0 @@ -package org.jetbrains.changelog - -import org.intellij.markdown.IElementType -import org.intellij.markdown.MarkdownElementTypes -import org.intellij.markdown.ast.ASTNode -import org.intellij.markdown.ast.getTextInNode -import org.intellij.markdown.parser.MarkdownParser -import org.jetbrains.changelog.exceptions.HeaderParseException -import org.jetbrains.changelog.exceptions.MissingFileException -import org.jetbrains.changelog.exceptions.MissingVersionException -import org.jetbrains.changelog.flavours.ChangelogFlavourDescriptor -import java.io.File - -class Changelog(extension: ChangelogPluginExtension) { - - val content = File(extension.path).run { - if (extension.path.isEmpty() || !exists()) { - throw MissingFileException(extension.path) - } - readText() - } - - @Suppress("MaxLineLength") - private val semVerRegex = - """^[Vv]?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?${'$'}""".toRegex() // ktlint-disable max-line-length - private val flavour = ChangelogFlavourDescriptor() - private val parser = MarkdownParser(flavour) - private val tree = parser.buildMarkdownTreeFromString(content) - - private val items = tree.children - .groupByType(MarkdownElementTypes.ATX_2) { - it.children.last().text().trim().run { - when { - startsWith(extension.unreleasedTerm)-> this.split(" ").first() - else -> split("""[^-+.0-9a-zA-Z]+""".toRegex()).firstOrNull( - (extension.headerParserRegex as Regex? ?: semVerRegex)::matches - ) ?: throw HeaderParseException(this, extension) - } - } - } - .filterKeys(String::isNotEmpty) - .mapValues { (key, value) -> - value - .drop(1) - .groupByType(MarkdownElementTypes.ATX_3) { - it.text().trimStart('#').trim() - } - .mapValues { - it.value - .joinToString("") { node -> node.text() } - .split("""\n${Regex.escape(extension.itemPrefix)}""".toRegex()) - .map { line -> extension.itemPrefix + line.trim('\n') } - .drop(1) - .filterNot(String::isEmpty) - }.run { - val isUnreleased = key == extension.unreleasedTerm - Item(key, value.first(), this, isUnreleased) - } - } - - fun has(version: String) = items.containsKey(version) - - fun get(version: String) = items[version] ?: throw MissingVersionException(version) - - fun getLatest() = items[items.keys.first()] ?: throw MissingVersionException("any") - - fun getAll() = items - - inner class Item( - val version: String, - private val header: ASTNode, - private val items: Map>, - private val isUnreleased: Boolean = false - ) { - - private var withHeader = false - private var filterCallback: ((String) -> Boolean)? = null - - fun withHeader(header: Boolean) = apply { - this.withHeader = header - } - - fun withFilter(filter: ((String) -> Boolean)?) = apply { - this.filterCallback = filter - } - - fun getHeaderNode() = header - - fun getHeader() = header.text() - - fun getSections() = items - .mapValues { - it.value.filter { item -> filterCallback?.invoke(item) ?: true } - } - .filterNot { - it.value.isEmpty() && !isUnreleased - } - - fun toText() = getSections().entries - .joinToString("\n\n") { (key, value) -> - (listOfNotNull("### $key".takeIf { key.isNotEmpty() }) + value).joinToString("\n\n") - }.trim().let { - when { - withHeader -> "${getHeader()}\n$it" - else -> it - } - } - - fun toHTML() = markdownToHTML(toText()) - - fun toPlainText() = markdownToPlainText(toText()) - - override fun toString() = toText() - } - - private fun ASTNode.text() = getTextInNode(content).toString() - - private fun List.groupByType( - type: IElementType, - getKey: ((item: ASTNode) -> String)? = null - ): Map> { - var key = "" - return groupBy { - if (it.type == type) { - key = getKey?.invoke(it) ?: it.text() - } - key - } - } -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPlugin.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPlugin.kt deleted file mode 100644 index 8e6c02a6..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPlugin.kt +++ /dev/null @@ -1,29 +0,0 @@ -package org.jetbrains.changelog - -import org.gradle.api.Plugin -import org.gradle.api.Project -import org.jetbrains.changelog.tasks.GetChangelogTask -import org.jetbrains.changelog.tasks.InitializeChangelogTask -import org.jetbrains.changelog.tasks.PatchChangelogTask - -class ChangelogPlugin : Plugin { - - override fun apply(project: Project) { - project.run { - extensions.create("changelogForIDEPlugin", ChangelogPluginExtension::class.java, objects, projectDir) - - tasks.apply { - create("patchChangelog", PatchChangelogTask::class.java) { - it.group = "changelog" - } - create("initializeChangelog", InitializeChangelogTask::class.java) { - it.group = "changelog" - } - create("getChangelog", GetChangelogTask::class.java) { - it.group = "changelog" - it.outputs.upToDateWhen { false } - } - } - } - } -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPluginExtension.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPluginExtension.kt deleted file mode 100644 index 0a0feb23..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/ChangelogPluginExtension.kt +++ /dev/null @@ -1,111 +0,0 @@ -package org.jetbrains.changelog - -import groovy.lang.Closure -import org.gradle.api.model.ObjectFactory -import org.gradle.api.tasks.Internal -import org.gradle.api.tasks.Optional -import org.jetbrains.changelog.exceptions.VersionNotSpecifiedException -import java.io.File -import java.util.regex.Pattern - -@Suppress("UnstableApiUsage") -open class ChangelogPluginExtension(objects: ObjectFactory, private val projectDir: File) { - - @Optional - @Internal - private val groupsProperty = objects.listProperty(String::class.java).apply { - set(listOf("Added", "Changed", "Deprecated", "Removed", "Fixed", "Security")) - } - var groups: List - get() = groupsProperty.getOrElse(emptyList()) - set(value) = groupsProperty.set(value) - - @Optional - @Internal - private val headerProperty = objects.property(Closure::class.java).apply { - set(closure { "[$version]" }) - } - var header: Closure<*> - get() = headerProperty.get() - set(value) = headerProperty.set(value) - - @Optional - @Internal - private val headerParserRegexProperty = objects.property(Regex::class.java) - var headerParserRegex: Any? - get() = headerParserRegexProperty.orNull - set(value) = headerParserRegexProperty.set(headerParserRegexHelper(value)) - - private fun headerParserRegexHelper(t: T) = when (t) { - is Regex -> t - is String -> t.toRegex() - is Pattern -> t.toRegex() - else -> throw IllegalArgumentException("Unsupported type of $t. Expected value types: Regex, String, Pattern.") - } - - @Optional - @Internal - private val itemPrefixProperty = objects.property(String::class.java).apply { - set("-") - } - var itemPrefix: String - get() = itemPrefixProperty.get() - set(value) = itemPrefixProperty.set(value) - - @Optional - @Internal - private val keepUnreleasedSectionProperty = objects.property(Boolean::class.java).apply { - set(true) - } - var keepUnreleasedSection: Boolean - get() = keepUnreleasedSectionProperty.get() - set(value) = keepUnreleasedSectionProperty.set(value) - - @Optional - @Internal - private val patchEmptyProperty = objects.property(Boolean::class.java).apply { - set(true) - } - var patchEmpty: Boolean - get() = patchEmptyProperty.get() - set(value) = patchEmptyProperty.set(value) - - @Optional - @Internal - private val pathProperty = objects.property(String::class.java).apply { - set("$projectDir/CHANGELOG.md") - } - var path: String - get() = pathProperty.get() - set(value) = pathProperty.set(value) - - @Internal - private val versionProperty = objects.property(String::class.java) - var version: String - get() = versionProperty.run { - if (isPresent) { - return get() - } - throw VersionNotSpecifiedException() - } - set(value) = versionProperty.set(value) - - @Optional - @Internal - private val unreleasedTermProperty = objects.property(String::class.java).apply { - set("[Unreleased]") - } - var unreleasedTerm: String - get() = unreleasedTermProperty.get() - set(value) = unreleasedTermProperty.set(value) - - fun getUnreleased() = get(unreleasedTerm) - - fun get(version: String) = Changelog(this).get(version) - - fun getLatest() = Changelog(this).getLatest() - - fun getAll() = Changelog(this).getAll() - - fun has(version: String) = Changelog(this).has(version) -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/PlainTextTagRenderer.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/PlainTextTagRenderer.kt deleted file mode 100644 index 82d36b88..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/PlainTextTagRenderer.kt +++ /dev/null @@ -1,18 +0,0 @@ -package org.jetbrains.changelog - -import org.intellij.markdown.ast.ASTNode -import org.intellij.markdown.html.HtmlGenerator - -class PlainTextTagRenderer : HtmlGenerator.TagRenderer { - - override fun openTag( - node: ASTNode, - tagName: CharSequence, - vararg attributes: CharSequence?, - autoClose: Boolean - ) = "" - - override fun closeTag(tagName: CharSequence) = "" - - override fun printHtml(html: CharSequence) = html -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/HeaderParseException.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/HeaderParseException.kt deleted file mode 100644 index 0c4d47f8..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/HeaderParseException.kt +++ /dev/null @@ -1,8 +0,0 @@ -package org.jetbrains.changelog.exceptions - -import org.jetbrains.changelog.ChangelogPluginExtension - -class HeaderParseException(value: String, extension: ChangelogPluginExtension) : Exception( - "Header '$value' does not contain version number. " + - ("Probably you want set unreleasedTerm to '$value'".takeIf { value.contains(extension.unreleasedTerm) } ?: "") -) diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/MissingFileException.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/MissingFileException.kt deleted file mode 100644 index 487da88f..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/MissingFileException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package org.jetbrains.changelog.exceptions - -class MissingFileException(path: String) : Exception("Changelog file does not exist: $path") diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/MissingVersionException.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/MissingVersionException.kt deleted file mode 100644 index ec14ad40..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/MissingVersionException.kt +++ /dev/null @@ -1,3 +0,0 @@ -package org.jetbrains.changelog.exceptions - -class MissingVersionException(version: String?) : Exception("Version is missing: $version") diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/VersionNotSpecifiedException.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/VersionNotSpecifiedException.kt deleted file mode 100644 index d121c854..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/exceptions/VersionNotSpecifiedException.kt +++ /dev/null @@ -1,5 +0,0 @@ -package org.jetbrains.changelog.exceptions - -class VersionNotSpecifiedException : Exception( - "Version is missing. Please provide the project version to the `changelog.version` property explicitly." -) diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/extensions.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/extensions.kt deleted file mode 100644 index 9ef3ee78..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/extensions.kt +++ /dev/null @@ -1,26 +0,0 @@ -package org.jetbrains.changelog - -import groovy.lang.Closure -import org.intellij.markdown.html.HtmlGenerator -import org.intellij.markdown.parser.MarkdownParser -import org.jetbrains.changelog.flavours.ChangelogFlavourDescriptor -import org.jetbrains.changelog.flavours.PlainTextFlavourDescriptor -import java.text.SimpleDateFormat -import java.util.Date - -fun closure(function: () -> T) = object : Closure(null) { - @Suppress("unused") - fun doCall() = function() -} - -fun date(pattern: String = "yyyy-MM-dd") = SimpleDateFormat(pattern).format(Date())!! - -fun markdownToHTML(input: String) = ChangelogFlavourDescriptor().run { - HtmlGenerator(input, MarkdownParser(this).buildMarkdownTreeFromString(input), this, false) - .generateHtml() -} - -fun markdownToPlainText(input: String) = PlainTextFlavourDescriptor().run { - HtmlGenerator(input, MarkdownParser(this).buildMarkdownTreeFromString(input), this, false) - .generateHtml(PlainTextTagRenderer()) -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/flavours/ChangelogFlavourDescriptor.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/flavours/ChangelogFlavourDescriptor.kt deleted file mode 100644 index 43ecb2f8..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/flavours/ChangelogFlavourDescriptor.kt +++ /dev/null @@ -1,15 +0,0 @@ -package org.jetbrains.changelog.flavours - -import org.intellij.markdown.MarkdownElementTypes -import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor -import org.intellij.markdown.html.TrimmingInlineHolderProvider -import org.intellij.markdown.parser.LinkMap -import java.net.URI - -class ChangelogFlavourDescriptor : GFMFlavourDescriptor() { - - override fun createHtmlGeneratingProviders(linkMap: LinkMap, baseURI: URI?) = - super.createHtmlGeneratingProviders(linkMap, baseURI) + hashMapOf( - MarkdownElementTypes.MARKDOWN_FILE to TrimmingInlineHolderProvider() - ) -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/flavours/PlainTextFlavourDescriptor.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/flavours/PlainTextFlavourDescriptor.kt deleted file mode 100644 index d1c79327..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/flavours/PlainTextFlavourDescriptor.kt +++ /dev/null @@ -1,31 +0,0 @@ -package org.jetbrains.changelog.flavours - -import org.intellij.markdown.MarkdownElementTypes -import org.intellij.markdown.MarkdownTokenTypes -import org.intellij.markdown.ast.ASTNode -import org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor -import org.intellij.markdown.html.HtmlGenerator -import org.intellij.markdown.html.OpenCloseGeneratingProvider -import org.intellij.markdown.parser.LinkMap -import java.net.URI - -class PlainTextFlavourDescriptor : GFMFlavourDescriptor() { - - override fun createHtmlGeneratingProviders(linkMap: LinkMap, baseURI: URI?) = - super.createHtmlGeneratingProviders(linkMap, baseURI) + hashMapOf( - MarkdownElementTypes.LIST_ITEM to CustomProvider("- "), - MarkdownTokenTypes.EOL to CustomProvider("", "\n") - ) - - private class CustomProvider(private val openTagName: String = "", private val closeTagName: String = "") : - OpenCloseGeneratingProvider() { - - override fun openTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { - visitor.consumeHtml(openTagName) - } - - override fun closeTag(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) { - visitor.consumeHtml(closeTagName) - } - } -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/GetChangelogTask.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/GetChangelogTask.kt deleted file mode 100644 index f1fd12ee..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/GetChangelogTask.kt +++ /dev/null @@ -1,58 +0,0 @@ -package org.jetbrains.changelog.tasks - -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.TaskAction -import org.gradle.api.tasks.options.Option -import org.jetbrains.changelog.Changelog -import org.jetbrains.changelog.ChangelogPluginExtension -import java.io.File - -open class GetChangelogTask : DefaultTask() { - - private val extension = project.extensions.getByType(ChangelogPluginExtension::class.java) - - private var noHeader = false - - @Suppress("UnstableApiUsage") - @Option(option = "no-header", description = "Omits header version line") - fun setNoHeader(noHeader: Boolean) { - this.noHeader = noHeader - } - - @Input - fun getNoHeader() = noHeader - - private var unreleased = false - - @Suppress("UnstableApiUsage") - @Option(option = "unreleased", description = "Returns Unreleased change notes") - fun setUnreleased(unreleased: Boolean) { - this.unreleased = unreleased - } - - @Input - fun getUnreleased() = unreleased - - @InputFile - fun getInputFile() = File(extension.path) - - @OutputFile - fun getOutputFile() = getInputFile() - - @TaskAction - fun run() = logger.quiet( - Changelog(extension).run { - val version = when (unreleased) { - true -> extension.unreleasedTerm - false -> extension.version - } - get(version).run { - withHeader(!noHeader) - toText() - } - } - ) -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTask.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTask.kt deleted file mode 100644 index 1cd8ba21..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTask.kt +++ /dev/null @@ -1,29 +0,0 @@ -package org.jetbrains.changelog.tasks - -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.TaskAction -import org.jetbrains.changelog.ChangelogPluginExtension -import java.io.File - -open class InitializeChangelogTask : DefaultTask() { - - private val extension = project.extensions.getByType(ChangelogPluginExtension::class.java) - - @TaskAction - fun run() { - File(extension.path).apply { - if (!exists()) { - createNewFile() - } - }.writeText( - """ - # Changelog - - ## ${extension.unreleasedTerm} - ### ${extension.groups.first()} - ${extension.itemPrefix} Example item - - """.trimIndent() + extension.groups.drop(1).joinToString("\n") { "### $it\n" } - ) - } -} diff --git a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/PatchChangelogTask.kt b/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/PatchChangelogTask.kt deleted file mode 100644 index 0824a604..00000000 --- a/gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/PatchChangelogTask.kt +++ /dev/null @@ -1,53 +0,0 @@ -package org.jetbrains.changelog.tasks - -import org.gradle.api.DefaultTask -import org.gradle.api.tasks.InputFile -import org.gradle.api.tasks.OutputFile -import org.gradle.api.tasks.StopActionException -import org.gradle.api.tasks.TaskAction -import org.jetbrains.changelog.Changelog -import org.jetbrains.changelog.ChangelogPluginExtension -import java.io.File - -open class PatchChangelogTask : DefaultTask() { - - private val extension = project.extensions.getByType(ChangelogPluginExtension::class.java) - - @InputFile - fun getInputFile() = File(extension.path) - - @OutputFile - fun getOutputFile() = getInputFile() - - @TaskAction - fun run() { - Changelog(extension).apply { - if (!has(extension.unreleasedTerm)) { - logger.warn( - ":patchChangelog task requires '${extension.unreleasedTerm}' section to be present. " + - "Add '## ${extension.unreleasedTerm}' section header to your changelog file: ${extension.path}" - ) - throw StopActionException() - } - get(extension.unreleasedTerm).let { item -> - val node = item.getHeaderNode() - val header = "## ${extension.header.call()}" - - if (extension.getUnreleased().getSections().isEmpty() && !extension.patchEmpty) { - return - } - - File(extension.path).writeText( - this.content.run { - if (extension.keepUnreleasedSection) { - val unreleasedGroups = extension.groups.joinToString("\n") { "### $it\n" } - StringBuilder(this).insert(node.endOffset, "\n$unreleasedGroups$header").toString() - } else { - replaceRange(node.startOffset, node.endOffset, header) - } - } - ) - } - } - } -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/BaseTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/BaseTest.kt deleted file mode 100644 index fd646629..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/BaseTest.kt +++ /dev/null @@ -1,62 +0,0 @@ -package org.jetbrains.changelog - -import org.gradle.api.internal.project.DefaultProject -import org.gradle.testfixtures.ProjectBuilder -import org.gradle.testkit.runner.BuildResult -import org.gradle.testkit.runner.GradleRunner -import java.io.File -import kotlin.test.BeforeTest - -open class BaseTest { - - protected lateinit var project: DefaultProject - protected lateinit var extension: ChangelogPluginExtension - - protected var changelog: String = "" - set(value) { - field = value - File(extension.path).run { - createNewFile() - writeText(value.trimIndent().trim()) - } - } - - protected var version: String - get() = project.version.toString() - set(value) { - project.version = value - } - - protected var buildFile = "" - set(value) { - field = value - File("${project.projectDir}/build.gradle").run { - createNewFile() - writeText(value.trimIndent()) - } - } - - @BeforeTest - fun setUp() { - project = ProjectBuilder.builder() - .withName("project") - .withProjectDir(createTempDir()).build() as DefaultProject - - project.version = "1.0.0" - project.plugins.apply(ChangelogPlugin::class.java) - - extension = project.extensions.getByType(ChangelogPluginExtension::class.java) - } - - private fun prepareTask(taskName: String, vararg arguments: String) = - GradleRunner.create() - .withProjectDir(project.projectDir) - .withArguments(taskName, "--console=plain", "--stacktrace", *arguments) - .withPluginClasspath() - - protected fun runTask(taskName: String, vararg arguments: String): BuildResult = - prepareTask(taskName, *arguments).build() - - protected fun runFailingTask(taskName: String, vararg arguments: String): BuildResult = - prepareTask(taskName, *arguments).buildAndFail() -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ChangelogPluginExtensionTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ChangelogPluginExtensionTest.kt deleted file mode 100644 index dc1a8410..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ChangelogPluginExtensionTest.kt +++ /dev/null @@ -1,460 +0,0 @@ -package org.jetbrains.changelog - -import org.jetbrains.changelog.exceptions.MissingFileException -import org.jetbrains.changelog.exceptions.MissingVersionException -import java.io.File -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -class ChangelogPluginExtensionTest : BaseTest() { - - @BeforeTest - fun localSetUp() { - changelog = - """ - # Changelog - - ## [Unreleased] - ### Added - - Foo - - ## [1.0.0] - ### Removed - - Bar - """ - } - - @Test - fun `throws MissingFileException when changelog file does not exist`() { - File(extension.path).delete() - assertFailsWith { - extension.get(version) - } - } - - @Test - fun `throws MissingVersionException if requested version is not available`() { - assertFailsWith { - extension.get("2.0.0") - } - } - - @Test - fun `returns change notes for the v1_0_0 version`() { - extension.get(version).apply { - assertEquals(project.version, version) - - assertEquals( - """ - ### Removed - - Bar - """.trimIndent(), - toText() - ) - - assertEquals( - """ - ### Removed - - Bar - """.trimIndent(), - toString() - ) - - assertEquals( - """ -

Removed

-
  • Bar
- """.trimIndent(), - toHTML() - ) - } - } - - @Test - fun `parses changelog with custom format`() { - changelog = changelog.replace("""\[([^]]+)]""".toRegex(), "[[$1]]") - extension.unreleasedTerm = "[[Unreleased]]" - extension.get(version).apply { - assertEquals("1.0.0", version) - } - } - - @Test - fun `getUnreleased() returns Unreleased section`() { - extension.getUnreleased().withHeader(true).apply { - assertEquals("[Unreleased]", version) - assertEquals( - """ - ## [Unreleased] - ### Added - - Foo - """.trimIndent(), - toText() - ) - } - } - - @Test - fun `getUnreleased() returns Upcoming section if unreleasedTerm is customised`() { - changelog = changelog.replace("Unreleased", "Upcoming") - extension.unreleasedTerm = "[Upcoming]" - extension.getUnreleased().withHeader(true).apply { - assertEquals("[Upcoming]", version) - assertEquals( - """ - ## [Upcoming] - ### Added - - Foo - """.trimIndent(), - toText() - ) - } - } - - @Test - @Suppress("LongMethod", "MaxLineLength") - fun `parses changelog into structured sections`() { - changelog = - """ - # Changelog - - ## [1.0.0] - ### Added - - Foo *FOO* foo - - Bar **BAR** bar - - Test [link](https://www.example.org) test - - Code `block` code - - Bravo - - Alpha - - ### Fixed - - Hello - - World - - ### Removed - - Hola - """ - - extension.get(version).apply { - assertEquals(this@ChangelogPluginExtensionTest.version, version) - assertEquals("## [1.0.0]", getHeader()) - withHeader(true).getSections().apply { - assertEquals(3, size) - assertTrue(containsKey("Added")) - assertEquals(6, get("Added")?.size) - assertTrue(containsKey("Fixed")) - assertEquals(2, get("Fixed")?.size) - assertTrue(containsKey("Removed")) - assertEquals(1, get("Removed")?.size) - } - assertEquals( - """ - ## [1.0.0] - ### Added - - Foo *FOO* foo - - Bar **BAR** bar - - Test [link](https://www.example.org) test - - Code `block` code - - Bravo - - Alpha - - ### Fixed - - Hello - - World - - ### Removed - - Hola - """.trimIndent(), - toText() - ) - assertEquals( - """ -

[1.0.0]

-

Added

-
  • Foo FOO foo
  • Bar BAR bar
  • Test link test
  • Code block code
  • Bravo
  • Alpha
- -

Fixed

-
  • Hello
  • World
- -

Removed

-
  • Hola
- """.trimIndent(), - toHTML() - ) - assertEquals( - """ - [1.0.0] - Added - - Foo FOO foo - - Bar BAR bar - - Test link test - - Code block code - - Bravo - - Alpha - - Fixed - - Hello - - World - - Removed - - Hola - """.trimIndent(), - toPlainText() - ) - } - } - - @Test - fun `filters out entries from the change notes for the given version`() { - changelog = - """ - # Changelog - - ## [1.0.0] - ### Added - - Foo - - Bar x - - Buz - - Bravo x - - Alpha - - ### Fixed - - Hello x - - World - - ### Removed - - Hola x - """ - - extension.get(version).apply { - assertEquals(this@ChangelogPluginExtensionTest.version, version) - assertEquals("## [1.0.0]", getHeader()) - withFilter { - !it.endsWith('x') - }.getSections().apply { - assertEquals(2, size) - assertTrue(containsKey("Added")) - assertEquals(3, get("Added")?.size) - assertTrue(containsKey("Fixed")) - assertEquals(1, get("Fixed")?.size) - assertFalse(containsKey("Removed")) - - assertEquals( - """ - ### Added - - Foo - - Buz - - Alpha - - ### Fixed - - World - """.trimIndent(), - toText() - ) - assertEquals( - """ -

Added

-
  • Foo
  • Buz
  • Alpha
- -

Fixed

-
  • World
- """.trimIndent(), - toHTML() - ) - } - } - } - - @Test - fun `returns latest change note`() { - extension.getLatest().apply { - assertEquals("[Unreleased]", version) - assertEquals("## [Unreleased]", getHeader()) - } - } - - @Test - fun `checks if the given version exists in the changelog`() { - assertTrue(extension.has("[Unreleased]")) - assertTrue(extension.has("1.0.0")) - assertFalse(extension.has("2.0.0")) - } - - @Test - fun `parses header with custom format containing version and date`() { - changelog = - """ - # Changelog - ## NEW VERSION - - Compatible with IDEA 2020.2 EAPs - - ## Version 1.0.1119-eap (29 May 2020) - - Compatible with IDEA 2020.2 EAPs - """ - - extension.unreleasedTerm = "NEW VERSION" - extension.get("1.0.1119-eap").apply { - assertEquals("1.0.1119-eap", version) - } - } - - @Test - fun `returns change notes without group sections if not present`() { - changelog = - """ - # Changelog - ## [1.0.0] - - Foo - """ - - extension.get("1.0.0").apply { - assertEquals("1.0.0", version) - - withHeader(true).getSections().apply { - assertEquals(1, size) - assertTrue(containsKey("")) - assertEquals(1, get("")?.size) - } - assertEquals( - """ - ## [1.0.0] - - Foo - """.trimIndent(), - toText() - ) - assertEquals( - """ -

[1.0.0]

-
  • Foo
- """.trimIndent(), - toHTML() - ) - } - } - - @Test - fun `splits change notes into a list by the given itemPrefix`() { - changelog = - """ - # Changelog - ## [1.0.0] - - Foo - bar - * Foo2 - - Bar - """ - - extension.get("1.0.0").apply { - assertEquals("1.0.0", version) - assertEquals(1, getSections().keys.size) - getSections().values.first().apply { - assertEquals(2, size) - assertEquals( - """ - - Foo - bar - * Foo2 - """.trimIndent(), - first() - ) - assertEquals("- Bar", last()) - } - } - } - - @Test - fun `returns all Changelog items`() { - extension.getAll().apply { - assertNotNull(this) - assertEquals(2, keys.size) - assertEquals("[Unreleased]", keys.first()) - assertEquals("1.0.0", keys.last()) - assertEquals("## [Unreleased]", values.first().getHeader()) - assertEquals("## [1.0.0]", values.last().getHeader()) - assertEquals( - """ - ### Added - - Foo - """.trimIndent(), - values.first().toText() - ) - assertEquals( - """ - ## [Unreleased] - ### Added - - Foo - """.trimIndent(), - values.first().withHeader(true).toText() - ) - assertEquals( - """ - ### Removed - - Bar - """.trimIndent(), - values.last().toText() - ) - assertEquals( - """ - ## [1.0.0] - ### Removed - - Bar - """.trimIndent(), - values.last().withHeader(true).toText() - ) - } - } - - @Test - fun `returns Changelog items for change note without category`() { - extension.itemPrefix = "*" - extension.unreleasedTerm = "Unreleased" - changelog = - """ - # My Changelog - - ## Unreleased - - * Foo - """ - - assertNotNull(extension.getLatest()) - assertEquals( - """ -

Unreleased

-
  • Foo
- """.trimIndent(), - extension.getLatest().withHeader(true).toHTML() - ) - } - - @Test - fun `allows to customize the header parser regex to match version in different format than semver`() { - changelog = - """ - # My Changelog - - ## 2020.1 - - * Foo - """ - - extension.headerParserRegex = - """\d+\.\d+""".toRegex() - assertNotNull(extension.get("2020.1")) - - extension.headerParserRegex = "\\d+\\.\\d+" - assertNotNull(extension.get("2020.1")) - - extension.headerParserRegex = - """\d+\.\d+""".toPattern() - assertNotNull(extension.get("2020.1")) - - assertFailsWith { - extension.headerParserRegex = 123 - assertNotNull(extension.get("2020.1")) - } - } -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ChangelogPluginTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ChangelogPluginTest.kt deleted file mode 100644 index e2b8a706..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ChangelogPluginTest.kt +++ /dev/null @@ -1,49 +0,0 @@ -package org.jetbrains.changelog - -import org.jetbrains.changelog.exceptions.VersionNotSpecifiedException -import org.jetbrains.changelog.tasks.GetChangelogTask -import org.jetbrains.changelog.tasks.InitializeChangelogTask -import org.jetbrains.changelog.tasks.PatchChangelogTask -import java.io.File -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -class ChangelogPluginTest : BaseTest() { - - @Test - fun `default properties values`() { - assertNotNull(extension) - assertTrue(extension.keepUnreleasedSection) - assertEquals("${project.projectDir}/CHANGELOG.md", extension.path) - assertEquals("[Unreleased]", extension.unreleasedTerm) - } - - @Test - fun `throws VersionNotSpecifiedException when changelog extension has no version provided`() { - assertFailsWith { - extension.version - } - - extension.version = "1.0.0" - assertEquals("1.0.0", extension.version) - } - - @Test - fun `tasks availability`() { - (project.tasks.findByName("initializeChangelog") as InitializeChangelogTask).apply { - assertNotNull(this) - } - - (project.tasks.findByName("getChangelog") as GetChangelogTask).apply { - assertNotNull(this) - assertEquals(File("${project.projectDir}/CHANGELOG.md").path, getInputFile().path) - } - - (project.tasks.findByName("patchChangelog") as PatchChangelogTask).apply { - assertNotNull(this) - } - } -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ExtensionsTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ExtensionsTest.kt deleted file mode 100644 index d75120ab..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/ExtensionsTest.kt +++ /dev/null @@ -1,65 +0,0 @@ -package org.jetbrains.changelog - -import java.text.SimpleDateFormat -import java.util.Date -import kotlin.test.Test -import kotlin.test.assertEquals - -class ExtensionsTest { - - @Test - fun closureTest() { - val c = closure { "response" } - - assertEquals("response", c.call()) - } - - @Test - fun dateTest() { - assertEquals(SimpleDateFormat("yyyy-MM-dd").format(Date()), date()) - - val pattern = "ddMMyyyy" - assertEquals(SimpleDateFormat(pattern).format(Date()), date(pattern)) - } - - @Test - fun markdownToHTMLTest() { - val content = - """ - # Foo - ## Bar - - buz - - [biz](https://jetbrains.com) - """.trimIndent() - - assertEquals( - """ -

Foo

-

Bar

- - """.trimIndent(), - markdownToHTML(content) - ) - } - - @Test - fun markdownToPlainTextTest() { - val content = - """ - # Foo - ## Bar - - buz - - [biz](https://jetbrains.com) - """.trimIndent() - - assertEquals( - """ - Foo - Bar - - buz - - biz - """.trimIndent(), - markdownToPlainText(content) - ) - } -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/GetChangelogTaskTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/GetChangelogTaskTest.kt deleted file mode 100644 index d316133a..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/GetChangelogTaskTest.kt +++ /dev/null @@ -1,160 +0,0 @@ -package org.jetbrains.changelog.tasks - -import org.jetbrains.changelog.BaseTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class GetChangelogTaskTest : BaseTest() { - - @BeforeTest - fun localSetUp() { - changelog = - """ - # Changelog - ## [Unreleased] - - bar - ## [1.0.0] - ### Added - - foo - """ - - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - } - """ - - project.evaluate() - } - - @Test - fun `returns change notes for the version specified with extension`() { - val result = runTask("getChangelog", "--quiet") - - assertEquals( - """ - ## [1.0.0] - ### Added - - foo - """.trimIndent(), - result.output.trim() - ) - } - - @Test - fun `returns the Unreleased change notes`() { - val result = runTask("getChangelog", "--quiet", "--unreleased") - - assertEquals( - """ - ## [Unreleased] - - bar - """.trimIndent(), - result.output.trim() - ) - } - - @Test - fun `returns change notes without header for the version specified with extension`() { - val result = runTask("getChangelog", "--quiet", "--no-header") - - assertEquals( - """ - ### Added - - foo - """.trimIndent(), - result.output.trim() - ) - } - - @Test - fun `returns change notes with Pattern set to headerParserRegex`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - headerParserRegex = ~/\d\.\d\.\d/ - } - """ - - project.evaluate() - - runTask("getChangelog") - } - - @Test - fun `returns change notes with String set to headerParserRegex`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - headerParserRegex = "\\d\\.\\d\\.\\d" - } - """ - - project.evaluate() - - runTask("getChangelog") - } - - @Test - fun `fails with Integer set to headerParserRegex`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - headerParserRegex = 123 - } - """ - - project.evaluate() - - runFailingTask("getChangelog") - } - - @Test - fun `throws VersionNotSpecifiedException when changelog extension has no version provided`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - } - """ - - project.evaluate() - - val result = runFailingTask("getChangelog") - - assertTrue( - result.output.contains( - "org.jetbrains.changelog.exceptions.VersionNotSpecifiedException: Version is missing. " + - "Please provide the project version to the `changelog.version` property explicitly." - ) - ) - } - - @Test - fun `task loads from the configuration cache`() { - runTask("getChangelog", "--configuration-cache") - val result = runTask("getChangelog", "--configuration-cache") - - assertTrue(result.output.contains("Reusing configuration cache.")) - } -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTaskTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTaskTest.kt deleted file mode 100644 index 9fb055ef..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTaskTest.kt +++ /dev/null @@ -1,150 +0,0 @@ -package org.jetbrains.changelog.tasks - -import org.jetbrains.changelog.BaseTest -import java.io.File -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -class InitializeChangelogTaskTest : BaseTest() { - - @BeforeTest - fun localSetUp() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - } - """ - - project.evaluate() - } - - @Test - fun `creates new changelog file`() { - runTask("initializeChangelog") - - extension.getAll().apply { - assertEquals(1, keys.size) - assertEquals("[Unreleased]", keys.first()) - assertEquals( - """ - ## [Unreleased] - ### Added - - Example item - - ### Changed - - ### Deprecated - - ### Removed - - ### Fixed - - ### Security - """.trimIndent(), - values.first().withHeader(true).toText() - ) - } - - assertNotNull(extension.getUnreleased()) - } - - @Test - fun `overrides existing changelog file`() { - changelog = - """ - # Changelog - """ - project.evaluate() - - runTask("initializeChangelog") - - assertEquals( - """ - ## [Unreleased] - ### Added - - Example item - - ### Changed - - ### Deprecated - - ### Removed - - ### Fixed - - ### Security - """.trimIndent(), - extension.getUnreleased().withHeader(true).toText() - ) - } - - @Test - fun `creates customized changelog file`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - path = "${File("${project.projectDir}/CHANGES.md").path.replace("\\", "\\\\")}" - itemPrefix = "*" - unreleasedTerm = "Upcoming version" - groups = ["Added", "Removed"] - } - """ - extension.apply { - path = File("${project.projectDir}/CHANGES.md").path - unreleasedTerm = "Upcoming version" - itemPrefix = "*" - } - project.evaluate() - - runTask("initializeChangelog") - - assertEquals( - """ - ## Upcoming version - ### Added - * Example item - - ### Removed - """.trimIndent(), - extension.getUnreleased().withHeader(true).toText() - ) - } - - @Test - fun `doesn't throw VersionNotSpecifiedException when changelog extension has no version provided`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - } - """ - - project.evaluate() - - val result = runTask("initializeChangelog") - - assertFalse(result.output.contains("VersionNotSpecifiedException")) - } - - @Test - fun `task loads from the configuration cache`() { - runTask("initializeChangelog", "--configuration-cache") - val result = runTask("initializeChangelog", "--configuration-cache") - - assertTrue(result.output.contains("Reusing configuration cache.")) - } -} diff --git a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/PatchChangelogTaskTest.kt b/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/PatchChangelogTaskTest.kt deleted file mode 100644 index 403d4ac0..00000000 --- a/gradle-changelog-plugin-main/src/test/kotlin/org/jetbrains/changelog/tasks/PatchChangelogTaskTest.kt +++ /dev/null @@ -1,357 +0,0 @@ -package org.jetbrains.changelog.tasks - -import org.jetbrains.changelog.BaseTest -import org.jetbrains.changelog.exceptions.MissingVersionException -import java.text.SimpleDateFormat -import java.util.Date -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertTrue - -class PatchChangelogTaskTest : BaseTest() { - - @BeforeTest - fun localSetUp() { - changelog = - """ - # Changelog - ## [Unreleased] - ### Added - - foo - """ - - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - - changelog { - version = "1.0.0" - } - """ - } - - @Test - fun `patches Unreleased version to the current one and creates empty Unreleased above`() { - project.evaluate() - runTask("patchChangelog") - - assertEquals( - """ - ### Added - - foo - """.trimIndent(), - extension.get(version).toText() - ) - - assertEquals( - """ - ## [Unreleased] - ### Added - - ### Changed - - ### Deprecated - - ### Removed - - ### Fixed - - ### Security - """.trimIndent(), - extension.getUnreleased().withHeader(true).toText() - ) - } - - @Test - fun `patches Unreleased version to the current one`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - keepUnreleasedSection = false - } - """ - - project.evaluate() - runTask("patchChangelog") - - assertEquals( - """ - ### Added - - foo - """.trimIndent(), - extension.get(version).toText() - ) - - assertFailsWith { - extension.getUnreleased() - } - } - - @Test - fun `applies custom header patcher`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - header = { "Foo ${'$'}version bar" } - } - """ - - project.evaluate() - runTask("patchChangelog") - - assertEquals("## Foo 1.0.0 bar", extension.get(version).getHeader()) - } - - @Test - fun `applies custom header with date`() { - changelog = - """ - # Changelog - All notable changes to this project will be documented in this file. - - ## [Unreleased] - ### Added - - Some other thing added. - - ## [1.0.0] - 2020-07-02 - - ### Added - - Something added. - """ - buildFile = - """ - import java.text.SimpleDateFormat - import java.util.Arrays - import java.util.Date - - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - header = { "[${'$'}version] - ${'$'}{new SimpleDateFormat("yyyy-MM-dd").format(new Date())}" } - } - """ - - project.evaluate() - runTask("patchChangelog") - - val date = SimpleDateFormat("yyyy-MM-dd").format(Date()) - assertEquals("## [1.0.0] - $date", extension.get(version).getHeader()) - } - - @Test - fun `doesn't patch changelog if no change notes provided in Unreleased section`() { - changelog = - """ - # Changelog - ## [Unreleased] - """ - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - patchEmpty = false - } - """ - - project.evaluate() - - runTask("patchChangelog") - - assertFailsWith { - extension.get(version) - } - } - - @Test - fun `create empty groups for the new Unreleased section`() { - project.evaluate() - runTask("patchChangelog") - - assertEquals( - """ - ## [Unreleased] - ### Added - - ### Changed - - ### Deprecated - - ### Removed - - ### Fixed - - ### Security - """.trimIndent(), - extension.getUnreleased().withHeader(true).toText() - ) - } - - @Test - fun `remove empty groups for the new released section`() { - changelog = - """ - # Changelog - ## [Unreleased] - ### Added - - foo - - ### Changed - - ### Deprecated - - ### Removed - - bar - - ### Fixed - - ### Security - """ - - project.evaluate() - runTask("patchChangelog") - - assertEquals( - """ - ## [1.0.0] - ### Added - - foo - - ### Removed - - bar - """.trimIndent(), - extension.get(version).withHeader(true).toText() - ) - } - - @Test - fun `create empty custom groups for the new Unreleased section`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - groups = ["Aaaa", "Bbb"] - } - """ - - project.evaluate() - runTask("patchChangelog") - - assertEquals( - """ - ## [Unreleased] - ### Aaaa - - ### Bbb - """.trimIndent(), - extension.getUnreleased().withHeader(true).toText() - ) - } - - @Test - fun `don't create groups for the new Unreleased section if empty array is provided`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - groups = [] - } - """ - - project.evaluate() - runTask("patchChangelog") - - assertEquals( - """ - ## [Unreleased] - - """.trimIndent(), - extension.getUnreleased().withHeader(true).toText() - ) - } - - @Test - fun `throws MissingUnreleasedSectionException when Unreleased section is not present`() { - val unreleasedTerm = "Not released" - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - version = "1.0.0" - unreleasedTerm = "$unreleasedTerm" - } - """ - changelog = - """ - ## [1.0.0] - """ - - project.evaluate() - val result = runTask("patchChangelog", "--warn") - - assertFailsWith { - extension.getUnreleased() - } - - assertEquals( - ":patchChangelog task requires '$unreleasedTerm' section to be present. " + - "Add '## $unreleasedTerm' section header to your changelog file: ${extension.path}", - result.output.trim() - ) - } - - @Test - fun `throws VersionNotSpecifiedException when changelog extension has no version provided`() { - buildFile = - """ - plugins { - id 'org.jetbrains.changelog' - } - changelog { - } - """ - - project.evaluate() - - val result = runFailingTask("patchChangelog") - - assertTrue( - result.output.contains( - "org.jetbrains.changelog.exceptions.VersionNotSpecifiedException: Version is missing. " + - "Please provide the project version to the `changelog.version` property explicitly." - ) - ) - } - - @Test - fun `task loads from the configuration cache`() { - runTask("patchChangelog", "--configuration-cache") - val result = runTask("patchChangelog", "--configuration-cache") - - assertTrue(result.output.contains("Reusing configuration cache.")) - } -} diff --git a/gradle.properties b/gradle.properties index 16089002..6e279377 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,4 @@ org.gradle.caching=true +kotlin.stdlib.default.dependency=false +# Fixes "Java heap space" errors in CI for Kotlin 1.8.x +kotlin.incremental.useClasspathSnapshot=false diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2a563242..ae04661e 100755 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/library/build.gradle b/library/build.gradle index 481430ce..d4acbe61 100755 --- a/library/build.gradle +++ b/library/build.gradle @@ -1,6 +1,5 @@ plugins { id 'org.jetbrains.kotlin.jvm' version '1.3.72' - id 'maven' id 'maven-publish' id 'signing' } diff --git a/settings.gradle.kts b/settings.gradle.kts index 97f9774c..ac22d36f 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,4 +1,3 @@ plugins { id("com.gradle.enterprise") version("3.6.1") -} -includeBuild("gradle-changelog-plugin-main") \ No newline at end of file +} \ No newline at end of file diff --git a/src/main/kotlin/wu/seal/jsontokotlin/ui/JsonInputDialog.kt b/src/main/kotlin/wu/seal/jsontokotlin/ui/JsonInputDialog.kt index 29022cdd..7b229e9c 100755 --- a/src/main/kotlin/wu/seal/jsontokotlin/ui/JsonInputDialog.kt +++ b/src/main/kotlin/wu/seal/jsontokotlin/ui/JsonInputDialog.kt @@ -57,13 +57,12 @@ class JsonInputDialog(classsName: String, private val project: Project) : Messag } override fun createNorthPanel(): JComponent? { - return jHorizontalLinearLayout { jIcon("/icons/icon_json_input_dialog.png") fixedSpace(5) jVerticalLinearLayout { alignLeftComponent { - jLabel(myMessage, 12f) + jLabel(myMessage ?: "Please input the JSON String and class name to generate Kotlin data class", 12f) } jHorizontalLinearLayout { jLabel("JSON Text: ", 14f) @@ -194,9 +193,11 @@ class JsonInputDialog(classsName: String, private val project: Project) : Messag p.isIndeterminate = true p.setRunnable { try { - val urlContent = URL(url).readText() - runWriteAction { - jsonContentEditor.document.setText(urlContent.replace("\r\n", "\n")) + if (url != null) { + val urlContent = URL(url).readText() + runWriteAction { + jsonContentEditor.document.setText(urlContent.replace("\r\n", "\n")) + } } } finally { p.stop() diff --git a/src/main/kotlin/wu/seal/jsontokotlin/ui/UIDSLV2.kt b/src/main/kotlin/wu/seal/jsontokotlin/ui/UIDSLV2.kt index 0b0de38f..6b01dc6b 100644 --- a/src/main/kotlin/wu/seal/jsontokotlin/ui/UIDSLV2.kt +++ b/src/main/kotlin/wu/seal/jsontokotlin/ui/UIDSLV2.kt @@ -309,7 +309,7 @@ fun Any.jGridLayout(rows: Int, columns: Int, init: JPanel.() -> Unit = {}): JPan * generate a icon component */ fun Any.jIcon(iconPath: String, init: JLabel.() -> Unit = {}): JLabel { - val icon = IconLoader.getIcon(iconPath) + val icon = IconLoader.getIcon(iconPath, javaClass) return JBLabel(icon).also { it.init() checkAddView(this, it) diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml index 0caf4772..ed390e1a 100755 --- a/src/main/resources/META-INF/plugin.xml +++ b/src/main/resources/META-INF/plugin.xml @@ -50,7 +50,7 @@ - +