diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..7c32d5f --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.jar filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 0000000..fa128c2 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,20 @@ +name: CI + +on: + push: + branches: [ main ] + +jobs: + build: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + name: Set up JDK 17 + with: + java-version: 17 + distribution: adopt-hotspot + - name: Build plugin + run: | + chmod +x gradlew + ./gradlew check buildPlugin --info diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ee1e9ea --- /dev/null +++ b/.gitignore @@ -0,0 +1,107 @@ +# Created by .ignore support plugin (hsz.mobi) +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +**/target/* + + +### IntelliJ +# User-specific stuff +**/.idea/workspace.xml +**/.idea/modules.xml +**/.idea/tasks.xml +**/.idea/misc.xml +**/.idea/sonarlint-state.xml +**/.idea/compiler.xml +**/.idea/jarRepositories.xml +**/.idea/usage.statistics.xml +**/.idea/dictionaries +**/.idea/shelf +**/.idea/sonarlint +**/.idea/sqldialects.xml +**/.idea/git_toolbox_prj.xml + + +# Generated files +**/.idea/contentModel.xml + +# Sensitive or high-churn files +**/.idea/artifacts/ +**/.idea/dataSources/ +**/.idea/dataSources.ids +**/.idea/dataSources.xml +**/.idea/dataSources.local.xml +**/.idea/encodings.xml +**/.idea/sqlDataSources.xml +**/.idea/dynamic.xml +**/.idea/uiDesigner.xml +**/.idea/dbnavigator.xml + +# Gradle +**/.idea/gradle.xml +**/.idea/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +.idea/modules.xml +.idea/modules +*.ipr +# project files +**.iml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +### macOS template +# General +.DS_Store +.AppleDouble +.LSOverride + +### Gradle template +.gradle +**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties +/.idea/jpa-buddy.xml diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..7001fd8 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..8705ae7 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,8 @@ +### Building the plugin +Use gradle tasks, e.g. `./gradlew clean check buildPlugin`, where `clean` and `check` are built-in gradle tasks, +and `buildPlugin` is provided by [gradle plugin for building IJ plugins](https://github.com/JetBrains/gradle-intellij-plugin). + +### Running the plugin +Use gradle `runIde` task provided by [gradle IJ plugin](https://github.com/JetBrains/gradle-intellij-plugin). +It will download IDE jars for the specified version and will start a new instance of IDE with the plugin. +To specify IDE version use `IJ_VERSION` env variable or modify `build.gradle` file. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..a0905e6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,288 @@ +plugins { + id 'org.jetbrains.intellij' version '1.17.3' + id 'java' + id "org.jsonschema2pojo" version "1.2.1" +} + +allprojects { + + group 'de.gebit.intellij.autoconfig' + + ext { + lombokVersion = '1.18.24' + commonsIoVersion = '2.12.0' + intellijPluginVersion = '1.17.3' + jakartaJwsVersion = '2.1.0' + javaxPersistenceVersion = '2.2' + jUnitJupiterVersion = '5.10.1' + intellijType = 'IC' // IC: Community Edition, IU: Ultimate Edition. + intellijVersion = '2024.1' // https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html + intellijSinceBuild = '231.1' + } +} + +repositories { + mavenCentral() +} + +// Must match Groovy version bundled with IntelliJ (see IJ/Contents/lib/groovy.jar/META-INF/org.codehaus.groovy.runtime.ExtensionModule) +ext.groovyVersion = "3.0.19" + +intellij { + // Available IDE versions: https://www.jetbrains.com/intellij-repository/releases and https://www.jetbrains.com/intellij-repository/snapshots + version = System.getenv().getOrDefault("IJ_VERSION", + "2024.1" + ) + pluginName = "AutoConfigPlugin" + downloadSources = true + updateSinceUntilBuild = false + instrumentCode = false + plugins = [ + "java", + "Git4Idea", + "junit", + "org.jetbrains.plugins.yaml", + "org.jetbrains.idea.maven" + ] +} +buildSearchableOptions.enabled = false // Disable because it takes a long time and the plugin doesn't need it +runIde.jbrVariant.set("jcef") // JVM with Java Chromium Embedded Framework because why not (see also https://github.com/JetBrains/gradle-intellij-plugin#running-dsl) + +dependencies { + // Required if generating JSR-303 annotations + implementation 'javax.validation:validation-api:1.1.0.CR2' + implementation 'jakarta.validation:jakarta.validation-api:3.0.0' + implementation 'com.google.code.findbugs:jsr305:3.0.2' + compileOnly("org.projectlombok:lombok:${lombokVersion}") + testCompileOnly("org.projectlombok:lombok:${lombokVersion}") + annotationProcessor("org.projectlombok:lombok:${lombokVersion}") + testAnnotationProcessor("org.projectlombok:lombok:${lombokVersion}") +} + +jsonSchema2Pojo { + + // Location of the JSON Schema file(s). This may refer to a single file or a directory of files. + source = files("${sourceSets.main.output.resourcesDir}/schema") + + // Target directory for generated Java source files. The plugin will add this directory to the + // java source set so the compiler will find and compile the newly generated source files. + targetDirectory = file("${project.buildDir}/generated-sources/js2p") + + // Package name used for generated Java classes (for types where a fully qualified name has not + // been supplied in the schema using the 'javaType' property). + targetPackage = 'de.gebit.intellij.autoconfig.model' + + // Whether to allow 'additional' properties to be supported in classes by adding a map to + // hold these. This is true by default, meaning that the schema rule 'additionalProperties' + // controls whether the map is added. Set this to false to globally disable additional properties. + includeAdditionalProperties = false + + // Whether to include a javax.annotation.Generated (Java 8 and lower) or + // javax.annotation.processing.Generated (Java 9+) in on generated types (default true). + // See also: targetVersion. + includeGeneratedAnnotation = true + + // Whether to generate builder-style methods of the form withXxx(value) (that return this), + // alongside the standard, void-return setters. + generateBuilders = false + + // If set to true, then the gang of four builder pattern will be used to generate builders on + // generated classes. Note: This property works in collaboration with generateBuilders. + // If generateBuilders is false then this property will not do anything. + useInnerClassBuilders = false + + // Whether to use primitives (long, double, boolean) instead of wrapper types where possible + // when generating bean properties (has the side-effect of making those properties non-null). + usePrimitives = false + + // The characters that should be considered as word delimiters when creating Java Bean property + // names from JSON property names. If blank or not set, JSON properties will be considered to + // contain a single word when creating Java Bean property names. + propertyWordDelimiters = [] as char[] + + // Whether to use the java type long (or Long) instead of int (or Integer) when representing the + // JSON Schema type 'integer'. + useLongIntegers = false + + // Whether to use the java type BigInteger when representing the JSON Schema type 'integer'. Note + // that this configuration overrides useLongIntegers + useBigIntegers = false + + // Whether to use the java type double (or Double) instead of float (or Float) when representing + // the JSON Schema type 'number'. + useDoubleNumbers = true + + // Whether to use the java type BigDecimal when representing the JSON Schema type 'number'. Note + // that this configuration overrides useDoubleNumbers + useBigDecimals = false + + // Whether to include hashCode and equals methods in generated Java types. + includeHashcodeAndEquals = true + + // Whether to include a toString method in generated Java types. + includeToString = true + + // The style of annotations to use in the generated Java types. Supported values: + // - jackson (alias of jackson2) + // - jackson2 (apply annotations from the Jackson 2.x library) + // - jsonb (apply annotations from the JSON-B 1 library) + // - jsonb2 (apply annotations from the JSON-B 2 library) + // - gson (apply annotations from the Gson library) + // - moshi1 (apply annotations from the Moshi 1.x library) + // - none (apply no annotations at all) + annotationStyle = 'jackson' + + // Whether to include JSR-303/349 annotations (for schema rules like minimum, maximum, etc) in + // generated Java types. Schema rules and the annotation they produce: + // - maximum = @DecimalMax + // - minimum = @DecimalMin + // - minItems,maxItems = @Size + // - minLength,maxLength = @Size + // - pattern = @Pattern + // - required = @NotNull + // Any Java fields which are an object or array of objects will be annotated with @Valid to + // support validation of an entire document tree. + includeJsr303Annotations = false + + // Whether to include JSR-305 annotations, for schema rules like Nullable, NonNull, etc + includeJsr305Annotations = true + + // The Level of inclusion to set in the generated Java types (for Jackson serializers) +// inclusionLevel = InclusionLevel.NON_NULL + + // Whether to use the 'title' property of the schema to decide the class name (if not + // set to true, the filename and property names are used). + useTitleAsClassname = true + + // The type of input documents that will be read. Supported values: + // - jsonschema (schema documents, containing formal rules that describe the structure of JSON data) + // - json (documents that represent an example of the kind of JSON data that the generated Java types + // will be mapped to) + // - yamlschema (JSON schema documents, represented as YAML) + // - yaml (documents that represent an example of the kind of YAML (or JSON) data that the generated Java types + // will be mapped to) + sourceType = 'jsonschema' + + // Whether to empty the target directory before generation occurs, to clear out all source files + // that have been generated previously. Be warned, when activated this option + // will cause jsonschema2pojo to indiscriminately delete the entire contents of the target + // directory (all files and folders) before it begins generating sources. + removeOldOutput = false + + // The character encoding that should be used when writing the generated Java source files + outputEncoding = 'UTF-8' + + // Whether to use {@link org.joda.time.DateTime} instead of {@link java.util.Date} when adding + // date type fields to generated Java types. + useJodaDates = false + + // Whether to add JsonFormat annotations when using Jackson 2 that cause format "date", "time", and "date-time" + // fields to be formatted as yyyy-MM-dd, HH:mm:ss.SSS and yyyy-MM-dd'T'HH:mm:ss.SSSZ respectively. To customize these + // patterns, use customDatePattern, customTimePattern, and customDateTimePattern config options or add these inside a + // schema to affect an individual field + formatDateTimes = true + formatDates = true + formatTimes = true + + // Whether to initialize Set and List fields as empty collections, or leave them as null. + initializeCollections = true + + // Whether to add a prefix to generated classes. + classNamePrefix = "" + + // Whether to add a suffix to generated classes. + classNameSuffix = "" + + // An array of strings that should be considered as file extensions and therefore not included in class names. + fileExtensions = [] as String[] + + // Whether to generate constructors or not. + includeConstructors = false + + // Whether to include java.beans.ConstructorProperties on generated constructors + includeConstructorPropertiesAnnotation = false + + // Whether to include only 'required' fields in generated constructors + constructorsRequiredPropertiesOnly = false + + // Whether to *add* a constructor that includes only 'required' fields, alongside other constructors. + // This property is irrelevant if constructorsRequiredPropertiesOnly = true + includeRequiredPropertiesConstructor = false + + // Whether to *add* a constructor that includes all fields, alongside other constructors. + // This property is irrelevant if constructorsRequiredPropertiesOnly = true + includeAllPropertiesConstructor = false + + // Include a constructor with the class itself as a parameter, with the expectation that all properties + // from the originating class will assigned to the new class. + // This property is irrelevant if constructorsRequiredPropertiesOnly = true + includeCopyConstructor = false + + // Whether to make the generated types Parcelable for Android + parcelable = false + + // Whether to make the generated types Serializable + serializable = false + + // Whether to include getters or to omit these accessor methods and create public fields instead. + includeGetters = true + + // Whether to include setters or to omit these accessor methods and create public fields instead. + includeSetters = true + + // Whether to include dynamic getters, setters, and builders or to omit these methods. + includeDynamicAccessors = false + + // Whether to include dynamic getters or to omit these methods. + includeDynamicGetters = false + + // Whether to include dynamic setters or to omit these methods. + includeDynamicSetters = false + + // Whether to include dynamic builders or to omit these methods. + includeDynamicBuilders = false + + // Which characters to use as 'path fragment delimiters' when trying to resolve a ref + refFragmentPathDelimiters = "#/." + + // Whether to include json type information; often required to support polymorphic type handling. + // By default the type information is stored in the @class property, this can be overridden using + // deserializationClassProperty in the schema + includeJsonTypeInfoAnnotation = false + + // Whether to use java.util.Optional for getters on properties that are not required + useOptionalForGetters = false + + // properties to exclude from generated toString + toStringExcludes = ["someProperty"] + + // What Java version to target with generated source code (1.6, 1.8, 9, 11, etc). + // By default, the version will be taken from the Gradle Java plugin's 'sourceCompatibility', + // which (if unset) itself defaults to the current JVM version + targetVersion = "17" + + // A sort order to use when reading input files, one of SourceSortOrder.OS (allow the OS to decide sort + // order), SourceSortOrder.FILES_FIRST or SourceSortOrder.SUBDIRS_FIRST +// sourceSortOrder = SourceSortOrder.OS + + // Whether to use annotations from jakarta.validation package instead of javax.validation package + // when adding JSR-303 annotations to generated Java types + useJakartaValidation = false +} + +sourceSets { + // Keep Groovy and Kotlin API source code in separate source sets, otherwise + // compilation fails because of inter-dependencies between Kotlin and Groovy files which confuse compiler, + // even though overall dependencies are unidirectional: pluginApiKotlin -> pluginApiGroovy -> main. + + main { + java { srcDir "src/main" } + resources { srcDir "resources" } + } +} + +compileJava { + sourceCompatibility = "17" + targetCompatibility = "17" +} + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..e5d9a95 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +kotlin.stdlib.default.dependency = false diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..c4868df --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33ad4583fd7ee156f533778736fa1b4940bd83b433934d1cc4e9f608e99a6a89 +size 59536 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..17655d0 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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 "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@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/settings.gradle b/settings.gradle new file mode 100644 index 0000000..139597f --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ + + diff --git a/src/main/java/de/gebit/intellij/autoconfig/AutoconfigStartup.java b/src/main/java/de/gebit/intellij/autoconfig/AutoconfigStartup.java new file mode 100644 index 0000000..6360835 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/AutoconfigStartup.java @@ -0,0 +1,58 @@ +// +// AutoconfigStartup.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig; + +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.extensions.ExtensionPointName; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.startup.ProjectActivity; +import kotlin.Unit; +import kotlin.coroutines.Continuation; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static de.gebit.intellij.autoconfig.util.Notifications.showInfo; + +/** + * Entry point for the opening of a project. The yaml configuration file is read here, the resulting configuration options object is passed to the CommonConfigurationHandler. + * At the end, a message is composed, displaying a list of all updated configuration options. + */ +public class AutoconfigStartup implements ProjectActivity { + private static final com.intellij.openapi.diagnostic.Logger LOG = Logger.getInstance(AutoconfigStartup.class); + + public static final ExtensionPointName> + EP_NAME = ExtensionPointName.create("de.gebit.intellij.autoconfig.configurationUpdater"); + + @Nullable + @Override + public Object execute(@NotNull Project project, @NotNull Continuation continuation) { + ConfigurationLoaderService projectService = project.getService(ConfigurationLoaderService.class); + if (projectService == null) { + return null; + } + + List changedConfigs = new ArrayList<>(); + + for (UpdateHandler updateHandler : EP_NAME.getExtensionList()) { + Optional extensionConfiguration = projectService.getConfiguration(updateHandler.getConfigurationClass(), updateHandler.getFileName()); + extensionConfiguration.ifPresentOrElse(config -> changedConfigs.addAll(updateHandler.updateConfiguration(config, project)), () -> LOG.info("No configuration for " + updateHandler.getUpdaterName() + " found.")); + } + + if (!changedConfigs.isEmpty()) { + String notification = String.join(", ", changedConfigs); + showInfo("New project configurations applied: " + notification, project); + } + + return changedConfigs; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/ConfigurationLoaderService.java b/src/main/java/de/gebit/intellij/autoconfig/ConfigurationLoaderService.java new file mode 100644 index 0000000..038c2c6 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/ConfigurationLoaderService.java @@ -0,0 +1,69 @@ +// +// ConfigurationLoaderService.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; +import com.intellij.openapi.application.ReadAction; +import com.intellij.openapi.components.Service; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFile; +import de.gebit.intellij.autoconfig.util.Notifications; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +/** + * Service used to load yaml files from project directory. + */ +@Service(Service.Level.PROJECT) +public final class ConfigurationLoaderService { + private final Project project; + + private final Map configurationOptions = new HashMap<>(); + + ConfigurationLoaderService(Project project) { + this.project = project; + } + + public Optional getConfiguration(Class objectClass, String configFileName) { + T configObject = null; + Object o = configurationOptions.get(objectClass.getCanonicalName()); + if (o != null && o.getClass().isAssignableFrom(objectClass)) { + configObject = (T) o; + } + if (configObject != null) { + return Optional.of(configObject); + } + var projectFile = project.getProjectFile(); + if (projectFile == null) { + return Optional.empty(); + } + VirtualFile autoconfigDirectory = projectFile.getParent().findChild("autoconfig"); + if (autoconfigDirectory == null) { + return Optional.empty(); + } + var configYaml = autoconfigDirectory.findChild(configFileName); + if (configYaml == null) { + return Optional.empty(); + } + try { + configObject = ReadAction.compute(() -> { + final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); + return objectMapper.readValue(configYaml.getInputStream(), objectClass); + }); + configurationOptions.put(objectClass.getCanonicalName(), configObject); + } catch (IOException e) { + Notifications.showInfo("Unable to parse configuration yaml: " + configFileName, project); + } + return Optional.ofNullable(configObject); + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/FormatOnSaveOptionsDefaultsProvider.java b/src/main/java/de/gebit/intellij/autoconfig/FormatOnSaveOptionsDefaultsProvider.java new file mode 100644 index 0000000..f6ac02c --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/FormatOnSaveOptionsDefaultsProvider.java @@ -0,0 +1,56 @@ +// +// FormatOnSaveOptionsDefaultsProvider.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig; + +import com.intellij.codeInsight.actions.onSave.FormatOnSaveOptionsBase; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.fileTypes.FileTypeRegistry; +import com.intellij.openapi.fileTypes.UnknownFileType; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * Supplier for default file formats that should be formatted or used for optimization of imports. + */ +public class FormatOnSaveOptionsDefaultsProvider implements FormatOnSaveOptionsBase.DefaultsProvider { + + /** + * List of file types used as defaults. + */ + private static Collection fileTypes; + + @Override + public @NotNull Collection<@NotNull FileType> getFileTypesFormattedOnSaveByDefault() { + return getFileTypes(); + } + + @Override + public @NotNull Collection<@NotNull FileType> getFileTypesWithOptimizeImportsOnSaveByDefault() { + return getFileTypes(); + } + + @NotNull + private static Collection getFileTypes() { + if (fileTypes != null) { + return fileTypes; + } + + fileTypes = new ArrayList<>(); + + for (String type : new String[]{"java", "dart", "groovy", "kt"}) { + FileType fileTypeByExtension = FileTypeRegistry.getInstance().getFileTypeByExtension(type); + if (!(fileTypeByExtension instanceof UnknownFileType)) { + fileTypes.add(fileTypeByExtension); + } + } + return fileTypes; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/UpdateHandler.java b/src/main/java/de/gebit/intellij/autoconfig/UpdateHandler.java new file mode 100644 index 0000000..9316780 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/UpdateHandler.java @@ -0,0 +1,51 @@ +// +// UpdateHandler.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig; + +import com.intellij.openapi.project.Project; + +import java.util.List; + +/** + * Extension point for used to supply configuration update handlers. + */ +public interface UpdateHandler { + + /** + * Provide the file name that is expected to contain the extensions' configuration. + * @return the file name that is expected to contain the extensions' configuration + */ + String getFileName(); + + /** + * The json schema containing/providing the information on how to write the configuration file. + * @return json schema containing/providing the information on how to write the configuration file + */ + String getJsonSchema(); + + /** + * The updater name is used for logging purposes and as a name for the json schema displayed in IntelliJ status bar. + * @return the name of this updater + */ + String getUpdaterName(); + + /** + * The configuration object class used to read/deserialize the configuration file. + * @return configuration object class used to read/deserialize the configuration file + */ + Class getConfigurationClass(); + + /** + * The implementation of the configuration updates. A configuration update object is supplied containing the information gathered from the yaml file. + * @param configuration the configuration object used for this update handler + * @param project the project that will receive the configuration updates in case they can be applied + * @return list of configuration parts that have been updated + */ + List updateConfiguration(T configuration, Project project); +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/handlers/AbstractHandler.java b/src/main/java/de/gebit/intellij/autoconfig/handlers/AbstractHandler.java new file mode 100644 index 0000000..ee56c55 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/handlers/AbstractHandler.java @@ -0,0 +1,28 @@ +// +// AbstractHandler.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.handlers; + +import java.util.List; +import java.util.function.Consumer; + +/** + * Base handler for configuration updater classes. + */ +public abstract class AbstractHandler { + + protected void applySetting(T newValue, T originalValue, Consumer setter, List changedConfigs, String description) { + if (newValue != null && !newValue.equals("") && !newValue.equals(originalValue)) { + setter.accept(newValue); + if (originalValue != null) { + // originalValue == null means always setting the newValue + changedConfigs.add(description); + } + } + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/handlers/CommonConfigurationHandler.java b/src/main/java/de/gebit/intellij/autoconfig/handlers/CommonConfigurationHandler.java new file mode 100644 index 0000000..5690dba --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/handlers/CommonConfigurationHandler.java @@ -0,0 +1,110 @@ +// +// CommonConfigurationHandler.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.handlers; + +import com.intellij.codeInsight.actions.onSave.FormatOnSaveOptions; +import com.intellij.codeInsight.actions.onSave.OptimizeImportsOnSaveOptions; +import com.intellij.externalDependencies.ExternalDependenciesManager; +import com.intellij.externalDependencies.impl.ExternalDependenciesManagerImpl; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.updateSettings.impl.UpdateSettings; +import com.intellij.openapi.vcs.IssueNavigationConfiguration; +import com.intellij.openapi.vcs.IssueNavigationLink; +import de.gebit.intellij.autoconfig.UpdateHandler; +import de.gebit.intellij.autoconfig.model.GeneralConfiguration; +import de.gebit.intellij.autoconfig.model.IssueNavigation; +import de.gebit.intellij.autoconfig.model.OnSave; +import org.jetbrains.annotations.NonNls; + +import java.util.ArrayList; +import java.util.List; + +/** + * The main class used to update the IntelliJ configuration. All supported options are checked, updated and logged in a list of changed configs. + */ +public class CommonConfigurationHandler extends AbstractHandler implements UpdateHandler { + private static final @NonNls String CONFIG_SCHEMA_JSON = "/schema/config.schema.json"; + + public static final @NonNls String CONFIG_FILE_NAME = "autoconfig.yaml"; + + @Override + public String getFileName() { + return CONFIG_FILE_NAME; + } + + @Override + public String getJsonSchema() { + return CONFIG_SCHEMA_JSON; + } + + @Override + public String getUpdaterName() { + return "Common configuration updater"; + } + + @Override + public Class getConfigurationClass() { + return GeneralConfiguration.class; + } + + @Override + public List updateConfiguration(GeneralConfiguration options, Project project) { + List updatedConfigs = new ArrayList<>(); + applyIssueNavigationConfiguration(options.getIssueNavigation(), project, updatedConfigs); + applyPluginHosts(options.getPluginRepositories(), project, updatedConfigs); + applyOnSaveOptions(options.getOnSave(), project, updatedConfigs); + return updatedConfigs; + } + + private void applyIssueNavigationConfiguration(List issueNavigationConfig, Project aProject, List updatedConfigs) { + if (issueNavigationConfig != null) { + var issueNavigationSettings = IssueNavigationConfiguration.getInstance(aProject); + var newSettingsList = new ArrayList(); + + for (IssueNavigation navigationConfig : issueNavigationConfig) { + newSettingsList.add(new IssueNavigationLink(navigationConfig.getExpression(), navigationConfig.getUrl())); + } + applySetting(newSettingsList, issueNavigationSettings.getLinks(), issueNavigationSettings::setLinks, updatedConfigs, "Issue navigation links"); + } + } + + private void applyOnSaveOptions(OnSave options, Project project, List updatedConfigs) { + if (options != null) { + FormatOnSaveOptions instance = FormatOnSaveOptions.getInstance(project); + applySetting(options.getFormat(), instance.isRunOnSaveEnabled(), instance::setRunOnSaveEnabled, updatedConfigs, "Code format on save"); + OptimizeImportsOnSaveOptions imports = OptimizeImportsOnSaveOptions.getInstance(project); + applySetting(options.getOptimizeImports(), imports.isRunOnSaveEnabled(), imports::setRunOnSaveEnabled, updatedConfigs, "Optimize imports on save"); + } + } + + void applyPluginHosts(List pluginHosts, Project aProject, List changedConfigs) { + if (pluginHosts != null) { + var updateSettings = UpdateSettings.getInstance(); + var storedPluginHosts = updateSettings.getStoredPluginHosts(); + var newHostAdded = false; + for (String pluginHost : pluginHosts) { + if (!storedPluginHosts.contains(pluginHost)) { + storedPluginHosts.add(pluginHost); + newHostAdded = true; + } + } + if (newHostAdded) { + changedConfigs.add("Plugin repositories"); + } + if (newHostAdded) { + var dependenciesManager = ExternalDependenciesManager.getInstance(aProject); + var dependenciesManagerImpl = (ExternalDependenciesManagerImpl) dependenciesManager; + // very sketchy but works for now + var state = dependenciesManagerImpl.getState(); + dependenciesManagerImpl.loadState(new ExternalDependenciesManagerImpl.ExternalDependenciesState()); + dependenciesManagerImpl.loadState(state); + } + } + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/handlers/git/GitHandler.java b/src/main/java/de/gebit/intellij/autoconfig/handlers/git/GitHandler.java new file mode 100644 index 0000000..0ffdb24 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/handlers/git/GitHandler.java @@ -0,0 +1,64 @@ +// +// GitHandler.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.handlers.git; + +import com.intellij.openapi.project.Project; +import de.gebit.intellij.autoconfig.UpdateHandler; +import de.gebit.intellij.autoconfig.handlers.AbstractHandler; +import de.gebit.intellij.autoconfig.model.GitConfiguration; +import git4idea.config.GitVcsSettings; +import git4idea.config.UpdateMethod; +import org.jetbrains.annotations.NonNls; + +import java.util.ArrayList; +import java.util.List; + +/** + * Handler implementing git configuration settings updates. + */ +public class GitHandler extends AbstractHandler implements UpdateHandler { + private static final @NonNls String CONFIG_SCHEMA_JSON = "/schema/git.schema.json"; + + public static final @NonNls String CONFIG_FILE_NAME = "autoconfigGit.yaml"; + + @Override + public String getFileName() { + return CONFIG_FILE_NAME; + } + + @Override + public String getJsonSchema() { + return CONFIG_SCHEMA_JSON; + } + + @Override + public String getUpdaterName() { + return "Git configuration updater"; + } + + @Override + public Class getConfigurationClass() { + return GitConfiguration.class; + } + + @Override + public List updateConfiguration(GitConfiguration configuration, Project project) { + List changedConfigs = new ArrayList<>(); + GitConfiguration.UpdateMethod updateMethod = configuration.getUpdateMethod(); + if (updateMethod != null) { + var method = switch (updateMethod) { + case MERGE -> UpdateMethod.MERGE; + case REBASE -> UpdateMethod.REBASE; + }; + GitVcsSettings vcsSettings = GitVcsSettings.getInstance(project); + applySetting(method, vcsSettings.getUpdateMethod(), vcsSettings::setUpdateMethod, changedConfigs, "Git update method"); + } + return changedConfigs; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/handlers/java/JavaHandler.java b/src/main/java/de/gebit/intellij/autoconfig/handlers/java/JavaHandler.java new file mode 100644 index 0000000..13bb87d --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/handlers/java/JavaHandler.java @@ -0,0 +1,76 @@ +// +// JavaHandler.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.handlers.java; + +import com.intellij.compiler.CompilerConfiguration; +import com.intellij.compiler.CompilerConfigurationImpl; +import com.intellij.compiler.impl.javaCompiler.BackendCompiler; +import com.intellij.openapi.project.Project; +import de.gebit.intellij.autoconfig.UpdateHandler; +import de.gebit.intellij.autoconfig.handlers.AbstractHandler; +import de.gebit.intellij.autoconfig.model.AnnotationProcessor; +import de.gebit.intellij.autoconfig.model.Compiler; +import de.gebit.intellij.autoconfig.model.JavaConfiguration; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.jps.model.java.compiler.ProcessorConfigProfile; + +import java.util.ArrayList; +import java.util.List; + +/** + * Handler used to update general Java settings in IntelliJ configuration. + */ +public class JavaHandler extends AbstractHandler implements UpdateHandler { + private static final @NonNls String CONFIG_SCHEMA_JSON = "/schema/java.schema.json"; + + public static final @NonNls String CONFIG_FILE_NAME = "autoconfigJava.yaml"; + + @Override + public String getFileName() { + return CONFIG_FILE_NAME; + } + + @Override + public String getJsonSchema() { + return CONFIG_SCHEMA_JSON; + } + + @Override + public String getUpdaterName() { + return "Java configuration updater"; + } + + @Override + public Class getConfigurationClass() { + return JavaConfiguration.class; + } + + @Override + public List updateConfiguration(JavaConfiguration configuration, Project project) { + List changedConfigs = new ArrayList<>(); + Compiler compiler = configuration.getCompiler(); + if (compiler != null && CompilerConfiguration.getInstance(project) instanceof CompilerConfigurationImpl compilerConfiguration) { + Compiler.JavaCompiler javaCompiler = compiler.getJavaCompiler(); + if (javaCompiler != null && !compilerConfiguration.getDefaultCompiler().getId().equals(javaCompiler.value())) { + for (BackendCompiler registeredCompiler : compilerConfiguration.getRegisteredJavaCompilers()) { + if (registeredCompiler.getId().equals(javaCompiler.value())) { + applySetting(registeredCompiler, compilerConfiguration.getDefaultCompiler(), compilerConfiguration::setDefaultCompiler, changedConfigs, "Java compiler"); + break; + } + } + } + AnnotationProcessor annotationProcessor = compiler.getAnnotationProcessor(); + if (annotationProcessor != null) { + ProcessorConfigProfile defaultProcessorProfile = compilerConfiguration.getDefaultProcessorProfile(); + applySetting(annotationProcessor.getEnable(), defaultProcessorProfile.isEnabled(), defaultProcessorProfile::setEnabled, changedConfigs, "Enable annotation processor"); + } + } + return changedConfigs; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/handlers/maven/MavenHandler.java b/src/main/java/de/gebit/intellij/autoconfig/handlers/maven/MavenHandler.java new file mode 100644 index 0000000..5555642 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/handlers/maven/MavenHandler.java @@ -0,0 +1,113 @@ +// +// MavenHandler.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.handlers.maven; + +import com.intellij.conversion.impl.ConversionContextImpl; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.projectRoots.ProjectJdkTable; +import com.intellij.openapi.projectRoots.Sdk; +import de.gebit.intellij.autoconfig.UpdateHandler; +import de.gebit.intellij.autoconfig.handlers.AbstractHandler; +import de.gebit.intellij.autoconfig.model.MavenConfiguration; +import de.gebit.intellij.autoconfig.util.Notifications; +import org.jetbrains.idea.maven.execution.MavenRunner; +import org.jetbrains.idea.maven.project.MavenProjectBundle; +import org.jetbrains.idea.maven.project.MavenProjectsManager; + +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +/** + * Maven configuration update handler. + */ +public class MavenHandler extends AbstractHandler implements UpdateHandler { + @Override + public String getFileName() { + return "autoconfigMaven.yaml"; + } + + @Override + public String getJsonSchema() { + return "/schema/maven.schema.json"; + } + + @Override + public String getUpdaterName() { + return "Maven settings updater"; + } + + @Override + public Class getConfigurationClass() { + return MavenConfiguration.class; + } + + @Override + @SuppressWarnings("java:S5738") + public List updateConfiguration(MavenConfiguration maven, Project project) { + List changedConfigs = new ArrayList<>(); + var mavenProject = MavenProjectsManager.getInstance(project); + var mavenProjectSettings = mavenProject.getGeneralSettings(); + applySetting(maven.getThreads(), mavenProjectSettings.getThreads(), mavenProjectSettings::setThreads, changedConfigs, "Maven thread parameter"); + + var settingsFilePath = maven.getSettingsFile(); + if (settingsFilePath != null && project.getBasePath() != null) { + var projectBasePath = Paths.get(project.getBasePath()); + var conversionContextImpl = new ConversionContextImpl(projectBasePath); + var expandPath = conversionContextImpl.expandPath(settingsFilePath); + applySetting(expandPath, mavenProjectSettings.getUserSettingsFile(), mavenProjectSettings::setUserSettingsFile, changedConfigs, "Maven user settings file"); + } + applySetting(getMavenHome(maven.getUseMavenWrapper()), mavenProjectSettings.getMavenHome(), mavenProjectSettings::setMavenHome, changedConfigs, "Maven home"); + applySetting(maven.getUseMavenConfig(), mavenProjectSettings.isUseMavenConfig(), mavenProjectSettings::setUseMavenConfig, changedConfigs, "Use maven config"); + + var mavenImportingConfig = maven.getImporting(); + if (mavenImportingConfig != null) { + var mavenImportingProjectSettings = mavenProject.getImportingSettings(); + applySetting(mavenImportingConfig.getDetectCompiler(), mavenImportingProjectSettings.isAutoDetectCompiler(), mavenImportingProjectSettings::setAutoDetectCompiler, changedConfigs, "Autodetect compiler"); + applySetting(mavenImportingConfig.getDownloadSources(), mavenImportingProjectSettings.isDownloadSourcesAutomatically(), mavenImportingProjectSettings::setDownloadSourcesAutomatically, changedConfigs, "Download sources"); + applySetting(mavenImportingConfig.getDownloadDocumentation(), mavenImportingProjectSettings.isDownloadDocsAutomatically(), mavenImportingProjectSettings::setDownloadDocsAutomatically, changedConfigs, "Download documentation"); + applySetting(mavenImportingConfig.getVmOptions(), mavenImportingProjectSettings.getVmOptionsForImporter(), mavenImportingProjectSettings::setVmOptionsForImporter, changedConfigs, "VM options for maven importer"); + applySetting(findProjectSdk(mavenImportingConfig.getJdk(), project), mavenImportingProjectSettings.getJdkForImporter(), mavenImportingProjectSettings::setJdkForImporter, changedConfigs, "JDK for importer"); + } + + var mavenRunnerConfig = maven.getRunner(); + if (mavenRunnerConfig != null) { + var mavenRunnerProjectSettings = MavenRunner.getInstance(project).getState(); + applySetting(mavenRunnerConfig.getVmOptions(), mavenRunnerProjectSettings.getVmOptions(), mavenRunnerProjectSettings::setVmOptions, changedConfigs, "VM options for maven runner"); + applySetting(findProjectSdk(mavenRunnerConfig.getJre(), project), mavenRunnerProjectSettings.getJreName(), mavenRunnerProjectSettings::setJreName, changedConfigs, "JRE for runner"); + } + + return changedConfigs; + } + + private String getMavenHome(Boolean useMavenWrapperConfig) { + if (useMavenWrapperConfig == null) { + return null; + } else { + if (useMavenWrapperConfig) { + return MavenProjectBundle.message("maven.wrapper.version.title"); + } else { + return MavenProjectBundle.message("maven.bundled.version.3.title"); + } + } + } + + private String findProjectSdk(String sdkName, Project project) { + if (sdkName == null) { + return null; + } + for (Sdk jdk : ProjectJdkTable.getInstance().getAllJdks()) { + if (jdk.getName().equals(sdkName)) { + return jdk.getName(); + } + } + Notifications.showError("SDK \"" + sdkName + " not found, please install it and add it in your SDK list.", project); + return null; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/json/ConfigurationJsonSchemeProviderFactory.java b/src/main/java/de/gebit/intellij/autoconfig/json/ConfigurationJsonSchemeProviderFactory.java new file mode 100644 index 0000000..ddaa695 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/json/ConfigurationJsonSchemeProviderFactory.java @@ -0,0 +1,35 @@ +// +// RPMcoConfigurationJsonSchemeProviderFactory.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.json; + +import com.intellij.openapi.project.Project; +import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider; +import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory; +import de.gebit.intellij.autoconfig.AutoconfigStartup; +import de.gebit.intellij.autoconfig.UpdateHandler; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; + +/** + * This class is invoked, when the configuration plugin starts up and will provide a json schema for YML and json files. + */ +public class ConfigurationJsonSchemeProviderFactory implements JsonSchemaProviderFactory { + + @NotNull + @Override + public List getProviders(@NotNull Project project) { + List schemaFileProviders = new ArrayList<>(); + for (UpdateHandler updateHandler : AutoconfigStartup.EP_NAME.getExtensionList()) { + schemaFileProviders.add(new SimpleJsonSchemeFileProvider(updateHandler.getUpdaterName(), updateHandler.getFileName(), updateHandler.getJsonSchema(), updateHandler.getConfigurationClass())); + } + return schemaFileProviders; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/json/SimpleJsonSchemeFileProvider.java b/src/main/java/de/gebit/intellij/autoconfig/json/SimpleJsonSchemeFileProvider.java new file mode 100644 index 0000000..977a5b6 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/json/SimpleJsonSchemeFileProvider.java @@ -0,0 +1,55 @@ +// +// SimpleJsonSchemeFileProvider.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.json; + +import com.intellij.openapi.vfs.VirtualFile; +import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider; +import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory; +import com.jetbrains.jsonSchema.extension.SchemaType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * A schema file provider used to handle mapping of json file to json schema.s + */ +class SimpleJsonSchemeFileProvider implements JsonSchemaFileProvider { + private final String name; + private final String fileName; + private final String schemaFile; + private final Class resourceSourceClass; + + SimpleJsonSchemeFileProvider(String aName, String aFileName, String aSchemaFile, Class resourceSourceClass) { + name = aName; + fileName = aFileName; + schemaFile = aSchemaFile; + this.resourceSourceClass = resourceSourceClass; + } + + public boolean isAvailable(@NotNull VirtualFile file) { + return fileName.equals(file.getName()); + } + + @NotNull + @Override + public String getName() { + return name; + } + + @Nullable + @Override + public VirtualFile getSchemaFile() { + return JsonSchemaProviderFactory.getResourceFile(resourceSourceClass, schemaFile); + } + + @NotNull + @Override + public SchemaType getSchemaType() { + return SchemaType.embeddedSchema; + } +} diff --git a/src/main/java/de/gebit/intellij/autoconfig/util/Notifications.java b/src/main/java/de/gebit/intellij/autoconfig/util/Notifications.java new file mode 100644 index 0000000..8470113 --- /dev/null +++ b/src/main/java/de/gebit/intellij/autoconfig/util/Notifications.java @@ -0,0 +1,39 @@ +// +// Notifications.java +// +// Copyright (C) 2024 +// GEBIT Solutions GmbH, +// Berlin, Duesseldorf, Stuttgart, Leipzig (Germany) +// All rights reserved. + +package de.gebit.intellij.autoconfig.util; + +import com.intellij.notification.NotificationGroup; +import com.intellij.notification.NotificationGroupManager; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.MessageType; + +/** + * Utility class used to display balloon notification messages. + */ +public class Notifications { + private static NotificationGroup notificationGroup; + + private Notifications() { + } + + public static NotificationGroup getNotifier() { + if (notificationGroup == null) { + notificationGroup = NotificationGroupManager.getInstance().getNotificationGroup("Autoconfig"); + } + return notificationGroup; + } + + public static void showInfo(String text, Project project) { + getNotifier().createNotification(text, MessageType.INFO).notify(project); + } + + public static void showError(String text, Project project) { + getNotifier().createNotification(text, MessageType.ERROR).notify(project); + } +} diff --git a/src/main/resources/META-INF/plugin-git.xml b/src/main/resources/META-INF/plugin-git.xml new file mode 100644 index 0000000..8423e64 --- /dev/null +++ b/src/main/resources/META-INF/plugin-git.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/META-INF/plugin-java.xml b/src/main/resources/META-INF/plugin-java.xml new file mode 100644 index 0000000..56a257b --- /dev/null +++ b/src/main/resources/META-INF/plugin-java.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/META-INF/plugin-maven.xml b/src/main/resources/META-INF/plugin-maven.xml new file mode 100644 index 0000000..6acca90 --- /dev/null +++ b/src/main/resources/META-INF/plugin-maven.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml new file mode 100644 index 0000000..9daf68d --- /dev/null +++ b/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,45 @@ + + de.gebit.intellij.autoconfig + Configuration updater plugin for IntelliJ + GEBIT Solutions GmbH + + Change this by patchPluginXml gradle task]]> + Change this by patchPluginXml gradle task]]> + 0.0.0 + + GEBIT Solutions GmbH + + + +
    +
  • initial plugin version
  • +
+ ]]> +
+ + com.intellij.modules.json + org.jetbrains.plugins.yaml + Git4Idea + org.jetbrains.idea.maven + com.intellij.modules.java + + + + + + + + + + + + + + + + +
diff --git a/src/main/resources/schema/config.schema.json b/src/main/resources/schema/config.schema.json new file mode 100644 index 0000000..f087ca5 --- /dev/null +++ b/src/main/resources/schema/config.schema.json @@ -0,0 +1,50 @@ +{ + "$id": "https://www.gebit.de/autoconfig-intellij-plugin/config.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "General configuration", + "type": "object", + "properties": { + "onSave": { + "type": "object", + "description": "Actions on save settings.", + "properties": { + "format": { + "type": "boolean", + "description": "Whether source code formatting is enabled." + }, + "optimizeImports": { + "type": "boolean", + "description": "Whether import optimization is enabled." + } + } + }, + "issueNavigation": { + "type": "array", + "description": "Jira links (can also be configured using .idea/vcs.xml).", + "items": { + "type": "object", + "required": [ + "expression", + "url" + ], + "properties": { + "expression": { + "type": "string", + "description": "Regular expression used to detect issue tags in commit messages." + }, + "url": { + "type": "string", + "description": "Jira URL to use with extracted issue tag." + } + } + } + }, + "pluginRepositories": { + "type": "array", + "description": "List of additional plugin repositories.", + "items": { + "type": "string" + } + } + } +} \ No newline at end of file diff --git a/src/main/resources/schema/git.schema.json b/src/main/resources/schema/git.schema.json new file mode 100644 index 0000000..be3e6f0 --- /dev/null +++ b/src/main/resources/schema/git.schema.json @@ -0,0 +1,14 @@ +{ + "$id": "https://www.gebit.de/autoconfig-intellij-plugin/git.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Git configuration", + "type": "object", + "properties": { + "updateMethod": { + "enum": [ + "Merge", + "Rebase" + ] + } + } +} \ No newline at end of file diff --git a/src/main/resources/schema/java.schema.json b/src/main/resources/schema/java.schema.json new file mode 100644 index 0000000..78194b9 --- /dev/null +++ b/src/main/resources/schema/java.schema.json @@ -0,0 +1,32 @@ +{ + "$id": "https://www.gebit.de/autoconfig-intellij-plugin/java.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Java configuration", + "type": "object", + "properties": { + "compiler": { + "type": "object", + "description": "Compiler settings", + "properties": { + "javaCompiler": { + "description": "Compiler setting", + "enum": [ + "Javac", + "Eclipse", + "Groovy-Eclipse" + ] + }, + "annotationProcessor": { + "type": "object", + "description": "Annotation processor settings", + "properties": { + "enable": { + "type": "boolean", + "description": "Enable or disable annotation processing" + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/main/resources/schema/maven.schema.json b/src/main/resources/schema/maven.schema.json new file mode 100644 index 0000000..458d5ed --- /dev/null +++ b/src/main/resources/schema/maven.schema.json @@ -0,0 +1,67 @@ +{ + "$id": "https://www.gebit.de/autoconfig-intellij-plugin/maven.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Maven configuration", + "type": "object", + "properties": { + "threads": { + "type": "string", + "description": "Thread parameter for -T command line option, e.g. 2C", + "examples": [ + "2C" + ] + }, + "settingsFile": { + "type": "string", + "description": "Path to settings.xml file, e.g. $PROJECT_DIR$/development/settings.xml" + }, + "useMavenWrapper": { + "type": "boolean", + "description": "Whether to use maven wrapper to fetch a given maven version (combine with .mvn/wrapper/maven-wrapper.properties file)" + }, + "useMavenConfig": { + "type": "boolean", + "description": "Whether a .mvn/maven.config file is in use." + }, + "importing": { + "type": "object", + "description": "Maven importing settings.", + "properties": { + "detectCompiler": { + "type": "boolean", + "description": "Whether the compiler should be detected from maven project (which may cause problems when using Eclipse compiler)." + }, + "downloadSources": { + "type": "boolean", + "description": "Whether sources of dependencies should be downloaded automatically (required for TREND projects!)." + }, + "downloadDocumentation": { + "type": "boolean", + "description": "Whether documentation for dependencies should be downloaded automatically." + }, + "vmOptions": { + "type": "string", + "description": "The VM options to use during maven import." + }, + "jdk": { + "type": "string", + "description": "The JDK (name) to use for importing, e.g. 17." + } + } + }, + "runner": { + "type": "object", + "description": "The maven runner settings.", + "properties": { + "vmOptions": { + "type": "string", + "description": "The VM options to use for maven runner." + }, + "jre": { + "type": "string", + "description": "The JRE (name) to use for importing, e.g. 17." + } + } + } + } +} \ No newline at end of file