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.
================================================
FILE: .mvn/wrapper/maven-wrapper.properties
================================================
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.8/apache-maven-3.9.8-bin.zip
================================================
FILE: .sdkmanrc
================================================
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=21.0.10-tem
================================================
FILE: CLAUDE.md
================================================
## Moderne Prethink Context
This repository contains pre-analyzed context generated by [Moderne Prethink](https://docs.moderne.io/user-documentation/recipes/prethink). Prethink extracts structured knowledge from codebases to help you work more effectively. The context files in `.moderne/context/` contain analyzed information about this codebase.
**IMPORTANT: Before exploring source code for architecture, dependency, or data flow questions:**
1. ALWAYS check `.moderne/context/` files FIRST
2. Do NOT perform broad codebase exploration (e.g., spawning Explore agents, searching multiple source files) unless CSV context is insufficient
3. NEVER read entire CSV files - use SQL queries to retrieve only the rows you need
**IMPORTANT: Prethink context is cheap to read — source code exploration is expensive. Always read MORE prethink context rather than less. The "do not explore broadly" rule applies to source code, NOT to prethink context files.**
For cross-cutting questions (data flow, deletion, dependencies between services),
ALWAYS query these context files in parallel on the first turn:
- `architecture.md` — system diagram and component overview
- `data-assets.csv` — entity fields and data model
- `database-connections.csv` — which services own which tables
- `service-endpoints.csv` — relevant API endpoints
- `messaging-connections.csv` — Kafka/async event flows
- `external-service-calls.csv` — cross-service HTTP calls
Do NOT stop after reading a single context file when others are clearly relevant.
### Available Context
| Context | Description | Details |
|---------|-------------|--------|
| Architecture | FINOS CALM architecture diagram | [`architecture.md`](.moderne/context/architecture.md) |
| Class Quality Metrics | Per-class cohesion, coupling, and complexity measurements | [`class-quality-metrics.md`](.moderne/context/class-quality-metrics.md) |
| Code Smells | Detected design problems with severity and evidence | [`code-smells.md`](.moderne/context/code-smells.md) |
| Coding Conventions | Naming patterns, import organization, and coding style | [`coding-conventions.md`](.moderne/context/coding-conventions.md) |
| Dependencies | Project dependencies including transitive dependencies | [`dependencies.md`](.moderne/context/dependencies.md) |
| Error Handling | Exception handling strategies and logging patterns | [`error-handling.md`](.moderne/context/error-handling.md) |
| Method Quality Metrics | Per-method complexity and quality measurements | [`method-quality-metrics.md`](.moderne/context/method-quality-metrics.md) |
| Package Quality Metrics | Per-package coupling, stability, and dependency cycle analysis | [`package-quality-metrics.md`](.moderne/context/package-quality-metrics.md) |
| Project Identity | Build system coordinates, names, and module structure | [`project-identity.md`](.moderne/context/project-identity.md) |
| Test Coverage | Maps test methods to implementation methods they verify | [`test-coverage.md`](.moderne/context/test-coverage.md) |
| Test Gaps | Public non-trivial methods lacking test coverage | [`test-gaps.md`](.moderne/context/test-gaps.md) |
| Test Quality | Test quality issues that may cause flakiness or silent failures | [`test-quality.md`](.moderne/context/test-quality.md) |
| Token Estimates | Estimated input tokens for method comprehension | [`token-estimates.md`](.moderne/context/token-estimates.md) |
### Querying Context Files
For .md context files: Read the full file in a single view call. Never grep it progressively.
For .csv context files: Query with DuckDB, SQLite, or grep (from most to least preference).
Upfront parallel reads: At the start of any architecture question, read all relevant context files in parallel rather than discovering which ones matter through iteration.
Use SQL to query CSV files efficiently. This returns only matching rows instead of loading entire files. Try these in order based on availability:
#### Option 1: DuckDB (Preferred)
DuckDB can query CSV files directly with no setup:
```bash
# Find all POST endpoints
duckdb -c "SELECT * FROM '.moderne/context/service-endpoints.csv' WHERE \"HTTP method\" = 'POST'"
# Find method descriptions containing a keyword
duckdb -c "SELECT \"Class name\", Signature, Description FROM '.moderne/context/method-descriptions.csv' WHERE Description LIKE '%authentication%'"
# Find tests for a specific class
duckdb -c "SELECT \"Test method\", \"Test summary\" FROM '.moderne/context/test-mapping.csv' WHERE \"Implementation class\" LIKE '%OrderService%'"
```
#### Option 2: SQLite
Import CSV into memory and query (available on most systems):
```bash
sqlite3 :memory: -cmd ".mode csv" -cmd ".import .moderne/context/service-endpoints.csv endpoints" \
"SELECT * FROM endpoints WHERE [HTTP method] = 'POST'"
```
#### Option 3: Grep (Last Resort)
If SQL tools are unavailable, use grep. Note this loads more content into context:
```bash
grep -i "POST" .moderne/context/service-endpoints.csv
```
**Note:** Column names with spaces require quoting - use double quotes in DuckDB (`"HTTP method"`) or square brackets in SQLite (`[HTTP method]`).
### Usage Pattern
1. Read the `.md` file to understand the schema and available columns
2. Query the `.csv` with DuckDB or SQLite to get only the rows you need
3. Only explore source if the context doesn't answer the question
When citing Moderne Prethink context, mention Moderne Prethink as the source (e.g., "Based on the architecture context from Moderne Prethink..." or "Based on the test coverage mapping from Prethink, this method is tested by...").
================================================
FILE: LICENSE/apache-license-v2.txt
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
## What is this?
This project provides a Maven plugin that applies [Rewrite](https://github.com/openrewrite/rewrite) checking and fixing tasks as build tasks, one of several possible workflows for propagating change across an organization's source code.
## Getting started
This `README` may not have the most up-to-date documentation. For the most up-to-date documentation and reference guides, see:
- [Auto-generated maven plugin documentation](https://openrewrite.github.io/rewrite-maven-plugin/plugin-info.html)
- [Maven Plugin Configuration](https://docs.openrewrite.org/reference/rewrite-maven-plugin)
- [OpenRewrite Quickstart Guide](https://docs.openrewrite.org/running-recipes/getting-started)
To configure, add the plugin to your POM:
```xml
...
org.openrewrite.mavenrewrite-maven-pluginorg.openrewrite.java.format.AutoFormat
```
If wanting to leverage recipes from other dependencies:
```xml
...
org.openrewrite.mavenrewrite-maven-pluginorg.openrewrite.java.testing.junit5.JUnit5BestPracticesorg.openrewrite.github.ActionsSetupJavaAdoptOpenJDKToTemurinorg.openrewrite.reciperewrite-testing-frameworksorg.openrewrite.reciperewrite-github-actions
```
To get started, try `mvn rewrite:help`, `mvn rewrite:discover`, `mvn rewrite:dryRun`, `mvn rewrite:run`, among other plugin goals.
See the [Maven Plugin Configuration](https://docs.openrewrite.org/reference/rewrite-maven-plugin) documentation for full configuration and usage options.
### Snapshots
To use the latest `-SNAPSHOT` version, add a `` entry for OSSRH snapshots. For example:
```xml
...
org.openrewrite.mavenrewrite-maven-plugin4.17.0-SNAPSHOTorg.openrewrite.java.logging.slf4j.Log4j2ToSlf4jorg.openrewrite.reciperewrite-testing-frameworks1.1.0-SNAPSHOTossrh-snapshotshttps://central.sonatype.com/repository/maven-snapshots
```
## Notes for developing and testing this plugin
This plugin uses the [`Maven Integration Testing Framework Extension`](https://github.com/khmarbaise/maven-it-extension) for tests.
All tests can be run from the command line using:
```sh
./mvnw verify
```
If you're looking for more information on the output from a test, try checking the `target/maven-it/**/*IT/**` directory contents after running the tests. It will contain the project state output, including maven logs, etc. Check the [`Integration Testing Framework Users Guide`](https://khmarbaise.github.io/maven-it-extension/itf-documentation/usersguide/usersguide.html) for information, too. It's good.
## Contributing
We appreciate all types of contributions. See the [contributing guide](https://github.com/openrewrite/.github/blob/main/CONTRIBUTING.md) for detailed instructions on how to get started.
### Resource guides
- https://blog.soebes.io/posts/2020/08/2020-08-17-itf-part-i/
- https://carlosvin.github.io/posts/creating-custom-maven-plugin/en/#_dependency_injection
- https://developer.okta.com/blog/2019/09/23/tutorial-build-a-maven-plugin
- https://medium.com/swlh/step-by-step-guide-to-developing-a-custom-maven-plugin-b6e3a0e09966
================================================
FILE: mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
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"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"
================================================
FILE: mvnw.cmd
================================================
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
================================================
FILE: pom.xml
================================================
4.0.0org.openrewrite.mavenrewrite-maven-plugin6.40.0-SNAPSHOTmaven-pluginrewrite-maven-pluginEliminate technical debt. At build time.https://openrewrite.github.io/rewrite-maven-plugin/2020Moderne, Inc.https://moderne.io/The Apache Software License, Version 2.0http://www.apache.org/licenses/LICENSE-2.0.txtJonathan Schneiderhttps://github.com/jkschneiderjkschneider3.3.1scm:git:https://github.com/openrewrite/rewrite-maven-plugin.git${developerConnectionUrl}https://github.com/openrewrite/rewrite-maven-plugin/tree/mainHEADGitHub Issueshttps://github.com/openrewrite/rewrite-maven-plugin/issuesossrhhttps://central.sonatype.com/repository/maven-snapshotsossrhhttps://oss.sonatype.org/service/local/staging/deploy/maven28.82.0-SNAPSHOT2.11.0-SNAPSHOTscm:git:ssh://git@github.com/openrewrite/rewrite-maven-plugin.git
UTF-88${maven.compiler.source}172.21.38.8.10.13.13.9.153.3.13.15.2com.fasterxml.jacksonjackson-bom${jackson-bom.version}pomimportorg.junitjunit-bom6.0.3importpomorg.assertjassertj-bom3.27.7importpomorg.openrewriterewrite-bom${rewrite.version}importpomorg.codehaus.plexusplexus-utils3.6.1org.apache.mavenmaven-api-meta4.0.0-rc-1providedorg.apache.mavenmaven-api-xml4.0.0-rc-5providedorg.apache.mavenmaven-xml-impl4.0.0-beta-5providedorg.openrewriterewrite-javaorg.openrewriterewrite-java-8org.openrewriterewrite-java-11org.openrewriterewrite-java-17org.openrewriterewrite-java-21org.openrewriterewrite-java-25org.openrewriterewrite-groovyorg.openrewriterewrite-kotlinorg.openrewriterewrite-xmlorg.openrewriterewrite-mavenorg.openrewriterewrite-polyglot${rewrite-polyglot.version}org.codehaus.plexusplexus-xml4.1.1io.micrometermicrometer-core1.16.5org.rocksdbrocksdbjni${rocksdbjni.version}org.apache.mavenmaven-plugin-api${maven-dependencies.version}providedorg.apache.mavenmaven-core${maven-dependencies.version}providedorg.apache.mavenmaven-settings${maven-dependencies.version}providedorg.apache.mavenmaven-model${maven-dependencies.version}providedorg.apache.maven.plugin-toolsmaven-plugin-annotations${maven-plugin-tools.version}providedorg.junit.jupiterjunit-jupiter-apitestorg.junit.jupiterjunit-jupiter-enginetestorg.junit.jupiterjunit-jupiter-paramstestcom.soebes.itf.jupiter.extensionitf-jupiter-extension${itf-maven.version}testorg.assertjassertj-coretestcom.soebes.itf.jupiter.extensionitf-assertj${itf-maven.version}testcom.soebes.itf.jupiter.extensionitf-extension-maven${itf-maven.version}testossrh-snapshotshttps://central.sonatype.com/repository/maven-snapshotstruefalsesrc/test/resourcesfalsesrc/test/resources-itstrueorg.apache.maven.pluginsmaven-enforcer-plugin3.6.2173.9.6enforceenforceorg.apache.maven.pluginsmaven-site-plugin4.0.0-M16com.soebes.itf.jupiter.extensionitf-maven-plugin${itf-maven.version}trueinstallingpre-integration-testinstallresources-itsorg.apache.maven.pluginsmaven-failsafe-plugin3.5.5integration-testverifyorg.apache.maven.pluginsmaven-plugin-plugin${maven-plugin-tools.version}rewrite8org.ow2.asmasm9.9.1generate-helpmojohelpmojoorg.apache.maven.pluginsmaven-compiler-plugin3.15.0-Xlint:deprecation-Xlint:uncheckednoneorg.apache.maven.pluginsmaven-javadoc-plugin3.12.0prepare-packagejavadocjarorg.apache.maven.pluginsmaven-source-plugin3.4.0prepare-packageaggregatejarorg.apache.maven.pluginsmaven-release-plugin${maven-release-plugin.version}releasev@{project.version}SemVerVersionPolicyorg.apache.maven.releasemaven-release-semver-policy${maven-release-plugin.version}com.mycilalicense-maven-plugin4.6.mvn/licenseHeader.txt*.xmlsuppressions.xml**/README.md**/.sdkmanrcLICENSE/apache-license-v2.txtsrc/test/resources-its/**src/test/resources/**src/main/resources/**.moderne/.mvn/com.mycilalicense-maven-plugin-git4.6firstformatprocess-sourcessecondcheckverifyorg.owaspdependency-check-maven12.2.2${env.NVD_API_KEY}9suppressions.xmlfalseorg.apache.maven.pluginsmaven-plugin-report-plugin${maven-plugin-tools.version}sign-artifactsorg.apache.maven.pluginsmaven-gpg-plugin3.2.8sign-artifactsverifysign--pinentry-modeloopbackreleaseorg.sonatype.pluginsnexus-staging-maven-plugin1.7.0trueossrhhttps://ossrh-staging-api.central.sonatype.com/true20truetruerelease-automationscm:git:https://github.com/openrewrite/rewrite-maven-plugin.git
avoid-maven-compiler-warnings[9,)8
================================================
FILE: rewrite.yml
================================================
#
# Copyright 2020 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.
#
#./mvnw org.openrewrite.maven:rewrite-maven-plugin:LATEST:run -Drewrite.recipeArtifactCoordinates=org.openrewrite.recipe:rewrite-static-analysis:RELEASE -Drewrite.activeRecipes=org.openrewrite.recipes.rewrite.OpenRewriteRecipeBestPracticesSubset
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.recipes.rewrite.OpenRewriteRecipeBestPracticesSubset
displayName: OpenRewrite best practices
description: Best practices for OpenRewrite recipe development.
recipeList:
- org.openrewrite.java.OrderImports:
removeUnused: true
- org.openrewrite.java.format.EmptyNewlineAtEndOfFile
- org.openrewrite.java.format.RemoveTrailingWhitespace
- org.openrewrite.maven.BestPractices
# - org.openrewrite.staticanalysis.OperatorWrap:
# wrapOption: EOL
# - org.openrewrite.staticanalysis.CommonStaticAnalysis
# - org.openrewrite.staticanalysis.CompareEnumsWithEqualityOperator
# - org.openrewrite.staticanalysis.MissingOverrideAnnotation
# - org.openrewrite.staticanalysis.RemoveSystemOutPrintln
# - org.openrewrite.staticanalysis.RemoveUnusedLocalVariables
# - org.openrewrite.staticanalysis.RemoveUnusedPrivateFields
# - org.openrewrite.staticanalysis.RemoveUnusedPrivateMethods
================================================
FILE: src/main/java/org/openrewrite/maven/AbstractRewriteBaseRunMojo.java
================================================
/*
* Copyright 2020 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.maven;
import io.micrometer.core.instrument.Metrics;
import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.jspecify.annotations.Nullable;
import org.openrewrite.*;
import org.openrewrite.config.CompositeRecipe;
import org.openrewrite.config.DeclarativeRecipe;
import org.openrewrite.config.Environment;
import org.openrewrite.config.RecipeDescriptor;
import org.openrewrite.internal.InMemoryLargeSourceSet;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.tree.J;
import org.openrewrite.kotlin.tree.K;
import org.openrewrite.marker.*;
import org.openrewrite.style.NamedStyles;
import org.openrewrite.xml.tree.Xml;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
public abstract class AbstractRewriteBaseRunMojo extends AbstractRewriteMojo {
@Parameter(property = "rewrite.exportDatatables", defaultValue = "false")
protected boolean exportDatatables;
@Parameter(property = "rewrite.options")
@Nullable
protected LinkedHashSet options;
/**
* The level used to log changes performed by recipes.
*/
@Parameter(property = "rewrite.recipeChangeLogLevel", defaultValue = "WARN")
protected LogLevel recipeChangeLogLevel;
protected void log(LogLevel logLevel, CharSequence content) {
switch (logLevel) {
case DEBUG:
getLog().debug(content);
break;
case INFO:
getLog().info(content);
break;
case WARN:
getLog().warn(content);
break;
case ERROR:
getLog().error(content);
break;
}
}
/**
* 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.
*/
protected Path repositoryRoot() {
Path buildRoot = getBuildRoot();
Path maybeBaseDir = buildRoot;
while (maybeBaseDir != null && !Files.exists(maybeBaseDir.resolve(".git"))) {
maybeBaseDir = maybeBaseDir.getParent();
}
if (maybeBaseDir == null) {
return buildRoot;
}
return maybeBaseDir;
}
protected ResultsContainer listResults(ExecutionContext ctx) throws MojoExecutionException, MojoFailureException {
try (MeterRegistryProvider meterRegistryProvider = new MeterRegistryProvider(getLog(), null)) {
if (!Metrics.globalRegistry.getRegistries().contains(meterRegistryProvider.registry())) {
Metrics.addRegistry(meterRegistryProvider.registry());
}
Path repositoryRoot = repositoryRoot();
getLog().info(String.format("Using active recipe(s) %s", getActiveRecipes()));
getLog().info(String.format("Using active styles(s) %s", getActiveStyles()));
if (getActiveRecipes().isEmpty()) {
return new ResultsContainer(repositoryRoot, emptyList());
}
URLClassLoader recipeArtifactCoordinatesClassloader = getRecipeArtifactCoordinatesClassloader();
if (recipeArtifactCoordinatesClassloader != null) {
merge(getClass().getClassLoader(), recipeArtifactCoordinatesClassloader);
}
Environment env = environment(recipeArtifactCoordinatesClassloader);
Recipe recipe = env.activateRecipes(getActiveRecipes());
if ("org.openrewrite.Recipe$Noop".equals(recipe.getName())) {
getLog().warn("No recipes were activated." +
" Activate a recipe with com.fully.qualified.RecipeClassName in this plugin's in your pom.xml," +
" or on the command line with -Drewrite.activeRecipes=com.fully.qualified.RecipeClassName");
return new ResultsContainer(repositoryRoot, emptyList());
}
if (options != null && !options.isEmpty()) {
configureRecipeOptions(recipe, options);
}
getLog().info("Validating active recipes...");
List> validations = new ArrayList<>();
recipe.validateAll(ctx, validations);
List> failedValidations = validations.stream().map(Validated::failures)
.flatMap(Collection::stream).collect(toList());
if (!failedValidations.isEmpty()) {
failedValidations.forEach(failedValidation -> getLog().error(
String.format(
"Recipe validation error in %s for property %s: %s",
recipe.getName(),
failedValidation.getProperty(),
failedValidation.getMessage()),
failedValidation.getException()));
if (failOnInvalidActiveRecipes) {
throw new MojoExecutionException("Recipe validation errors detected as part of one or more activeRecipe(s). Please check error logs.");
}
getLog().error("Recipe validation errors detected as part of one or more activeRecipe(s). Execution will continue regardless.");
}
LargeSourceSet sourceSet = loadSourceSet(repositoryRoot, env, ctx);
List results = runRecipe(recipe, sourceSet, ctx);
Metrics.removeRegistry(meterRegistryProvider.registry());
return new ResultsContainer(repositoryRoot, results);
} catch (DependencyResolutionRequiredException e) {
throw new MojoExecutionException("Dependency resolution required", e);
}
}
private static void configureRecipeOptions(Recipe recipe, Set options) throws MojoExecutionException {
if (recipe instanceof CompositeRecipe ||
recipe instanceof DeclarativeRecipe ||
recipe instanceof Recipe.DelegatingRecipe ||
!recipe.getRecipeList().isEmpty()) {
// We don't (yet) support configuring potentially nested recipes, as recipes might occur more than once,
// and setting the same value twice might lead to unexpected behavior.
throw new MojoExecutionException(
"Recipes containing other recipes can not be configured from the command line: " + recipe);
}
Map optionValues = new HashMap<>();
for (String option : options) {
String[] parts = option.split("=", 2);
if (parts.length == 2) {
optionValues.put(parts[0], parts[1]);
}
}
for (Field field : recipe.getClass().getDeclaredFields()) {
String removed = optionValues.remove(field.getName());
updateOption(recipe, field, removed);
}
if (!optionValues.isEmpty()) {
throw new MojoExecutionException(
String.format("Unknown recipe options: %s", String.join(", ", optionValues.keySet())));
}
}
private static void updateOption(Recipe recipe, Field field, @Nullable String optionValue) throws MojoExecutionException {
Object convertedOptionValue = convertOptionValue(field.getName(), optionValue, field.getType());
if (convertedOptionValue == null) {
return;
}
try {
field.setAccessible(true);
field.set(recipe, convertedOptionValue);
field.setAccessible(false);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new MojoExecutionException(
String.format("Unable to configure recipe '%s' option '%s' with value '%s'",
recipe.getClass().getSimpleName(), field.getName(), optionValue));
}
}
private static @Nullable Object convertOptionValue(String name, @Nullable String optionValue, Class> type)
throws MojoExecutionException {
if (optionValue == null) {
return null;
}
if (type.isAssignableFrom(String.class)) {
return optionValue;
}
if (type.isAssignableFrom(boolean.class) || type.isAssignableFrom(Boolean.class)) {
return Boolean.parseBoolean(optionValue);
}
if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) {
return Integer.parseInt(optionValue);
}
if (type.isAssignableFrom(long.class) || type.isAssignableFrom(Long.class)) {
return Long.parseLong(optionValue);
}
throw new MojoExecutionException(
String.format("Unable to convert option: %s value: %s to type: %s", name, optionValue, type));
}
protected LargeSourceSet loadSourceSet(Path repositoryRoot, Environment env, ExecutionContext ctx) throws DependencyResolutionRequiredException, MojoExecutionException, MojoFailureException {
List styles = loadStyles(project, env);
//Parse and collect source files from each project in the maven session.
MavenMojoProjectParser projectParser = new MavenMojoProjectParser(getLog(), repositoryRoot, pomCacheEnabled, pomCacheDirectory, runtime, skipMavenParsing, getExclusions(), getPlainTextMasks(), sizeThresholdMb, mavenSession, settingsDecrypter, runPerSubmodule, true);
Stream sourceFiles = projectParser.listSourceFiles(project, styles, ctx);
List sourceFileList = sourcesWithAutoDetectedStyles(sourceFiles);
return new InMemoryLargeSourceSet(sourceFileList);
}
protected List runRecipe(Recipe recipe, LargeSourceSet sourceSet, ExecutionContext ctx) {
getLog().info("Running recipe(s)...");
CsvDataTableStore csvDataTableStore = null;
if (exportDatatables) {
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss-SSS"));
Path datatableDirectoryPath = Paths.get("target", "rewrite", "datatables", timestamp);
getLog().info(String.format("Printing available datatables to: %s", datatableDirectoryPath));
csvDataTableStore = new CsvDataTableStore(datatableDirectoryPath);
DataTableExecutionContextView.view(ctx).setDataTableStore(csvDataTableStore);
}
RecipeRun recipeRun = recipe.run(sourceSet, ctx);
if (csvDataTableStore != null) {
csvDataTableStore.close();
}
return recipeRun.getChangeset().getAllResults().stream().filter(source -> {
// Remove ASTs originating from generated files
if (source.getBefore() != null) {
return !source.getBefore().getMarkers().findFirst(Generated.class).isPresent();
}
return true;
}).collect(toList());
}
private List sourcesWithAutoDetectedStyles(Stream sourceFiles) {
org.openrewrite.java.style.Autodetect.Detector javaDetector = org.openrewrite.java.style.Autodetect.detector();
org.openrewrite.kotlin.style.Autodetect.Detector kotlinDetector = org.openrewrite.kotlin.style.Autodetect.detector();
org.openrewrite.xml.style.Autodetect.Detector xmlDetector = org.openrewrite.xml.style.Autodetect.detector();
List sourceFileList = sourceFiles
.peek(s -> {
if (s instanceof K.CompilationUnit) {
kotlinDetector.sample(s);
} else if (s instanceof J.CompilationUnit) {
javaDetector.sample(s);
}
})
.peek(xmlDetector::sample)
.collect(toList());
Map, NamedStyles> stylesByType = new HashMap<>();
stylesByType.put(J.CompilationUnit.class, javaDetector.build());
stylesByType.put(K.CompilationUnit.class, kotlinDetector.build());
stylesByType.put(Xml.Document.class, xmlDetector.build());
return ListUtils.map(sourceFileList, applyAutodetectedStyle(stylesByType));
}
private UnaryOperator applyAutodetectedStyle(Map, NamedStyles> stylesByType) {
return before -> {
for (Map.Entry, NamedStyles> styleTypeEntry : stylesByType.entrySet()) {
if (styleTypeEntry.getKey().isAssignableFrom(before.getClass())) {
before = before.withMarkers(before.getMarkers().add(styleTypeEntry.getValue()));
}
}
return before;
};
}
private void merge(ClassLoader targetClassLoader, URLClassLoader sourceClassLoader) {
ClassRealm targetClassRealm;
try {
targetClassRealm = (ClassRealm) targetClassLoader;
} catch (ClassCastException e) {
getLog().warn("Could not merge ClassLoaders due to unexpected targetClassLoader type", e);
return;
}
Set existingVersionlessJars = new HashSet<>();
for (URL existingUrl : targetClassRealm.getURLs()) {
existingVersionlessJars.add(stripVersion(existingUrl));
}
for (URL newUrl : sourceClassLoader.getURLs()) {
if (!existingVersionlessJars.contains(stripVersion(newUrl))) {
targetClassRealm.addURL(newUrl);
}
}
}
private String stripVersion(URL jarUrl) {
return jarUrl.toString().replaceAll("/[^/]+/[^/]+\\.jar", "");
}
public static class ResultsContainer {
final Path projectRoot;
final List generated = new ArrayList<>();
final List deleted = new ArrayList<>();
final List moved = new ArrayList<>();
final List refactoredInPlace = new ArrayList<>();
public ResultsContainer(Path projectRoot, Collection results) {
this.projectRoot = projectRoot;
for (Result result : results) {
if (result.getBefore() == null && result.getAfter() == null) {
// This situation shouldn't happen / makes no sense, log and skip
continue;
}
if (result.getBefore() == null && result.getAfter() != null) {
generated.add(result);
} else if (result.getBefore() != null && result.getAfter() == null) {
deleted.add(result);
} else if (result.getBefore() != null && result.getAfter() != null && !result.getBefore().getSourcePath().equals(result.getAfter().getSourcePath())) {
moved.add(result);
} else {
FencedMarkerPrinter markerPrinter = new FencedMarkerPrinter();
String beforePrint = result.getBefore().printAll(new PrintOutputCapture<>(0, markerPrinter));
String afterPrint = result.getAfter().printAll(new PrintOutputCapture<>(0, markerPrinter));
if (!beforePrint.equals(afterPrint)) {
refactoredInPlace.add(result);
}
}
}
}
public @Nullable RuntimeException getFirstException() {
for (Result result : generated) {
for (RuntimeException error : getRecipeErrors(result)) {
return error;
}
}
for (Result result : deleted) {
for (RuntimeException error : getRecipeErrors(result)) {
return error;
}
}
for (Result result : moved) {
for (RuntimeException error : getRecipeErrors(result)) {
return error;
}
}
for (Result result : refactoredInPlace) {
for (RuntimeException error : getRecipeErrors(result)) {
return error;
}
}
return null;
}
private List getRecipeErrors(Result result) {
List exceptions = new ArrayList<>();
new TreeVisitor() {
@Override
public Tree preVisit(Tree tree, Integer integer) {
Markers markers = tree.getMarkers();
markers.findFirst(Markup.Error.class).ifPresent(e -> {
Optional sourceFile = Optional.ofNullable(getCursor().firstEnclosing(SourceFile.class));
String sourcePath = sourceFile.map(SourceFile::getSourcePath).map(Path::toString).orElse("");
exceptions.add(new RuntimeException("Error while visiting " + sourcePath + ": " + e.getDetail()));
});
return tree;
}
}.visit(result.getAfter(), 0);
return exceptions;
}
public Path getProjectRoot() {
return projectRoot;
}
public boolean isNotEmpty() {
return !generated.isEmpty() || !deleted.isEmpty() || !moved.isEmpty() || !refactoredInPlace.isEmpty();
}
/**
* List directories that are empty as a result of applying recipe changes
*/
public List newlyEmptyDirectories() {
Set maybeEmptyDirectories = new LinkedHashSet<>();
for (Result result : moved) {
assert result.getBefore() != null;
maybeEmptyDirectories.add(projectRoot.resolve(result.getBefore().getSourcePath()).getParent());
}
for (Result result : deleted) {
assert result.getBefore() != null;
maybeEmptyDirectories.add(projectRoot.resolve(result.getBefore().getSourcePath()).getParent());
}
if (maybeEmptyDirectories.isEmpty()) {
return emptyList();
}
List emptyDirectories = new ArrayList<>(maybeEmptyDirectories.size());
for (Path maybeEmptyDirectory : maybeEmptyDirectories) {
try (Stream contents = Files.list(maybeEmptyDirectory)) {
if (contents.findAny().isPresent()) {
continue;
}
Files.delete(maybeEmptyDirectory);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
return emptyDirectories;
}
/**
* Only retains output for markers of type {@code SearchResult} and {@code Markup}.
*/
private static class FencedMarkerPrinter implements PrintOutputCapture.MarkerPrinter {
@Override
public String beforeSyntax(Marker marker, Cursor cursor, UnaryOperator commentWrapper) {
return marker instanceof SearchResult || marker instanceof Markup ? "{{" + marker.getId() + "}}" : "";
}
@Override
public String afterSyntax(Marker marker, Cursor cursor, UnaryOperator commentWrapper) {
return marker instanceof SearchResult || marker instanceof Markup ? "{{" + marker.getId() + "}}" : "";
}
}
}
protected void logRecipesThatMadeChanges(Result result) {
String indent = " ";
String prefix = " ";
for (RecipeDescriptor recipeDescriptor : result.getRecipeDescriptorsThatMadeChanges()) {
logRecipe(recipeDescriptor, prefix);
prefix = prefix + indent;
}
}
private void logRecipe(RecipeDescriptor rd, String prefix) {
StringBuilder recipeString = new StringBuilder(prefix + rd.getName());
if (!rd.getOptions().isEmpty()) {
String opts = rd.getOptions().stream().map(option -> {
if (option.getValue() != null) {
return option.getName() + "=" + option.getValue();
}
return null;
}
).filter(Objects::nonNull).collect(joining(", "));
if (!opts.isEmpty()) {
recipeString.append(": {").append(opts).append("}");
}
}
log(recipeChangeLogLevel, recipeString.toString());
for (RecipeDescriptor rchild : rd.getRecipeList()) {
logRecipe(rchild, prefix + " ");
}
}
protected Duration estimateTimeSavedSum(Result result, Duration timeSaving) {
if (null != result.getTimeSavings()) {
return timeSaving.plus(result.getTimeSavings());
}
return timeSaving;
}
protected String formatDuration(Duration duration) {
return duration.toString()
.substring(2)
.replaceAll("(\\d[HMS])(?!$)", "$1 ")
.toLowerCase()
.trim();
}
}
================================================
FILE: src/main/java/org/openrewrite/maven/AbstractRewriteDryRunMojo.java
================================================
/*
* Copyright 2020 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.maven;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Result;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Base mojo for rewrite:dryRun and rewrite:dryRunNoFork.
*
* Generate warnings to the console for any recipe that would make changes, but do not make changes.
*/
public class AbstractRewriteDryRunMojo extends AbstractRewriteBaseRunMojo {
@Parameter(property = "reportOutputDirectory")
@Nullable
private String reportOutputDirectory;
/**
* Whether to throw an exception if there are any result changes produced.
*/
@Parameter(property = "failOnDryRunResults", defaultValue = "false")
private boolean failOnDryRunResults;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (rewriteSkip) {
getLog().info("Skipping execution");
putState(State.SKIPPED);
return;
}
putState(State.TO_BE_PROCESSED);
// If the plugin is configured to run over all projects (at the end of the build) only proceed if the plugin
// is being run on the last project.
if (!runPerSubmodule && !allProjectsMarked()) {
getLog().info("REWRITE: Delaying execution to the end of multi-module project for " +
project.getGroupId() + ":" +
project.getArtifactId()+ ":" +
project.getVersion());
return;
}
List throwables = new ArrayList<>();
ExecutionContext ctx = executionContext(throwables);
ResultsContainer results = listResults(ctx);
RuntimeException firstException = results.getFirstException();
if (firstException != null) {
getLog().error("The recipe produced an error. Please report this to the recipe author.");
throw firstException;
}
if (!throwables.isEmpty()) {
getLog().warn("The recipe produced " + throwables.size() + " warning(s). Please report this to the recipe author.");
if (!getLog().isDebugEnabled() && !exportDatatables) {
getLog().warn("Run with `--debug` or `-Drewrite.exportDatatables=true` to see all warnings.", throwables.get(0));
}
}
if (results.isNotEmpty()) {
Duration estimateTimeSaved = Duration.ZERO;
for (Result result : results.generated) {
assert result.getAfter() != null;
getLog().warn("These recipes would generate a new file " +
result.getAfter().getSourcePath() +
":");
logRecipesThatMadeChanges(result);
estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved);
}
for (Result result : results.deleted) {
assert result.getBefore() != null;
getLog().warn("These recipes would delete a file " +
result.getBefore().getSourcePath() +
":");
logRecipesThatMadeChanges(result);
estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved);
}
for (Result result : results.moved) {
assert result.getBefore() != null;
assert result.getAfter() != null;
getLog().warn("These recipes would move a file from " +
result.getBefore().getSourcePath() + " to " +
result.getAfter().getSourcePath() + ":");
logRecipesThatMadeChanges(result);
estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved);
}
for (Result result : results.refactoredInPlace) {
assert result.getBefore() != null;
getLog().warn("These recipes would make changes to " +
result.getBefore().getSourcePath() +
":");
logRecipesThatMadeChanges(result);
estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved);
}
Path outPath;
if (reportOutputDirectory != null) {
outPath = Paths.get(reportOutputDirectory);
} else if (runPerSubmodule) {
outPath = Paths.get(project.getBuild().getDirectory()).resolve("rewrite");
} else {
outPath = Paths.get(mavenSession.getTopLevelProject().getBuild().getDirectory()).resolve("rewrite");
}
try {
Files.createDirectories(outPath);
} catch (IOException e) {
throw new RuntimeException("Could not create the folder [ " + outPath + "].", e);
}
Path patchFile = outPath.resolve("rewrite.patch");
try (BufferedWriter writer = Files.newBufferedWriter(patchFile)) {
Stream.concat(
Stream.concat(results.generated.stream(), results.deleted.stream()),
Stream.concat(results.moved.stream(), results.refactoredInPlace.stream())
)
.map(Result::diff)
.forEach(diff -> {
try {
writer.write(diff + "\n");
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} catch (Exception e) {
throw new MojoExecutionException("Unable to generate rewrite result.", e);
}
getLog().warn("Patch file available:");
getLog().warn(" " + patchFile.normalize());
getLog().warn("Estimate time saved: " + formatDuration(estimateTimeSaved));
getLog().warn("Run 'mvn rewrite:run' to apply the recipes.");
if (failOnDryRunResults) {
throw new MojoExecutionException("Applying recipes would make changes. See logs for more details.");
}
} else {
getLog().info("Applying recipes would make no changes. No patch file generated.");
}
putState(State.PROCESSED);
}
}
================================================
FILE: src/main/java/org/openrewrite/maven/AbstractRewriteMojo.java
================================================
/*
* Copyright 2020 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.maven;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.rtinfo.RuntimeInformation;
import org.apache.maven.settings.crypto.SettingsDecrypter;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.artifact.Artifact;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.InMemoryExecutionContext;
import org.openrewrite.config.ClasspathScanningLoader;
import org.openrewrite.config.Environment;
import org.openrewrite.config.YamlResourceLoader;
import org.openrewrite.ipc.http.HttpSender;
import org.openrewrite.ipc.http.HttpUrlConnectionSender;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import static java.util.Collections.sort;
@SuppressWarnings("NotNullFieldNotInitialized")
public abstract class AbstractRewriteMojo extends ConfigurableRewriteMojo {
@Parameter(defaultValue = "${project}", readonly = true, required = true)
protected MavenProject project;
/**
* Whether to resolve properties in YAML configuration files, like{@code ${project.artifactId} }.
* Default true; set to false to disable.
*/
@Parameter(property = "rewrite.resolvePropertiesInYaml", defaultValue = "true")
protected boolean resolvePropertiesInYaml;
@Inject
protected RuntimeInformation runtime;
@Inject
protected SettingsDecrypter settingsDecrypter;
@Inject
protected RepositorySystem repositorySystem;
protected Environment environment() throws MojoExecutionException {
return environment(getRecipeArtifactCoordinatesClassloader());
}
static class Config {
final InputStream inputStream;
final URI uri;
Config(InputStream inputStream, URI uri) {
this.inputStream = inputStream;
this.uri = uri;
}
}
@Nullable
Config getConfig() throws IOException {
try {
URI uri = new URI(configLocation);
if (uri.getScheme() != null && uri.getScheme().startsWith("http")) {
HttpSender httpSender = new HttpUrlConnectionSender();
//noinspection resource
return new Config(httpSender.get(configLocation).send().getBody(), uri);
}
} catch (URISyntaxException e) {
// Try to load as a path
}
Path absoluteConfigLocation = Paths.get(configLocation);
if (!absoluteConfigLocation.isAbsolute()) {
absoluteConfigLocation = project.getBasedir().toPath().resolve(configLocation);
}
File rewriteConfig = absoluteConfigLocation.toFile();
if (rewriteConfig.exists()) {
return new Config(Files.newInputStream(rewriteConfig.toPath()), rewriteConfig.toURI());
}
getLog().debug("No rewrite configuration found at " + absoluteConfigLocation);
return null;
}
protected Environment environment(@Nullable ClassLoader recipeClassLoader) throws MojoExecutionException {
@Nullable Properties propertiesToResolve;
if (resolvePropertiesInYaml) {
Properties userProperties = mavenSession.getUserProperties();
if (userProperties.isEmpty()) {
propertiesToResolve = project.getProperties();
} else {
propertiesToResolve = new Properties(project.getProperties());
for (Map.Entry