├── .github
└── workflows
│ └── gradle-publish.yml
├── .gitignore
├── .idea
├── .gitignore
├── gradle.xml
├── kotlinc.xml
├── misc.xml
├── uiDesigner.xml
└── vcs.xml
├── .run
└── Run IDE with Plugin.run.xml
├── README.MD
├── build.gradle.kts
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src
└── main
├── kotlin
└── io
│ └── github
│ └── tt432
│ └── k9tools
│ ├── AnActionExtension.kt
│ ├── GenerateCodecAction.kt
│ └── GenerateStreamCodecAction.kt
└── resources
└── META-INF
├── plugin.xml
└── pluginIcon.svg
/.github/workflows/gradle-publish.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on: [ push, pull_request ]
4 |
5 | permissions:
6 | contents: write # 需要写入权限来创建 release
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 | outputs:
12 | version: ${{ steps.get-version.outputs.version }}
13 | steps:
14 | - uses: actions/checkout@v4
15 |
16 | - name: Setup JDK 17
17 | uses: actions/setup-java@v3
18 | with:
19 | java-version: '17'
20 | distribution: 'temurin'
21 | architecture: x64
22 |
23 | - name: Run chmod to make gradlew executable
24 | run: chmod +x ./gradlew
25 |
26 | - name: Setup Gradle
27 | uses: gradle/gradle-build-action@v2
28 | - name: Run build with Gradle Wrapper
29 | run: ./gradlew build
30 |
31 | - uses: actions/upload-artifact@v4
32 | with:
33 | name: Package
34 | path: build/libs
35 | - name: Get version from Gradle task
36 | id: get-version
37 | run: echo "version=$(./gradlew printVersion --quiet)" >> $GITHUB_OUTPUT
38 | # 需确保任务在 build 之后执行,因为 gradle 任务依赖项目配置
39 | release:
40 | needs: build # 依赖构建任务完成
41 | runs-on: ubuntu-latest
42 | steps:
43 | - name: Download build artifacts
44 | uses: actions/download-artifact@v4
45 | with:
46 | name: Package
47 | path: build/libs
48 |
49 | - name: Create GitHub Release
50 | uses: ncipollo/release-action@v1 # 使用官方推荐的 ncipollo/release-action
51 | with:
52 | # 基础配置
53 | token: ${{ github.token }}
54 | tag: ${{ needs.build.outputs.version }}
55 | body: |
56 | ### 构建信息
57 | - 构建时间:${{ github.run_timestamp }}
58 | - 提交哈希:[${{ github.sha }}](https://github.com/${{ github.repository }}/commit/${{ github.sha }})
59 | artifacts: build/libs/**/**.jar
60 | asset_path: build/libs/${{ env.artifact_name }}
61 | asset_name: ${{ env.artifact_name }}
62 | asset_content_type: application/java-archive
63 | env:
64 | artifact_name: $(ls build/libs)
65 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | .idea/modules.xml
9 | .idea/jarRepositories.xml
10 | .idea/compiler.xml
11 | .idea/libraries/
12 | *.iws
13 | *.iml
14 | *.ipr
15 | out/
16 | !**/src/main/**/out/
17 | !**/src/test/**/out/
18 |
19 | ### Eclipse ###
20 | .apt_generated
21 | .classpath
22 | .factorypath
23 | .project
24 | .settings
25 | .springBeans
26 | .sts4-cache
27 | bin/
28 | !**/src/main/**/bin/
29 | !**/src/test/**/bin/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
41 | ### Mac OS ###
42 | .DS_Store
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
10 | /sonarlint/
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
15 |
16 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/uiDesigner.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | -
6 |
7 |
8 | -
9 |
10 |
11 | -
12 |
13 |
14 | -
15 |
16 |
17 | -
18 |
19 |
20 |
21 |
22 |
23 | -
24 |
25 |
26 |
27 |
28 |
29 | -
30 |
31 |
32 |
33 |
34 |
35 | -
36 |
37 |
38 |
39 |
40 |
41 | -
42 |
43 |
44 |
45 |
46 | -
47 |
48 |
49 |
50 |
51 | -
52 |
53 |
54 |
55 |
56 | -
57 |
58 |
59 |
60 |
61 | -
62 |
63 |
64 |
65 |
66 | -
67 |
68 |
69 |
70 |
71 | -
72 |
73 |
74 | -
75 |
76 |
77 |
78 |
79 | -
80 |
81 |
82 |
83 |
84 | -
85 |
86 |
87 |
88 |
89 | -
90 |
91 |
92 |
93 |
94 | -
95 |
96 |
97 |
98 |
99 | -
100 |
101 |
102 | -
103 |
104 |
105 | -
106 |
107 |
108 | -
109 |
110 |
111 | -
112 |
113 |
114 |
115 |
116 | -
117 |
118 |
119 | -
120 |
121 |
122 |
123 |
124 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.run/Run IDE with Plugin.run.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | true
20 | true
21 | false
22 |
23 |
24 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | ## 功能
2 |
3 | 可以在 Action 中下载 GitHub Workflow 构建的 jar 包。
4 |
5 | ### Generate/GenerateCodecAction
6 |
7 | 可以生成 Minecraft Mod 所需的 Codec。
8 |
9 | - 已测试 Record 类;
10 | - 支持注解 Nullable;
11 | - 支持 Optional, List, Map 类;
12 | - 支持 enum。
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | id("java")
3 | id("org.jetbrains.kotlin.jvm") version "1.9.21"
4 | id("org.jetbrains.intellij") version "1.16.1"
5 | }
6 |
7 | group = "io.github.tt432"
8 | version = "1.2.2-SNAPSHOT"
9 |
10 | repositories {
11 | mavenCentral()
12 | }
13 |
14 | // Configure Gradle IntelliJ Plugin
15 | // Read more: https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html
16 | intellij {
17 | version.set("2024.3")
18 | type.set("IC") // Target IDE Platform
19 |
20 | plugins.set(listOf("java"))
21 | }
22 |
23 | tasks {
24 | // Set the JVM compatibility versions
25 | withType {
26 | sourceCompatibility = "17"
27 | targetCompatibility = "17"
28 | }
29 | withType {
30 | kotlinOptions.jvmTarget = "17"
31 | }
32 |
33 | patchPluginXml {
34 | sinceBuild.set("231")
35 | untilBuild.set("260.*")
36 | }
37 |
38 | signPlugin {
39 | certificateChain.set(System.getenv("CERTIFICATE_CHAIN"))
40 | privateKey.set(System.getenv("PRIVATE_KEY"))
41 | password.set(System.getenv("PRIVATE_KEY_PASSWORD"))
42 | }
43 |
44 | publishPlugin {
45 | token.set(System.getenv("PUBLISH_TOKEN"))
46 | }
47 |
48 | register("printVersion") {
49 | notCompatibleWithConfigurationCache("直接访问 project 对象")
50 |
51 | doLast {
52 | println(version.toString())
53 | }
54 | }
55 | }
56 |
57 | idea {
58 | module {
59 | isDownloadJavadoc = true
60 | isDownloadSources = true
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib
2 | kotlin.stdlib.default.dependency=false
3 | # Enable Gradle Configuration Cache -> https://docs.gradle.org/current/userguide/configuration_cache.html
4 | org.gradle.configuration-cache=true
5 | # Enable Gradle Build Cache -> https://docs.gradle.org/current/userguide/build_cache.html
6 | org.gradle.caching=true
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TT432/k9tools/831ade4a53fb426ece817030ce6cb398533a92a5/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | pluginManagement {
2 | repositories {
3 | mavenCentral()
4 | gradlePluginPortal()
5 | }
6 | }
7 |
8 | rootProject.name = "k9tools"
--------------------------------------------------------------------------------
/src/main/kotlin/io/github/tt432/k9tools/AnActionExtension.kt:
--------------------------------------------------------------------------------
1 | package io.github.tt432.k9tools
2 |
3 | import com.intellij.openapi.actionSystem.AnActionEvent
4 | import com.intellij.openapi.actionSystem.CommonDataKeys
5 | import com.intellij.openapi.editor.Editor
6 | import com.intellij.psi.PsiClass
7 | import com.intellij.psi.PsiField
8 | import com.intellij.psi.PsiMethod
9 | import com.intellij.psi.PsiTypeElement
10 | import com.intellij.psi.util.PsiTreeUtil
11 |
12 | /**
13 | * @author TT432
14 | */
15 |
16 | data class Result(val editor: Editor?, val psiClass: PsiClass?)
17 |
18 | fun getFieldAndGetterMethod(psiClass: PsiClass): Map {
19 | return psiClass.allFields.associateWith { field ->
20 | psiClass.allMethods.firstOrNull { method ->
21 | method.name == field.name || method.name == "get${field.name.replaceFirstChar { it.uppercase() }} }"
22 | }
23 | }
24 | }
25 |
26 | fun getGetterName(className: String, field: PsiField, map: Map): String {
27 | return if (map.containsKey(field) && map[field] != null) "$className::${map[field]?.name}" else "o -> o.${field.name}"
28 | }
29 |
30 | fun getPsiClass(event: AnActionEvent): Result {
31 | val editor = event.getData(CommonDataKeys.EDITOR)
32 | val psiFile = event.getData(CommonDataKeys.PSI_FILE)
33 |
34 | if (editor == null || psiFile == null) return Result(null, null)
35 |
36 | val element = psiFile.findElementAt(editor.caretModel.offset)
37 | val psiClass = PsiTreeUtil.getParentOfType(element, PsiClass::class.java)
38 |
39 | return Result(editor, psiClass)
40 | }
41 |
42 | fun getFieldGeneric(type: PsiTypeElement?): Array {
43 | type ?: return arrayOfNulls(0)
44 | val ref = type.innermostComponentReferenceElement ?: return arrayOfNulls(0)
45 | val parameterList = ref.parameterList ?: return arrayOfNulls(0)
46 | return parameterList.typeParameterElements
47 | }
48 |
49 | fun getTypeName(field: PsiField): String {
50 | return field.type.getCanonicalText(true)
51 | //val typeElement = field.typeElement ?: return ""
52 | //return getTypeName(typeElement)
53 | }
54 |
55 | fun getTypeName(element: PsiTypeElement?): String {
56 | val ref = element!!.innermostComponentReferenceElement ?: return element.text
57 | return ref.qualifiedName
58 | }
--------------------------------------------------------------------------------
/src/main/kotlin/io/github/tt432/k9tools/GenerateCodecAction.kt:
--------------------------------------------------------------------------------
1 | package io.github.tt432.k9tools
2 |
3 | import com.intellij.lang.jvm.JvmModifier
4 | import com.intellij.openapi.actionSystem.AnAction
5 | import com.intellij.openapi.actionSystem.AnActionEvent
6 | import com.intellij.openapi.command.WriteCommandAction
7 | import com.intellij.openapi.project.Project
8 | import com.intellij.psi.PsiClass
9 | import com.intellij.psi.PsiElementFactory
10 | import com.intellij.psi.PsiField
11 | import com.intellij.psi.PsiTypeElement
12 | import com.intellij.psi.codeStyle.JavaCodeStyleManager
13 |
14 | /**
15 | * @author TT432
16 | */
17 | class GenerateCodecAction : AnAction() {
18 | companion object {
19 | private val vanillaCodecClasses = listOf(
20 | "java.lang.Boolean",
21 | "java.lang.Byte",
22 | "java.lang.Short",
23 | "java.lang.Integer",
24 | "java.lang.Long",
25 | "java.lang.Float",
26 | "java.lang.Double",
27 | "java.lang.String",
28 | "java.nio.ByteBuffer",
29 | "java.util.stream.IntStream",
30 | "java.util.stream.LongStream"
31 | )
32 |
33 | private val vanillaKeywordCodec = listOf(
34 | "boolean",
35 | "byte",
36 | "short",
37 | "int",
38 | "long",
39 | "float",
40 | "double"
41 | )
42 |
43 | private val vanillaCodecFieldName = listOf(
44 | "BOOL",
45 | "BYTE",
46 | "SHORT",
47 | "INT",
48 | "LONG",
49 | "FLOAT",
50 | "DOUBLE",
51 | "STRING",
52 | "BYTE_BUFFER",
53 | "INT_STREAM",
54 | "LONG_STREAM"
55 | )
56 |
57 | private const val Codec: String = "com.mojang.serialization.Codec"
58 | private const val StringRepresentable: String = "net.minecraft.util.StringRepresentable"
59 | private const val NotNull: String = "org.jetbrains.annotations.NotNull"
60 | private const val RecordCodecBuilder: String = "com.mojang.serialization.codecs.RecordCodecBuilder"
61 | }
62 |
63 | override fun actionPerformed(event: AnActionEvent) {
64 | val project = event.project ?: return
65 |
66 | WriteCommandAction.runWriteCommandAction(project) {
67 | val (editor, psiClass) = getPsiClass(event);
68 |
69 | if (editor == null || psiClass == null) return@runWriteCommandAction
70 |
71 | if (psiClass.isEnum) {
72 | val factory = PsiElementFactory.getInstance(project)
73 |
74 | val codecField = factory.createFieldFromText(
75 | "public static final $Codec<${psiClass.name}> CODEC = $StringRepresentable.fromEnum(${psiClass.name}::values);",
76 | psiClass
77 | )
78 |
79 | val styleManager = JavaCodeStyleManager.getInstance(project)
80 | psiClass.add(styleManager.shortenClassReferences(codecField))
81 |
82 | val stringRepresentableImpl = factory.createMethodFromText(
83 | " @Override\n" +
84 | " @$NotNull\n" +
85 | " public String getSerializedName() {\n" +
86 | " return name();\n" +
87 | " }",
88 | psiClass
89 | )
90 |
91 | psiClass.add(styleManager.shortenClassReferences(stringRepresentableImpl))
92 |
93 | val offset: Int = psiClass.implementsList?.textOffset ?: (psiClass.nameIdentifier?.textOffset ?: -1)
94 |
95 | if (offset > 0) {
96 | editor.document.insertString(offset, " implements StringRepresentable ")
97 | }
98 | } else {
99 | processRecordOrClass(psiClass, project)
100 | }
101 | }
102 | }
103 |
104 | private fun processRecordOrClass(psiClass: PsiClass, project: Project) {
105 | val fields = psiClass.allFields
106 |
107 | if (fields.any { it.name == "CODEC" }) return
108 |
109 | val fieldsStr = StringBuilder()
110 | val className = psiClass.name!!
111 |
112 | fields.filter { !it.hasModifier(JvmModifier.STATIC) }.forEach {
113 | fieldsStr.append(
114 | " ${getCodecRef(it.typeElement)}.${getFieldOf(it)}.forGetter(${
115 | getGetterName(
116 | className,
117 | it,
118 | getFieldAndGetterMethod(psiClass)
119 | )
120 | }),\n"
121 | )
122 | }
123 |
124 | psiClass.add(
125 | JavaCodeStyleManager.getInstance(project).shortenClassReferences(
126 | PsiElementFactory.getInstance(project).createFieldFromText(
127 | "public static final $Codec<$className> CODEC = $RecordCodecBuilder.create(ins -> ins.group(\n" +
128 | "${fieldsStr.toString().removeSuffix(",\n") + "\n"}).apply(ins, $className::new));",
129 | psiClass
130 | )
131 | )
132 | )
133 | }
134 |
135 | private fun getCodecRef(field: PsiTypeElement?, typeName: String = getTypeName(field)): String {
136 | if (vanillaCodecClasses.contains(typeName)) {
137 | return "$Codec.${vanillaCodecFieldName[vanillaCodecClasses.indexOf(typeName)]}"
138 | } else if (vanillaKeywordCodec.contains(typeName)) {
139 | return "$Codec.${vanillaCodecFieldName[vanillaKeywordCodec.indexOf(typeName)]}"
140 | } else when (typeName) {
141 | "java.util.List" -> {
142 | val fieldGeneric = getFieldGeneric(field)
143 |
144 | if (fieldGeneric.isNotEmpty()) {
145 | return "${getCodecRef(fieldGeneric[0], getTypeName(fieldGeneric[0]))}.listOf()"
146 | }
147 | }
148 |
149 | "java.util.Map" -> {
150 | val fieldGeneric = getFieldGeneric(field)
151 |
152 | if (fieldGeneric.isNotEmpty()) {
153 | return "$Codec.unboundedMap(${
154 | getCodecRef(
155 | fieldGeneric[0],
156 | getTypeName(fieldGeneric[0])
157 | )
158 | }, ${getCodecRef(fieldGeneric[1], getTypeName(fieldGeneric[1]))})"
159 | }
160 | }
161 |
162 | "java.util.Optional" -> {
163 | val fieldGeneric = getFieldGeneric(field)
164 |
165 | if (fieldGeneric.isNotEmpty()) {
166 | return getCodecRef(fieldGeneric[0], getTypeName(fieldGeneric[0]))
167 | }
168 | }
169 |
170 | else -> {
171 | return "$typeName.CODEC"
172 | }
173 | }
174 |
175 | return ""
176 | }
177 |
178 | private fun getFieldOf(field: PsiField): String {
179 | field.annotations.forEach {
180 | val name = it.qualifiedName ?: return@forEach
181 | val split = name.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
182 |
183 | if (split.isNotEmpty() && split[split.size - 1] == "Nullable") {
184 | return "optionalFieldOf(\"${field.name}\", ${getDefaultValue(field)})"
185 | }
186 | }
187 |
188 | return when (getTypeName(field)) {
189 | "java.util.Optional" -> "optionalFieldOf(\"${field.name}\")"
190 | else -> "fieldOf(\"${field.name}\")"
191 | }
192 | }
193 |
194 | private fun getDefaultValue(field: PsiField): String {
195 | val typeName = getTypeName(field)
196 |
197 | return when (vanillaCodecClasses.indexOf(typeName) + vanillaKeywordCodec.indexOf(typeName) + 1) {
198 | 0 -> "false"
199 | 1 -> "(byte) 0"
200 | 2 -> "(short) 0"
201 | 3 -> "0"
202 | 4 -> "0L"
203 | 5 -> "0.0F"
204 | 6 -> "0.0D"
205 | 7 -> "\"\""
206 | else -> "null"
207 | }
208 | }
209 | }
210 |
--------------------------------------------------------------------------------
/src/main/kotlin/io/github/tt432/k9tools/GenerateStreamCodecAction.kt:
--------------------------------------------------------------------------------
1 | @file:Suppress("UnstableApiUsage")
2 |
3 | package io.github.tt432.k9tools
4 |
5 | import com.intellij.lang.jvm.JvmModifier
6 | import com.intellij.openapi.actionSystem.AnAction
7 | import com.intellij.openapi.actionSystem.AnActionEvent
8 | import com.intellij.openapi.command.WriteCommandAction
9 | import com.intellij.openapi.project.Project
10 | import com.intellij.openapi.util.NlsSafe
11 | import com.intellij.psi.*
12 | import com.intellij.psi.codeStyle.JavaCodeStyleManager
13 |
14 | /**
15 | * @author TT432
16 | */
17 | class GenerateStreamCodecAction : AnAction() {
18 | companion object {
19 | private val vanillaCodecClasses = listOf(
20 | "java.lang.Boolean",
21 | "java.lang.Byte",
22 | "java.lang.Short",
23 | "java.lang.Integer",
24 | "java.lang.Long",
25 | "java.lang.Float",
26 | "java.lang.Double",
27 | "java.lang.String",
28 | "net.minecraft.nbt.Tag",
29 | "net.minecraft.nbt.CompoundTag",
30 | "org.joml.Vector3f",
31 | "org.joml.Quaternionf",
32 | "com.mojang.authlib.properties.PropertyMap",
33 | "com.mojang.authlib.GameProfile",
34 | "byte[]"
35 | )
36 |
37 | private val vanillaCodecFieldName = listOf(
38 | "BOOL",
39 | "BYTE",
40 | "SHORT",
41 | "VAR_INT",
42 | "VAR_LONG",
43 | "FLOAT",
44 | "DOUBLE",
45 | "STRING_UTF8",
46 | "TAG",
47 | "COMPOUND_TAG",
48 | "VECTOR3F",
49 | "QUATERNIONF",
50 | "GAME_PROFILE_PROPERTIES",
51 | "GAME_PROFILE",
52 | "BYTE_ARRAY"
53 | )
54 |
55 | private val vanillaKeywordCodec = listOf(
56 | "boolean",
57 | "byte",
58 | "short",
59 | "int",
60 | "long",
61 | "float",
62 | "double"
63 | )
64 |
65 | const val ByteBufCodecsName: String = "net.minecraft.network.codec.ByteBufCodecs"
66 | const val StreamCodec = "net.minecraft.network.codec.StreamCodec"
67 | }
68 |
69 | private fun getCodecRef(field: PsiTypeElement?, typeName: String = getTypeName(field)): String {
70 | if (vanillaCodecClasses.contains(typeName)) {
71 | return "$ByteBufCodecsName.${vanillaCodecFieldName[vanillaCodecClasses.indexOf(typeName)]}"
72 | } else if (vanillaKeywordCodec.contains(typeName)) {
73 | return "$ByteBufCodecsName.${vanillaCodecFieldName[vanillaKeywordCodec.indexOf(typeName)]}"
74 | } else when (typeName) {
75 | "java.util.List" -> {
76 | val fieldGeneric = getFieldGeneric(field)
77 |
78 | if (fieldGeneric.isNotEmpty()) {
79 | return "$ByteBufCodecsName.collection(java.util.ArrayList::new, ${
80 | getCodecRef(
81 | fieldGeneric[0],
82 | getTypeName(fieldGeneric[0])
83 | )
84 | })"
85 | }
86 | }
87 |
88 | "java.util.Map" -> {
89 | val fieldGeneric = getFieldGeneric(field)
90 |
91 | if (fieldGeneric.isNotEmpty()) {
92 | return "$ByteBufCodecsName.map(java.util.HashMap::new, ${
93 | getCodecRef(
94 | fieldGeneric[0],
95 | getTypeName(fieldGeneric[0])
96 | )
97 | }, ${getCodecRef(fieldGeneric[1], getTypeName(fieldGeneric[1]))})"
98 | }
99 | }
100 |
101 | "java.util.Optional" -> {
102 | val fieldGeneric = getFieldGeneric(field)
103 |
104 | if (fieldGeneric.isNotEmpty()) {
105 | return "$ByteBufCodecsName.optional(${getCodecRef(fieldGeneric[0], getTypeName(fieldGeneric[0]))})"
106 | }
107 | }
108 |
109 | else -> {
110 | return "$typeName.STREAM_CODEC"
111 | }
112 | }
113 |
114 | return ""
115 | }
116 |
117 | override fun actionPerformed(event: AnActionEvent) {
118 | val project = event.project ?: return
119 |
120 | WriteCommandAction.runWriteCommandAction(project) {
121 | val (editor, psiClass) = getPsiClass(event)
122 |
123 | if (editor == null || psiClass == null) return@runWriteCommandAction
124 |
125 | val className = psiClass.name!!
126 |
127 | var fields = psiClass.allFields
128 |
129 | if (fields.any { it.name == "STREAM_CODEC" }) return@runWriteCommandAction
130 |
131 | fields = fields.filter { !it.hasModifier(JvmModifier.STATIC) }.toTypedArray()
132 |
133 | if (fields.size <= 6) { serializeWithinSixFields(fields, className, psiClass, project) }
134 | else serializeMoreThanSixFields(fields, className, psiClass, project)
135 | }
136 | }
137 |
138 | private fun serializeWithinSixFields(
139 | fields: Array,
140 | className: @NlsSafe String,
141 | psiClass: PsiClass,
142 | project: Project
143 | ) {
144 | val fieldsStr = StringBuilder()
145 |
146 | fields.forEach {
147 | fieldsStr.append(
148 | " ${getCodecRef(it.typeElement)},\n" +
149 | " ${getGetterName(className, it, getFieldAndGetterMethod(psiClass))},\n"
150 | )
151 | }
152 |
153 | psiClass.add(
154 | JavaCodeStyleManager.getInstance(project).shortenClassReferences(
155 | PsiElementFactory.getInstance(project).createFieldFromText(
156 | "public static final $StreamCodec STREAM_CODEC = $StreamCodec.composite(\n" +
157 | "$fieldsStr" +
158 | " $className::new\n" +
159 | ");",
160 | psiClass
161 | )
162 | )
163 | )
164 | }
165 |
166 | private fun serializeMoreThanSixFields(
167 | fields: Array,
168 | className: @NlsSafe String,
169 | psiClass: PsiClass,
170 | project: Project
171 | ) {
172 | val decodeStr = StringBuilder()
173 | val decodeConstructStrBuilder = StringBuilder()
174 | val encodeStr = StringBuilder()
175 |
176 | fields.forEach {
177 | decodeStr.append(
178 | " ${getTypeName(it)} ${it.name} = ${getCodecRef(it.typeElement)}.decode(buf);\n"
179 | )
180 | decodeConstructStrBuilder.append(
181 | "${it.name}, "
182 | )
183 | encodeStr.append(
184 | " ${getCodecRef(it.typeElement)}.encode(buf, ${getDirectGetterName(it, getFieldAndGetterMethod(psiClass))});\n"
185 | )
186 | }
187 |
188 | val decodeConstructStr = decodeConstructStrBuilder.substring(0, decodeConstructStrBuilder.length - 2)
189 |
190 | psiClass.add(
191 | JavaCodeStyleManager.getInstance(project).shortenClassReferences(
192 | PsiElementFactory.getInstance(project).createFieldFromText(
193 | "public static final $StreamCodec STREAM_CODEC = new $StreamCodec<>() {\n" +
194 | " @java.lang.Override\n" +
195 | " public $className decode(io.netty.buffer.ByteBuf buf) {\n" +
196 | "$decodeStr" +
197 | " return new $className($decodeConstructStr);\n" +
198 | " }\n\n" +
199 | " @java.lang.Override\n" +
200 | " public void encode(io.netty.buffer.ByteBuf buf, $className value) {\n" +
201 | "$encodeStr" +
202 | " }\n" +
203 | "};",
204 | psiClass
205 | )
206 | )
207 | )
208 | }
209 |
210 | private fun getDirectGetterName(field: PsiField, map: Map): String {
211 | return "value." + if (map.containsKey(field) && map[field] != null) "${map[field]?.name}()" else field.name
212 | }
213 | }
214 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | io.github.tt432.k9tools
5 |
6 |
8 | K9tools
9 |
10 |
11 | TT432
12 |
13 |
16 |
21 |
22 |
24 | com.intellij.modules.platform
25 | com.intellij.java
26 |
27 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/pluginIcon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------