diff --git a/sbm-gradle-tooling-model/.gitattributes b/sbm-gradle-tooling-model/.gitattributes new file mode 100644 index 000000000..d21dc057c --- /dev/null +++ b/sbm-gradle-tooling-model/.gitattributes @@ -0,0 +1,54 @@ +* text eol=lf + +# +# The above will handle all files NOT found below +# https://help.github.com/articles/dealing-with-line-endings/ +# https://github.com/Danimoth/gitattributes + +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + +# These files are text and should be normalized (Convert crlf => lf) +*.bash text eol=lf +*.css text diff=css +*.htm text diff=html +*.html text diff=html +*.java text diff=java +*.sh text eol=lf + + +# These files are binary and should be left untouched +# (binary is a macro for -text -diff) +*.a binary +*.lib binary +*.icns binary +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.mov binary +*.mp4 binary +*.mp3 binary +*.flv binary +*.fla binary +*.swf binary +*.gz binary +*.zip binary +*.jar binary +*.tar binary +*.tar.gz binary +*.7z binary +*.ttf binary +*.pyc binary +*.gpg binary +*.bin binary +*.exe binary +*.dll binary +*.so binary +*.dylib binary +*.class binary +*.jar binary +*.war binary +*.ear binary +*.rar binary diff --git a/sbm-gradle-tooling-model/.gitignore b/sbm-gradle-tooling-model/.gitignore new file mode 100644 index 000000000..31742a8b8 --- /dev/null +++ b/sbm-gradle-tooling-model/.gitignore @@ -0,0 +1,5 @@ +build/ +.gradle/ +out/ +.idea/ +/spring-petclinic/ diff --git a/sbm-gradle-tooling-model/build.gradle.kts b/sbm-gradle-tooling-model/build.gradle.kts new file mode 100644 index 000000000..5cc7fa1f0 --- /dev/null +++ b/sbm-gradle-tooling-model/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + id("org.openrewrite.build.root") version("latest.release") +} + +allprojects { + group = "org.springframework.sbm.gradle.tooling" + description = "A model for extracting semantic information out of Gradle build files necessary for refactoring them." +} diff --git a/sbm-gradle-tooling-model/demo/.gitignore b/sbm-gradle-tooling-model/demo/.gitignore new file mode 100644 index 000000000..c2065bc26 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/sbm-gradle-tooling-model/demo/build.gradle.kts b/sbm-gradle-tooling-model/demo/build.gradle.kts new file mode 100644 index 000000000..4e449bdd7 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + java + id("org.springframework.boot") version "3.1.2" + id("io.spring.dependency-management") version "1.1.2" +} + +group = "com.example" +version = "0.0.1-SNAPSHOT" + +java { + sourceCompatibility = JavaVersion.VERSION_17 +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter") + testImplementation("org.springframework.boot:spring-boot-starter-test") +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/sbm-gradle-tooling-model/demo/gradle/wrapper/gradle-wrapper.jar b/sbm-gradle-tooling-model/demo/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..c1962a79e Binary files /dev/null and b/sbm-gradle-tooling-model/demo/gradle/wrapper/gradle-wrapper.jar differ diff --git a/sbm-gradle-tooling-model/demo/gradle/wrapper/gradle-wrapper.properties b/sbm-gradle-tooling-model/demo/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..37aef8d3f --- /dev/null +++ b/sbm-gradle-tooling-model/demo/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sbm-gradle-tooling-model/demo/gradlew b/sbm-gradle-tooling-model/demo/gradlew new file mode 100755 index 000000000..aeb74cbb4 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + 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*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, 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 \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/sbm-gradle-tooling-model/demo/gradlew.bat b/sbm-gradle-tooling-model/demo/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +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% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/sbm-gradle-tooling-model/demo/settings.gradle.kts b/sbm-gradle-tooling-model/demo/settings.gradle.kts new file mode 100644 index 000000000..dae155f33 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "demo" diff --git a/sbm-gradle-tooling-model/demo/src/main/java/com/example/demo/DemoApplication.java b/sbm-gradle-tooling-model/demo/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 000000000..64b538a17 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } + +} diff --git a/sbm-gradle-tooling-model/demo/src/main/resources/application.properties b/sbm-gradle-tooling-model/demo/src/main/resources/application.properties new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/sbm-gradle-tooling-model/demo/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/sbm-gradle-tooling-model/demo/src/test/java/com/example/demo/DemoApplicationTests.java b/sbm-gradle-tooling-model/demo/src/test/java/com/example/demo/DemoApplicationTests.java new file mode 100644 index 000000000..2778a6a7e --- /dev/null +++ b/sbm-gradle-tooling-model/demo/src/test/java/com/example/demo/DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/sbm-gradle-tooling-model/gradle.properties b/sbm-gradle-tooling-model/gradle.properties new file mode 100644 index 000000000..e395682a6 --- /dev/null +++ b/sbm-gradle-tooling-model/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.caching=true +org.gradle.parallel=true +git.root=/Users/aboyko/git/spring-boot-migrator diff --git a/sbm-gradle-tooling-model/gradle/licenseHeader.txt b/sbm-gradle-tooling-model/gradle/licenseHeader.txt new file mode 100644 index 000000000..571870a07 --- /dev/null +++ b/sbm-gradle-tooling-model/gradle/licenseHeader.txt @@ -0,0 +1,13 @@ +Copyright 2022 the original author or authors. +

+Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +

+https://www.apache.org/licenses/LICENSE-2.0 +

+Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/sbm-gradle-tooling-model/gradle/wrapper/gradle-wrapper.jar b/sbm-gradle-tooling-model/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..c1962a79e Binary files /dev/null and b/sbm-gradle-tooling-model/gradle/wrapper/gradle-wrapper.jar differ diff --git a/sbm-gradle-tooling-model/gradle/wrapper/gradle-wrapper.properties b/sbm-gradle-tooling-model/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..f398c33c4 --- /dev/null +++ b/sbm-gradle-tooling-model/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sbm-gradle-tooling-model/gradlew b/sbm-gradle-tooling-model/gradlew new file mode 100755 index 000000000..aeb74cbb4 --- /dev/null +++ b/sbm-gradle-tooling-model/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + 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*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, 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 \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/sbm-gradle-tooling-model/gradlew.bat b/sbm-gradle-tooling-model/gradlew.bat new file mode 100644 index 000000000..93e3f59f1 --- /dev/null +++ b/sbm-gradle-tooling-model/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +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% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/sbm-gradle-tooling-model/model/build.gradle.kts b/sbm-gradle-tooling-model/model/build.gradle.kts new file mode 100644 index 000000000..8409a96b8 --- /dev/null +++ b/sbm-gradle-tooling-model/model/build.gradle.kts @@ -0,0 +1,10 @@ +plugins { + id("org.openrewrite.build.language-library") +} + +dependencies { + implementation(gradleApi()) + + implementation("org.openrewrite.gradle.tooling:model:latest.integration") + +} diff --git a/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/GradleProjectData.java b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/GradleProjectData.java new file mode 100644 index 000000000..3aef7a978 --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/GradleProjectData.java @@ -0,0 +1,43 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import org.openrewrite.gradle.toolingapi.GradleProject; +import org.openrewrite.gradle.toolingapi.GradleSettings; + +import java.io.File; +import java.util.Collection; +import java.util.Map; + +public interface GradleProjectData extends GradleProject { + + GradleSettings getGradleSettings(); + String getGradleVersion(); + boolean isRootProject(); + File getRootProjectDir(); + Collection getSubprojects(); + File getProjectDir(); + File getBuildDir(); + File getBuildscriptFile(); + File getSettingsBuildscriptFile(); + Map getProperties(); + Collection getJavaSourceSets(); + boolean isMultiPlatformKotlinProject(); + Collection getKotlinSourceSets(); + Collection getBuildscriptClasspath(); + Collection getSettingsClasspath(); + +} diff --git a/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/JavaSourceSetData.java b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/JavaSourceSetData.java new file mode 100644 index 000000000..02c11989d --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/JavaSourceSetData.java @@ -0,0 +1,37 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import java.io.File; +import java.util.Collection; + +public interface JavaSourceSetData { + String getName(); + + Collection getSources(); + + Collection getSourceDirectories(); + + Collection getJava(); + + Collection getClassesDirs(); + + Collection getCompileClasspath(); + + Collection getImplementationClasspath(); + + JavaVersionData getJavaVersionData(); +} diff --git a/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/JavaVersionData.java b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/JavaVersionData.java new file mode 100644 index 000000000..47ab04b27 --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/JavaVersionData.java @@ -0,0 +1,24 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +public interface JavaVersionData { + String getCreatedBy(); + String getVmVendor(); + String getSourceCompatibility(); + String getTargetCompatibility(); + +} diff --git a/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/KotlinSourceSetData.java b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/KotlinSourceSetData.java new file mode 100644 index 000000000..f1621b347 --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/KotlinSourceSetData.java @@ -0,0 +1,31 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import java.io.File; +import java.util.Collection; + +public interface KotlinSourceSetData { + + String getName(); + + Collection getKotlin(); + + Collection getCompileClasspath(); + + Collection getImplementationClasspath(); + +} diff --git a/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/ModelBuilder.java b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/ModelBuilder.java new file mode 100644 index 000000000..786275591 --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/main/java/org/springframework/sbm/gradle/tooling/ModelBuilder.java @@ -0,0 +1,70 @@ +/* + * Copyright 2022 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import org.gradle.tooling.GradleConnector; +import org.gradle.tooling.ProjectConnection; +import org.gradle.tooling.internal.consumer.DefaultGradleConnector; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.List; + +public class ModelBuilder { + public static T forProjectDirectory(File projectDir, File buildFile, Class modelClass) { + DefaultGradleConnector connector = (DefaultGradleConnector) GradleConnector.newConnector(); + if (Files.exists(projectDir.toPath().resolve("gradle/wrapper/gradle-wrapper.properties"))) { + connector.useBuildDistribution(); + } else { + connector.useGradleVersion("7.6"); + } + connector.forProjectDirectory(projectDir); + List arguments = new ArrayList<>(); + if (buildFile != null && buildFile.exists()) { + arguments.add("-b"); + arguments.add(buildFile.getAbsolutePath()); + } + arguments.add("--init-script"); + Path init = projectDir.toPath().resolve("openrewrite-tooling.gradle").toAbsolutePath(); + arguments.add(init.toString()); + try (ProjectConnection connection = connector.connect()) { + org.gradle.tooling.ModelBuilder customModelBuilder = connection.model(modelClass); + try (InputStream is = ModelBuilder.class.getResourceAsStream("/init.gradle")) { + if (is == null) { + throw new IllegalStateException("Expected to find init.gradle on the classpath"); + } + Files.copy(is, init, StandardCopyOption.REPLACE_EXISTING); + customModelBuilder.withArguments(arguments); + return customModelBuilder.get(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } finally { + try { + Files.delete(init); + } catch (IOException e) { + //noinspection ThrowFromFinallyBlock + throw new UncheckedIOException(e); + } + } + } + } +} diff --git a/sbm-gradle-tooling-model/model/src/main/resources/init.gradle b/sbm-gradle-tooling-model/model/src/main/resources/init.gradle new file mode 100644 index 000000000..84913fe76 --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/main/resources/init.gradle @@ -0,0 +1,41 @@ +/** + * Copyright 2022 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +initscript { + repositories { + mavenLocal() + maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } + mavenCentral() + } + + configurations.all { + resolutionStrategy { + cacheChangingModulesFor 0, 'seconds' + cacheDynamicVersionsFor 0, 'seconds' + } + } + + dependencies { + classpath 'org.springframework.sbm.gradle.tooling:plugin:latest.integration' + classpath 'org.springframework.sbm.gradle.tooling:model:latest.integration' + classpath 'org.openrewrite.gradle.tooling:model:latest.integration' + classpath 'org.openrewrite:rewrite-maven:latest.integration' + classpath gradleApi() + } +} + +allprojects { + apply plugin: org.springframework.sbm.gradle.tooling.ToolingApiSbmModelPlugin +} diff --git a/sbm-gradle-tooling-model/model/src/test/java/org/openrewrite/gradle/toolingapi/.editorconfig b/sbm-gradle-tooling-model/model/src/test/java/org/openrewrite/gradle/toolingapi/.editorconfig new file mode 100644 index 000000000..a4824935e --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/test/java/org/openrewrite/gradle/toolingapi/.editorconfig @@ -0,0 +1,5 @@ +root = true + +[*.java] +indent_size = 4 +ij_continuation_indent_size = 2 diff --git a/sbm-gradle-tooling-model/model/src/test/java/org/openrewrite/gradle/toolingapi/UseToolingModel.java b/sbm-gradle-tooling-model/model/src/test/java/org/openrewrite/gradle/toolingapi/UseToolingModel.java new file mode 100644 index 000000000..cd73ab19b --- /dev/null +++ b/sbm-gradle-tooling-model/model/src/test/java/org/openrewrite/gradle/toolingapi/UseToolingModel.java @@ -0,0 +1,43 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.openrewrite.gradle.toolingapi; + +import org.springframework.sbm.gradle.tooling.GradleProjectData; +import org.springframework.sbm.gradle.tooling.ModelBuilder; + +import java.io.File; + +public class UseToolingModel { + public static void main(String[] args) { + GradleProjectData projectData = ModelBuilder.forProjectDirectory(new File("sample"), new File("sample/build.gradle"), GradleProjectData.class); + System.out.println(projectData.getBuildDir()); + System.out.println(projectData.getBuildscriptClasspath()); + System.out.println(projectData.getBuildscriptFile()); + System.out.println(projectData.getGradleSettings()); + System.out.println(projectData.getProjectDir()); + System.out.println(projectData.getGradleVersion()); + System.out.println(projectData.getJavaSourceSets()); + System.out.println(projectData.getKotlinSourceSets()); + System.out.println(projectData.getProperties()); + System.out.println(projectData.getRootProjectDir()); + System.out.println(projectData.getSettingsBuildscriptFile()); + System.out.println(projectData.getSettingsClasspath()); + System.out.println(projectData.getMavenRepositories()); + System.out.println(projectData.getPlugins()); + + + } +} diff --git a/sbm-gradle-tooling-model/parser/build.gradle.kts b/sbm-gradle-tooling-model/parser/build.gradle.kts new file mode 100644 index 000000000..eaf75a46e --- /dev/null +++ b/sbm-gradle-tooling-model/parser/build.gradle.kts @@ -0,0 +1,45 @@ +plugins { + id("org.openrewrite.build.language-library") +} + +group = "org.springframework.sbm.gradle.tooling" + +repositories { + if (!project.hasProperty("releasing")) { + mavenLocal { + mavenContent { + excludeVersionByRegex(".+", ".+", ".+-rc-?[0-9]*") + } + } + + maven { + url = uri("https://oss.sonatype.org/content/repositories/snapshots") + } + } + + mavenCentral { + mavenContent { + excludeVersionByRegex(".+", ".+", ".+-rc-?[0-9]*") + } + } +} + +dependencies { + implementation(project(":model")) + implementation("org.openrewrite:rewrite-core:latest.integration") + implementation("org.openrewrite:rewrite-gradle:latest.integration") + implementation("org.openrewrite.gradle.tooling:model:latest.integration") + implementation("org.openrewrite:rewrite-groovy:latest.integration") + implementation("org.openrewrite:rewrite-hcl:latest.integration") + implementation("org.openrewrite:rewrite-java:latest.integration") + implementation("org.openrewrite:rewrite-json:latest.integration") + implementation("org.openrewrite:rewrite-kotlin:latest.integration") + implementation("org.openrewrite:rewrite-python:latest.integration") + implementation("org.openrewrite:rewrite-properties:latest.integration") + implementation("org.openrewrite:rewrite-protobuf:latest.integration") + implementation("org.openrewrite:rewrite-xml:latest.integration") + implementation("org.openrewrite:rewrite-yaml:latest.integration") + implementation("org.openrewrite.recipe:rewrite-all:latest.integration") + implementation(gradleApi()) + implementation("org.openrewrite.gradle.tooling:model:latest.integration") +} diff --git a/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/DefaultParserConfig.java b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/DefaultParserConfig.java new file mode 100644 index 000000000..c562ecc5d --- /dev/null +++ b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/DefaultParserConfig.java @@ -0,0 +1,66 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.parser; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class DefaultParserConfig implements ParseConfig { + + private final List exclusions = new ArrayList<>(); + private final List plainTextMasks = new ArrayList<>(); + + private int sizeThresholdMb = 10; + + @Override + public List getPlainTextMasks() { + if (plainTextMasks.isEmpty()) { + plainTextMasks.addAll(Arrays.asList( + "**gradlew", + "**META-INF/services/**", + "**/META-INF/spring.factories", + "**/META-INF/spring/**", + "**.gitignore", + "**.gitattributes", + "**.java-version", + "**.sdkmanrc", + "**.sh", + "**.bash", + "**.bat", + "**.ksh", + "**.txt", + "**.jsp", + "**.sql", + "**Dockerfile", + "**Jenkinsfile", + "**.kts" + )); + } + return plainTextMasks; + } + + @Override + public List getExclusions() { + return exclusions; + } + + @Override + public int getSizeThresholdMb() { + return sizeThresholdMb; + } + +} diff --git a/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/DefaultProjectParser.java b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/DefaultProjectParser.java new file mode 100644 index 000000000..de9036bed --- /dev/null +++ b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/DefaultProjectParser.java @@ -0,0 +1,499 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.parser; + +import org.gradle.util.GradleVersion; +import org.openrewrite.ExecutionContext; +import org.openrewrite.OmniParser; +import org.openrewrite.SourceFile; +import org.openrewrite.config.Environment; +import org.openrewrite.gradle.marker.GradleProject; +import org.openrewrite.gradle.marker.GradleSettings; +import org.openrewrite.groovy.GroovyParser; +import org.openrewrite.internal.lang.Nullable; +import org.openrewrite.java.JavaParser; +import org.openrewrite.java.internal.JavaTypeCache; +import org.openrewrite.java.marker.JavaProject; +import org.openrewrite.java.marker.JavaSourceSet; +import org.openrewrite.java.marker.JavaVersion; +import org.openrewrite.kotlin.KotlinParser; +import org.openrewrite.marker.*; +import org.openrewrite.marker.ci.BuildEnvironment; +import org.openrewrite.style.NamedStyles; +import org.openrewrite.tree.ParseError; +import org.springframework.sbm.gradle.tooling.GradleProjectData; +import org.springframework.sbm.gradle.tooling.JavaSourceSetData; +import org.springframework.sbm.gradle.tooling.KotlinSourceSetData; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; +import static org.openrewrite.PathUtils.separatorsToUnix; +import static org.openrewrite.Tree.randomId; + +class DefaultProjectParser { + + private final AtomicBoolean firstWarningLogged = new AtomicBoolean(false); + protected final Path baseDir; + + protected final ParseConfig parserConfig; + protected final GradleProjectData project; + private final List sharedProvenance; + + private List styles; + private Environment environment; + + DefaultProjectParser(GradleProjectData project, ParseConfig parserConfig) { + this.baseDir = repositoryRoot(project); + this.parserConfig = parserConfig; + this.project = project; + + BuildEnvironment buildEnvironment = BuildEnvironment.build(System::getenv); + sharedProvenance = Stream.of( + buildEnvironment, + gitProvenance(baseDir, buildEnvironment), + OperatingSystemProvenance.current(), + new BuildTool(randomId(), BuildTool.Type.Gradle, project.getGradleVersion())) + .filter(Objects::nonNull) + .collect(toList()); + } + + /** + * Attempt to determine the root of the git repository for the given project. + * Many Gradle builds co-locate the build root with the git repository root, but that is not required. + * If no git repository can be located in any folder containing the build, the build root will be returned. + */ + static Path repositoryRoot(GradleProjectData project) { + Path buildRoot = project.getRootProjectDir().toPath(); + Path maybeBaseDir = buildRoot; + while (maybeBaseDir != null && !Files.exists(maybeBaseDir.resolve(".git"))) { + maybeBaseDir = maybeBaseDir.getParent(); + } + if (maybeBaseDir == null) { + return buildRoot; + } + return maybeBaseDir; + } + + @Nullable + private GitProvenance gitProvenance(Path baseDir, @Nullable BuildEnvironment buildEnvironment) { + try { + return GitProvenance.fromProjectDirectory(baseDir, buildEnvironment); + } catch (Exception e) { + // Logging at a low level as this is unlikely to happen except in non-git projects, where it is expected +// logger.debug("Unable to determine git provenance", e); + } + return null; + } + + public Stream parse(ExecutionContext ctx) { + Stream builder = Stream.of(); + Set alreadyParsed = new HashSet<>(); + if (project.isRootProject()) { + for (GradleProjectData subProject : project.getSubprojects()) { + builder = Stream.concat(builder, parse(subProject, alreadyParsed, ctx)); + } + } + builder = Stream.concat(builder, parse(project, alreadyParsed, ctx)); + + // log parse errors here at the end, so that we don't log parse errors for files that were excluded + return builder.map(this::logParseErrors); + } + + private SourceFile logParseErrors(SourceFile source) { + if (source instanceof ParseError) { + if (firstWarningLogged.compareAndSet(false, true)) { +// logger.warn("There were problems parsing some source files, run with --info to see full stack traces"); + } +// logger.warn("There were problems parsing " + source.getSourcePath()); + } + return source; + } + + protected Environment environment() { + if (environment == null) { + Map gradleProps = project.getProperties().entrySet().stream() + .filter(entry -> entry.getKey() != null && entry.getValue() != null) + .collect(toMap( + Map.Entry::getKey, + Map.Entry::getValue)); + + Properties properties = new Properties(); + properties.putAll(gradleProps); + + Environment.Builder env = Environment.builder(); +// env.scanClassLoader(getClass().getClassLoader()); + +// File rewriteConfig = extension.getConfigFile(); +// if (rewriteConfig.exists()) { +// try (FileInputStream is = new FileInputStream(rewriteConfig)) { +// YamlResourceLoader resourceLoader = new YamlResourceLoader(is, rewriteConfig.toURI(), properties, getClass().getClassLoader()); +// env.load(resourceLoader); +// } catch (IOException e) { +// throw new RuntimeException("Unable to load rewrite configuration", e); +// } +// } else if (extension.getConfigFileSetDeliberately()) { +// logger.warn("Rewrite configuration file {} does not exist.", rewriteConfig); +// } + + environment = env.build(); + } + return environment; + } + + private List getStyles() { +// if (styles == null) { +// styles = environment().activateStyles(getActiveStyles()); +// File checkstyleConfig = extension.getCheckstyleConfigFile(); +// if (checkstyleConfig != null && checkstyleConfig.exists()) { +// try { +// styles.add(CheckstyleConfigLoader.loadCheckstyleConfig(checkstyleConfig.toPath(), extension.getCheckstyleProperties())); +// } catch (Exception e) { +// logger.warn("Unable to parse Checkstyle configuration", e); +// } +// } +// } + return styles; + } + + private boolean isExcluded(Collection exclusions, Path path) { + for (PathMatcher excluded : exclusions) { + if (excluded.matches(path)) { + return true; + } + } + return false; + } + + private Collection pathMatchers(Path basePath, Collection pathExpressions) { + return pathExpressions.stream() + .map(o -> basePath.getFileSystem().getPathMatcher("glob:" + o)) + .collect(Collectors.toList()); + } + + private static Collection mergeExclusions(GradleProjectData project, Path baseDir, ParseConfig parserConfig) { + return Stream.concat( + project.getSubprojects().stream() + .map(subproject -> separatorsToUnix(baseDir.relativize(subproject.getProjectDir().toPath()).toString())), + parserConfig.getExclusions().stream() + ).collect(toList()); + } + + private OmniParser omniParser(Set alreadyParsed) { + return OmniParser.builder() + .plainTextMasks(pathMatchers(baseDir, parserConfig.getPlainTextMasks())) + .exclusionMatchers(pathMatchers(baseDir, mergeExclusions(project, baseDir, parserConfig))) + .exclusions(alreadyParsed) + .sizeThresholdMb(parserConfig.getSizeThresholdMb()) + .build(); + } + + private UnaryOperator addProvenance(List projectProvenance, @Nullable Marker sourceSet) { + return s -> { + Markers m = s.getMarkers(); + for (Marker marker : projectProvenance) { + m = m.add(marker); + } + if (sourceSet != null) { + m = m.add(sourceSet); + } + return s.withMarkers(m); + }; + } + + protected Stream parseNonProjectResources(GradleProjectData subproject, Set alreadyParsed, ExecutionContext ctx, List projectProvenance, Stream sourceFiles) { + //Collect any additional yaml/properties/xml files that are NOT already in a source set. + return omniParser(alreadyParsed).parseAll(subproject.getProjectDir().toPath()); + } + + public Stream parse(GradleProjectData subproject, Set alreadyParsed, ExecutionContext ctx) { + GradleProject gradleProjectMarker = GradleProject.fromToolingModel(subproject); + Collection exclusions = parserConfig.getExclusions().stream() + .map(pattern -> subproject.getProjectDir().toPath().getFileSystem().getPathMatcher("glob:" + pattern)) + .collect(toList()); + if (isExcluded(exclusions, subproject.getProjectDir().toPath())) { +// logger.lifecycle("Skipping project {} because it is excluded", subproject.getName()); + return Stream.empty(); + } + + try { +// logger.lifecycle("Scanning sources in project {}", subproject.getName()); + List styles = getStyles(); + Collection sourceSets = subproject.getJavaSourceSets(); + List projectProvenance; + if (sourceSets.isEmpty()) { + projectProvenance = sharedProvenance; + } else { + projectProvenance = new ArrayList<>(sharedProvenance); + projectProvenance.add(new JavaProject(randomId(), subproject.getName(), + new JavaProject.Publication(subproject.getGroup(), + subproject.getName(), + subproject.getVersion()))); + } + + Stream sourceFiles = Stream.of(); + //noinspection DataFlowIssue + if (subproject.isMultiPlatformKotlinProject()) { + sourceFiles = parseMultiplatformKotlinProject(subproject, exclusions, alreadyParsed, projectProvenance, ctx); + } + + for (JavaSourceSetData sourceSet : sourceSets) { + Stream sourceSetSourceFiles = Stream.of(); + JavaTypeCache javaTypeCache = new JavaTypeCache(); + JavaVersion javaVersion = new JavaVersion(randomId(), sourceSet.getJavaVersionData().getCreatedBy(), + sourceSet.getJavaVersionData().getVmVendor(), + sourceSet.getJavaVersionData().getSourceCompatibility(), + sourceSet.getJavaVersionData().getTargetCompatibility()); + + List javaPaths = sourceSet.getJava().stream() + .filter(it -> it.isFile() && it.getName().endsWith(".java")) + .map(File::toPath) + .map(Path::toAbsolutePath) + .map(Path::normalize) + .collect(toList()); + + Collection implementationClasspath = sourceSet.getImplementationClasspath(); + // The implementation configuration doesn't include build/source directories from project dependencies + // So mash it and our rewriteImplementation together to get everything + List dependencyPaths = Stream.concat(implementationClasspath.stream(), sourceSet.getCompileClasspath().stream()) + .map(File::toPath) + .map(Path::toAbsolutePath) + .map(Path::normalize) + .distinct() + .collect(toList()); + + if (!javaPaths.isEmpty()) { + alreadyParsed.addAll(javaPaths); + Stream cus = Stream + .of((Supplier) () -> JavaParser.fromJavaVersion() + .classpath(dependencyPaths) + .styles(styles) + .typeCache(javaTypeCache) +// .logCompilationWarningsAndErrors(extension.getLogCompilationWarningsAndErrors()) + .build()) + .map(Supplier::get) + .flatMap(jp -> jp.parse(javaPaths, baseDir, ctx)) + .map(cu -> { + if (isExcluded(exclusions, cu.getSourcePath()) || + cu.getSourcePath().startsWith(baseDir.relativize(subproject.getBuildDir().toPath()))) { + return null; + } + return cu; + }) + .filter(Objects::nonNull) + .map(it -> it.withMarkers(it.getMarkers().add(javaVersion))); + sourceSetSourceFiles = Stream.concat(sourceSetSourceFiles, cus); +// logger.info("Scanned {} Java sources in {}/{}", javaPaths.size(), subproject.getName(), sourceSet.getName()); + } + + if (subproject.getPlugins().stream().anyMatch(p -> "org.jetbrains.kotlin.jvm".equals(p.getId()))) { + List kotlinPaths = sourceSet.getSources().stream() + .filter(it -> it.isFile() && it.getName().endsWith(".kt")) + .map(File::toPath) + .map(Path::toAbsolutePath) + .map(Path::normalize) + .collect(toList()); + + if (!kotlinPaths.isEmpty()) { + alreadyParsed.addAll(kotlinPaths); + Stream cus = Stream + .of((Supplier) () -> KotlinParser.builder() + .classpath(dependencyPaths) + .styles(styles) + .typeCache(javaTypeCache) +// .logCompilationWarningsAndErrors(extension.getLogCompilationWarningsAndErrors()) + .build()) + .map(Supplier::get) + .flatMap(kp -> kp.parse(kotlinPaths, baseDir, ctx)) + .map(cu -> { + if (isExcluded(exclusions, cu.getSourcePath())) { + return null; + } + return cu; + }) + .filter(Objects::nonNull) + .map(it -> it.withMarkers(it.getMarkers().add(javaVersion))); + sourceSetSourceFiles = Stream.concat(sourceSetSourceFiles, cus); +// logger.info("Scanned {} Kotlin sources in {}/{}", kotlinPaths.size(), subproject.getName(), sourceSet.getName()); + } + } + + if (subproject.getPlugins().stream().anyMatch(p -> "org.gradle.api.plugins.GroovyPlugin".equals(p.getId()))) { + List groovyPaths = sourceSet.getSources().stream() + .filter(it -> it.isFile() && it.getName().endsWith(".groovy")) + .map(File::toPath) + .map(Path::toAbsolutePath) + .map(Path::normalize) + .collect(toList()); + + if (!groovyPaths.isEmpty()) { + // Groovy sources are aware of java types that are intermixed in the same directory/sourceSet + // Include the build directory containing class files so these definitions are available + List dependenciesWithBuildDirs = Stream.concat( + dependencyPaths.stream(), + sourceSet.getClassesDirs().stream().map(File::toPath) + ).collect(toList()); + + alreadyParsed.addAll(groovyPaths); + + Stream cus = Stream + .of((Supplier) () -> GroovyParser.builder() + .classpath(dependenciesWithBuildDirs) + .styles(styles) + .typeCache(javaTypeCache) + .logCompilationWarningsAndErrors(false) + .build()) + .map(Supplier::get) + .flatMap(gp -> gp.parse(groovyPaths, baseDir, ctx)) + .map(cu -> { + if (isExcluded(exclusions, cu.getSourcePath())) { + return null; + } + return cu; + }) + .filter(Objects::nonNull) + .map(it -> it.withMarkers(it.getMarkers().add(javaVersion))); + sourceSetSourceFiles = Stream.concat(sourceSetSourceFiles, cus); +// logger.info("Scanned {} Groovy sources in {}/{}", groovyPaths.size(), subproject.getName(), sourceSet.getName()); + } + } + + for (File resourcesDir : sourceSet.getSourceDirectories()) { + if (resourcesDir.exists()) { + sourceSetSourceFiles = Stream.concat(sourceSetSourceFiles, omniParser(alreadyParsed) + .parseAll(resourcesDir.toPath())); + } + } + + JavaSourceSet sourceSetProvenance = JavaSourceSet.build(sourceSet.getName(), dependencyPaths, javaTypeCache, false); + sourceFiles = Stream.concat(sourceFiles, sourceSetSourceFiles.map(addProvenance(projectProvenance, sourceSetProvenance))); + } + + sourceFiles = Stream.concat(sourceFiles, parseNonProjectResources(subproject, alreadyParsed, ctx, projectProvenance, sourceFiles) + .map(addProvenance(projectProvenance, null))); + + // Attach GradleProject marker to the build script + if (this.project.getBuildscriptFile() != null) { + Path buildScriptPath = baseDir.relativize(this.project.getBuildscriptFile().toPath()); + if (!isExcluded(exclusions, buildScriptPath)) { + sourceFiles = sourceFiles.map(sourceFile -> { + if (!sourceFile.getSourcePath().equals(buildScriptPath)) { + return sourceFile; + } + try { + GradleProject gp = GradleProject.fromToolingModel(subproject); + return sourceFile.withMarkers(sourceFile.getMarkers().add(gp)); + } catch (Exception e) { + // Gradle dependency resolution exceptions may be cyclic, which can be a problem for serialization + RuntimeException sanitizedException = new RuntimeException(e.getMessage()); + sanitizedException.setStackTrace(e.getStackTrace()); + return Markup.warn(sourceFile, sanitizedException); + } + }); + } + } + + if (GradleVersion.current().compareTo(GradleVersion.version("4.4")) >= 0) { + if (project.getSettingsBuildscriptFile() != null) { + Path settingsScriptPath = baseDir.relativize(project.getSettingsBuildscriptFile().toPath()); + if (!isExcluded(exclusions, settingsScriptPath)) { + sourceFiles = sourceFiles.map(sourceFile -> { + if (!sourceFile.getSourcePath().equals(settingsScriptPath)) { + return sourceFile; + } + try { + GradleSettings gs = GradleSettings.fromToolingModel(project.getGradleSettings()); + return sourceFile.withMarkers(sourceFile.getMarkers().add(gs)); + } catch (Exception e) { + RuntimeException sanitizedException = new RuntimeException(e.getMessage()); + sanitizedException.setStackTrace(e.getStackTrace()); + return Markup.warn(sourceFile, sanitizedException); + } + }); + } + } + } + + return sourceFiles; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private Stream parseMultiplatformKotlinProject(GradleProjectData subproject, Collection exclusions, Set alreadyParsed, List projectProvenance, ExecutionContext ctx) { + Stream sourceFiles = Stream.of(); + for (KotlinSourceSetData sourceSet : project.getKotlinSourceSets()) { + try { + List kotlinPaths = sourceSet.getKotlin().stream() + .filter(it -> it.isFile() && it.getName().endsWith(".kt")) + .map(File::toPath) + .map(Path::toAbsolutePath) + .map(Path::normalize) + .collect(toList()); + + // The implementation configuration doesn't include build/source directories from project dependencies + // So mash it and our rewriteImplementation together to get everything + List dependencyPaths = Stream.concat(sourceSet.getImplementationClasspath().stream(), sourceSet.getCompileClasspath().stream()) + .map(File::toPath) + .map(Path::toAbsolutePath) + .map(Path::normalize) + .distinct() + .collect(toList()); + + if (!kotlinPaths.isEmpty()) { + JavaTypeCache javaTypeCache = new JavaTypeCache(); + KotlinParser kp = KotlinParser.builder() + .classpath(dependencyPaths) + .styles(getStyles()) + .typeCache(javaTypeCache) +// .logCompilationWarningsAndErrors(extension.getLogCompilationWarningsAndErrors()) + .build(); + + Stream cus = kp.parse(kotlinPaths, baseDir, ctx); + alreadyParsed.addAll(kotlinPaths); + cus = cus.map(cu -> { + if (isExcluded(exclusions, cu.getSourcePath())) { + return null; + } + return cu; + }).filter(Objects::nonNull); + JavaSourceSet sourceSetProvenance = JavaSourceSet.build(sourceSet.getName(), dependencyPaths, javaTypeCache, false); + + sourceFiles = Stream.concat(sourceFiles, cus.map(addProvenance(projectProvenance, sourceSetProvenance))); +// logger.info("Scanned {} Kotlin sources in {}/{}", kotlinPaths.size(), subproject.getName(), sourceSet.getName()); + } + return sourceFiles; + } catch (Exception e) { +// logger.warn("Failed to resolve sourceSet from {}:{}. Some type information may be incomplete", +// subproject.getPath(), sourceSet.getName()); + } + } + + return Stream.empty(); + } + +} + diff --git a/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/GradleProjectParser.java b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/GradleProjectParser.java new file mode 100644 index 000000000..324df6c0e --- /dev/null +++ b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/GradleProjectParser.java @@ -0,0 +1,32 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.parser; + +import org.openrewrite.ExecutionContext; +import org.openrewrite.SourceFile; +import org.springframework.sbm.gradle.tooling.GradleProjectData; +import org.springframework.sbm.gradle.tooling.ModelBuilder; + +import java.io.File; +import java.util.stream.Stream; + +public class GradleProjectParser { + + public static Stream parse(File projectDir, File buildFile, ExecutionContext context, ParseConfig config) { + GradleProjectData project = ModelBuilder.forProjectDirectory(projectDir, buildFile, GradleProjectData.class); + return new DefaultProjectParser(project, config).parse(context); + } +} diff --git a/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/Main.java b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/Main.java new file mode 100644 index 000000000..71c80fd12 --- /dev/null +++ b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/Main.java @@ -0,0 +1,36 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.parser; + +import org.openrewrite.InMemoryExecutionContext; +import org.openrewrite.SourceFile; + +import java.io.File; +import java.util.List; +import java.util.stream.Collectors; + +public class Main { + public static void main(String[] args) { +// List sources = GradleProjectParser.parse(new File("sample"), new File("sample/build.gradle.kts"), new InMemoryExecutionContext(), new DefaultParserConfig()).collect(Collectors.toList()); +// System.out.println(sources.size()); +// +// sources = GradleProjectParser.parse(new File("demo"), new File("demo/build.gradle.kts"), new InMemoryExecutionContext(), new DefaultParserConfig()).collect(Collectors.toList()); +// System.out.println(sources.size()); + + List sources = GradleProjectParser.parse(new File("/Users/aboyko/Documents/STS4-arm/spring-petclinic"), new File("/Users/aboyko/Documents/STS4-arm/spring-petclinic/build.gradle"), new InMemoryExecutionContext(), new DefaultParserConfig()).collect(Collectors.toList()); + System.out.println(sources.size()); + } +} \ No newline at end of file diff --git a/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/ParseConfig.java b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/ParseConfig.java new file mode 100644 index 000000000..d492227b5 --- /dev/null +++ b/sbm-gradle-tooling-model/parser/src/main/java/org/springframework/sbm/gradle/parser/ParseConfig.java @@ -0,0 +1,28 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.parser; + +import java.util.List; + +public interface ParseConfig { + + List getExclusions(); + + List getPlainTextMasks(); + + int getSizeThresholdMb(); + +} diff --git a/sbm-gradle-tooling-model/plugin/build.gradle.kts b/sbm-gradle-tooling-model/plugin/build.gradle.kts new file mode 100644 index 000000000..3a23ade10 --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/build.gradle.kts @@ -0,0 +1,33 @@ +plugins { + id("org.openrewrite.build.language-library") +} + +repositories { + if (!project.hasProperty("releasing")) { + mavenLocal { + mavenContent { + excludeVersionByRegex(".+", ".+", ".+-rc-?[0-9]*") + } + } + + maven { + url = uri("https://oss.sonatype.org/content/repositories/snapshots") + } + } + + mavenCentral { + mavenContent { + excludeVersionByRegex(".+", ".+", ".+-rc-?[0-9]*") + } + } +} + + +dependencies { + implementation(project(":model")) + implementation("org.openrewrite.gradle.tooling:model:latest.integration") + implementation("org.openrewrite:rewrite-maven:latest.integration") + implementation(gradleApi()) + compileOnly("org.projectlombok:lombok:1.18.28") + annotationProcessor("org.projectlombok:lombok:1.18.28") +} diff --git a/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/GradleProjectDataImpl.java b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/GradleProjectDataImpl.java new file mode 100644 index 000000000..c73e704c8 --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/GradleProjectDataImpl.java @@ -0,0 +1,248 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import lombok.AllArgsConstructor; +import lombok.Value; +import org.gradle.api.NamedDomainObjectContainer; +import org.gradle.api.Project; +import org.gradle.api.artifacts.Configuration; +import org.gradle.api.file.SourceDirectorySet; +import org.gradle.api.initialization.Settings; +import org.gradle.api.plugins.JavaPluginConvention; +import org.gradle.api.tasks.SourceSet; +import org.gradle.api.tasks.compile.JavaCompile; +import org.gradle.invocation.DefaultGradle; +import org.gradle.util.GradleVersion; +import org.openrewrite.gradle.marker.*; +import org.openrewrite.maven.tree.MavenRepository; + +import java.io.File; +import java.io.Serializable; +import java.util.*; +import java.util.stream.Collectors; + +@Value +@AllArgsConstructor +public class GradleProjectDataImpl implements Serializable { + + private static Class[] SUPPORTED_GRADLE_PROPERTY_VALUE_TYPES =new Class[] { + Number.class, + Boolean.class, + String.class, + Character.class + }; + + private final String name; + private final String path; + private final String group; + private final String version; + private final List plugins; + private final List mavenRepositories; + private final List mavenPluginRepositories; + private final Map nameToConfiguration; + + private final GradleSettings gradleSettings; + private final String gradleVersion; + private final boolean rootProject; + private final File rootProjectDir; + private final Collection subprojects; + private final File projectDir; + private final File buildDir; + private final File buildscriptFile; + private final File settingsBuildscriptFile; + private final Map properties; + private final Collection javaSourceSets; + private final boolean multiPlatformKotlinProject; + private final Collection kotlinSourceSets; + private final Collection buildscriptClasspath; + private final Collection settingsClasspath; + + public static GradleProjectDataImpl from(Project project) { + GradleProject gardleProjectMarker = GradleProjectBuilder.gradleProject(project); + return new GradleProjectDataImpl( + gardleProjectMarker.getName(), + gardleProjectMarker.getPath(), + gardleProjectMarker.getGroup(), + gardleProjectMarker.getVersion(), + gardleProjectMarker.getPlugins(), + gardleProjectMarker.getMavenRepositories(), + gardleProjectMarker.getMavenPluginRepositories(), + gardleProjectMarker.getNameToConfiguration(), + + GradleSettingsBuilder.gradleSettings(((DefaultGradle)project.getGradle()).getSettings()), + project.getGradle().getGradleVersion(), + project == project.getRootProject(), + project.getRootProject().getProjectDir(), + subprojects(project.getSubprojects()), + project.getProjectDir(), + project.getBuildDir(), + project.getBuildscript().getSourceFile(), + settingsBuildscriptFile(project), + properties(project.getProperties()), + javaSourceSets(project), + isMultiPlatformKotlinProject(project), + kotlinSourceSets(project), + project.getBuildscript().getConfigurations().getByName("classpath").resolve(), + settingsClasspath(project) + ); + } + + private static Collection subprojects(Collection subprojects) { + List sub = new ArrayList(subprojects.size()); + Iterator var2 = subprojects.iterator(); + while(var2.hasNext()) { + Project s = (Project)var2.next(); + sub.add(from(s)); + } + return sub; + } + + private static File settingsBuildscriptFile(Project project) { + Settings settings = ((DefaultGradle)project.getGradle()).getSettings(); + return settings.getBuildscript().getSourceFile() == null ? null : settings.getBuildscript().getSourceFile(); + } + + private static Map properties(Map props) { + return props.entrySet() + .stream() + .filter(e -> Arrays.stream(SUPPORTED_GRADLE_PROPERTY_VALUE_TYPES).anyMatch(c -> c.isInstance(e.getValue()))) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + } + + private static List javaSourceSets(Project project) { + JavaPluginConvention javaConvention = (JavaPluginConvention)project.getConvention().findPlugin(JavaPluginConvention.class); + if (javaConvention == null) { + return Collections.emptyList(); + } else { + List sourceSetData = new ArrayList(javaConvention.getSourceSets().size()); + Iterator var3 = javaConvention.getSourceSets().iterator(); + + while(var3.hasNext()) { + final SourceSet sourceSet = (SourceSet)var3.next(); + sourceSetData.add(new JavaSourceSetDataImpl( + sourceSet.getName(), + sourceSet.getResources().getSourceDirectories().getFiles(), + sourceSet.getAllJava().getFiles(), + sourceSet.getOutput().getClassesDirs().getFiles(), + sourceSet.getCompileClasspath().getFiles(), + sourceSet.getCompileClasspath().getFiles(), + javaSourceSetImplementationClasspath(project, sourceSet), + sourceSetJavaVersion(project, sourceSet) + )); + } + return sourceSetData; + } + } + + private static Collection javaSourceSetImplementationClasspath(Project project, SourceSet sourceSet) { + Configuration implementation = project.getConfigurations().getByName(sourceSet.getImplementationConfigurationName()); + Configuration rewriteImplementation = project.getConfigurations().maybeCreate("rewrite" + sourceSet.getImplementationConfigurationName()); + rewriteImplementation.extendsFrom(new Configuration[]{implementation}); + + try { + return rewriteImplementation.resolve(); + } catch (Exception var5) { + return Collections.emptySet(); + } + } + + private static JavaVersionDataImpl sourceSetJavaVersion(Project project, SourceSet sourceSet) { + final JavaCompile javaCompileTask = (JavaCompile)project.getTasks().getByName(sourceSet.getCompileJavaTaskName()); + return new JavaVersionDataImpl( + System.getProperty("java.runtime.version"), + System.getProperty("java.vm.vendor"), + javaCompileTask.getSourceCompatibility(), + javaCompileTask.getTargetCompatibility() + ); + } + + private static boolean isMultiPlatformKotlinProject(Project project) { + try { + return project.getPlugins().hasPlugin("org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension") || project.getExtensions().findByName("kotlin") != null && project.getExtensions().findByName("kotlin").getClass().getCanonicalName().startsWith("org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension"); + } catch (Throwable t) { + return false; + } + } + + private static Collection kotlinSourceSets(Project project) { + NamedDomainObjectContainer sourceSets; + try { + Object kotlinExtension = project.getExtensions().getByName("kotlin"); + Class clazz = kotlinExtension.getClass().getClassLoader().loadClass("org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension"); + sourceSets = (NamedDomainObjectContainer)clazz.getMethod("getSourceSets").invoke(kotlinExtension); + } catch (Exception e) { + return Collections.emptyList(); + } + + SortedSet sourceSetNames; + try { + sourceSetNames = (SortedSet)sourceSets.getClass().getMethod("getNames").invoke(sourceSets); + } catch (Exception var19) { + return Collections.emptyList(); + } + + List kotlinSourceSetData = new ArrayList(sourceSetNames.size()); + Iterator it = sourceSetNames.iterator(); + + while(it.hasNext()) { + final String sourceSetName = (String)it.next(); + + try { + Object sourceSet = sourceSets.getClass().getMethod("getByName", String.class).invoke(sourceSets, sourceSetName); + final SourceDirectorySet kotlinDirectorySet = (SourceDirectorySet)sourceSet.getClass().getMethod("getKotlin").invoke(sourceSet); + String implementationName = (String)sourceSet.getClass().getMethod("getImplementationConfigurationName").invoke(sourceSet); + Configuration implementation = project.getConfigurations().getByName(implementationName); + Configuration rewriteImplementation = (Configuration)project.getConfigurations().maybeCreate("rewrite" + implementationName); + rewriteImplementation.extendsFrom(new Configuration[]{implementation}); + + Set implementationClasspath; + try { + implementationClasspath = rewriteImplementation.resolve(); + } catch (Exception e) { + implementationClasspath = Collections.emptySet(); + } + + String compileName = (String)sourceSet.getClass().getMethod("getCompileOnlyConfigurationName").invoke(sourceSet); + Configuration compileOnly = project.getConfigurations().getByName(compileName); + Configuration rewriteCompileOnly = (Configuration)project.getConfigurations().maybeCreate("rewrite" + compileName); + rewriteCompileOnly.setCanBeResolved(true); + rewriteCompileOnly.extendsFrom(new Configuration[]{compileOnly}); + final Set compClasspath = rewriteCompileOnly.getFiles(); + kotlinSourceSetData.add(new KotlinSourceSetDataImpl( + sourceSetName, + kotlinDirectorySet.getFiles(), + compClasspath, + implementationClasspath + )); + } catch (Exception e) { + } + } + + return kotlinSourceSetData; + } + + private static Collection settingsClasspath(Project project) { + if (GradleVersion.current().compareTo(GradleVersion.version("4.4")) >= 0) { + Settings settings = ((DefaultGradle)project.getGradle()).getSettings(); + return settings.getBuildscript().getConfigurations().getByName("classpath").resolve(); + } else { + return Collections.emptyList(); + } + } + + +} diff --git a/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/JavaSourceSetDataImpl.java b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/JavaSourceSetDataImpl.java new file mode 100644 index 000000000..54bb5fcbd --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/JavaSourceSetDataImpl.java @@ -0,0 +1,36 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import lombok.AllArgsConstructor; +import lombok.Value; + +import java.io.File; +import java.io.Serializable; +import java.util.Collection; + +@AllArgsConstructor +@Value +public class JavaSourceSetDataImpl implements JavaSourceSetData, Serializable { + private final String name; + private final Collection sources; + private final Collection sourceDirectories; + private final Collection java; + private final Collection classesDirs; + private final Collection compileClasspath; + private final Collection implementationClasspath; + private final JavaVersionDataImpl javaVersionData; +} diff --git a/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/JavaVersionDataImpl.java b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/JavaVersionDataImpl.java new file mode 100644 index 000000000..95548df07 --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/JavaVersionDataImpl.java @@ -0,0 +1,30 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import lombok.AllArgsConstructor; +import lombok.Value; + +import java.io.Serializable; + +@AllArgsConstructor +@Value +public class JavaVersionDataImpl implements JavaVersionData, Serializable { + private String createdBy; + private String vmVendor; + private String sourceCompatibility; + private String targetCompatibility; +} diff --git a/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/KotlinSourceSetDataImpl.java b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/KotlinSourceSetDataImpl.java new file mode 100644 index 000000000..3132f6c85 --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/KotlinSourceSetDataImpl.java @@ -0,0 +1,34 @@ +/* + * Copyright 2023 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import lombok.AllArgsConstructor; +import lombok.Value; + +import java.io.File; +import java.io.Serializable; +import java.util.Collection; + +@AllArgsConstructor +@Value +public class KotlinSourceSetDataImpl implements KotlinSourceSetData, Serializable { + + private final String name; + private final Collection kotlin; + private final Collection compileClasspath; + private final Collection implementationClasspath; + +} diff --git a/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/ToolingApiSbmModelPlugin.java b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/ToolingApiSbmModelPlugin.java new file mode 100644 index 000000000..a41f8d793 --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/ToolingApiSbmModelPlugin.java @@ -0,0 +1,51 @@ +/* + * Copyright 2022 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.sbm.gradle.tooling; + +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.tooling.provider.model.ToolingModelBuilder; +import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry; + +import javax.inject.Inject; + +public class ToolingApiSbmModelPlugin implements Plugin { + private final ToolingModelBuilderRegistry registry; + + @Inject + public ToolingApiSbmModelPlugin(ToolingModelBuilderRegistry registry) { + this.registry = registry; + } + + @Override + public void apply(Project project) { + registry.register(new GradleProjectDataBuilder()); + } + + private static class GradleProjectDataBuilder implements ToolingModelBuilder { + @Override + public boolean canBuild(String modelName) { + return modelName.equals(GradleProjectData.class.getName()); + } + + @Override + public Object buildAll(String modelName, Project project) { + return GradleProjectDataImpl.from(project); + } + } + + +} diff --git a/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/package-info.java b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/package-info.java new file mode 100644 index 000000000..47552c653 --- /dev/null +++ b/sbm-gradle-tooling-model/plugin/src/main/java/org/springframework/sbm/gradle/tooling/package-info.java @@ -0,0 +1,19 @@ +/* + * Copyright 2021 the original author or authors. + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * https://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@NonNullApi +package org.springframework.sbm.gradle.tooling; + +import org.gradle.api.NonNullApi; diff --git a/sbm-gradle-tooling-model/sample/build.gradle b/sbm-gradle-tooling-model/sample/build.gradle new file mode 100644 index 000000000..889e5866f --- /dev/null +++ b/sbm-gradle-tooling-model/sample/build.gradle @@ -0,0 +1,11 @@ +plugins { + id 'java' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.apache.commons:commons-lang3:3.4' +} diff --git a/sbm-gradle-tooling-model/sample/settings.gradle b/sbm-gradle-tooling-model/sample/settings.gradle new file mode 100644 index 000000000..ce8420a3e --- /dev/null +++ b/sbm-gradle-tooling-model/sample/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "sample" diff --git a/sbm-gradle-tooling-model/settings.gradle.kts b/sbm-gradle-tooling-model/settings.gradle.kts new file mode 100644 index 000000000..1430950c9 --- /dev/null +++ b/sbm-gradle-tooling-model/settings.gradle.kts @@ -0,0 +1,50 @@ +pluginManagement { + repositories { + mavenLocal() + gradlePluginPortal() + } +} + +rootProject.name = "sbm-gradle-tooling-model" + +include("model") +include("plugin") +include("parser") + +plugins { + id("com.gradle.enterprise") version "latest.release" + id("com.gradle.common-custom-user-data-gradle-plugin") version "latest.release" +} + +gradleEnterprise { + val isCiServer = System.getenv("CI")?.equals("true") ?: false + server = "https://ge.openrewrite.org/" + val gradleCacheRemoteUsername: String? = System.getenv("GRADLE_ENTERPRISE_CACHE_USERNAME") + val gradleCacheRemotePassword: String? = System.getenv("GRADLE_ENTERPRISE_CACHE_PASSWORD") + + buildCache { + remote(HttpBuildCache::class) { + url = uri("https://ge.openrewrite.org/cache/") + isPush = isCiServer + if (!gradleCacheRemoteUsername.isNullOrBlank() && !gradleCacheRemotePassword.isNullOrBlank()) { + credentials { + username = gradleCacheRemoteUsername + password = gradleCacheRemotePassword + } + } + } + } + + buildScan { + capture { + isTaskInputFiles = true + } + + isUploadInBackground = !isCiServer + + publishAlways() + this as com.gradle.enterprise.gradleplugin.internal.extension.BuildScanExtensionWithHiddenFeatures + publishIfAuthenticated() + } + +}