Repository: openrewrite/rewrite-maven-plugin Branch: main Commit: 4985717de28e Files: 168 Total size: 378.1 KB Directory structure: gitextract_bkmjst1t/ ├── .claude/ │ └── settings.json ├── .editorconfig ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── bump-snapshots.yml │ ├── ci.yml │ ├── pages.yml │ ├── publish.yml │ ├── repository-backup.yml │ └── stale.yml ├── .gitignore ├── .mvn/ │ ├── develocity.xml │ ├── extensions.xml │ ├── licenseHeader.txt │ └── wrapper/ │ └── maven-wrapper.properties ├── .sdkmanrc ├── CLAUDE.md ├── LICENSE/ │ └── apache-license-v2.txt ├── README.md ├── mvnw ├── mvnw.cmd ├── pom.xml ├── rewrite.yml ├── src/ │ ├── main/ │ │ └── java/ │ │ └── org/ │ │ └── openrewrite/ │ │ └── maven/ │ │ ├── AbstractRewriteBaseRunMojo.java │ │ ├── AbstractRewriteDryRunMojo.java │ │ ├── AbstractRewriteMojo.java │ │ ├── AbstractRewriteRunMojo.java │ │ ├── ArtifactResolver.java │ │ ├── ConfigurableRewriteMojo.java │ │ ├── LogLevel.java │ │ ├── MavenLoggingMeterRegistry.java │ │ ├── MavenLoggingResolutionEventListener.java │ │ ├── MavenMojoProjectParser.java │ │ ├── MavenPomCacheBuilder.java │ │ ├── MeterRegistryProvider.java │ │ ├── RecipeCsvGenerateMojo.java │ │ ├── RewriteDiscoverMojo.java │ │ ├── RewriteDryRunMojo.java │ │ ├── RewriteDryRunNoForkMojo.java │ │ ├── RewriteRunMojo.java │ │ ├── RewriteRunNoForkMojo.java │ │ ├── RewriteTypeTableMojo.java │ │ ├── SanitizedMarkerPrinter.java │ │ └── package-info.java │ └── test/ │ ├── java/ │ │ └── org/ │ │ └── openrewrite/ │ │ └── maven/ │ │ ├── AbstractRewriteMojoTest.java │ │ ├── BasicIT.java │ │ ├── DiscoverNoActiveRecipeIT.java │ │ ├── KotlinIT.java │ │ ├── MavenCLIExtra.java │ │ ├── MavenMojoProjectParserIsExcludedTest.java │ │ ├── MavenMojoProjectParserTest.java │ │ ├── RecipeCsvGenerateIT.java │ │ ├── RewriteDiscoverIT.java │ │ ├── RewriteDryRunIT.java │ │ ├── RewriteRunIT.java │ │ ├── RewriteRunParallelIT.java │ │ ├── RewriteTypeTableIT.java │ │ └── jupiter/ │ │ └── extension/ │ │ ├── GitITExtension.java │ │ └── GitJupiterExtension.java │ ├── resources/ │ │ ├── .gitkeep │ │ └── junit-platform.properties │ └── resources-its/ │ └── org/ │ └── openrewrite/ │ └── maven/ │ ├── BasicIT/ │ │ ├── groupid_artifactid_should_be_ok/ │ │ │ └── pom.xml │ │ ├── null_check_profile_activation/ │ │ │ ├── pom.xml │ │ │ └── settings.xml │ │ ├── resolves_maven_properties_from_user_provided_system_properties/ │ │ │ └── pom.xml │ │ ├── resolves_settings/ │ │ │ ├── pom.xml │ │ │ └── settings-user.xml │ │ └── snapshot_ok/ │ │ └── pom.xml │ ├── DiscoverNoActiveRecipeIT/ │ │ └── single_project/ │ │ └── pom.xml │ ├── KotlinIT/ │ │ ├── kotlin_in_src_main_java/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── MyClass.kt │ │ └── kotlin_in_src_main_test/ │ │ ├── pom.xml │ │ └── src/ │ │ └── test/ │ │ └── java/ │ │ └── sample/ │ │ └── MyTest.kt │ ├── RecipeCsvGenerateIT/ │ │ ├── generates_csv_from_java_recipe/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── org/ │ │ │ └── openrewrite/ │ │ │ └── test/ │ │ │ └── SampleJavaRecipe.java │ │ └── generates_csv_from_yaml_recipe/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ └── resources/ │ │ └── META-INF/ │ │ └── rewrite/ │ │ └── rewrite.yml │ ├── RewriteDiscoverIT/ │ │ ├── RecipeLookup/ │ │ │ ├── rewrite_discover_detail/ │ │ │ │ └── pom.xml │ │ │ ├── rewrite_discover_recipe_lookup_case_insensitive/ │ │ │ │ └── pom.xml │ │ │ └── rewrite_discover_recursion/ │ │ │ └── pom.xml │ │ ├── rewrite_discover_default/ │ │ │ └── pom.xml │ │ ├── rewrite_discover_multi_module/ │ │ │ ├── a/ │ │ │ │ └── pom.xml │ │ │ ├── b/ │ │ │ │ └── pom.xml │ │ │ └── pom.xml │ │ └── rewrite_discover_rewrite_yml/ │ │ ├── pom.xml │ │ └── rewrite.yml │ ├── RewriteDryRunIT/ │ │ ├── fail_on_dry_run/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── BadSpacing.java │ │ ├── multi_module_project/ │ │ │ ├── a/ │ │ │ │ ├── pom.xml │ │ │ │ └── src/ │ │ │ │ └── main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ ├── MyInterface.java │ │ │ │ └── SimplifyBooleanSample.java │ │ │ ├── b/ │ │ │ │ ├── pom.xml │ │ │ │ └── src/ │ │ │ │ └── main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ └── EmptyBlockSample.java │ │ │ ├── pom.xml │ │ │ └── rewrite.yml │ │ ├── no_plugin_in_pom/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── SampleTest.java │ │ ├── recipe_order/ │ │ │ ├── pom.xml │ │ │ ├── rewrite.yml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ ├── EmptyBlockSample.java │ │ │ └── SimplifyBooleanSample.java │ │ └── single_project/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── sample/ │ │ ├── EmptyBlockSample.java │ │ └── SimplifyBooleanSample.java │ ├── RewriteRunIT/ │ │ ├── basedir_resource_no_plaintext_leak/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ └── Main.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── MainTest.java │ │ ├── checkstyle_inline_rules/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── SimplifyBooleanSample.java │ │ ├── cloud_suitability_project/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── resource/ │ │ │ └── some.jks │ │ ├── command_line_options/ │ │ │ └── pom.xml │ │ ├── command_line_options_json/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── SomeClass.java │ │ ├── container_masks/ │ │ │ ├── Containerfile │ │ │ ├── Dockerfile │ │ │ ├── build.dockerfile │ │ │ ├── containerfile.build │ │ │ ├── pom.xml │ │ │ └── rewrite.yml │ │ ├── datatable_export/ │ │ │ ├── pom.xml │ │ │ └── rewrite.yml │ │ ├── java_compiler_plugin_project/ │ │ │ ├── parent/ │ │ │ │ └── pom.xml │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── SimplifyBooleanSample.java │ │ ├── java_upgrade_project/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── MyInterface.java │ │ ├── lombok_jdk25_linkage_error/ │ │ │ ├── .mvn/ │ │ │ │ └── jvm.config │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ └── App.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── AppTest.java │ │ ├── multi_main_source_sets_project/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── additional-main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ └── AdditionalMainClass.java │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── MainClass.java │ │ ├── multi_module_project/ │ │ │ ├── a/ │ │ │ │ ├── pom.xml │ │ │ │ └── src/ │ │ │ │ └── main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ ├── MyInterface.java │ │ │ │ └── SimplifyBooleanSample.java │ │ │ ├── b/ │ │ │ │ ├── pom.xml │ │ │ │ └── src/ │ │ │ │ └── main/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ └── EmptyBlockSample.java │ │ │ ├── pom.xml │ │ │ └── rewrite.yml │ │ ├── multi_module_resources/ │ │ │ ├── a/ │ │ │ │ ├── pom.xml │ │ │ │ └── src/ │ │ │ │ └── main/ │ │ │ │ └── resources/ │ │ │ │ └── example.xml │ │ │ ├── pom.xml │ │ │ └── rewrite.yml │ │ ├── multi_source_sets_project/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ ├── integration-test/ │ │ │ │ └── java/ │ │ │ │ └── sample/ │ │ │ │ └── IntegrationTest.java │ │ │ └── test/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── RegularTest.java │ │ ├── plaintext_masks/ │ │ │ ├── .in-root │ │ │ ├── from-default-list.py │ │ │ ├── in-root.ignored │ │ │ ├── pom.xml │ │ │ ├── rewrite.yml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ ├── Dummy.java │ │ │ └── in-src.ext │ │ ├── recipe_project/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── ThrowingRecipe.java │ │ └── single_project/ │ │ ├── pom.xml │ │ └── src/ │ │ └── main/ │ │ └── java/ │ │ └── sample/ │ │ ├── EmptyBlockSample.java │ │ └── SimplifyBooleanSample.java │ ├── RewriteRunParallelIT/ │ │ └── multi_module_project/ │ │ ├── a/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ ├── MyInterface.java │ │ │ └── SimplifyBooleanSample.java │ │ ├── b/ │ │ │ ├── pom.xml │ │ │ └── src/ │ │ │ └── main/ │ │ │ └── java/ │ │ │ └── sample/ │ │ │ └── EmptyBlockSample.java │ │ ├── pom.xml │ │ └── rewrite.yml │ └── RewriteTypeTableIT/ │ └── typetable_default/ │ └── pom.xml └── suppressions.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .claude/settings.json ================================================ { "permissions": { "allow": [ "Bash(./gradlew:*)", "Bash(cat:*)", "Bash(echo:*)", "Bash(find:*)", "Bash(gh:*)", "Bash(git:*)", "Bash(grep:*)", "Bash(javac:*)", "Bash(mv:*)", "Bash(npm test:*)", "Bash(rg:*)", "Bash(rm:*)", "Bash(timeout:*)", "WebFetch(domain:github.com)", "mcp__github__get_issue", "mcp__github__get_issue_comments", "mcp__github__get_pull_request", "mcp__github__get_pull_request_comments", "mcp__idea__find_files_by_name_substring", "mcp__idea__get_file_text_by_path", "mcp__idea__get_open_in_editor_file_path", "mcp__idea__get_open_in_editor_file_text", "mcp__idea__get_selected_in_editor_text", "mcp__idea__list_directory_tree_in_folder", "mcp__idea__list_files_in_folder", "mcp__idea__open_file_in_editor", "mcp__idea__replace_selected_text", "mcp__idea__replace_specific_text", "mcp__idea__search_in_files_content" ], "deny": [] } } ================================================ FILE: .editorconfig ================================================ root = true [*] insert_final_newline = true trim_trailing_whitespace = true [src/test*/java/**.java] indent_size = 4 ij_continuation_indent_size = 2 ================================================ FILE: .github/dependabot.yml ================================================ --- version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: weekly commit-message: prefix: "chore(ci)" - package-ecosystem: maven directory: / schedule: interval: weekly commit-message: prefix: "chore(ci)" ignore: - dependency-name: "com.puppycrawl.tools:checkstyle" ================================================ FILE: .github/workflows/bump-snapshots.yml ================================================ --- name: bump-snapshots on: workflow_dispatch: {} schedule: - cron: 0 11 * * THU jobs: bump-snapshots: timeout-minutes: 30 runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - uses: actions/setup-java@v5 with: distribution: temurin java-version: 17 cache: maven server-id: ossrh settings-path: ${{ github.workspace }} - name: configure-git-user run: | git config user.email "team@moderne.io" git config user.name "team-moderne[bot]" - name: bump-rewrite-properties-to-snapshots run: | ./mvnw versions:update-properties -DincludeProperties=rewrite.version,rewrite-polyglot.version -DallowSnapshots=true git diff-index --quiet HEAD pom.xml || (git commit -m "Bump rewrite.version property" pom.xml && git push origin main) ================================================ FILE: .github/workflows/ci.yml ================================================ --- name: ci on: push: branches: - main tags-ignore: - "*" pull_request: branches: - main workflow_dispatch: {} schedule: - cron: 0 17 * * * concurrency: group: ci-${{ github.ref }} cancel-in-progress: true env: GRADLE_ENTERPRISE_CACHE_USERNAME: ${{ secrets.gradle_enterprise_cache_username }} GRADLE_ENTERPRISE_CACHE_PASSWORD: ${{ secrets.gradle_enterprise_cache_password }} DEVELOCITY_ACCESS_KEY: ${{ secrets.gradle_enterprise_access_key }} jobs: build: runs-on: ubuntu-latest timeout-minutes: 30 steps: - uses: actions/checkout@v6 - uses: actions/setup-java@v5 with: distribution: temurin java-version: 17 cache: maven server-id: ossrh settings-path: ${{ github.workspace }} server-username: SONATYPE_USERNAME server-password: SONATYPE_PASSWORD gpg-private-key: ${{ secrets.OSSRH_SIGNING_KEY }} gpg-passphrase: SONATYPE_SIGNING_PASSWORD - name: validate-develocity-access-key run: | if [ -n "$DEVELOCITY_ACCESS_KEY" ] && ! echo "$DEVELOCITY_ACCESS_KEY" | grep -q '='; then echo "DEVELOCITY_ACCESS_KEY is malformed (missing server-host= prefix), unsetting" echo "DEVELOCITY_ACCESS_KEY=" >> $GITHUB_ENV fi - name: build run: ./mvnw --show-version --no-transfer-progress --update-snapshots clean verify --file=pom.xml --fail-at-end --batch-mode -Dstyle.color=always - name: publish-snapshots if: github.event_name != 'pull_request' run: ./mvnw --show-version --no-transfer-progress --settings=${{ github.workspace }}/settings.xml --file=pom.xml --batch-mode -Dstyle.color=always --activate-profiles=sign-artifacts clean deploy -DskipTests env: GITHUB_TOKEN: ${{ github.token }} SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.SONATYPE_TOKEN }} SONATYPE_SIGNING_PASSWORD: ${{ secrets.OSSRH_SIGNING_PASSWORD }} - name: slack-notification if: failure() && github.event_name == 'schedule' && (github.repository_owner == 'openrewrite' || github.repository_owner == 'moderneinc') uses: rtCamp/action-slack-notify@e31e87e03dd19038e411e38ae27cbad084a90661 continue-on-error: true env: SLACK_WEBHOOK: ${{ secrets.OPS_GITHUB_ACTIONS_WEBHOOK }} MSG_MINIMAL: true SLACK_MESSAGE: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} SLACK_USERNAME: ${{ github.repository }} CI failure SLACK_COLOR: failure SLACK_FOOTER: '' ================================================ FILE: .github/workflows/pages.yml ================================================ # Simple workflow for deploying static content to GitHub Pages name: Deploy plugin docs to Pages on: push: tags: - v* workflow_dispatch: {} workflow_run: workflows: ["publish"] types: - completed # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. concurrency: group: "pages" cancel-in-progress: false jobs: pages: environment: name: github-pages url: ${{steps.deployment.outputs.page_url}} runs-on: ubuntu-latest timeout-minutes: 30 steps: - uses: actions/checkout@v6 - uses: actions/setup-java@v5 with: distribution: temurin java-version: 17 cache: maven - name: site run: ./mvnw --show-version --no-transfer-progress --update-snapshots clean site --file=pom.xml --fail-at-end --batch-mode -Dstyle.color=always -Ddependency-check.skip=true - uses: actions/configure-pages@v6 - uses: actions/upload-pages-artifact@v5 with: path: target/site - uses: actions/deploy-pages@v5 ================================================ FILE: .github/workflows/publish.yml ================================================ --- name: publish on: workflow_dispatch: inputs: version: description: 'Project version to set before releasing (e.g. 6.33.0-SNAPSHOT). Leave empty to release the current version.' required: false type: string jobs: release: runs-on: ubuntu-latest timeout-minutes: 30 steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - uses: actions/setup-java@v5 with: distribution: temurin java-version: 17 cache: maven server-id: ossrh settings-path: ${{ github.workspace }} server-username: SONATYPE_USERNAME server-password: SONATYPE_PASSWORD gpg-private-key: ${{ secrets.OSSRH_SIGNING_KEY }} gpg-passphrase: SONATYPE_SIGNING_PASSWORD - name: configure-git-user run: | git config user.email "team@moderne.io" git config user.name "team-moderne[bot]" - name: set-project-version if: ${{ inputs.version != '' }} run: ./mvnw versions:set -DnewVersion=${{ inputs.version }} -DgenerateBackupFiles=false - name: bump-rewrite-properties-to-releases run: | ./mvnw versions:update-properties -DincludeProperties=rewrite.version,rewrite-polyglot.version -DallowDowngrade=true git diff-index --quiet HEAD pom.xml || git commit -m "Bump rewrite.version property" pom.xml && rm -f pom.xml.versionsBackup - name: publish-release run: ./mvnw --show-version --settings=${{ github.workspace }}/settings.xml --file=pom.xml --activate-profiles=sign-artifacts,release,release-automation help:active-profiles release:prepare release:perform --batch-mode -Dstyle.color=always env: GITHUB_TOKEN: ${{ github.token }} SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} SONATYPE_PASSWORD: ${{ secrets.SONATYPE_TOKEN }} SONATYPE_SIGNING_PASSWORD: ${{ secrets.OSSRH_SIGNING_PASSWORD }} - name: github-release if: ${{ success() }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | export tag=$(git describe --tags --abbrev=0) gh release create "$tag" \ --repo="$GITHUB_REPOSITORY" \ --title="${tag#v}" \ --generate-notes - name: rollback if: ${{ failure() }} run: ./mvnw --show-version --settings=${{github.workspace}}/settings.xml --file=pom.xml --activate-profiles=sign-artifacts,release,release-automation help:active-profiles release:rollback --batch-mode -Dstyle.color=always env: GITHUB_TOKEN: ${{ github.token }} - name: bump-rewrite-properties-to-snapshots run: | ./mvnw versions:update-properties -DincludeProperties=rewrite.version,rewrite-polyglot.version -DallowSnapshots=true git diff-index --quiet HEAD pom.xml || (git commit -m "Bump rewrite.version property" pom.xml && git push origin main && rm -f pom.xml.versionsBackup) ================================================ FILE: .github/workflows/repository-backup.yml ================================================ --- name: repository-backup on: workflow_dispatch: {} schedule: - cron: 0 17 * * * concurrency: group: backup-${{ github.ref }} cancel-in-progress: false jobs: repository-backup: uses: openrewrite/gh-automation/.github/workflows/repository-backup.yml@main secrets: bucket_mirror_target: ${{ secrets.S3_GITHUB_REPOSITORY_BACKUPS_BUCKET_NAME }} bucket_access_key_id: ${{ secrets.S3_GITHUB_REPOSITORY_BACKUPS_ACCESS_KEY_ID }} bucket_secret_access_key: ${{ secrets.S3_GITHUB_REPOSITORY_BACKUPS_SECRET_ACCESS_KEY }} ================================================ FILE: .github/workflows/stale.yml ================================================ --- name: stale on: workflow_dispatch: {} schedule: - cron: 36 4 * * 1 jobs: build: uses: openrewrite/gh-automation/.github/workflows/stale.yml@main ================================================ FILE: .gitignore ================================================ build/ target/ ry/ release.properties pom.xml.releaseBackup pom.xml.versionsBackup .idea/ *.iml .classpath .project .settings .vscode/ .mvn/.develocity/ # Moderne CLI .moderne/* !.moderne/context/ ================================================ FILE: .mvn/develocity.xml ================================================ https://ge.openrewrite.org/ true true #{isTrue(env['CI'])} #{env['GRADLE_ENTERPRISE_CACHE_USERNAME']} #{env['GRADLE_ENTERPRISE_CACHE_PASSWORD']} ================================================ FILE: .mvn/extensions.xml ================================================ com.gradle develocity-maven-extension 2.2.1 ================================================ FILE: .mvn/licenseHeader.txt ================================================ Copyright ${year} 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. ================================================ 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 ================================================

OpenRewrite Logo

rewrite-maven-plugin

[![ci](https://github.com/openrewrite/rewrite-maven-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/openrewrite/rewrite-maven-plugin/actions/workflows/ci.yml) [![Maven Central](https://img.shields.io/maven-central/v/org.openrewrite.maven/rewrite-maven-plugin.svg)](https://mvnrepository.com/artifact/org.openrewrite.maven/rewrite-maven-plugin) [![Contributing Guide](https://img.shields.io/badge/Contributing-Guide-informational)](https://github.com/openrewrite/.github/blob/main/CONTRIBUTING.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.maven rewrite-maven-plugin org.openrewrite.java.format.AutoFormat ``` If wanting to leverage recipes from other dependencies: ```xml ... org.openrewrite.maven rewrite-maven-plugin org.openrewrite.java.testing.junit5.JUnit5BestPractices org.openrewrite.github.ActionsSetupJavaAdoptOpenJDKToTemurin org.openrewrite.recipe rewrite-testing-frameworks org.openrewrite.recipe rewrite-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.maven rewrite-maven-plugin 4.17.0-SNAPSHOT org.openrewrite.java.logging.slf4j.Log4j2ToSlf4j org.openrewrite.recipe rewrite-testing-frameworks 1.1.0-SNAPSHOT ossrh-snapshots https://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.0 org.openrewrite.maven rewrite-maven-plugin 6.40.0-SNAPSHOT maven-plugin rewrite-maven-plugin Eliminate technical debt. At build time. https://openrewrite.github.io/rewrite-maven-plugin/ 2020 Moderne, Inc. https://moderne.io/ The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt Jonathan Schneider https://github.com/jkschneider jkschneider 3.3.1 scm:git:https://github.com/openrewrite/rewrite-maven-plugin.git ${developerConnectionUrl} https://github.com/openrewrite/rewrite-maven-plugin/tree/main HEAD GitHub Issues https://github.com/openrewrite/rewrite-maven-plugin/issues ossrh https://central.sonatype.com/repository/maven-snapshots ossrh https://oss.sonatype.org/service/local/staging/deploy/maven2 8.82.0-SNAPSHOT 2.11.0-SNAPSHOT scm:git:ssh://git@github.com/openrewrite/rewrite-maven-plugin.git UTF-8 8 ${maven.compiler.source} 17 2.21.3 8.8.1 0.13.1 3.9.15 3.3.1 3.15.2 com.fasterxml.jackson jackson-bom ${jackson-bom.version} pom import org.junit junit-bom 6.0.3 import pom org.assertj assertj-bom 3.27.7 import pom org.openrewrite rewrite-bom ${rewrite.version} import pom org.codehaus.plexus plexus-utils 3.6.1 org.apache.maven maven-api-meta 4.0.0-rc-1 provided org.apache.maven maven-api-xml 4.0.0-rc-5 provided org.apache.maven maven-xml-impl 4.0.0-beta-5 provided org.openrewrite rewrite-java org.openrewrite rewrite-java-8 org.openrewrite rewrite-java-11 org.openrewrite rewrite-java-17 org.openrewrite rewrite-java-21 org.openrewrite rewrite-java-25 org.openrewrite rewrite-groovy org.openrewrite rewrite-kotlin org.openrewrite rewrite-xml org.openrewrite rewrite-maven org.openrewrite rewrite-polyglot ${rewrite-polyglot.version} org.codehaus.plexus plexus-xml 4.1.1 io.micrometer micrometer-core 1.16.5 org.rocksdb rocksdbjni ${rocksdbjni.version} org.apache.maven maven-plugin-api ${maven-dependencies.version} provided org.apache.maven maven-core ${maven-dependencies.version} provided org.apache.maven maven-settings ${maven-dependencies.version} provided org.apache.maven maven-model ${maven-dependencies.version} provided org.apache.maven.plugin-tools maven-plugin-annotations ${maven-plugin-tools.version} provided org.junit.jupiter junit-jupiter-api test org.junit.jupiter junit-jupiter-engine test org.junit.jupiter junit-jupiter-params test com.soebes.itf.jupiter.extension itf-jupiter-extension ${itf-maven.version} test org.assertj assertj-core test com.soebes.itf.jupiter.extension itf-assertj ${itf-maven.version} test com.soebes.itf.jupiter.extension itf-extension-maven ${itf-maven.version} test ossrh-snapshots https://central.sonatype.com/repository/maven-snapshots true false src/test/resources false src/test/resources-its true org.apache.maven.plugins maven-enforcer-plugin 3.6.2 17 3.9.6 enforce enforce org.apache.maven.plugins maven-site-plugin 4.0.0-M16 com.soebes.itf.jupiter.extension itf-maven-plugin ${itf-maven.version} true installing pre-integration-test install resources-its org.apache.maven.plugins maven-failsafe-plugin 3.5.5 integration-test verify org.apache.maven.plugins maven-plugin-plugin ${maven-plugin-tools.version} rewrite 8 org.ow2.asm asm 9.9.1 generate-helpmojo helpmojo org.apache.maven.plugins maven-compiler-plugin 3.15.0 -Xlint:deprecation -Xlint:unchecked none org.apache.maven.plugins maven-javadoc-plugin 3.12.0 prepare-package javadoc jar org.apache.maven.plugins maven-source-plugin 3.4.0 prepare-package aggregate jar org.apache.maven.plugins maven-release-plugin ${maven-release-plugin.version} release v@{project.version} SemVerVersionPolicy org.apache.maven.release maven-release-semver-policy ${maven-release-plugin.version} com.mycila license-maven-plugin 4.6
.mvn/licenseHeader.txt
*.xml suppressions.xml **/README.md **/.sdkmanrc LICENSE/apache-license-v2.txt src/test/resources-its/** src/test/resources/** src/main/resources/** .moderne/ .mvn/
com.mycila license-maven-plugin-git 4.6 first format process-sources second check verify
org.owasp dependency-check-maven 12.2.2 ${env.NVD_API_KEY} 9 suppressions.xml false
org.apache.maven.plugins maven-plugin-report-plugin ${maven-plugin-tools.version} sign-artifacts org.apache.maven.plugins maven-gpg-plugin 3.2.8 sign-artifacts verify sign --pinentry-mode loopback release org.sonatype.plugins nexus-staging-maven-plugin 1.7.0 true ossrh https://ossrh-staging-api.central.sonatype.com/ true 20 true true release-automation scm: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 entry : userProperties.entrySet()) { propertiesToResolve.put(entry.getKey(), entry.getValue()); } } } else { propertiesToResolve = null; } Environment.Builder env = Environment.builder(propertiesToResolve); if (recipeClassLoader == null) { env.scanRuntimeClasspath() .scanUserHome(); } else { env.load(new ClasspathScanningLoader(propertiesToResolve, recipeClassLoader)); } try { Config rewriteConfig = getConfig(); if (rewriteConfig != null) { try (InputStream is = rewriteConfig.inputStream) { env.load(new YamlResourceLoader(is, rewriteConfig.uri, propertiesToResolve)); } } } catch (IOException e) { throw new MojoExecutionException("Unable to load rewrite configuration", e); } return env.build(); } protected ExecutionContext executionContext(List throwables) { return new InMemoryExecutionContext(t -> { getLog().debug(t); throwables.add(t); }); } protected Path getBuildRoot() { Path localRepositoryFolder = Paths.get(mavenSession.getLocalRepository().getBasedir()).normalize(); Set baseFolders = new HashSet<>(); for (MavenProject project : mavenSession.getAllProjects()) { collectBasePaths(project, baseFolders, localRepositoryFolder); } if (!baseFolders.isEmpty()) { List sortedPaths = new ArrayList<>(baseFolders); sort(sortedPaths); return sortedPaths.get(0); } return Paths.get(mavenSession.getExecutionRootDirectory()); } private void collectBasePaths(MavenProject project, Set paths, Path localRepository) { Path baseDir = project.getBasedir() == null ? null : project.getBasedir().toPath().normalize(); if (baseDir == null || baseDir.startsWith(localRepository) || paths.contains(baseDir)) { return; } paths.add(baseDir); MavenProject parent = project.getParent(); while (parent != null && parent.getBasedir() != null) { collectBasePaths(parent, paths, localRepository); parent = parent.getParent(); } } protected @Nullable URLClassLoader getRecipeArtifactCoordinatesClassloader() throws MojoExecutionException { if (getRecipeArtifactCoordinates().isEmpty()) { return null; } ArtifactResolver resolver = new ArtifactResolver(repositorySystem, mavenSession); Set artifacts = new HashSet<>(); for (String coordinate : getRecipeArtifactCoordinates()) { artifacts.add(resolver.createArtifact(coordinate)); } Set resolvedArtifacts = resolver.resolveArtifactsAndDependencies(artifacts); URL[] urls = resolvedArtifacts.stream() .map(Artifact::getFile) .map(File::toURI) .map(uri -> { try { return uri.toURL(); } catch (MalformedURLException e) { throw new RuntimeException("Failed to resolve artifacts from rewrite.recipeArtifactCoordinates", e); } }) .toArray(URL[]::new); return new URLClassLoader( urls, AbstractRewriteMojo.class.getClassLoader() ); } } ================================================ FILE: src/main/java/org/openrewrite/maven/AbstractRewriteRunMojo.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.openrewrite.ExecutionContext; import org.openrewrite.FileAttributes; import org.openrewrite.PrintOutputCapture; import org.openrewrite.Result; import org.openrewrite.binary.Binary; import org.openrewrite.quark.Quark; import org.openrewrite.remote.Remote; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.ArrayList; import java.util.List; /** * Run the configured recipes and apply the changes locally. *

* Base mojo for rewrite:run and rewrite:runNoFork. */ public class AbstractRewriteRunMojo extends AbstractRewriteBaseRunMojo { @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; log(recipeChangeLogLevel, "Generated new file " + result.getAfter().getSourcePath().normalize() + " by:"); logRecipesThatMadeChanges(result); estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved); } for (Result result : results.deleted) { assert result.getBefore() != null; log(recipeChangeLogLevel, "Deleted file " + result.getBefore().getSourcePath().normalize() + " by:"); logRecipesThatMadeChanges(result); estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved); } for (Result result : results.moved) { assert result.getAfter() != null; assert result.getBefore() != null; log(recipeChangeLogLevel, "File has been moved from " + result.getBefore().getSourcePath().normalize() + " to " + result.getAfter().getSourcePath().normalize() + " by:"); logRecipesThatMadeChanges(result); estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved); } for (Result result : results.refactoredInPlace) { assert result.getBefore() != null; log(recipeChangeLogLevel, "Changes have been made to " + result.getBefore().getSourcePath().normalize() + " by:"); logRecipesThatMadeChanges(result); estimateTimeSaved = estimateTimeSavedSum(result, estimateTimeSaved); } log(recipeChangeLogLevel, "Please review and commit the results."); log(recipeChangeLogLevel, "Estimate time saved: " + formatDuration(estimateTimeSaved)); try { for (Result result : results.generated) { assert result.getAfter() != null; writeAfter(results.getProjectRoot(), result, ctx); } for (Result result : results.deleted) { assert result.getBefore() != null; Path originalLocation = results.getProjectRoot().resolve(result.getBefore().getSourcePath()).normalize(); boolean deleteSucceeded = originalLocation.toFile().delete(); if (!deleteSucceeded) { throw new IOException("Unable to delete file " + originalLocation.toAbsolutePath()); } } for (Result result : results.moved) { // Should we try to use git to move the file first, and only if that fails fall back to this? assert result.getBefore() != null; Path originalLocation = results.getProjectRoot().resolve(result.getBefore().getSourcePath()); File originalParentDir = originalLocation.toFile().getParentFile(); assert result.getAfter() != null; // Ensure directories exist in case something was moved into a hitherto non-existent package Path afterLocation = results.getProjectRoot().resolve(result.getAfter().getSourcePath()); File afterParentDir = afterLocation.toFile().getParentFile(); // Rename the directory if its name case has been changed, e.g. camel case to lower case. if (afterParentDir.exists() && afterParentDir.getAbsolutePath().equalsIgnoreCase((originalParentDir.getAbsolutePath())) && !afterParentDir.getAbsolutePath().equals(originalParentDir.getAbsolutePath())) { if (!originalParentDir.renameTo(afterParentDir)) { throw new RuntimeException("Unable to rename directory from " + originalParentDir.getAbsolutePath() + " To: " + afterParentDir.getAbsolutePath()); } } else if (!afterParentDir.exists() && !afterParentDir.mkdirs()) { throw new RuntimeException("Unable to create directory " + afterParentDir.getAbsolutePath()); } if (result.getAfter() instanceof Quark) { // We don't know the contents of a Quark, but we can move it Files.move(originalLocation, results.getProjectRoot().resolve(result.getAfter().getSourcePath())); } else { // On Mac this can return "false" even when the file was deleted, so skip the check //noinspection ResultOfMethodCallIgnored originalLocation.toFile().delete(); writeAfter(results.getProjectRoot(), result, ctx); } } for (Result result : results.refactoredInPlace) { assert result.getBefore() != null; assert result.getAfter() != null; writeAfter(results.getProjectRoot(), result, ctx); } List emptyDirectories = results.newlyEmptyDirectories(); if (!emptyDirectories.isEmpty()) { getLog().info("Removing " + emptyDirectories.size() + " newly empty directories:"); for (Path emptyDirectory : emptyDirectories) { getLog().info(" " + emptyDirectory); Files.delete(emptyDirectory); } } } catch (IOException e) { throw new RuntimeException("Unable to rewrite source files", e); } } putState(State.PROCESSED); } private static void writeAfter(Path root, Result result, ExecutionContext ctx) { if (result.getAfter() == null || result.getAfter() instanceof Quark) { return; } Path targetPath = root.resolve(result.getAfter().getSourcePath()); File targetFile = targetPath.toFile(); if (!targetFile.getParentFile().exists()) { //noinspection ResultOfMethodCallIgnored targetFile.getParentFile().mkdirs(); } if (result.getAfter() instanceof Binary) { try (FileOutputStream sourceFileWriter = new FileOutputStream(targetFile)) { sourceFileWriter.write(((Binary) result.getAfter()).getBytes()); } catch (IOException e) { throw new UncheckedIOException("Unable to rewrite source files", e); } } else if (result.getAfter() instanceof Remote) { Remote remote = (Remote) result.getAfter(); try (FileOutputStream sourceFileWriter = new FileOutputStream(targetFile)) { InputStream source = remote.getInputStream(ctx); byte[] buf = new byte[4096]; int length; while ((length = source.read(buf)) > 0) { sourceFileWriter.write(buf, 0, length); } } catch (IOException e) { throw new UncheckedIOException("Unable to rewrite source files", e); } } else if (!(result.getAfter() instanceof Quark)) { // Don't attempt to write to a Quark; it has already been logged as change that has been made Charset charset = result.getAfter().getCharset() == null ? StandardCharsets.UTF_8 : result.getAfter().getCharset(); try (BufferedWriter sourceFileWriter = Files.newBufferedWriter(targetPath, charset)) { sourceFileWriter.write(result.getAfter().printAll(new PrintOutputCapture<>(0, new SanitizedMarkerPrinter()))); } catch (IOException e) { throw new UncheckedIOException("Unable to rewrite source files", e); } } if (result.getAfter().getFileAttributes() != null) { FileAttributes fileAttributes = result.getAfter().getFileAttributes(); if (targetFile.canRead() != fileAttributes.isReadable()) { //noinspection ResultOfMethodCallIgnored targetFile.setReadable(fileAttributes.isReadable()); } if (targetFile.canWrite() != fileAttributes.isWritable()) { //noinspection ResultOfMethodCallIgnored targetFile.setWritable(fileAttributes.isWritable()); } if (targetFile.canExecute() != fileAttributes.isExecutable()) { //noinspection ResultOfMethodCallIgnored targetFile.setExecutable(fileAttributes.isExecutable()); } } } } ================================================ FILE: src/main/java/org/openrewrite/maven/ArtifactResolver.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.RepositoryUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoExecutionException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.collection.CollectRequest; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.DependencyResult; import org.eclipse.aether.util.artifact.JavaScopes; import java.util.HashSet; import java.util.List; import java.util.Set; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toList; public class ArtifactResolver { private final RepositorySystem repositorySystem; private final RepositorySystemSession repositorySystemSession; private final List remoteRepositories; public ArtifactResolver(RepositorySystem repositorySystem, MavenSession session) { this.repositorySystem = repositorySystem; this.repositorySystemSession = session.getRepositorySession(); this.remoteRepositories = RepositoryUtils.toRepos(session.getCurrentProject().getRemoteArtifactRepositories()); } public Artifact createArtifact(String coordinates) throws MojoExecutionException { String[] parts = coordinates.split(":"); if (parts.length < 3) { throw new MojoExecutionException("Must include at least groupId:artifactId:version in artifact coordinates" + coordinates); } return new DefaultArtifact(parts[0], parts[1], null, "jar", parts[2]); } public Set resolveArtifactsAndDependencies(Set artifacts) throws MojoExecutionException { if (artifacts.isEmpty()) { return emptySet(); } Set elements = new HashSet<>(); try { List dependencies = artifacts.stream().map(a -> new Dependency(a, JavaScopes.RUNTIME)).collect(toList()); CollectRequest collectRequest = new CollectRequest(dependencies, emptyList(), remoteRepositories); DependencyRequest dependencyRequest = new DependencyRequest(); dependencyRequest.setCollectRequest(collectRequest); DependencyResult dependencyResult = repositorySystem.resolveDependencies(repositorySystemSession, dependencyRequest); for (ArtifactResult resolved : dependencyResult.getArtifactResults()) { elements.add(resolved.getArtifact()); } return elements; } catch (DependencyResolutionException e) { throw new MojoExecutionException("Failed to resolve requested artifacts transitive dependencies.", e); } } } ================================================ FILE: src/main/java/org/openrewrite/maven/ConfigurableRewriteMojo.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.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.MXSerializer; import org.intellij.lang.annotations.Language; import org.jspecify.annotations.Nullable; import org.openrewrite.config.Environment; import org.openrewrite.style.NamedStyles; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableSet; import static java.util.stream.Collectors.toCollection; import static org.openrewrite.java.style.CheckstyleConfigLoader.loadCheckstyleConfig; @SuppressWarnings("FieldMayBeFinal") public abstract class ConfigurableRewriteMojo extends AbstractMojo { private static final String CHECKSTYLE_DOCTYPE = "module PUBLIC " + "\"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN\" " + "\"https://checkstyle.org/dtds/configuration_1_3.dtd\""; @Parameter(property = "rewrite.configLocation", alias = "configLocation", defaultValue = "${maven.multiModuleProjectDirectory}/rewrite.yml") protected String configLocation; @Parameter(property = "rewrite.activeRecipes") @Nullable protected LinkedHashSet activeRecipes; @Parameter(property = "rewrite.activeStyles") @Nullable protected LinkedHashSet activeStyles; @Parameter(property = "rewrite.pomCacheEnabled", alias = "pomCacheEnabled", defaultValue = "true") protected boolean pomCacheEnabled; @Parameter(property = "rewrite.pomCacheDirectory", alias = "pomCacheDirectory") @Nullable protected String pomCacheDirectory; @Parameter(property = "rewrite.skip", defaultValue = "false") protected boolean rewriteSkip; /** * When enabled, skip parsing Maven `pom.xml`s, and any transitive poms, as source files. * This can be an efficiency improvement in certain situations. */ @Parameter(property = "skipMavenParsing", defaultValue = "false") protected boolean skipMavenParsing; @Parameter(property = "rewrite.checkstyleConfigFile", alias = "checkstyleConfigFile") @Nullable protected String checkstyleConfigFile; @Parameter(property = "rewrite.checkstyleDetectionEnabled", alias = "checkstyleDetectionEnabled", defaultValue = "true") protected boolean checkstyleDetectionEnabled; @Parameter(property = "rewrite.exclusions") @Nullable private LinkedHashSet exclusions; protected Set getExclusions() { return getCleanedSet(exclusions); } /** * Override default plain text masks. If this is specified, * {@code rewrite.additionalPlainTextMasks} will have no effect. */ @Parameter(property = "rewrite.plainTextMasks") @Nullable private LinkedHashSet plainTextMasks; /** * Allows adding additional plain text masks without overriding * the defaults. */ @Parameter(property = "rewrite.additionalPlainTextMasks") @Nullable private LinkedHashSet additionalPlainTextMasks; protected Set getPlainTextMasks() { Set masks = getCleanedSet(plainTextMasks); if (!masks.isEmpty()) { return masks; } //If not defined, use a default set of masks masks = new HashSet<>(Arrays.asList( "**/*.adoc", "**/*.aj", "**/*.bash", "**/*.bat", "**/CODEOWNERS", "**/*.css", "**/*.config", "**/[dD]ockerfile*", "**/*.[dD]ockerfile", "**/*[cC]ontainerfile*", "**/*.[cC]ontainerfile", "**/*.env", "**/.gitattributes", "**/.gitignore", "**/*.htm*", "**/gradlew", "**/.java-version", "**/*.jelly", "**/*.jsp", "**/*.ksh", "**/*.lock", "**/lombok.config", "**/[mM]akefile", "**/*.md", "**/*.mf", "**/META-INF/services/**", "**/META-INF/spring/**", "**/META-INF/spring.factories", "**/mvnw", "**/mvnw.cmd", "**/*.qute.java", "**/.sdkmanrc", "**/*.sh", "**/*.sql", "**/*.svg", "**/*.tsx", "**/*.txt", "**/*.py" )); masks.addAll(getCleanedSet(additionalPlainTextMasks)); return unmodifiableSet(masks); } @Parameter(property = "sizeThresholdMb", defaultValue = "10") protected int sizeThresholdMb; /** * Whether to throw an exception if an activeRecipe fails configuration validation. * This may happen if the activeRecipe is improperly configured, or any downstream recipes are improperly configured. *

* For the time, this default is "false" to prevent one improper recipe from failing the build. * In the future, this default may be changed to "true" to be more restrictive. */ @Parameter(property = "rewrite.failOnInvalidActiveRecipes", alias = "failOnInvalidActiveRecipes", defaultValue = "false") protected boolean failOnInvalidActiveRecipes; @Parameter(property = "rewrite.runPerSubmodule", alias = "runPerSubmodule", defaultValue = "false") protected boolean runPerSubmodule; @Parameter(defaultValue = "${session}", readonly = true) protected MavenSession mavenSession; @Parameter(defaultValue = "${plugin}", required = true, readonly = true) protected PluginDescriptor pluginDescriptor; protected enum State { SKIPPED, PROCESSED, TO_BE_PROCESSED } private static final String OPENREWRITE_PROCESSED_MARKER = "openrewrite.processed"; protected void putState(State state) { //noinspection unchecked getPluginContext().put(OPENREWRITE_PROCESSED_MARKER, state.name()); } private boolean hasState(MavenProject project) { Map pluginContext = mavenSession.getPluginContext(pluginDescriptor, project); return pluginContext.containsKey(OPENREWRITE_PROCESSED_MARKER); } protected boolean allProjectsMarked() { return mavenSession.getProjects().stream().allMatch(this::hasState); } @Parameter(property = "rewrite.recipeArtifactCoordinates") @Nullable private LinkedHashSet recipeArtifactCoordinates; @Nullable private volatile Set computedRecipes; @Nullable private volatile Set computedStyles; @Nullable private volatile Set computedRecipeArtifactCoordinates; protected Set getActiveRecipes() { if (computedRecipes == null) { synchronized (this) { if (computedRecipes == null) { computedRecipes = getCleanedSet(activeRecipes); } } } //noinspection ConstantConditions return computedRecipes; } protected Set getActiveStyles() { if (computedStyles == null) { synchronized (this) { if (computedStyles == null) { computedStyles = getCleanedSet(activeStyles); } } } //noinspection ConstantConditions return computedStyles; } protected List loadStyles(MavenProject project, Environment env) { List styles = env.activateStyles(getActiveStyles()); try { Plugin checkstylePlugin = project.getPlugin("org.apache.maven.plugins:maven-checkstyle-plugin"); if (checkstyleConfigFile != null && !checkstyleConfigFile.isEmpty()) { styles.add(loadCheckstyleConfig(Paths.get(checkstyleConfigFile), emptyMap())); } else if (checkstyleDetectionEnabled && checkstylePlugin != null) { Object checkstyleConfRaw = checkstylePlugin.getConfiguration(); if (checkstyleConfRaw instanceof Xpp3Dom) { Xpp3Dom xmlCheckstyleConf = (Xpp3Dom) checkstyleConfRaw; Xpp3Dom xmlConfigLocation = xmlCheckstyleConf.getChild("configLocation"); Xpp3Dom xmlCheckstyleRules = xmlCheckstyleConf.getChild("checkstyleRules"); if (xmlConfigLocation != null) { // resolve location against plugin location (could be in parent pom) Path configPath = Paths.get(checkstylePlugin.getLocation("").getSource().getLocation()) .resolveSibling(xmlConfigLocation.getValue()); if (configPath.toFile().exists()) { styles.add(loadCheckstyleConfig(configPath, emptyMap())); } } else if (xmlCheckstyleRules != null && xmlCheckstyleRules.getChildCount() > 0) { styles.add(loadCheckstyleConfig(toCheckStyleDocument(xmlCheckstyleRules.getChild(0)), emptyMap())); } else { // When no config location is specified, the maven-checkstyle-plugin falls back on sun_checks.xml try (InputStream is = org.openrewrite.tools.checkstyle.Checker.class.getResourceAsStream("/sun_checks.xml")) { if (is != null) { styles.add(loadCheckstyleConfig(is, emptyMap())); } } } } } } catch (Exception e) { getLog().warn("Unable to parse checkstyle configuration. Checkstyle will not inform rewrite execution.", e); } return styles; } private @Language("XML") String toCheckStyleDocument(final Xpp3Dom dom) throws IOException { StringWriter stringWriter = new StringWriter(); MXSerializer serializer = new MXSerializer(); serializer.setOutput(stringWriter); serializer.docdecl(CHECKSTYLE_DOCTYPE); dom.writeToSerializer("", serializer); return stringWriter.toString(); } protected Set getRecipeArtifactCoordinates() { if (computedRecipeArtifactCoordinates == null) { synchronized (this) { if (computedRecipeArtifactCoordinates == null) { computedRecipeArtifactCoordinates = getCleanedSet(recipeArtifactCoordinates); } } } //noinspection ConstantConditions return computedRecipeArtifactCoordinates; } private static Set getCleanedSet(@Nullable Set<@Nullable String> set) { if (set == null) { return emptySet(); } Set cleaned = set.stream() .filter(Objects::nonNull) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(toCollection(LinkedHashSet::new)); return unmodifiableSet(cleaned); } } ================================================ FILE: src/main/java/org/openrewrite/maven/LogLevel.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; public enum LogLevel { DEBUG, INFO, WARN, ERROR } ================================================ FILE: src/main/java/org/openrewrite/maven/MavenLoggingMeterRegistry.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.*; import io.micrometer.core.instrument.binder.BaseUnits; import io.micrometer.core.instrument.cumulative.*; import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; import io.micrometer.core.instrument.distribution.HistogramSnapshot; import io.micrometer.core.instrument.distribution.pause.PauseDetector; import io.micrometer.core.instrument.internal.DefaultGauge; import io.micrometer.core.instrument.internal.DefaultLongTaskTimer; import io.micrometer.core.instrument.internal.DefaultMeter; import io.micrometer.core.instrument.util.TimeUtils; import org.apache.maven.plugin.logging.Log; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.function.ToDoubleFunction; import java.util.function.ToLongFunction; import java.util.stream.StreamSupport; import static io.micrometer.core.instrument.util.DoubleFormat.decimalOrNan; import static java.util.stream.Collectors.joining; @NullMarked public class MavenLoggingMeterRegistry extends MeterRegistry { private final Log log; public MavenLoggingMeterRegistry(Log log) { super(Clock.SYSTEM); this.log = log; } @Override public void close() { getMeters().stream() .sorted((m1, m2) -> { int typeComp = m1.getId().getType().compareTo(m2.getId().getType()); if (typeComp == 0) { return m1.getId().getName().compareTo(m2.getId().getName()); } return typeComp; }) .forEach(m -> { Printer print = new Printer(m); m.use( gauge -> log.info(print.id() + " value=" + print.value(gauge.value())), counter -> { double count = counter.count(); log.info(print.id() + " count=" + print.count(count)); }, timer -> { HistogramSnapshot snapshot = timer.takeSnapshot(); long count = snapshot.count(); log.info(print.id() + " count=" + print.unitlessCount(count) + " mean=" + print.time(snapshot.mean(getBaseTimeUnit())) + " max=" + print.time(snapshot.max(getBaseTimeUnit()))); }, summary -> { HistogramSnapshot snapshot = summary.takeSnapshot(); long count = snapshot.count(); log.info(print.id() + " count=" + print.unitlessCount(count) + " mean=" + print.value(snapshot.mean()) + " max=" + print.value(snapshot.max())); }, longTaskTimer -> { int activeTasks = longTaskTimer.activeTasks(); log.info(print.id() + " active=" + print.value(activeTasks) + " duration=" + print.time(longTaskTimer.duration(getBaseTimeUnit()))); }, timeGauge -> { double value = timeGauge.value(getBaseTimeUnit()); log.info(print.id() + " value=" + print.time(value)); }, counter -> { double count = counter.count(); log.info(print.id() + " count=" + print.count(count)); }, timer -> { double count = timer.count(); log.info(print.id() + " count=" + print.count(count) + " mean=" + print.time(timer.mean(getBaseTimeUnit()))); }, meter -> log.info(writeMeter(meter, print)) ); }); } String writeMeter(Meter meter, Printer print) { return StreamSupport.stream(meter.measure().spliterator(), false) .map(ms -> { String msLine = ms.getStatistic().getTagValueRepresentation() + "="; switch (ms.getStatistic()) { case TOTAL: case MAX: case VALUE: return msLine + print.value(ms.getValue()); case TOTAL_TIME: case DURATION: return msLine + print.time(ms.getValue()); case COUNT: return "count=" + print.count(ms.getValue()); default: return msLine + decimalOrNan(ms.getValue()); } }) .collect(joining(", ", print.id() + " ", "")); } @Override protected Timer newTimer(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, PauseDetector pauseDetector) { return new CumulativeTimer(id, clock, distributionStatisticConfig, pauseDetector, getBaseTimeUnit(), false); } @Override protected DistributionSummary newDistributionSummary(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double scale) { return new CumulativeDistributionSummary(id, clock, distributionStatisticConfig, scale, false); } @Override protected Counter newCounter(Meter.Id id) { return new CumulativeCounter(id); } @Override protected Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction valueFunction) { return new DefaultGauge<>(id, obj, valueFunction); } @Override protected FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction countFunction, ToDoubleFunction totalTimeFunction, TimeUnit totalTimeFunctionUnit) { return new CumulativeFunctionTimer<>(id, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit, getBaseTimeUnit()); } @Override protected FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction countFunction) { return new CumulativeFunctionCounter<>(id, obj, countFunction); } @Override protected LongTaskTimer newLongTaskTimer(Meter.Id id, DistributionStatisticConfig distributionStatisticConfig) { return new DefaultLongTaskTimer(id, clock, getBaseTimeUnit(), distributionStatisticConfig, false); } @Override protected Meter newMeter(Meter.Id id, Meter.Type type, Iterable measurements) { return new DefaultMeter(id, type, measurements); } @Override protected DistributionStatisticConfig defaultHistogramConfig() { return DistributionStatisticConfig.builder() .expiry(Duration.ofMinutes(1)) .bufferLength(3) .build(); } class Printer { private final Meter meter; Printer(Meter meter) { this.meter = meter; } String id() { return getConventionName(meter.getId()) + getConventionTags(meter.getId()).stream() .map(t -> t.getKey() + "=" + t.getValue()) .collect(joining(",", "{", "}")); } String count(double count) { return humanReadableBaseUnit(count); } String unitlessCount(double count) { return decimalOrNan(count); } String time(double time) { return TimeUtils.format(Duration.ofNanos((long) TimeUtils.convert(time, getBaseTimeUnit(), TimeUnit.NANOSECONDS))); } String value(double value) { return humanReadableBaseUnit(value); } // see https://stackoverflow.com/a/3758880/510017 @SuppressWarnings("StringConcatenationMissingWhitespace") String humanReadableByteCount(double bytes) { int unit = 1024; if (bytes < unit || Double.isNaN(bytes)) { return decimalOrNan(bytes) + " B"; } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = "KMGTPE".charAt(exp - 1) + "i"; return decimalOrNan(bytes / Math.pow(unit, exp)) + " " + pre + "B"; } String humanReadableBaseUnit(double value) { String baseUnit = meter.getId().getBaseUnit(); if (BaseUnits.BYTES.equals(baseUnit)) { return humanReadableByteCount(value); } return decimalOrNan(value) + (baseUnit != null ? " " + baseUnit : ""); } } @Override protected TimeUnit getBaseTimeUnit() { return TimeUnit.MILLISECONDS; } } ================================================ FILE: src/main/java/org/openrewrite/maven/MavenLoggingResolutionEventListener.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.logging.Log; import org.jspecify.annotations.Nullable; import org.openrewrite.maven.tree.*; import java.util.List; class MavenLoggingResolutionEventListener implements ResolutionEventListener { private final Log logger; public MavenLoggingResolutionEventListener(Log logger) { this.logger = logger; } @Override public void downloadSuccess(ResolvedGroupArtifactVersion gav, @Nullable ResolvedPom containing) { if (logger.isDebugEnabled()) { logger.debug("Downloaded " + gav + pomContaining(containing)); } } @Override public void downloadError(GroupArtifactVersion gav, List attemptedUris, @Nullable Pom containing) { StringBuilder sb = new StringBuilder("Failed to download " + gav + pomContaining(containing) + ". Attempted URIs:"); attemptedUris.forEach(uri -> sb.append("\n - ").append(uri)); logger.warn(sb); } @Override public void repositoryAccessFailed(String uri, Throwable e) { logger.warn("Failed to access maven repository " + uri + " due to: " + e.getMessage()); logger.debug(e); } private static String pomContaining(@Nullable Pom containing) { return containing != null ? " from " + containing.getGav() : ""; } private static String pomContaining(@Nullable ResolvedPom containing) { return containing != null ? " from " + containing.getGav() : ""; } } ================================================ FILE: src/main/java/org/openrewrite/maven/MavenMojoProjectParser.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 com.fasterxml.jackson.core.JsonProcessingException; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.PluginManagement; import org.apache.maven.model.Repository; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.rtinfo.RuntimeInformation; import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest; import org.apache.maven.settings.crypto.SettingsDecrypter; import org.apache.maven.settings.crypto.SettingsDecryptionRequest; import org.apache.maven.settings.crypto.SettingsDecryptionResult; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.jspecify.annotations.Nullable; import org.openrewrite.ExecutionContext; import org.openrewrite.HttpSenderExecutionContextView; import org.openrewrite.ParseExceptionResult; import org.openrewrite.PathUtils; import org.openrewrite.SourceFile; import org.openrewrite.groovy.GroovyParser; import org.openrewrite.internal.GitIgnore; import org.openrewrite.internal.StringUtils; import org.openrewrite.ipc.http.HttpUrlConnectionSender; 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.jgit.api.Git; import org.openrewrite.jgit.lib.ObjectId; import org.openrewrite.jgit.revwalk.RevCommit; import org.openrewrite.jgit.revwalk.RevWalk; import org.openrewrite.jgit.treewalk.TreeWalk; import org.openrewrite.jgit.treewalk.filter.PathFilter; import org.openrewrite.kotlin.KotlinParser; import org.openrewrite.marker.*; import org.openrewrite.marker.ci.BuildEnvironment; import org.openrewrite.maven.cache.InMemoryMavenPomCache; import org.openrewrite.maven.cache.MavenPomCache; import org.openrewrite.maven.internal.MavenXmlMapper; import org.openrewrite.maven.internal.RawPom; import org.openrewrite.maven.internal.RawRepositories; import org.openrewrite.maven.tree.Pom; import org.openrewrite.maven.tree.ProfileActivation; import org.openrewrite.maven.tree.ResolvedGroupArtifactVersion; import org.openrewrite.maven.utilities.MavenWrapper; import org.openrewrite.polyglot.OmniParser; import org.openrewrite.quark.QuarkParser; import org.openrewrite.style.NamedStyles; import org.openrewrite.text.PlainTextParser; import org.openrewrite.xml.tree.Xml; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.time.Duration; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Pattern; import java.util.stream.Stream; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.openrewrite.PathUtils.separatorsToUnix; import static org.openrewrite.Tree.randomId; import static org.openrewrite.maven.MavenMojoProjectParser.MavenScope.MAIN; import static org.openrewrite.maven.MavenMojoProjectParser.MavenScope.TEST; import static org.openrewrite.tree.ParsingExecutionContextView.view; // ----------------------------------------------------------------------------------------------------------------- // Notes About Provenance Information: // // There are always three markers applied to each source file and there can potentially be up to five provenance markers // total: // // BuildTool - What build tool was used to compile the source file (This will always be Maven) // JavaVersion - What Java version/vendor was used when compiling the source file. // JavaProject - For each maven module/submodule, the same JavaProject will be associated with ALL source files belonging to that module. // // Optional: // // GitProvenance - If the project exists in the context of a git repository, all source files (for all modules) will have the same GitProvenance. // JavaSourceSet - All Java source files and all resource files that exist in src/main or src/test will have a JavaSourceSet marker assigned to them. // ----------------------------------------------------------------------------------------------------------------- public class MavenMojoProjectParser { private static final String MVN_JVM_CONFIG = ".mvn/jvm.config"; private static final String MVN_MAVEN_CONFIG = ".mvn/maven.config"; private static final String MAVEN_COMPILER_PLUGIN = "org.apache.maven.plugins:maven-compiler-plugin"; @Nullable public static MavenPomCache POM_CACHE; private final Log logger; private final AtomicBoolean firstWarningLogged = new AtomicBoolean(false); private final Path baseDir; private final org.openrewrite.jgit.lib.@Nullable Repository repository; private final boolean pomCacheEnabled; @Nullable private final String pomCacheDirectory; private final boolean skipMavenParsing; private final BuildTool buildTool; private final Collection exclusions; private final Collection plainTextMasks; private final int sizeThresholdMb; private final MavenSession mavenSession; private final SettingsDecrypter settingsDecrypter; private final boolean runPerSubmodule; private final boolean parseAdditionalResources; @SuppressWarnings("BooleanParameter") public MavenMojoProjectParser(Log logger, Path baseDir, boolean pomCacheEnabled, @Nullable String pomCacheDirectory, RuntimeInformation runtime, boolean skipMavenParsing, Collection exclusions, Collection plainTextMasks, int sizeThresholdMb, MavenSession session, SettingsDecrypter settingsDecrypter, boolean runPerSubmodule, boolean parseAdditionalResources) { this.logger = logger; this.baseDir = baseDir; this.repository = getRepository(baseDir); this.pomCacheEnabled = pomCacheEnabled; this.pomCacheDirectory = pomCacheDirectory; this.skipMavenParsing = skipMavenParsing; this.buildTool = new BuildTool(randomId(), BuildTool.Type.Maven, runtime.getMavenVersion()); this.exclusions = exclusions; this.plainTextMasks = plainTextMasks; this.sizeThresholdMb = sizeThresholdMb; this.mavenSession = session; this.settingsDecrypter = settingsDecrypter; this.runPerSubmodule = runPerSubmodule; this.parseAdditionalResources = parseAdditionalResources; } protected JavaTypeCache createTypeCache() { return new JavaTypeCache(); } public Stream listSourceFiles(MavenProject mavenProject, List styles, ExecutionContext ctx) throws DependencyResolutionRequiredException, MojoExecutionException, MojoFailureException { if (runPerSubmodule) { //If running per submodule, parse the source files for only the current project. List projectProvenance = generateProvenance(mavenProject); Xml.Document maven = parseMaven(mavenProject, projectProvenance, ctx); return listSourceFiles(mavenProject, maven, projectProvenance, styles, ctx); } //If running across all projects, iterate and parse source files from each project Map> projectProvenances = mavenSession.getProjects().stream() .collect(toMap(Function.identity(), this::generateProvenance)); Map projectMap = parseMaven(mavenSession.getProjects(), projectProvenances, ctx); return mavenSession.getProjects().stream() .flatMap(project -> { List projectProvenance = projectProvenances.get(project); try { return listSourceFiles(project, projectMap.get(project), projectProvenance, styles, ctx); } catch (DependencyResolutionRequiredException | MojoExecutionException e) { throw sneakyThrow(e); } }); } public Stream listSourceFiles(MavenProject mavenProject, Xml.@Nullable Document maven, List projectProvenance, List styles, ExecutionContext ctx) throws DependencyResolutionRequiredException, MojoExecutionException { return listSourceFiles(mavenProject, maven, projectProvenance, Arrays.asList(MAIN, TEST), styles, ctx); } public Stream listSourceFiles(MavenProject mavenProject, Xml.@Nullable Document maven, List projectProvenance, List scopes, List styles, ExecutionContext ctx) throws DependencyResolutionRequiredException, MojoExecutionException { Stream sourceFiles = Stream.empty(); Set parsedPaths = new HashSet<>(); if (maven != null) { sourceFiles = Stream.of(maven); parsedPaths.add(baseDir.resolve(maven.getSourcePath())); } JavaParser.Builder javaParserBuilder = JavaParser.fromJavaVersion() .styles(styles) .logCompilationWarningsAndErrors(false); // todo, add styles from autoDetect KotlinParser.Builder kotlinParserBuilder = KotlinParser.builder(); GroovyParser.Builder groovyParserBuilder = GroovyParser.builder(); // Pre-populate parsedPaths with all source paths from both scopes (including generated sources) // to prevent resource parsers from claiming these as PlainText parsedPaths.addAll(listJavaSources(mavenProject, mavenProject.getExecutionProject().getCompileSourceRoots())); parsedPaths.addAll(listKotlinSources(mavenProject, "compile", mavenProject.getBuild().getSourceDirectory())); parsedPaths.addAll(listGroovySources(mavenProject, mavenProject.getExecutionProject().getCompileSourceRoots())); parsedPaths.addAll(listJavaSources(mavenProject, mavenProject.getExecutionProject().getTestCompileSourceRoots())); parsedPaths.addAll(listKotlinSources(mavenProject, "test-compile", mavenProject.getBuild().getTestSourceDirectory())); parsedPaths.addAll(listGroovySources(mavenProject, mavenProject.getExecutionProject().getTestCompileSourceRoots())); if (scopes.contains(MAIN)) { sourceFiles = Stream.concat(sourceFiles, processMainSources(mavenProject, javaParserBuilder.clone(), kotlinParserBuilder.clone(), groovyParserBuilder.clone(), parsedPaths, ctx)); } if (scopes.contains(TEST)) { sourceFiles = Stream.concat(sourceFiles, processTestSources(mavenProject, javaParserBuilder.clone(), kotlinParserBuilder.clone(), groovyParserBuilder.clone(), parsedPaths, ctx)); } Collection exclusionMatchers = exclusions.stream() .map(pattern -> baseDir.getFileSystem().getPathMatcher("glob:" + pattern)) .collect(toList()); Path buildDirectory = baseDir.relativize(Paths.get(mavenProject.getBuild().getDirectory())); sourceFiles = sourceFiles .filter(sourceFile -> !sourceFile.getSourcePath().startsWith(buildDirectory) && !isExcluded(repository, exclusionMatchers, sourceFile.getSourcePath())); Stream mavenWrapperFiles = parseMavenWrapperFiles(mavenProject, exclusionMatchers, parsedPaths, ctx); sourceFiles = Stream.concat(sourceFiles, mavenWrapperFiles); Stream nonProjectResources = parseNonProjectResources(mavenProject, parsedPaths, ctx); sourceFiles = Stream.concat(sourceFiles, nonProjectResources); return sourceFiles.map(addProvenance(projectProvenance)) .map(addGitTreeEntryInformation()) .map(this::logParseErrors); } static boolean isExcluded(org.openrewrite.jgit.lib.@Nullable Repository repository, Collection exclusionMatchers, Path path) { for (PathMatcher excluded : exclusionMatchers) { if (excluded.matches(path)) { return true; } } // PathMatcher will not evaluate the path "pom.xml" to be matched by the pattern "**/pom.xml" // This is counter-intuitive for most users and would otherwise require separate exclusions for files at the root and files in subdirectories if (!path.isAbsolute() && !path.startsWith(File.separator)) { Path prefixed = Paths.get("/" + path); for (PathMatcher excluded : exclusionMatchers) { if (excluded.matches(prefixed)) { return true; } } } if (repository != null) { return GitIgnore.isIgnoredAndUntracked(repository, separatorsToUnix(path.toString())); } return false; } public enum MavenScope { MAIN, TEST } static Optional getCharset(MavenProject mavenProject) { String compilerPluginKey = MAVEN_COMPILER_PLUGIN; Plugin plugin = Optional.ofNullable(mavenProject.getPlugin(compilerPluginKey)) .orElseGet(() -> { PluginManagement pluginManagement = mavenProject.getPluginManagement(); return pluginManagement != null ? pluginManagement.getPluginsAsMap().get(compilerPluginKey) : null; }); if (plugin != null && plugin.getConfiguration() instanceof Xpp3Dom) { Xpp3Dom encoding = ((Xpp3Dom) plugin.getConfiguration()).getChild("encoding"); if (encoding != null && StringUtils.isNotEmpty(encoding.getValue())) { String resolved = resolveProperty(encoding.getValue(), mavenProject); if (resolved != null) { return Optional.of(Charset.forName(resolved)); } } } Object mavenSourceEncoding = mavenProject.getProperties().get("project.build.sourceEncoding"); if (mavenSourceEncoding != null) { String resolved = resolveProperty(mavenSourceEncoding.toString(), mavenProject); if (resolved != null) { return Optional.of(Charset.forName(resolved)); } } return Optional.empty(); } private static @Nullable String resolveProperty(String value, MavenProject mavenProject) { if (value.startsWith("${") && value.endsWith("}")) { String propertyName = value.substring(2, value.length() - 1); String resolved = mavenProject.getProperties().getProperty(propertyName); if (resolved != null && !resolved.contains("${")) { return resolved; } return null; } return value.contains("${") ? null : value; } static org.openrewrite.jgit.lib.@Nullable Repository getRepository(Path rootDir) { try (Git git = Git.open(rootDir.toFile())) { return git.getRepository(); } catch (IOException e) { // no git return null; } } private SourceFile logParseErrors(SourceFile source) { source.getMarkers().findFirst(ParseExceptionResult.class).ifPresent(e -> { if (firstWarningLogged.compareAndSet(false, true)) { logger.warn("There were problems parsing some source files" + (mavenSession.getRequest().isShowErrors() ? "" : ", run with --errors to see full stack traces")); } logger.warn("There were problems parsing " + source.getSourcePath()); if (mavenSession.getRequest().isShowErrors()) { logger.warn(e.getMessage()); } }); return source; } public List generateProvenance(MavenProject mavenProject) { BuildEnvironment buildEnvironment = BuildEnvironment.build(System::getenv); return Stream.of( buildEnvironment, gitProvenance(baseDir, buildEnvironment), OperatingSystemProvenance.current(), buildTool, new JavaProject(randomId(), mavenProject.getName(), new JavaProject.Publication( mavenProject.getGroupId(), mavenProject.getArtifactId(), mavenProject.getVersion() ))) .filter(Objects::nonNull) .collect(toList()); } private static JavaVersion getSrcMainJavaVersion(MavenProject mavenProject) { String sourceCompatibility = null; String targetCompatibility = null; Plugin compilerPlugin = mavenProject.getPlugin(MAVEN_COMPILER_PLUGIN); if (compilerPlugin != null && compilerPlugin.getConfiguration() instanceof Xpp3Dom) { Xpp3Dom dom = (Xpp3Dom) compilerPlugin.getConfiguration(); Xpp3Dom release = dom.getChild("release"); if (release != null && StringUtils.isNotEmpty(release.getValue()) && !release.getValue().contains("${")) { sourceCompatibility = release.getValue(); targetCompatibility = release.getValue(); } else { Xpp3Dom source = dom.getChild("source"); if (source != null && StringUtils.isNotEmpty(source.getValue()) && !source.getValue().contains("${")) { sourceCompatibility = source.getValue(); } Xpp3Dom target = dom.getChild("target"); if (target != null && StringUtils.isNotEmpty(target.getValue()) && !target.getValue().contains("${")) { targetCompatibility = target.getValue(); } } } if (sourceCompatibility == null || targetCompatibility == null) { String propertiesReleaseCompatibility = (String) mavenProject.getProperties().get("maven.compiler.release"); if (propertiesReleaseCompatibility != null) { sourceCompatibility = propertiesReleaseCompatibility; targetCompatibility = propertiesReleaseCompatibility; } else { String propertiesSourceCompatibility = (String) mavenProject.getProperties().get("maven.compiler.source"); if (sourceCompatibility == null && propertiesSourceCompatibility != null) { sourceCompatibility = propertiesSourceCompatibility; } String propertiesTargetCompatibility = (String) mavenProject.getProperties().get("maven.compiler.target"); if (targetCompatibility == null && propertiesTargetCompatibility != null) { targetCompatibility = propertiesTargetCompatibility; } } } return getJavaVersionMarker(sourceCompatibility, targetCompatibility); } static JavaVersion getSrcTestJavaVersion(MavenProject mavenProject) { String sourceCompatibility = null; String targetCompatibility = null; Plugin compilerPlugin = mavenProject.getPlugin(MAVEN_COMPILER_PLUGIN); if (compilerPlugin != null && compilerPlugin.getConfiguration() instanceof Xpp3Dom) { Xpp3Dom dom = (Xpp3Dom) compilerPlugin.getConfiguration(); Xpp3Dom release = dom.getChild("testRelease"); if (release != null && StringUtils.isNotEmpty(release.getValue()) && !release.getValue().contains("${")) { sourceCompatibility = release.getValue(); targetCompatibility = release.getValue(); } else { Xpp3Dom source = dom.getChild("testSource"); if (source != null && StringUtils.isNotEmpty(source.getValue()) && !source.getValue().contains("${")) { sourceCompatibility = source.getValue(); } Xpp3Dom target = dom.getChild("testTarget"); if (target != null && StringUtils.isNotEmpty(target.getValue()) && !target.getValue().contains("${")) { targetCompatibility = target.getValue(); } } } if (sourceCompatibility == null || targetCompatibility == null) { String propertiesReleaseCompatibility = (String) mavenProject.getProperties().get("maven.compiler.testRelease"); if (propertiesReleaseCompatibility != null) { sourceCompatibility = propertiesReleaseCompatibility; targetCompatibility = propertiesReleaseCompatibility; } else { String propertiesSourceCompatibility = (String) mavenProject.getProperties().get("maven.compiler.testSource"); if (sourceCompatibility == null && propertiesSourceCompatibility != null) { sourceCompatibility = propertiesSourceCompatibility; } String propertiesTargetCompatibility = (String) mavenProject.getProperties().get("maven.compiler.testTarget"); if (targetCompatibility == null && propertiesTargetCompatibility != null) { targetCompatibility = propertiesTargetCompatibility; } } } // Fall back to main source compatibility if test source compatibility is not set, or only partially set. if (sourceCompatibility == null || targetCompatibility == null) { JavaVersion srcMainJavaVersion = getSrcMainJavaVersion(mavenProject); if (sourceCompatibility == null && targetCompatibility == null) { return srcMainJavaVersion; } sourceCompatibility = sourceCompatibility == null ? srcMainJavaVersion.getSourceCompatibility() : sourceCompatibility; targetCompatibility = targetCompatibility == null ? srcMainJavaVersion.getTargetCompatibility() : targetCompatibility; } return getJavaVersionMarker(sourceCompatibility, targetCompatibility); } private static JavaVersion getJavaVersionMarker(@Nullable String sourceCompatibility, @Nullable String targetCompatibility) { String javaRuntimeVersion = System.getProperty("java.specification.version"); String javaVendor = System.getProperty("java.vm.vendor"); if (sourceCompatibility == null) { sourceCompatibility = javaRuntimeVersion; } if (targetCompatibility == null) { targetCompatibility = sourceCompatibility; } return new JavaVersion(randomId(), javaRuntimeVersion, javaVendor, sourceCompatibility, targetCompatibility); } private Stream processMainSources( MavenProject mavenProject, JavaParser.Builder javaParserBuilder, KotlinParser.Builder kotlinParserBuilder, GroovyParser.Builder groovyParserBuilder, Set parsedPaths, ExecutionContext ctx) throws DependencyResolutionRequiredException, MojoExecutionException { Stream sourceFiles = Stream.of(); // Skip generated source roots under the build directory; their compiled classes are // already on the classpath via getCompileClasspathElements() and available for type attribution. List sourceRoots = filterGeneratedSourceRoots(mavenProject, mavenProject.getExecutionProject().getCompileSourceRoots()); // scan Java files Collection mainJavaSources = listJavaSources(mavenProject, sourceRoots); // scan Kotlin files List mainKotlinSources = listKotlinSources(mavenProject, "compile", mavenProject.getBuild().getSourceDirectory()); // scan Groovy files List mainGroovySources = listGroovySources(mavenProject, sourceRoots); logInfo(mavenProject, "Parsing source files"); List dependencies = mavenProject.getCompileClasspathElements().stream() .distinct() .map(Paths::get) .collect(toList()); JavaTypeCache typeCache = createTypeCache(); javaParserBuilder.classpath(dependencies).typeCache(typeCache); kotlinParserBuilder.classpath(dependencies).typeCache(typeCache); groovyParserBuilder.classpath(dependencies).typeCache(typeCache); if (!mainJavaSources.isEmpty()) { Stream parsedJava = Stream.of((Supplier) javaParserBuilder::build) .map(Supplier::get) .flatMap(jp -> { view(ctx).setCharset(getCharset(mavenProject).orElse(null)); return jp.parse(mainJavaSources, baseDir, ctx).onClose(() -> view(ctx).setCharset(null)); }); sourceFiles = Stream.concat(sourceFiles, parsedJava); logDebug(mavenProject, "Scanned " + mainJavaSources.size() + " java source files in main scope."); } if (!mainKotlinSources.isEmpty()) { Stream parsedKotlin = Stream.of((Supplier) kotlinParserBuilder::build) .map(Supplier::get) .flatMap(kp -> { view(ctx).setCharset(StandardCharsets.UTF_8); // Kotlin requires UTF-8 return kp.parse(mainKotlinSources, baseDir, ctx).onClose(() -> view(ctx).setCharset(null)); }); sourceFiles = Stream.concat(sourceFiles, parsedKotlin); logDebug(mavenProject, "Scanned " + mainKotlinSources.size() + " kotlin source files in main scope."); } if (!mainGroovySources.isEmpty()) { Stream parsedGroovy = Stream.of((Supplier) groovyParserBuilder::build) .map(Supplier::get) .flatMap(gp -> gp.parse(mainGroovySources, baseDir, ctx)); sourceFiles = Stream.concat(sourceFiles, parsedGroovy); logDebug(mavenProject, "Scanned " + mainGroovySources.size() + " groovy source files in main scope."); } OmniParser omniParser = omniParser(parsedPaths, mavenProject); for (Resource resource : mavenProject.getResources()) { Path resourcePath = mavenProject.getBasedir().toPath().resolve(resource.getDirectory()); if (Files.exists(resourcePath) && !parsedPaths.contains(resourcePath)) { List accepted = omniParser.acceptedPaths(baseDir, resourcePath); parsedPaths.add(resourcePath); sourceFiles = Stream.concat(sourceFiles, omniParser.parse(accepted, baseDir, ctx)); parsedPaths.addAll(accepted); } } // Also parse webapp resources (e.g., web.xml) for WAR projects if ("war".equals(mavenProject.getPackaging())) { Path webappPath = mavenProject.getBasedir().toPath().resolve("src/main/webapp"); if (Files.exists(webappPath) && !parsedPaths.contains(webappPath)) { List accepted = omniParser.acceptedPaths(baseDir, webappPath); parsedPaths.add(webappPath); sourceFiles = Stream.concat(sourceFiles, omniParser.parse(accepted, baseDir, ctx)); parsedPaths.addAll(accepted); } } List mainProjectProvenance = new ArrayList<>(); mainProjectProvenance.add(JavaSourceSet.build("main", dependencies)); mainProjectProvenance.add(getSrcMainJavaVersion(mavenProject)); return sourceFiles .map(addProvenance(mainProjectProvenance)); } private Stream processTestSources( MavenProject mavenProject, JavaParser.Builder javaParserBuilder, KotlinParser.Builder kotlinParserBuilder, GroovyParser.Builder groovyParserBuilder, Set parsedPaths, ExecutionContext ctx) throws DependencyResolutionRequiredException, MojoExecutionException { Stream sourceFiles = Stream.of(); // Skip generated source roots under the build directory; their compiled classes are // already on the classpath via getTestClasspathElements() and available for type attribution. List testSourceRoots = filterGeneratedSourceRoots(mavenProject, mavenProject.getExecutionProject().getTestCompileSourceRoots()); // scan Java files Collection testJavaSources = listJavaSources(mavenProject, testSourceRoots); // scan Kotlin files List testKotlinSources = listKotlinSources(mavenProject, "test-compile", mavenProject.getBuild().getTestSourceDirectory()); // scan Groovy files List testGroovySources = listGroovySources(mavenProject, testSourceRoots); List testDependencies = mavenProject.getTestClasspathElements().stream() .distinct() .map(Paths::get) .collect(toList()); JavaTypeCache typeCache = createTypeCache(); javaParserBuilder.classpath(testDependencies).typeCache(typeCache); kotlinParserBuilder.classpath(testDependencies).typeCache(typeCache); groovyParserBuilder.classpath(testDependencies).typeCache(typeCache); if (!testJavaSources.isEmpty()) { Stream parsedJava = Stream.of((Supplier) javaParserBuilder::build) .map(Supplier::get) .flatMap(jp -> { view(ctx).setCharset(getCharset(mavenProject).orElse(null)); return jp.parse(testJavaSources, baseDir, ctx).onClose(() -> view(ctx).setCharset(null)); }); sourceFiles = Stream.concat(sourceFiles, parsedJava); logDebug(mavenProject, "Scanned " + testJavaSources.size() + " java source files in test scope."); } if (!testKotlinSources.isEmpty()) { Stream parsedKotlin = Stream.of((Supplier) kotlinParserBuilder::build) .map(Supplier::get) .flatMap(kp -> { view(ctx).setCharset(StandardCharsets.UTF_8); // Kotlin requires UTF-8 return kp.parse(testKotlinSources, baseDir, ctx).onClose(() -> view(ctx).setCharset(null)); }); sourceFiles = Stream.concat(sourceFiles, parsedKotlin); logDebug(mavenProject, "Scanned " + testKotlinSources.size() + " kotlin source files in test scope."); } if (!testGroovySources.isEmpty()) { Stream parsedGroovy = Stream.of((Supplier) groovyParserBuilder::build) .map(Supplier::get) .flatMap(gp -> gp.parse(testGroovySources, baseDir, ctx)); sourceFiles = Stream.concat(sourceFiles, parsedGroovy); logDebug(mavenProject, "Scanned " + testGroovySources.size() + " groovy source files in test scope."); } OmniParser omniParser = omniParser(parsedPaths, mavenProject); for (Resource resource : mavenProject.getTestResources()) { Path resourcePath = mavenProject.getBasedir().toPath().resolve(resource.getDirectory()); if (Files.exists(resourcePath) && !parsedPaths.contains(resourcePath)) { List accepted = omniParser.acceptedPaths(baseDir, resourcePath); parsedPaths.add(resourcePath); sourceFiles = Stream.concat(sourceFiles, omniParser.parse(accepted, baseDir, ctx)); parsedPaths.addAll(accepted); } } List testProjectProvenance = new ArrayList<>(); testProjectProvenance.add(JavaSourceSet.build("test", testDependencies)); testProjectProvenance.add(getSrcTestJavaVersion(mavenProject)); return sourceFiles .map(addProvenance(testProjectProvenance)); } public Xml.@Nullable Document parseMaven(MavenProject mavenProject, List projectProvenance, ExecutionContext ctx) throws MojoFailureException { return parseMaven(singletonList(mavenProject), singletonMap(mavenProject, projectProvenance), ctx).get(mavenProject); } public Map parseMaven(List mavenProjects, Map> projectProvenances, ExecutionContext ctx) throws MojoFailureException { if (skipMavenParsing) { logger.info("Skipping Maven parsing..."); return emptyMap(); } MavenSettings settings = buildSettings(); MavenExecutionContextView mavenExecutionContext = MavenExecutionContextView.view(ctx); mavenExecutionContext.setMavenSettings(settings); mavenExecutionContext.setResolutionListener(new MavenLoggingResolutionEventListener(logger)); configureProxy(settings, ctx); // The default pom cache is enabled as a two-layer cache L1 == in-memory and L2 == RocksDb // If the flag is set to false, only the default, in-memory cache is used. MavenPomCache pomCache = pomCacheEnabled ? getPomCache(pomCacheDirectory, logger) : mavenExecutionContext.getPomCache(); mavenExecutionContext.setPomCache(pomCache); MavenProject topLevelProject = mavenSession.getTopLevelProject(); logInfo(topLevelProject, "Resolving Poms..."); Set allPoms = new LinkedHashSet<>(); mavenProjects.forEach(p -> collectPoms(p, allPoms, mavenExecutionContext)); for (MavenProject mavenProject : mavenProjects) { mavenSession.getProjectDependencyGraph().getUpstreamProjects(mavenProject, true).forEach(p -> collectPoms(p, allPoms, mavenExecutionContext)); } MavenParser.Builder mavenParserBuilder = MavenParser.builder(); mavenParserBuilder.property("basedir", topLevelProject.getBasedir().getAbsoluteFile().getParent()); mavenParserBuilder.property("project.basedir", topLevelProject.getBasedir().getAbsoluteFile().getParent()); topLevelProject.getActiveProfiles().forEach(it -> mavenParserBuilder.activeProfiles(it.getId())); topLevelProject.getInjectedProfileIds().forEach((gav, profiles) -> mavenParserBuilder.activeProfiles(profiles.toArray(new String[0]))); mavenSession.getRequest().getActiveProfiles().forEach(mavenParserBuilder::activeProfiles); mavenSession.getUserProperties().forEach((key, value) -> mavenParserBuilder.property((String) key, (String) value)); List mavens = mavenParserBuilder.build() .parse(allPoms, baseDir, ctx) .collect(toList()); if (logger.isDebugEnabled()) { logDebug(topLevelProject, "Base directory : '" + baseDir + "'"); if (allPoms.isEmpty()) { logDebug(topLevelProject, "There were no collected pom paths."); } else { for (Path path : allPoms) { logDebug(topLevelProject, " Collected Maven POM : '" + path + "'"); } } if (mavens.isEmpty()) { logDebug(topLevelProject, "There were no parsed maven source files."); } else { for (SourceFile source : mavens) { logDebug(topLevelProject, " Maven Source : '" + baseDir.resolve(source.getSourcePath()) + "'"); } } } Map projectsByPath = mavenProjects.stream().collect(toMap(MavenMojoProjectParser::pomPath, Function.identity())); Map projectMap = new HashMap<>(); for (SourceFile document : mavens) { Path path = baseDir.resolve(document.getSourcePath()); MavenProject mavenProject = projectsByPath.get(path); if (mavenProject != null) { Optional parseExceptionResult = document.getMarkers().findFirst(ParseExceptionResult.class); if (parseExceptionResult.isPresent()) { throw new MojoFailureException( mavenProject, "Failed to parse or resolve the Maven POM file or one of its dependencies; " + "We can not reliably continue without this information.", parseExceptionResult.get().getMessage()); } projectMap.put(mavenProject, (Xml.Document) document); } } for (MavenProject mavenProject : mavenProjects) { if (projectMap.get(mavenProject) == null) { logError(mavenProject, "Parse resulted in no Maven source files. Maven Project File '" + mavenProject.getFile().toPath() + "'"); return emptyMap(); } } // assign provenance markers for (MavenProject mavenProject : mavenProjects) { Xml.Document document = projectMap.get(mavenProject); List provenance = projectProvenances.getOrDefault(mavenProject, emptyList()); Markers markers = document.getMarkers(); for (Marker marker : provenance) { markers = markers.addIfAbsent(marker); } projectMap.put(mavenProject, document.withMarkers(markers)); } return projectMap; } /** * Recursively navigate the maven project to collect any poms that are local (on disk) * * @param project A maven project to examine for any children/parent poms. * @param paths A list of paths to poms that have been collected so far. * @param ctx The execution context for the current project. */ private void collectPoms(MavenProject project, Set paths, MavenExecutionContextView ctx) { if (!paths.add(pomPath(project))) { return; } ResolvedGroupArtifactVersion gav = createResolvedGAV(project, ctx); ctx.getPomCache().putPom(gav, createPom(project)); // children if (project.getCollectedProjects() != null) { for (MavenProject child : project.getCollectedProjects()) { Path path = pomPath(child); if (!paths.contains(path)) { collectPoms(child, paths, ctx); } } } MavenProject parent = project.getParent(); while (parent != null && parent.getFile() != null) { Path path = pomPath(parent); if (!paths.contains(path)) { collectPoms(parent, paths, ctx); } parent = parent.getParent(); } } private static Path pomPath(MavenProject mavenProject) { Path pomPath = mavenProject.getFile().toPath(); if (pomPath.endsWith(".flattened-pom.xml") ||// org.codehaus.mojo:flatten-maven-plugin pomPath.endsWith("dependency-reduced-pom.xml") || // org.apache.maven.plugins:maven-shade-plugin pomPath.endsWith(".ci-friendly-pom.xml") || // com.outbrain.swinfra:ci-friendly-flatten-maven-plugin pomPath.endsWith(".tycho-consumer-pom.xml")) { // org.eclipse.tycho:tycho-packaging-plugin:update-consumer-pom Path normalPom = mavenProject.getBasedir().toPath().resolve("pom.xml"); // check for the existence of the POM, since Tycho can work pom-less if (Files.isReadable(normalPom) && Files.isRegularFile(normalPom)) { return normalPom; } } return pomPath; } private static MavenPomCache getPomCache(@Nullable String pomCacheDirectory, Log logger) { if (POM_CACHE == null) { POM_CACHE = new MavenPomCacheBuilder(logger).build(pomCacheDirectory); } if (POM_CACHE == null) { POM_CACHE = new InMemoryMavenPomCache(); } return POM_CACHE; } public MavenSettings buildSettings() { MavenExecutionRequest mer = mavenSession.getRequest(); MavenSettings.Profiles profiles = new MavenSettings.Profiles(); profiles.setProfiles( mer.getProfiles().stream().map(p -> new MavenSettings.Profile( p.getId(), p.getActivation() == null ? null : new ProfileActivation( p.getActivation().isActiveByDefault(), p.getActivation().getJdk(), p.getActivation().getProperty() == null ? null : new ProfileActivation.Property( p.getActivation().getProperty().getName(), p.getActivation().getProperty().getValue() ) ), buildRawRepositories(p.getRepositories()) ) ).collect(toList())); MavenSettings.ActiveProfiles activeProfiles = new MavenSettings.ActiveProfiles(); activeProfiles.setActiveProfiles(mer.getActiveProfiles()); MavenSettings.Mirrors mirrors = new MavenSettings.Mirrors(); mirrors.setMirrors( mer.getMirrors().stream().map(m -> new MavenSettings.Mirror( m.getId(), m.getUrl(), m.getMirrorOf(), null, null )).collect(toList()) ); MavenSettings.Servers servers = new MavenSettings.Servers(); servers.setServers(mer.getServers().stream().map(s -> { SettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(s); SettingsDecryptionResult decryptionResult = settingsDecrypter.decrypt(decryptionRequest); MavenSettings.ServerConfiguration configuration = null; if (s.getConfiguration() != null) { try { // No need to interpolate in property placeholders like ${env.Foo}, Maven has already done this configuration = MavenXmlMapper.readMapper().readValue(s.getConfiguration().toString(), MavenSettings.ServerConfiguration.class); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return new MavenSettings.Server( s.getId(), s.getUsername(), decryptionResult.getServer().getPassword(), configuration ); }).collect(toList())); MavenSettings.Proxies proxies = new MavenSettings.Proxies(); proxies.setProxies(mer.getProxies().stream().map(p -> { SettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(); decryptionRequest.setProxies(singletonList(p)); SettingsDecryptionResult decryptionResult = settingsDecrypter.decrypt(decryptionRequest); org.apache.maven.settings.Proxy decryptedProxy = decryptionResult.getProxies().isEmpty() ? p : decryptionResult.getProxies().get(0); return new MavenSettings.Proxy( p.getId(), p.isActive(), p.getProtocol(), p.getHost(), p.getPort(), p.getUsername(), decryptedProxy.getPassword(), p.getNonProxyHosts() ); }).collect(toList())); return new MavenSettings(mer.getLocalRepositoryPath().toString(), profiles, activeProfiles, mirrors, servers, proxies); } private void configureProxy(MavenSettings settings, ExecutionContext ctx) { if (settings.getProxies() == null || settings.getProxies().getProxies().isEmpty()) { return; } // Use the first active proxy MavenSettings.Proxy activeProxy = settings.getProxies().getProxies().stream() .filter(p -> p.getActive() == null || p.getActive()) .findFirst() .orElse(null); if (activeProxy == null) { return; } java.net.Proxy proxy = new java.net.Proxy( java.net.Proxy.Type.HTTP, new InetSocketAddress(activeProxy.getHost(), activeProxy.getPort()) ); if (activeProxy.getUsername() != null && !activeProxy.getUsername().isEmpty()) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { return new PasswordAuthentication( activeProxy.getUsername(), activeProxy.getPassword() != null ? activeProxy.getPassword().toCharArray() : new char[0] ); } return null; } }); } HttpUrlConnectionSender proxiedSender = new HttpUrlConnectionSender( Duration.ofSeconds(1), Duration.ofSeconds(10), proxy); HttpUrlConnectionSender directSender = new HttpUrlConnectionSender( Duration.ofSeconds(1), Duration.ofSeconds(10)); String nonProxyHosts = activeProxy.getNonProxyHosts(); if (nonProxyHosts == null || nonProxyHosts.isEmpty()) { HttpSenderExecutionContextView.view(ctx).setHttpSender(proxiedSender); } else { // Parse nonProxyHosts patterns (pipe-delimited, * wildcards) into a regex String regex = Arrays.stream(nonProxyHosts.split("\\|")) .map(String::trim) .filter(s -> !s.isEmpty()) .map(pattern -> pattern.replace(".", "\\.").replace("*", ".*")) .collect(joining("|")); Pattern nonProxyPattern = Pattern.compile(regex); HttpSenderExecutionContextView.view(ctx).setHttpSender(request -> { String host = request.getUrl().getHost(); if (nonProxyPattern.matcher(host).matches()) { return directSender.send(request); } return proxiedSender.send(request); }); } } private static @Nullable RawRepositories buildRawRepositories(@Nullable List repositoriesToMap) { if (repositoriesToMap == null) { return null; } RawRepositories rawRepositories = new RawRepositories(); List transformedRepositories = repositoriesToMap.stream().map(r -> new RawRepositories.Repository( r.getId(), r.getUrl(), r.getReleases() == null ? null : new RawRepositories.ArtifactPolicy(Boolean.toString(r.getReleases().isEnabled())), r.getSnapshots() == null ? null : new RawRepositories.ArtifactPolicy(Boolean.toString(r.getSnapshots().isEnabled())) )).collect(toList()); rawRepositories.setRepositories(transformedRepositories); return rawRepositories; } /** * Used to scope `Files.walkFileTree` to the current maven project by skipping the subtrees of other MavenProjects. */ private Set pathsToOtherMavenProjects(MavenProject mavenProject) { return mavenSession.getProjects().stream() .filter(o -> o != mavenProject) .map(o -> o.getBasedir().toPath()) .collect(toSet()); } private UnaryOperator addProvenance(List provenance) { return s -> { Markers markers = s.getMarkers(); for (Marker marker : provenance) { markers = markers.addIfAbsent(marker); } return s.withMarkers(markers); }; } private UnaryOperator addGitTreeEntryInformation() { return s -> { if (repository == null) { return s; } try { ObjectId head = repository.resolve("HEAD"); if (head == null) { return s; } try (RevWalk revWalk = new RevWalk(repository); TreeWalk treeWalk = new TreeWalk(repository)) { RevCommit commit = revWalk.parseCommit(head); treeWalk.addTree(commit.getTree()); treeWalk.setRecursive(true); treeWalk.setFilter(PathFilter.create(PathUtils.separatorsToUnix(s.getSourcePath().toString()))); if (treeWalk.next()) { return s.withMarkers(s.getMarkers().add(new GitTreeEntry(randomId(), treeWalk.getObjectId(0).name(), treeWalk.getRawMode(0)))); } return s; } } catch (IOException e) { throw new UncheckedIOException(e); } }; } private static List filterGeneratedSourceRoots(MavenProject mavenProject, List sourceRoots) { Path buildDirectory = Paths.get(mavenProject.getBuild().getDirectory()); return sourceRoots.stream() .filter(root -> !Paths.get(root).startsWith(buildDirectory)) .collect(toList()); } private static Collection listJavaSources(MavenProject mavenProject, List compileSourceRoots) throws MojoExecutionException { Set javaSources = new LinkedHashSet<>(); for (String compileSourceRoot : compileSourceRoots) { javaSources.addAll(listSources(mavenProject.getBasedir().toPath().resolve(compileSourceRoot), ".java")); } return javaSources; } private List listKotlinSources(MavenProject mavenProject, String executionId, String fallbackSourceDirectory) throws MojoExecutionException { Plugin kotlinPlugin = mavenProject.getPlugin("org.jetbrains.kotlin:kotlin-maven-plugin"); if (kotlinPlugin == null) { return emptyList(); } PluginExecution execution = kotlinPlugin.getExecutionsAsMap().get(executionId); if (execution != null && execution.getConfiguration() instanceof Xpp3Dom) { Xpp3Dom configuration = (Xpp3Dom) execution.getConfiguration(); Xpp3Dom sourceDirs = configuration.getChild("sourceDirs"); if (sourceDirs != null) { List kotlinSources = new ArrayList<>(); for (Xpp3Dom sourceDir : sourceDirs.getChildren("sourceDir")) { Path sourceDirectory = mavenProject.getBasedir().toPath().resolve(sourceDir.getValue()); kotlinSources.addAll(listSources(sourceDirectory, ".kt")); } return kotlinSources; } } return listSources(mavenProject.getBasedir().toPath().resolve(fallbackSourceDirectory), ".kt"); } private static List listGroovySources(MavenProject mavenProject, List compileSourceRoots) throws MojoExecutionException { List groovySources = new ArrayList<>(); for (String compileSourceRoot : compileSourceRoots) { groovySources.addAll(listSources(mavenProject.getBasedir().toPath().resolve(compileSourceRoot), ".groovy")); } // Also check conventional Groovy source directories Path basedir = mavenProject.getBasedir().toPath(); for (String compileSourceRoot : compileSourceRoots) { Path javaRoot = basedir.resolve(compileSourceRoot); // If the source root is src/main/java, also check src/main/groovy if (javaRoot.endsWith("java")) { Path groovyRoot = javaRoot.resolveSibling("groovy"); if (Files.exists(groovyRoot)) { groovySources.addAll(listSources(groovyRoot, ".groovy")); } } } return groovySources; } private static List listSources(Path sourceDirectory, String extension) throws MojoExecutionException { if (!Files.exists(sourceDirectory)) { return emptyList(); } try { List result = new ArrayList<>(); Files.walkFileTree(sourceDirectory, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.toString().endsWith(extension)) { result.add(file); } return FileVisitResult.CONTINUE; } }); return result; } catch (IOException e) { throw new MojoExecutionException("Unable to list source files of " + extension, e); } } private Stream parseMavenWrapperFiles(MavenProject mavenProject, Collection exclusions, Set parsedPaths, ExecutionContext ctx) { Stream sourceFiles = Stream.empty(); if (mavenProject.getParent() == null) { OmniParser omniParser = omniParser(parsedPaths, mavenProject); List mavenWrapperFiles = Stream.of( Paths.get(MVN_JVM_CONFIG), Paths.get(MVN_MAVEN_CONFIG), MavenWrapper.WRAPPER_BATCH_LOCATION, MavenWrapper.WRAPPER_JAR_LOCATION, MavenWrapper.WRAPPER_PROPERTIES_LOCATION, MavenWrapper.WRAPPER_SCRIPT_LOCATION) .map(Path::toAbsolutePath) .filter(Files::exists) .filter(it -> !isExcluded(repository, exclusions, it)) .filter(omniParser::accept) .collect(toList()); sourceFiles = omniParser.parse(mavenWrapperFiles, baseDir, ctx); } return sourceFiles; } protected Stream parseNonProjectResources(MavenProject mavenProject, Set parsedPaths, ExecutionContext ctx) { if (!parseAdditionalResources) { return Stream.empty(); } //Collect any additional yaml/properties/xml files that are NOT already in a source set. OmniParser omniParser = omniParser(parsedPaths, mavenProject); List accepted = omniParser.acceptedPaths(baseDir, mavenProject.getBasedir().toPath()); return omniParser.parse(accepted, baseDir, ctx); } private OmniParser omniParser(Set parsedPaths, MavenProject mavenProject) { return OmniParser.builder( OmniParser.defaultResourceParsers(), PlainTextParser.builder() .plainTextMasks(baseDir, plainTextMasks) .build(), QuarkParser.builder().build() ) .exclusionMatchers(pathMatchers(baseDir, mergeExclusions(mavenProject))) .exclusions(parsedPaths) .sizeThresholdMb(sizeThresholdMb) .build(); } private Collection mergeExclusions(MavenProject mavenProject) { Path projectPath = mavenProject.getBasedir().toPath(); return Stream.concat( pathsToOtherMavenProjects(mavenProject).stream() .filter(otherProjectPath -> !projectPath.startsWith(otherProjectPath)) .map(subproject -> separatorsToUnix(baseDir.relativize(subproject).toString())), exclusions.stream() ).collect(toList()); } private Collection pathMatchers(Path basePath, Collection pathExpressions) { return pathExpressions.stream() .map(o -> basePath.getFileSystem().getPathMatcher("glob:" + o)) .collect(toList()); } private static final Map REPO_ROOT_TO_PROVENANCE = new HashMap<>(); private @Nullable GitProvenance gitProvenance(Path baseDir, @Nullable BuildEnvironment buildEnvironment) { try { // Computing git provenance can be expensive for repositories with many commits, ensure we do it only once return REPO_ROOT_TO_PROVENANCE.computeIfAbsent(baseDir, dir -> GitProvenance.fromProjectDirectory(dir, 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; } private void logError(MavenProject mavenProject, String message) { logger.error("Project [" + mavenProject.getName() + "] " + message); } private void logInfo(MavenProject mavenProject, String message) { logger.info("Project [" + mavenProject.getName() + "] " + message); } private void logDebug(MavenProject mavenProject, String message) { logger.debug("Project [" + mavenProject.getName() + "] " + message); } @SuppressWarnings({"RedundantThrows", "unchecked"}) private static E sneakyThrow(Throwable e) throws E { return (E) e; } private static ResolvedGroupArtifactVersion createResolvedGAV(MavenProject project, MavenExecutionContextView ctx) { return new ResolvedGroupArtifactVersion( ctx.getLocalRepository().getUri(), project.getGroupId(), project.getArtifactId(), project.getVersion(), project.getVersion().endsWith("-SNAPSHOT") ? null : project.getVersion() ); } private static @Nullable Pom createPom(MavenProject project) { Path pomPath = project.getFile().toPath(); try (InputStream is = Files.newInputStream(pomPath)) { RawPom rawPom = RawPom.parse(is, null); return rawPom.toPom(project.getBasedir().toPath().relativize(pomPath), null); } catch (IOException e) { return null; } } } ================================================ FILE: src/main/java/org/openrewrite/maven/MavenPomCacheBuilder.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.logging.Log; import org.jspecify.annotations.Nullable; import org.openrewrite.maven.cache.CompositeMavenPomCache; import org.openrewrite.maven.cache.InMemoryMavenPomCache; import org.openrewrite.maven.cache.MavenPomCache; import org.openrewrite.maven.cache.RocksdbMavenPomCache; import java.nio.file.Paths; public class MavenPomCacheBuilder { private final Log logger; public MavenPomCacheBuilder(Log logger) { this.logger = logger; } public @Nullable MavenPomCache build(@Nullable String pomCacheDirectory) { if (isJvm64Bit()) { try { if (pomCacheDirectory == null) { //Default directory in the RocksdbMavenPomCache is ".rewrite-cache" return new CompositeMavenPomCache( new InMemoryMavenPomCache(), new RocksdbMavenPomCache(Paths.get(System.getProperty("user.home"))) ); } return new CompositeMavenPomCache( new InMemoryMavenPomCache(), new RocksdbMavenPomCache(Paths.get(pomCacheDirectory)) ); } catch (Throwable e) { logger.warn("Unable to initialize RocksdbMavenPomCache, falling back to InMemoryMavenPomCache"); logger.debug(e); } } else { logger.warn("RocksdbMavenPomCache is not supported on 32-bit JVM. falling back to InMemoryMavenPomCache"); } return null; } private static boolean isJvm64Bit() { //It appears most JVM vendors set this property. Only return false if the //property has been set AND it is set to 32. return !"32".equals(System.getProperty("sun.arch.data.model", "64")); } } ================================================ FILE: src/main/java/org/openrewrite/maven/MeterRegistryProvider.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.MeterRegistry; import io.micrometer.core.instrument.composite.CompositeMeterRegistry; import org.apache.maven.plugin.logging.Log; import org.jspecify.annotations.Nullable; public class MeterRegistryProvider implements AutoCloseable { private final Log log; @Nullable private final String destination; @Nullable private MeterRegistry registry; public MeterRegistryProvider(Log log, @Nullable String destination) { this.log = log; this.destination = destination; } public MeterRegistry registry() { if (this.registry == null) { this.registry = buildRegistry(); } return this.registry; } private MeterRegistry buildRegistry() { if ("LOG".equals(destination)) { return new MavenLoggingMeterRegistry(log); } return new CompositeMeterRegistry(); } @Override public void close() { if (registry != null) { registry.close(); } } } ================================================ FILE: src/main/java/org/openrewrite/maven/RecipeCsvGenerateMojo.java ================================================ /* * Copyright 2026 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.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; import org.openrewrite.marketplace.RecipeMarketplace; import org.openrewrite.marketplace.RecipeMarketplaceReader; import org.openrewrite.marketplace.RecipeMarketplaceWriter; import org.openrewrite.maven.marketplace.MavenRecipeMarketplaceGenerator; import org.openrewrite.maven.tree.GroupArtifact; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * Generate a {@code recipes.csv} marketplace file from the recipes found in this project. * Scans compiled classes and resources in {@code target/classes/} for recipe definitions * (both Java class-based and YAML declarative recipes) and writes the result to * {@code src/main/resources/META-INF/rewrite/recipes.csv}. *

* If an existing {@code recipes.csv} is present, generated data is merged into it, * preserving any manually added entries. *

* {@code ./mvnw rewrite:recipeCsvGenerate} */ @Execute(phase = LifecyclePhase.PROCESS_CLASSES) @Mojo(name = "recipeCsvGenerate", requiresDependencyResolution = ResolutionScope.RUNTIME, threadSafe = true) public class RecipeCsvGenerateMojo extends AbstractRewriteMojo { @Override public void execute() throws MojoExecutionException { if (rewriteSkip) { getLog().info("Skipping execution"); return; } if ("pom".equals(project.getPackaging())) { getLog().info("Skipping pom-packaging project"); return; } Path classesDir = Paths.get(project.getBuild().getOutputDirectory()); if (!Files.exists(classesDir)) { getLog().warn("No compiled classes found at " + classesDir + ". Skipping."); return; } String groupId = project.getGroupId(); String artifactId = project.getArtifactId(); List classpath; try { classpath = new ArrayList<>(); for (String element : project.getRuntimeClasspathElements()) { Path p = Paths.get(element); if (!p.equals(classesDir)) { classpath.add(p); } } } catch (Exception e) { throw new MojoExecutionException("Failed to resolve runtime classpath", e); } getLog().info("Generating recipe CSV from: " + classesDir); getLog().info("Using GAV: " + groupId + ":" + artifactId); MavenRecipeMarketplaceGenerator generator = new MavenRecipeMarketplaceGenerator( new GroupArtifact(groupId, artifactId), classesDir, classpath ); RecipeMarketplace generated = generator.generate(); Path outputPath = project.getBasedir().toPath() .resolve("src/main/resources/META-INF/rewrite/recipes.csv"); RecipeMarketplace marketplace = generated; if (Files.exists(outputPath)) { getLog().info("Found existing recipes.csv, merging..."); RecipeMarketplaceReader reader = new RecipeMarketplaceReader(); RecipeMarketplace existing = reader.fromCsv(outputPath); existing.getRoot().merge(generated.getRoot()); marketplace = existing; } RecipeMarketplaceWriter writer = new RecipeMarketplaceWriter(); String csv = writer.toCsv(marketplace); // Skip if CSV has only a header line (no actual recipes) int lineCount = 0; for (int i = 0; i < csv.length(); i++) { if (csv.charAt(i) == '\n') { lineCount++; } } if (lineCount <= 1) { getLog().info("No recipes found, skipping recipes.csv generation"); return; } try { Files.createDirectories(outputPath.getParent()); Files.write(outputPath, csv.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new MojoExecutionException("Failed to write recipes.csv", e); } getLog().info("Generated recipes.csv at: " + outputPath.toAbsolutePath()); } } ================================================ FILE: src/main/java/org/openrewrite/maven/RewriteDiscoverMojo.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.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.jspecify.annotations.Nullable; import org.openrewrite.config.Environment; import org.openrewrite.config.OptionDescriptor; import org.openrewrite.config.RecipeDescriptor; import org.openrewrite.internal.StringUtils; import org.openrewrite.style.NamedStyles; import java.util.*; /** * Generate a report of the available recipes and styles found on the classpath.
*
* Can also be used to display information about a specific recipe. For example:
* {@code ./mvnw rewrite:discover -Ddetail=true -Drecipe=org.openrewrite.java.format.AutoFormat} */ @Mojo(name = "discover", threadSafe = true, requiresProject = false, aggregator = true) @SuppressWarnings("unused") public class RewriteDiscoverMojo extends AbstractRewriteMojo { /** * The name of a specific recipe to show details for. For example:
* {@code ./mvnw rewrite:discover -Ddetail=true -Drecipe=org.openrewrite.java.format.AutoFormat} */ @Parameter(property = "recipe") @Nullable String recipe; /** * Whether to display recipe details such as displayName, description, and configuration options. */ @Parameter(property = "detail", defaultValue = "false") boolean detail; /** * The maximum level of recursion to display recipe descriptors under recipeList. */ @Parameter(property = "recursion", defaultValue = "0") int recursion; @Override public void execute() throws MojoExecutionException { Environment env = environment(); Collection availableRecipeDescriptors = env.listRecipeDescriptors(); if (recipe != null) { RecipeDescriptor rd = getRecipeDescriptor(recipe, availableRecipeDescriptors); writeRecipeDescriptor(rd, detail, 0, 0); } else { Collection activeRecipeDescriptors = new HashSet<>(); for (String activeRecipe : getActiveRecipes()) { RecipeDescriptor rd = getRecipeDescriptor(activeRecipe, availableRecipeDescriptors); activeRecipeDescriptors.add(rd); } writeDiscovery(availableRecipeDescriptors, activeRecipeDescriptors, env.listStyles()); } } private static final String RECIPE_NOT_FOUND_EXCEPTION_MSG = "Could not find recipe '%s' among available recipes"; private static RecipeDescriptor getRecipeDescriptor(String recipe, Collection recipeDescriptors) throws MojoExecutionException { return recipeDescriptors.stream() .filter(r -> r.getName().equalsIgnoreCase(recipe)) .findAny() .orElseThrow(() -> new MojoExecutionException(String.format(RECIPE_NOT_FOUND_EXCEPTION_MSG, recipe))); } private void writeDiscovery(Collection availableRecipeDescriptors, Collection activeRecipeDescriptors, Collection availableStyles) { List availableRecipesSorted = new ArrayList<>(availableRecipeDescriptors); availableRecipesSorted.sort(Comparator.comparing(RecipeDescriptor::getName, String.CASE_INSENSITIVE_ORDER)); getLog().info("Available Recipes:"); for (RecipeDescriptor recipeDescriptor : availableRecipesSorted) { writeRecipeDescriptor(recipeDescriptor, detail, 0, 1); } List availableStylesSorted = new ArrayList<>(availableStyles); availableStylesSorted.sort(Comparator.comparing(NamedStyles::getName, String.CASE_INSENSITIVE_ORDER)); getLog().info(""); getLog().info("Available Styles:"); for (NamedStyles style : availableStylesSorted) { getLog().info(" " + style.getName()); } List activeStylesSorted = new ArrayList<>(getActiveStyles()); activeStylesSorted.sort(String.CASE_INSENSITIVE_ORDER); getLog().info(""); getLog().info("Active Styles:"); for (String activeStyle : activeStylesSorted) { getLog().info(" " + activeStyle); } List activeRecipesSorted = new ArrayList<>(activeRecipeDescriptors); activeRecipesSorted.sort(Comparator.comparing(RecipeDescriptor::getName, String.CASE_INSENSITIVE_ORDER)); getLog().info(""); getLog().info("Active Recipes:"); for (RecipeDescriptor recipeDescriptor : activeRecipesSorted) { writeRecipeDescriptor(recipeDescriptor, detail, 0, 1); } getLog().info(""); getLog().info("Found " + availableRecipeDescriptors.size() + " available recipes and " + availableStyles.size() + " available styles."); getLog().info("Configured with " + activeRecipeDescriptors.size() + " active recipes and " + getActiveStyles().size() + " active styles."); } private void writeRecipeDescriptor(RecipeDescriptor rd, boolean verbose, int currentRecursionLevel, int indentLevel) { String indent = StringUtils.repeat(" ", indentLevel); if (currentRecursionLevel <= recursion) { if (verbose) { getLog().info(indent + rd.getDisplayName()); getLog().info(indent + " " + rd.getName()); // Recipe parsed from yaml might have null description, even though that isn't technically allowed //noinspection ConstantConditions if (rd.getDescription() != null && !rd.getDescription().isEmpty()) { getLog().info(indent + " " + rd.getDescription()); } if (!rd.getOptions().isEmpty()) { getLog().info(indent + "options: "); for (OptionDescriptor od : rd.getOptions()) { getLog().info(indent + " " + od.getName() + ": " + od.getType() + (od.isRequired() ? "!" : "")); if (od.getDescription() != null && !od.getDescription().isEmpty()) { getLog().info(indent + " " + " " + od.getDescription()); } } } } else { getLog().info(indent + rd.getName()); } if (!rd.getRecipeList().isEmpty() && (currentRecursionLevel + 1 <= recursion)) { getLog().info(indent + "recipeList:"); for (RecipeDescriptor r : rd.getRecipeList()) { writeRecipeDescriptor(r, verbose, currentRecursionLevel + 1, indentLevel + 1); } } if (verbose) { getLog().info(""); } } } } ================================================ FILE: src/main/java/org/openrewrite/maven/RewriteDryRunMojo.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.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Generate warnings to the console for any recipe that would make changes, but do not make changes. *

* This variant of rewrite:dryRun will fork the maven life cycle and can be run as a "stand-alone" goal. It will * execute the maven build up to the process-test-classes phase. */ @Execute(phase = LifecyclePhase.PROCESS_TEST_CLASSES) @Mojo(name = "dryRun", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true, defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES) public class RewriteDryRunMojo extends AbstractRewriteDryRunMojo { } ================================================ FILE: src/main/java/org/openrewrite/maven/RewriteDryRunNoForkMojo.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.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Generate warnings to the console for any recipe that would make changes, but do not make changes. *

* This variant of rewrite:dryRun will not fork the maven life cycle and can be used (along with other goals) without * triggering repeated life-cycle events. It will execute the maven build up to the process-test-classes phase. */ @Mojo(name = "dryRunNoFork", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true, defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES) public class RewriteDryRunNoForkMojo extends AbstractRewriteDryRunMojo { } ================================================ FILE: src/main/java/org/openrewrite/maven/RewriteRunMojo.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.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Run the configured recipes and apply the changes locally. *

* This variant of rewrite:run will fork the maven life cycle and can be run as a "stand-alone" goal. It will * execute the maven build up to the process-test-classes phase. */ @Execute(phase = LifecyclePhase.PROCESS_TEST_CLASSES) @Mojo(name = "run", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true, defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES) public class RewriteRunMojo extends AbstractRewriteRunMojo { } ================================================ FILE: src/main/java/org/openrewrite/maven/RewriteRunNoForkMojo.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.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; /** * Run the configured recipes and apply the changes locally. *

* This variant of rewrite:run will not fork the maven life cycle and can be used (along with other goals) without * triggering repeated life-cycle events. */ @Mojo(name = "runNoFork", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true, defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES) public class RewriteRunNoForkMojo extends AbstractRewriteRunMojo { } ================================================ FILE: src/main/java/org/openrewrite/maven/RewriteTypeTableMojo.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.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.ResolutionScope; import org.eclipse.aether.artifact.Artifact; import org.openrewrite.java.internal.parser.TypeTable; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; import static java.nio.file.Files.exists; import static java.util.Collections.singleton; /** * Create a TypeTable in `src/main/resources/META-INF/rewrite/classpath.tsv.zip` for `rewrite.recipeArtifactCoordinates`. * {@code ./mvnw rewrite:typetable} */ @Execute(phase = LifecyclePhase.GENERATE_RESOURCES) @Mojo(name = "typetable", requiresDependencyResolution = ResolutionScope.TEST, defaultPhase = LifecyclePhase.GENERATE_RESOURCES) public class RewriteTypeTableMojo extends AbstractRewriteMojo { @Override public void execute() throws MojoExecutionException { Set recipeArtifactCoordinates = getRecipeArtifactCoordinates(); String srcMainResources = project.getResources().get(0).getDirectory(); Path tsvFile = Paths.get(srcMainResources).resolve(TypeTable.DEFAULT_RESOURCE_PATH); Path parentFile = tsvFile.getParent(); if (!parentFile.toFile().mkdirs() && !exists(parentFile)) { throw new MojoExecutionException("Unable to create " + parentFile); } try (TypeTable.Writer writer = TypeTable.newWriter(Files.newOutputStream(tsvFile))) { for (String recipeArtifactCoordinate : recipeArtifactCoordinates) { // Resolve per GAV, to handle multiple versions of the same artifact for (Artifact artifact : resolveArtifacts(recipeArtifactCoordinate)) { writer.jar(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion()) .write(artifact.getFile().toPath()); getLog().info(String.format("Wrote %s", artifact)); } } getLog().info("Wrote " + project.getBasedir().toPath().relativize(tsvFile)); } catch (IOException e) { throw new MojoExecutionException("Unable to generate TypeTable", e); } } private Set resolveArtifacts(String recipeArtifactCoordinate) throws MojoExecutionException { ArtifactResolver resolver = new ArtifactResolver(repositorySystem, mavenSession); Artifact artifact = resolver.createArtifact(recipeArtifactCoordinate); return resolver.resolveArtifactsAndDependencies(singleton(artifact)); } } ================================================ FILE: src/main/java/org/openrewrite/maven/SanitizedMarkerPrinter.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.openrewrite.Cursor; import org.openrewrite.PrintOutputCapture; import org.openrewrite.marker.Marker; import org.openrewrite.marker.SearchResult; import java.util.function.UnaryOperator; /** * A {@link PrintOutputCapture} that sanitizes the diff of informational markers, * so these aren't accidentally committed to source control. */ public class SanitizedMarkerPrinter implements PrintOutputCapture.MarkerPrinter { @Override public String beforeSyntax(Marker marker, Cursor cursor, UnaryOperator commentWrapper) { if (marker instanceof SearchResult) { return DEFAULT.beforeSyntax(marker, cursor, commentWrapper); } return ""; } @Override public String afterSyntax(Marker marker, Cursor cursor, UnaryOperator commentWrapper) { if (marker instanceof SearchResult) { return DEFAULT.afterSyntax(marker, cursor, commentWrapper); } return ""; } } ================================================ FILE: src/main/java/org/openrewrite/maven/package-info.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. */ @org.jspecify.annotations.NullMarked package org.openrewrite.maven; ================================================ FILE: src/test/java/org/openrewrite/maven/AbstractRewriteMojoTest.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.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.DefaultMavenExecutionResult; import org.apache.maven.execution.MavenSession; import org.apache.maven.project.MavenProject; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.openrewrite.Recipe; import org.openrewrite.config.Environment; import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; class AbstractRewriteMojoTest { @Test void resolvePropertiesInYamlUsesUserProperties(@TempDir Path temp) throws Exception { DefaultMavenExecutionRequest request = new DefaultMavenExecutionRequest(); Properties userProps = new Properties(); userProps.setProperty("myValue", "resolvedValue"); request.setUserProperties(userProps); MavenSession session = new MavenSession(null, null, request, new DefaultMavenExecutionResult()); String yaml = """ type: specs.openrewrite.org/v1beta/recipe name: test.UserPropRecipe displayName: "${myValue}" recipeList: [] """; Files.writeString(temp.resolve("rewrite.yml"), yaml); AbstractRewriteMojo mojo = new AbstractRewriteMojo() { { configLocation = "rewrite.yml"; resolvePropertiesInYaml = true; project = new MavenProject(); project.setFile(new File(temp.toFile(), "pom.xml")); mavenSession = session; } @Override public void execute() { } }; Environment env = mojo.environment(null); Collection recipes = env.listRecipes(); Recipe recipe = recipes.stream() .filter(r -> "test.UserPropRecipe".equals(r.getName())) .findFirst() .orElseThrow(() -> new AssertionError("Recipe not found")); assertThat(recipe.getDisplayName()).isEqualTo("resolvedValue"); } @ParameterizedTest @ValueSource(strings = {"rewrite.yml"}) void configLocation(String loc, @TempDir Path temp) throws Exception { AbstractRewriteMojo mojo = new AbstractRewriteMojo() { { configLocation = loc; project = new MavenProject(); project.setFile(new File(temp.toFile(), "pom.xml")); } @Override public void execute() { } }; if (!loc.startsWith("http")) { Files.writeString(temp.resolve(loc), "rewrite"); } AbstractRewriteMojo.Config config = mojo.getConfig(); assertThat(config).isNotNull(); try (InputStream is = config.inputStream) { assertThat(is.readAllBytes()).isNotEmpty(); } } } ================================================ FILE: src/test/java/org/openrewrite/maven/BasicIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.Disabled; import org.openrewrite.maven.jupiter.extension.GitJupiterExtension; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @GitJupiterExtension @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) class BasicIT { @MavenGoal("clean") @MavenGoal("package") @MavenTest void groupid_artifactid_should_be_ok(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .containsOnly("JAR will be empty - no content was marked for inclusion!"); } @Disabled @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:dryRun") @MavenOption(value = MavenCLIOptions.SETTINGS, parameter = "settings.xml") @MavenTest void null_check_profile_activation(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("Applying recipes would make no changes. No patch file generated.")); assertThat(result) .isSuccessful() .out() .warn() // Ignore warning logged on Mac OS X; https://github.com/openrewrite/rewrite-maven-plugin/issues/506 .filteredOn(warn -> !"Unable to initialize RocksdbMavenPomCache, falling back to InMemoryMavenPomCache".equals(warn)) .isEmpty(); } @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:dryRun") @MavenTest @SystemProperty(value = "ossrh_snapshots_url", content = "https://central.sonatype.com/repository/maven-snapshots") void resolves_maven_properties_from_user_provided_system_properties(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .allSatisfy(line -> assertThat(line).doesNotContain("Invalid repository URL ${ossrh_snapshots_url}")) .allSatisfy(line -> assertThat(line).doesNotContain("Unable to resolve property ${ossrh_snapshots_url}")); } @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:dryRun") @MavenOption(value = MavenCLIOptions.SETTINGS, parameter = "settings-user.xml") @MavenProfile("example_profile_id") @MavenTest @SystemProperty(value = "REPOSITORY_URL", content = "https://maven-eu.nuxeo.org/nexus/content/repositories/public/") void resolves_settings(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .plain() .allSatisfy(line -> assertThat(line).doesNotContain("Illegal character in path at index 1")); } @MavenGoal("clean") @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:dryRun") @MavenTest void snapshot_ok(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .isEmpty(); assertThat(result).out().info().contains("Running recipe(s)..."); } } ================================================ FILE: src/test/java/org/openrewrite/maven/DiscoverNoActiveRecipeIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:discover") @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) class DiscoverNoActiveRecipeIT { @MavenTest void single_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .error() .noneSatisfy(line -> assertThat(line).contains("Could not find recipe 'null' among available recipes")); } } ================================================ FILE: src/test/java/org/openrewrite/maven/KotlinIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.openrewrite.maven.jupiter.extension.GitJupiterExtension; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @DisabledOnOs(OS.WINDOWS) @MavenGoal("install") @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:run") @GitJupiterExtension @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) @MavenOption(MavenCLIOptions.VERBOSE) class KotlinIT { @MavenTest void kotlin_in_src_main_java(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .debug() .anySatisfy(line -> assertThat(line).contains("Scanned 1 kotlin source files in main scope.")) .anySatisfy(line -> assertThat(line).contains("org.openrewrite.kotlin.format.AutoFormat")); } @MavenTest void kotlin_in_src_main_test(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .debug() .anySatisfy(line -> assertThat(line).contains("Scanned 1 kotlin source files in test scope.")) .anySatisfy(line -> assertThat(line).contains("org.openrewrite.kotlin.format.AutoFormat")); } } ================================================ FILE: src/test/java/org/openrewrite/maven/MavenCLIExtra.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; final class MavenCLIExtra { /** * User property to mute Maven 3.9.2+ "plugin validation" warnings. */ static final String MUTE_PLUGIN_VALIDATION_WARNING = "-Dorg.slf4j.simpleLogger.log.org.apache.maven.plugin.internal.DefaultPluginValidationManager=off"; } ================================================ FILE: src/test/java/org/openrewrite/maven/MavenMojoProjectParserIsExcludedTest.java ================================================ /* * Copyright 2026 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.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.openrewrite.jgit.api.Git; import org.openrewrite.jgit.lib.Repository; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.Collection; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for the gitignore handling in {@link MavenMojoProjectParser#isExcluded}. *

* The original implementation had a bug where the recursive call that prepends * "/" for PathMatcher compatibility caused the JGit TreeWalk path comparison * to never match, making the gitignore check dead code. These tests verify * that gitignore exclusions actually take effect for relative paths. */ class MavenMojoProjectParserIsExcludedTest { @Test void untrackedGitIgnoredFileIsExcluded(@TempDir Path tempDir) throws Exception { try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Repository repo = git.getRepository(); writeFile(tempDir.resolve(".gitignore"), "generated.txt\n"); writeFile(tempDir.resolve("generated.txt"), "untracked content"); git.add().addFilepattern(".gitignore").call(); git.commit().setMessage("initial").call(); assertThat(MavenMojoProjectParser.isExcluded(repo, emptyList(), Path.of("generated.txt"))) .as("untracked gitignored file should be excluded") .isTrue(); } } @Test void trackedGitIgnoredFileIsNotExcluded(@TempDir Path tempDir) throws Exception { try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Repository repo = git.getRepository(); writeFile(tempDir.resolve("tracked-ignored.txt"), "content"); git.add().addFilepattern("tracked-ignored.txt").call(); git.commit().setMessage("initial").call(); writeFile(tempDir.resolve(".gitignore"), "tracked-ignored.txt\n"); git.add().addFilepattern(".gitignore").call(); git.commit().setMessage("add gitignore").call(); assertThat(MavenMojoProjectParser.isExcluded(repo, emptyList(), Path.of("tracked-ignored.txt"))) .as("tracked gitignored file should NOT be excluded") .isFalse(); } } @Test void untrackedFileInGitIgnoredDirectoryIsExcluded(@TempDir Path tempDir) throws Exception { try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Repository repo = git.getRepository(); writeFile(tempDir.resolve(".gitignore"), "target/\n"); writeFile(tempDir.resolve("target/output.txt"), "untracked content"); git.add().addFilepattern(".gitignore").call(); git.commit().setMessage("initial").call(); assertThat(MavenMojoProjectParser.isExcluded(repo, emptyList(), Path.of("target/output.txt"))) .as("untracked file in gitignored directory should be excluded") .isTrue(); } } @Test void trackedFileInGitIgnoredDirectoryIsNotExcluded(@TempDir Path tempDir) throws Exception { try (Git git = Git.init().setDirectory(tempDir.toFile()).call()) { Repository repo = git.getRepository(); writeFile(tempDir.resolve("target/output.txt"), "tracked content"); git.add().addFilepattern("target/output.txt").call(); git.commit().setMessage("initial").call(); writeFile(tempDir.resolve(".gitignore"), "target/\n"); git.add().addFilepattern(".gitignore").call(); git.commit().setMessage("add gitignore").call(); assertThat(MavenMojoProjectParser.isExcluded(repo, emptyList(), Path.of("target/output.txt"))) .as("tracked file in gitignored directory should NOT be excluded") .isFalse(); } } @Test void exclusionMatcherMatchesDirectly() { Collection matchers = singletonList( FileSystems.getDefault().getPathMatcher("glob:**/secret.properties")); assertThat(MavenMojoProjectParser.isExcluded(null, matchers, Path.of("config/secret.properties"))) .as("path matching exclusion pattern should be excluded") .isTrue(); } @Test void exclusionMatcherDoesNotMatchUnrelatedPath() { Collection matchers = singletonList( FileSystems.getDefault().getPathMatcher("glob:**/secret.properties")); assertThat(MavenMojoProjectParser.isExcluded(null, matchers, Path.of("config/application.properties"))) .as("path not matching exclusion pattern should not be excluded") .isFalse(); } @Test void exclusionMatcherMatchesRootFileViaPrefixedSlash() { // PathMatcher won't match "pom.xml" against "**/pom.xml" without a leading slash; // isExcluded handles this by re-checking with a "/" prefix for relative paths Collection matchers = singletonList( FileSystems.getDefault().getPathMatcher("glob:**/pom.xml")); assertThat(MavenMojoProjectParser.isExcluded(null, matchers, Path.of("pom.xml"))) .as("root-level file should match **/pom.xml via leading-slash prefixing") .isTrue(); } @Test void exclusionMatcherMatchesRootFileWithLeadingSlash() { // When the path already has a leading slash, it should match directly // without needing the prefixing logic Collection matchers = singletonList( FileSystems.getDefault().getPathMatcher("glob:**/pom.xml")); assertThat(MavenMojoProjectParser.isExcluded(null, matchers, Path.of("/pom.xml"))) .as("root-level file with leading slash should match **/pom.xml directly") .isTrue(); } @Test void exclusionMatcherMatchesSubdirFileWithoutPrefixing() { // A file in a subdirectory should match directly without needing the "/" prefix path Collection matchers = singletonList( FileSystems.getDefault().getPathMatcher("glob:**/pom.xml")); assertThat(MavenMojoProjectParser.isExcluded(null, matchers, Path.of("module/pom.xml"))) .as("subdirectory file should match **/pom.xml directly") .isTrue(); } private static void writeFile(Path path, String content) throws Exception { Files.createDirectories(path.getParent()); Files.write(path, content.getBytes(StandardCharsets.UTF_8)); } } ================================================ FILE: src/test/java/org/openrewrite/maven/MavenMojoProjectParserTest.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.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.openrewrite.java.marker.JavaVersion; import java.nio.charset.Charset; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; /** * @author Fabian Krüger */ class MavenMojoProjectParserTest { @DisplayName("Given No Java version information exists in Maven Then java.specification.version should be used") @Test void givenNoJavaVersionInformationExistsInMavenThenJavaSpecificationVersionShouldBeUsed() { JavaVersion marker = MavenMojoProjectParser.getSrcTestJavaVersion(new MavenProject()); assertThat(marker.getSourceCompatibility()).isEqualTo(System.getProperty("java.specification.version")); assertThat(marker.getTargetCompatibility()).isEqualTo(System.getProperty("java.specification.version")); } @DisplayName("getCharset should resolve encoding from property placeholder") @Test void getCharsetShouldResolveEncodingFromPropertyPlaceholder() { MavenProject mavenProject = new MavenProject(); mavenProject.getProperties().setProperty("java.encoding", "UTF-8"); // Set up maven-compiler-plugin with encoding as property placeholder Plugin compilerPlugin = new Plugin(); compilerPlugin.setGroupId("org.apache.maven.plugins"); compilerPlugin.setArtifactId("maven-compiler-plugin"); Xpp3Dom configuration = new Xpp3Dom("configuration"); Xpp3Dom encoding = new Xpp3Dom("encoding"); encoding.setValue("${java.encoding}"); configuration.addChild(encoding); compilerPlugin.setConfiguration(configuration); Build build = new Build(); build.addPlugin(compilerPlugin); mavenProject.setBuild(build); // Should resolve the property and return the charset Optional charset = MavenMojoProjectParser.getCharset(mavenProject); assertThat(charset).isPresent(); assertThat(charset.get().name()).isEqualTo("UTF-8"); } @DisplayName("getCharset should return empty when property placeholder is unresolved") @Test void getCharsetShouldReturnEmptyWhenPropertyPlaceholderIsUnresolved() { MavenProject mavenProject = new MavenProject(); // Set up maven-compiler-plugin with encoding as property placeholder (not defined) Plugin compilerPlugin = new Plugin(); compilerPlugin.setGroupId("org.apache.maven.plugins"); compilerPlugin.setArtifactId("maven-compiler-plugin"); Xpp3Dom configuration = new Xpp3Dom("configuration"); Xpp3Dom encoding = new Xpp3Dom("encoding"); encoding.setValue("${java.encoding}"); configuration.addChild(encoding); compilerPlugin.setConfiguration(configuration); Build build = new Build(); build.addPlugin(compilerPlugin); mavenProject.setBuild(build); // Should not throw IllegalCharsetNameException assertThatCode(() -> MavenMojoProjectParser.getCharset(mavenProject)) .doesNotThrowAnyException(); // Should return empty when encoding is unresolved placeholder Optional charset = MavenMojoProjectParser.getCharset(mavenProject); assertThat(charset).isEmpty(); } @DisplayName("getCharset should not throw when project.build.sourceEncoding is a property placeholder") @Test void getCharsetShouldNotThrowWhenSourceEncodingIsPropertyPlaceholder() { MavenProject mavenProject = new MavenProject(); mavenProject.setBuild(new Build()); mavenProject.getProperties().setProperty("project.build.sourceEncoding", "${java.encoding}"); // Should not throw IllegalCharsetNameException assertThatCode(() -> MavenMojoProjectParser.getCharset(mavenProject)) .doesNotThrowAnyException(); // Should return empty when encoding is unresolved placeholder Optional charset = MavenMojoProjectParser.getCharset(mavenProject); assertThat(charset).isEmpty(); } @DisplayName("getCharset should return charset when encoding is valid") @Test void getCharsetShouldReturnCharsetWhenEncodingIsValid() { MavenProject mavenProject = new MavenProject(); // Set up maven-compiler-plugin with valid encoding Plugin compilerPlugin = new Plugin(); compilerPlugin.setGroupId("org.apache.maven.plugins"); compilerPlugin.setArtifactId("maven-compiler-plugin"); Xpp3Dom configuration = new Xpp3Dom("configuration"); Xpp3Dom encoding = new Xpp3Dom("encoding"); encoding.setValue("UTF-8"); configuration.addChild(encoding); compilerPlugin.setConfiguration(configuration); Build build = new Build(); build.addPlugin(compilerPlugin); mavenProject.setBuild(build); Optional charset = MavenMojoProjectParser.getCharset(mavenProject); assertThat(charset).isPresent(); assertThat(charset.get().name()).isEqualTo("UTF-8"); } } ================================================ FILE: src/test/java/org/openrewrite/maven/RecipeCsvGenerateIT.java ================================================ /* * Copyright 2026 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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:recipeCsvGenerate") @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) class RecipeCsvGenerateIT { @MavenTest void generates_csv_from_yaml_recipe(MavenExecutionResult result) { assertThat(result) .isSuccessful() .project() .has("src/main/resources/META-INF/rewrite"); assertThat(result).out().info() .anySatisfy(line -> assertThat(line).contains("Generated recipes.csv")); } @MavenTest void generates_csv_from_java_recipe(MavenExecutionResult result) { assertThat(result) .isSuccessful() .project() .has("src/main/resources/META-INF/rewrite"); assertThat(result).out().info() .anySatisfy(line -> assertThat(line).contains("Generated recipes.csv")); } } ================================================ FILE: src/test/java/org/openrewrite/maven/RewriteDiscoverIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.Nested; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenGoal("clean") @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:discover") @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) class RewriteDiscoverIT { @Nested class RecipeLookup { @MavenTest @SystemProperty(value = "detail", content = "true") void rewrite_discover_detail(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("options")); assertThat(result).out().warn().isEmpty(); } @MavenTest @SystemProperty(value = "recipe", content = "org.openrewrite.JAVA.format.AutoFormAT") void rewrite_discover_recipe_lookup_case_insensitive(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.java.format.AutoFormat")); } @MavenTest @SystemProperty(value = "recursion", content = "1") void rewrite_discover_recursion(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("recipeList")); assertThat(result).out().warn().isEmpty(); } } @MavenTest void rewrite_discover_default(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .matches(logLines -> logLines.stream().anyMatch(logLine -> logLine.contains("org.openrewrite.java.format.AutoFormat")) ) .matches(logLines -> logLines.stream().anyMatch(logLine -> logLine.contains("org.openrewrite.java.SpringFormat")) ); assertThat(result).out().warn().isEmpty(); } @MavenTest void rewrite_discover_rewrite_yml(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("com.example.RewriteDiscoverIT.CodeCleanup")); assertThat(result).out().warn().isEmpty(); } @MavenTest void rewrite_discover_multi_module(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .satisfiesOnlyOnce(line -> assertThat(line).contains(":discover")); assertThat(result).out().warn().isEmpty(); } } ================================================ FILE: src/test/java/org/openrewrite/maven/RewriteDryRunIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.openrewrite.maven.jupiter.extension.GitJupiterExtension; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:dryRun") @GitJupiterExtension @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) @MavenOption(MavenCLIOptions.VERBOSE) class RewriteDryRunIT { @MavenTest void fail_on_dry_run(MavenExecutionResult result) { assertThat(result) .isFailure() .out() .error() .anySatisfy(line -> assertThat(line).contains("Applying recipes would make changes")); } @MavenTest void multi_module_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.staticanalysis.SimplifyBooleanExpression")); } @MavenTest void recipe_order(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("Using active recipe(s) [com.example.RewriteDryRunIT.CodeCleanup, org.openrewrite.java.format.AutoFormat, org.openrewrite.staticanalysis.SimplifyBooleanExpression]")); } @MavenTest void single_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.java.format.AutoFormat")); } @MavenTest @SystemProperties({ @SystemProperty(value = "rewrite.recipeArtifactCoordinates", content = "org.openrewrite.recipe:rewrite-testing-frameworks:2.0.3"), @SystemProperty(value = "rewrite.activeRecipes", content = "org.openrewrite.java.testing.cleanup.AssertTrueNullToAssertNull") }) void no_plugin_in_pom(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.java.testing.cleanup.AssertTrueNullToAssertNull")); } } ================================================ FILE: src/test/java/org/openrewrite/maven/RewriteRunIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; import org.junit.jupiter.api.condition.OS; import org.openrewrite.maven.jupiter.extension.GitJupiterExtension; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.InstanceOfAssertFactories.STRING; import static org.openrewrite.PathUtils.separatorsToSystem; @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:run") @GitJupiterExtension @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) class RewriteRunIT { @MavenTest void multi_module_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.staticanalysis.SimplifyBooleanExpression")); } @MavenTest void multi_module_resources(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains("Changes have been made to %s by:".formatted(separatorsToSystem("project/a/src/main/resources/example.xml"))) .contains(" org.openrewrite.xml.ChangeTagName: {elementName=/foo, newName=bar}"); } @MavenGoal("generate-test-sources") @MavenTest @SystemProperties({ @SystemProperty(value = "rewrite.activeRecipes", content = "org.openrewrite.java.search.FindTypes"), @SystemProperty(value = "rewrite.options", content = "fullyQualifiedTypeName=org.junit.jupiter.api.Test") }) void multi_source_sets_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains("Changes have been made to %s by:".formatted(separatorsToSystem("project/src/integration-test/java/sample/IntegrationTest.java"))) .contains("Changes have been made to %s by:".formatted(separatorsToSystem("project/src/test/java/sample/RegularTest.java"))); } @MavenGoal("generate-sources") @MavenTest @SystemProperties({ @SystemProperty(value = "rewrite.activeRecipes", content = "org.openrewrite.java.format.SingleLineComments"), }) void multi_main_source_sets_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains("Changes have been made to project/src/main/java/sample/MainClass.java by:") .contains("Changes have been made to project/src/additional-main/java/sample/AdditionalMainClass.java by:"); } @MavenTest void basedir_resource_no_plaintext_leak(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains( "Changes have been made to %s by:".formatted(separatorsToSystem("project/src/main/java/sample/Main.java")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/src/test/java/sample/MainTest.java")) ); } @MavenTest void single_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.java.format.AutoFormat")); } @MavenTest void checkstyle_inline_rules(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .noneSatisfy(line -> assertThat(line).contains("Unable to parse checkstyle configuration")); } @MavenTest void recipe_project(MavenExecutionResult result) { assertThat(result) .isFailure() .out() .error() .anySatisfy(line -> assertThat(line).contains(separatorsToSystem("/sample/ThrowingRecipe.java"), "This recipe throws an exception")); } @MavenTest void cloud_suitability_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("some.jks")); } @MavenTest @SystemProperties({ @SystemProperty(value = "rewrite.activeRecipes", content = "org.openrewrite.maven.RemovePlugin"), @SystemProperty(value = "rewrite.options", content = "groupId=org.openrewrite.maven,artifactId=rewrite-maven-plugin") }) void command_line_options(MavenExecutionResult result) { assertThat(result).isSuccessful().out().error().isEmpty(); assertThat(result).isSuccessful().out().warn() .contains("Changes have been made to %s by:".formatted(separatorsToSystem("project/pom.xml"))) .contains(" org.openrewrite.maven.RemovePlugin: {groupId=org.openrewrite.maven, artifactId=rewrite-maven-plugin}"); assertThat(result.getMavenProjectResult().getModel().getBuild()).isNull(); } @DisabledOnOs(value = OS.WINDOWS, disabledReason = "Quotes for comment are removed during execution") @SystemProperties({ @SystemProperty(value = "rewrite.activeRecipes", content = "org.openrewrite.java.AddCommentToMethod"), @SystemProperty(value = "rewrite.options", content = "comment='{\"test\":{\"some\":\"yeah\"}}',methodPattern=sample.SomeClass doTheThing(..)") }) @MavenTest void command_line_options_json(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains("Changes have been made to %s by:".formatted(separatorsToSystem("project/src/main/java/sample/SomeClass.java"))) .contains(" org.openrewrite.java.AddCommentToMethod: {comment='{\"test\":{\"some\":\"yeah\"}}', methodPattern=sample.SomeClass doTheThing(..)}"); } @MavenTest void java_upgrade_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .filteredOn(line -> line.contains("Changes have been made")) .hasSize(1); } @MavenTest void java_compiler_plugin_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .filteredOn(line -> line.contains("Changes have been made")) .hasSize(1); } @MavenTest void container_masks(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains( "Changes have been made to %s by:".formatted(separatorsToSystem("project/containerfile.build")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/Dockerfile")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/Containerfile")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/build.dockerfile")) ); } @MavenTest void datatable_export(MavenExecutionResult result) throws Exception { assertThat(result).isSuccessful().out().error().isEmpty(); assertThat(result).isSuccessful().out().warn() .contains("Changes have been made to %s by:".formatted(separatorsToSystem("project/pom.xml"))) .contains( " org.openrewrite.maven.search.DependencyInsight: {groupIdPattern=*, artifactIdPattern=guava, scope=compile}", " org.openrewrite.maven.search.DependencyInsight: {groupIdPattern=*, artifactIdPattern=lombok, scope=compile}" ); Path targetProjectDirectory = result.getMavenProjectResult().getTargetProjectDirectory(); // Verify that a CSV file with DependenciesInUse datatable exists Path datatablesDir = targetProjectDirectory.resolve("target/rewrite/datatables"); assertThat(datatablesDir).exists().isDirectory(); // Find the timestamped directory (format: YYYY-MM-DD_HH-mm-ss-SSS) Path csvFile; try (Stream timestampedDirs = Files.list(datatablesDir)) { Path timestampedDir = timestampedDirs .filter(Files::isDirectory) .findFirst() .orElseThrow(() -> new AssertionError("No timestamped directory found in " + datatablesDir)); try (Stream csvFiles = Files.list(timestampedDir)) { csvFile = csvFiles .filter(p -> p.getFileName().toString().startsWith("org.openrewrite.maven.table.DependenciesInUse") && p.getFileName().toString().endsWith(".csv")) .findFirst() .orElseThrow(() -> new AssertionError("No DependenciesInUse CSV file found in " + timestampedDir)); } assertThat(csvFile).exists().isRegularFile(); } // Verify CSV contains expected structure and data rows // CSV format: 3 comment lines (@name, @instanceName, @group), header row, data rows List lines = Files.readAllLines(csvFile); // Filter out comment lines List dataLines = lines.stream() .filter(l -> !l.startsWith("#")) .collect(toList()); assertThat(dataLines) .hasSizeGreaterThanOrEqualTo(3) // header + 2 data rows .first(as(STRING)) .contains("groupId", "artifactId"); // CSV header // Get only the data rows (skip header) assertThat(dataLines.subList(1, dataLines.size())) .hasSizeGreaterThanOrEqualTo(2) .anySatisfy(line -> assertThat(line).contains("com.google.guava", "guava")) .anySatisfy(line -> assertThat(line).contains("org.projectlombok", "lombok")); } @MavenTest @SystemProperty(value = "rewrite.additionalPlainTextMasks", content = "**/*.ext,**/.in-root") void plaintext_masks(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .warn() .contains( "Changes have been made to %s by:".formatted(separatorsToSystem("project/src/main/java/sample/in-src.ext")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/.in-root")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/from-default-list.py")), "Changes have been made to %s by:".formatted(separatorsToSystem("project/src/main/java/sample/Dummy.java")) ) .doesNotContain("in-root.ignored"); } /** * On JDK 25, Lombok annotation processing on comment-free main sources followed by test sources * with comments triggers a LinkageError in JavaUnrestrictedClassLoader.defineClass(). * Requires --add-exports flags in .mvn/jvm.config for the fallback to work. */ @MavenTest @EnabledForJreRange(min = JRE.JAVA_25) void lombok_jdk25_linkage_error(MavenExecutionResult result) { assertThat(result) .isSuccessful(); } } ================================================ FILE: src/test/java/org/openrewrite/maven/RewriteRunParallelIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.openrewrite.maven.jupiter.extension.GitJupiterExtension; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @DisabledOnOs(OS.WINDOWS) @MavenGoal("${project.groupId}:${project.artifactId}:${project.version}:run") @GitJupiterExtension @MavenJupiterExtension @MavenOption(value = MavenCLIOptions.THREADS, parameter = "2") @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) class RewriteRunParallelIT { @MavenTest void multi_module_project(MavenExecutionResult result) { assertThat(result) .isSuccessful() .out() .info() .anySatisfy(line -> assertThat(line).contains("Delaying execution to the end of multi-module project for org.openrewrite.maven:b:1.0")); assertThat(result) .isSuccessful() .out() .warn() .anySatisfy(line -> assertThat(line).contains("org.openrewrite.staticanalysis.SimplifyBooleanExpression")); } } ================================================ FILE: src/test/java/org/openrewrite/maven/RewriteTypeTableIT.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 com.soebes.itf.jupiter.extension.*; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; import static org.openrewrite.PathUtils.separatorsToSystem; @MavenJupiterExtension @MavenOption(MavenCLIOptions.NO_TRANSFER_PROGRESS) @MavenOption(MavenCLIExtra.MUTE_PLUGIN_VALIDATION_WARNING) @MavenProfile("create-typetable") class RewriteTypeTableIT { @MavenTest void typetable_default(MavenExecutionResult result) { assertThat(result) .isSuccessful() .project().has("src/main/resources/META-INF/rewrite"); assertThat(result).out().info() .matches(logLines -> logLines.stream().anyMatch(line -> line.contains("Wrote com.google.guava:guava:jar:33.3.1-jre")), "contains guava 33.3.1-jre") .matches(logLines -> logLines.stream().anyMatch(line -> line.contains("Wrote com.google.guava:guava:jar:32.0.0-jre")), "contains guava 32.0.0-jre") .matches(logLines -> logLines.stream().anyMatch(line -> line.contains("Wrote %s".formatted(separatorsToSystem("src/main/resources/META-INF/rewrite/classpath.tsv.gz")))), "write classpath.tsv.gz"); assertThat(result).out().error().isEmpty(); } } ================================================ FILE: src/test/java/org/openrewrite/maven/jupiter/extension/GitITExtension.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.jupiter.extension; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtensionConfigurationException; import org.junit.jupiter.api.extension.ExtensionContext; import org.openrewrite.jgit.api.Git; import java.lang.reflect.Method; import java.nio.file.Path; class GitITExtension implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) throws Exception { Class testClass = context.getTestClass() .orElseThrow(() -> new ExtensionConfigurationException("MavenITExtension is only supported for classes.")); Method methodName = context.getTestMethod().orElseThrow(() -> new IllegalStateException("No method given")); Path targetTestClassesDirectory = getTargetDir().resolve("maven-it"); String toFullyQualifiedPath = toFullyQualifiedPath(testClass); Path mavenItTestCaseDirectory = targetTestClassesDirectory.resolve(toFullyQualifiedPath).resolve(methodName.getName()); Git.init().setDirectory(mavenItTestCaseDirectory.toFile()).call().close(); } static Path getMavenBaseDir() { return Path.of(System.getProperty("basedir", System.getProperty("user.dir", "."))); } static String toFullyQualifiedPath(Class testClass) { return testClass.getCanonicalName().replace('.', '/'); } /** * @return the target directory of the current project. */ static Path getTargetDir() { return getMavenBaseDir().resolve("target"); } } ================================================ FILE: src/test/java/org/openrewrite/maven/jupiter/extension/GitJupiterExtension.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.jupiter.extension; import org.junit.jupiter.api.extension.ExtendWith; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @ExtendWith(GitITExtension.class) @Documented public @interface GitJupiterExtension { } ================================================ FILE: src/test/resources/.gitkeep ================================================ ================================================ FILE: src/test/resources/junit-platform.properties ================================================ # # Copyright 2025 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. # junit.jupiter.execution.parallel.enabled = true junit.jupiter.execution.parallel.mode.default = concurrent junit.jupiter.execution.parallel.mode.classes.default = same_thread ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/groupid_artifactid_should_be_ok/pom.xml ================================================ 4.0.0 org.openrewrite.maven groupid_artifactid_should_be_ok 1.0 jar BasicIT#groupid_artifactid_should_be_ok 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/null_check_profile_activation/pom.xml ================================================ 4.0.0 org.openrewrite.maven null_check_profile_activation 1.0 jar BasicIT#null_check_profile_activation 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/null_check_profile_activation/settings.xml ================================================ example_profile_id true example_repository_id https://repo.maven.apache.org/maven2/ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/resolves_maven_properties_from_user_provided_system_properties/pom.xml ================================================ 4.0.0 org.openrewrite.maven resolves_maven_properties_from_user_provided_system_properties 1.0 jar BasicIT#resolves_maven_properties_from_user_provided_system_properties 1.8 1.8 UTF-8 ossrh_snapshots ${ossrh_snapshots_url} never ignore true never ignore false @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/resolves_settings/pom.xml ================================================ 4.0.0 org.openrewrite.maven resolves_settings 1.0 jar BasicIT#resolves_settings 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/resolves_settings/settings-user.xml ================================================ example_profile_id example_repository_id ${REPOSITORY_URL} ================================================ FILE: src/test/resources-its/org/openrewrite/maven/BasicIT/snapshot_ok/pom.xml ================================================ 4.0.0 org.openrewrite.maven snapshot_ok 1.0-SNAPSHOT jar BasicIT#snapshot_ok 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/DiscoverNoActiveRecipeIT/single_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven single_project 1.0 jar ConfigureMojoITNoActiveRecipe#single_project 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ ${some.property} ================================================ FILE: src/test/resources-its/org/openrewrite/maven/KotlinIT/kotlin_in_src_main_java/pom.xml ================================================ 4.0.0 org.openrewrite.maven basic_kotlin_project 1.0 jar KotlinIT#basic_kotlin_project 1.9.10 17 ${jdk.version} ${jdk.version} ${jdk.version} UTF-8 org.jetbrains.kotlin kotlin-maven-plugin ${kotlin.version} compile process-sources compile ${project.basedir}/src/main/java org.apache.maven.plugins maven-compiler-plugin 3.13.0 ${java.version} ${java.version} default-compile none default-testCompile none java-compile compile compile java-test-compile test-compile testCompile @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.kotlin.format.AutoFormat org.openrewrite.recipe rewrite-all 1.3.4 org.jetbrains.kotlin kotlin-stdlib ${kotlin.version} mavenCentral https://repo1.maven.org/maven2/ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/KotlinIT/kotlin_in_src_main_java/src/main/java/sample/MyClass.kt ================================================ package sample class MyClass { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/KotlinIT/kotlin_in_src_main_test/pom.xml ================================================ 4.0.0 org.openrewrite.maven basic_kotlin_project 1.0 jar KotlinIT#basic_kotlin_project 1.9.10 17 ${jdk.version} ${jdk.version} ${jdk.version} UTF-8 org.jetbrains.kotlin kotlin-maven-plugin ${kotlin.version} compile process-sources compile ${project.basedir}/src/main/java org.apache.maven.plugins maven-compiler-plugin 3.13.0 ${java.version} ${java.version} default-compile none default-testCompile none java-compile compile compile java-test-compile test-compile testCompile @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.kotlin.format.AutoFormat org.openrewrite.recipe rewrite-all 1.3.4 org.jetbrains.kotlin kotlin-stdlib ${kotlin.version} mavenCentral https://repo1.maven.org/maven2/ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/KotlinIT/kotlin_in_src_main_test/src/test/java/sample/MyTest.kt ================================================ package sample class MyTest { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RecipeCsvGenerateIT/generates_csv_from_java_recipe/pom.xml ================================================ 4.0.0 org.openrewrite.test test-java-recipe-project 1.0.0 jar RecipeCsvGenerateIT#generates_csv_from_java_recipe 8 8 org.openrewrite rewrite-core @rewrite.version@ @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RecipeCsvGenerateIT/generates_csv_from_java_recipe/src/main/java/org/openrewrite/test/SampleJavaRecipe.java ================================================ package org.openrewrite.test; import org.openrewrite.ExecutionContext; import org.openrewrite.Recipe; import org.openrewrite.TreeVisitor; public class SampleJavaRecipe extends Recipe { @Override public String getDisplayName() { return "Sample Java recipe"; } @Override public String getDescription() { return "A sample imperative recipe for testing CSV generation."; } @Override public TreeVisitor getVisitor() { return TreeVisitor.noop(); } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RecipeCsvGenerateIT/generates_csv_from_yaml_recipe/pom.xml ================================================ 4.0.0 org.openrewrite.test test-recipe-project 1.0.0 jar RecipeCsvGenerateIT#generates_csv_from_yaml_recipe 8 8 org.openrewrite rewrite-core @rewrite.version@ @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RecipeCsvGenerateIT/generates_csv_from_yaml_recipe/src/main/resources/META-INF/rewrite/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: org.openrewrite.test.TestRecipe displayName: Test recipe description: A test recipe for CSV generation testing. recipeList: - org.openrewrite.text.ChangeText: toText: "Hello World" ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/RecipeLookup/rewrite_discover_detail/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_detail 1.0 jar RewriteDiscoverIT#rewrite_discover_detail @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/RecipeLookup/rewrite_discover_recipe_lookup_case_insensitive/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_recipe_lookup_case_insensitive 1.0 jar RewriteDiscoverIT#rewrite_discover_recipe_lookup_case_insensitive @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/RecipeLookup/rewrite_discover_recursion/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_recursion 1.0 jar RewriteDiscoverIT#rewrite_discover_recursion @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_default/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_default 1.0 jar RewriteDiscoverIT#rewrite_discover_default @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_multi_module/a/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_multi_module 1.0 a ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_multi_module/b/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_multi_module 1.0 b ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_multi_module/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_multi_module 1.0 pom RewriteDiscoverIT#multi_module a b @project.groupId@ @project.artifactId@ @project.version@ ${project.build.directory}/maven-it/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_multi_module/project/target/pomCache ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_rewrite_yml/pom.xml ================================================ 4.0.0 org.openrewrite.maven rewrite_discover_rewrite_yml 1.0 jar RewriteDiscoverIT#rewrite_discover_rewrite_yml @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteDiscoverIT.CodeCleanup ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_rewrite_yml/rewrite.yml ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDiscoverIT/rewrite_discover_rewrite_yml/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteDiscoverIT.CodeCleanup recipeList: - org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/fail_on_dry_run/pom.xml ================================================ 4.0.0 org.openrewrite.maven fail_on_dry_run 1.0 jar RewriteDryRunIT#fail_on_dry_run 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat true ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/fail_on_dry_run/src/main/java/sample/BadSpacing.java ================================================ package sample; public class BadSpacing { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/a/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 a ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/a/src/main/java/sample/MyInterface.java ================================================ package sample; public interface MyInterface { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/a/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/b/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 b org.openrewrite.maven a 1.0 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/b/src/main/java/sample/EmptyBlockSample.java ================================================ package sample; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Random; public class EmptyBlockSample implements MyInterface { int n = sideEffect(); static { } int sideEffect() { return new Random().nextInt(); } boolean boolSideEffect() { return sideEffect() == 0; } public void lotsOfIfs() { if(sideEffect() == 1) {} if(sideEffect() == sideEffect()) {} int n; if((n = sideEffect()) == 1) {} if((n /= sideEffect()) == 1) {} if(new EmptyBlockSample().n == 1) {} if(!boolSideEffect()) {} if(1 == 2) {} } public void emptyTry() { try { Files.lines(Paths.get("somewhere")); } catch (Throwable t) { } finally { } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 pom a b 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteDryRunIT.CodeCleanup ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/rewrite.yml org.openrewrite.recipe rewrite-static-analysis 1.0.4 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/multi_module_project/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteDryRunIT.CodeCleanup recipeList: - org.openrewrite.staticanalysis.SimplifyBooleanExpression - org.openrewrite.staticanalysis.SimplifyBooleanReturn - org.openrewrite.staticanalysis.UnnecessaryParentheses ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/no_plugin_in_pom/pom.xml ================================================ 4.0.0 org.openrewrite.maven no_plugin_in_pom 1.0 jar RewriteDryRunIT#no_plugin_in_pom org.junit.jupiter junit-jupiter 5.9.1 test org.junit.jupiter junit-jupiter-api 5.9.1 test 1.8 1.8 UTF-8 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/no_plugin_in_pom/src/test/java/sample/SampleTest.java ================================================ package sample; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class SampleTest { @Test public void testMethod() { String s = null; assertTrue(s == null); } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/recipe_order/pom.xml ================================================ 4.0.0 org.openrewrite.maven recipe_order 1.0 jar RewriteDryRunIT#recipe_order 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteDryRunIT.CodeCleanup org.openrewrite.java.format.AutoFormat org.openrewrite.staticanalysis.SimplifyBooleanExpression ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/recipe_order/rewrite.yml org.openrewrite.recipe rewrite-static-analysis 1.0.4 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/recipe_order/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteDryRunIT.CodeCleanup recipeList: - org.openrewrite.staticanalysis.SimplifyBooleanExpression - org.openrewrite.staticanalysis.SimplifyBooleanReturn - org.openrewrite.staticanalysis.UnnecessaryParentheses ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/recipe_order/src/main/java/sample/EmptyBlockSample.java ================================================ package sample; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Random; public class EmptyBlockSample { int n = sideEffect(); static { } int sideEffect() { return new Random().nextInt(); } boolean boolSideEffect() { return sideEffect() == 0; } public void lotsOfIfs() { if(sideEffect() == 1) {} if(sideEffect() == sideEffect()) {} int n; if((n = sideEffect()) == 1) {} if((n /= sideEffect()) == 1) {} if(new EmptyBlockSample().n == 1) {} if(!boolSideEffect()) {} if(1 == 2) {} } public void emptyTry() { try { Files.lines(Paths.get("somewhere")); } catch (Throwable t) { } finally { } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/recipe_order/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/single_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven single_project 1.0 jar RewriteDryRunIT#single_project 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/single_project/src/main/java/sample/EmptyBlockSample.java ================================================ package sample; import java.nio.file.*; import java.util.Random; public class EmptyBlockSample { int n = sideEffect(); static { } int sideEffect() { return new Random().nextInt(); } boolean boolSideEffect() { return sideEffect() == 0; } public void lotsOfIfs() { if(sideEffect() == 1) {} if(sideEffect() == sideEffect()) {} int n; if((n = sideEffect()) == 1) {} if((n /= sideEffect()) == 1) {} if(new EmptyBlockSample().n == 1) {} if(!boolSideEffect()) {} if(1 == 2) {} } public void emptyTry() { try { Files.lines(Paths.get("somewhere")); } catch (Throwable t) { } finally { } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteDryRunIT/single_project/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/basedir_resource_no_plaintext_leak/pom.xml ================================================ 4.0.0 org.openrewrite.maven basedir_resource_no_plaintext_leak 1.0 jar RewriteRunIT#basedir_resource_no_plaintext_leak 1.8 1.8 UTF-8 ${project.basedir} **/* ${project.basedir} **/* @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/basedir_resource_no_plaintext_leak/src/main/java/sample/Main.java ================================================ package sample; public class Main { public void hello() { if(true) {} } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/basedir_resource_no_plaintext_leak/src/test/java/sample/MainTest.java ================================================ package sample; public class MainTest { public void test() { if(true) {} } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/checkstyle_inline_rules/pom.xml ================================================ 4.0.0 org.openrewrite.maven checkstyle_inline_rules 1.0 jar RewriteRunIT#checkstyle_inline_rules 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat org.apache.maven.plugins maven-checkstyle-plugin 3.3.1 verify-style process-classes check false ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/checkstyle_inline_rules/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/cloud_suitability_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven cloud_suitability_project 1.0 jar RewriteRunIT#cloud_suitability_project 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.cloudsuitability.FindJks org.openrewrite.recipe rewrite-cloud-suitability-analyzer 1.3.0 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/cloud_suitability_project/src/main/resource/some.jks ================================================ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/command_line_options/pom.xml ================================================ 4.0.0 org.openrewrite.maven command_line_options 1.0 jar RewriteRunIT#command_line_options 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/command_line_options_json/pom.xml ================================================ 4.0.0 org.openrewrite.maven command_line_options 1.0 jar RewriteRunIT#command_line_options_json 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/command_line_options_json/src/main/java/sample/SomeClass.java ================================================ package sample; public class SomeClass { public void doTheThing() {} } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/Containerfile ================================================ FROM alpine:latest CMD ["echo", "Hello World"] ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/Dockerfile ================================================ FROM alpine:latest CMD ["echo", "Hello World"] ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/build.dockerfile ================================================ FROM alpine:latest CMD ["echo", "Hello World"] ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/containerfile.build ================================================ FROM alpine:latest CMD ["echo", "Hello World"] ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/pom.xml ================================================ 4.0.0 org.openrewrite.maven single_project 1.0 jar RewriteRunIT#container_masks 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteRunIT.ContainerMasks ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/rewrite.yml ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/container_masks/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteRunIT.ContainerMasks recipeList: - org.openrewrite.text.FindAndReplace: find: 'alpine:latest' replace: 'alpine' regex: false ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/datatable_export/pom.xml ================================================ 4.0.0 com.mycompany.app my-app 1 com.google.guava guava 32.0.0-jre org.projectlombok lombok 1.18.42 @project.groupId@ @project.artifactId@ @project.version@ com.github.timtebeek.FindBoth ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteRunIT/datatable_export/rewrite.yml true ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/datatable_export/rewrite.yml ================================================ type: specs.openrewrite.org/v1beta/recipe name: com.github.timtebeek.FindBoth displayName: Find dependencies description: Find all usages of both Guava and Lombok dependencies in Maven projects. recipeList: - org.openrewrite.maven.search.DependencyInsight: groupIdPattern: "*" artifactIdPattern: "guava" scope: compile - org.openrewrite.maven.search.DependencyInsight: groupIdPattern: "*" artifactIdPattern: "lombok" scope: compile ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/java_compiler_plugin_project/parent/pom.xml ================================================ 4.0.0 org.openrewrite.maven parent 1.0 pom 11 UTF-8 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/java_compiler_plugin_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven parent 1.0 parent java_compiler_plugin_project 1.0 jar RewriteRunIT#java_compiler_plugin_project 1.8 1.8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat maven-compiler-plugin 3.10.1 ${maven.compiler.release} -parameters ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/java_compiler_plugin_project/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/java_upgrade_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven java_upgrade_project 1.0 jar RewriteRunIT#java_upgrade_project 11 11 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.migrate.UpgradeToJava17 org.openrewrite.recipe rewrite-migrate-java 3.31.0 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/java_upgrade_project/src/main/java/sample/MyInterface.java ================================================ package sample; public interface MyInterface { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/lombok_jdk25_linkage_error/.mvn/jvm.config ================================================ --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/lombok_jdk25_linkage_error/pom.xml ================================================ 4.0.0 org.openrewrite.maven lombok_jdk25_linkage_error 1.0 jar RewriteRunIT#lombok_jdk25_linkage_error 25 25 UTF-8 org.projectlombok lombok 1.18.38 provided org.apache.maven.plugins maven-compiler-plugin 3.14.0 true org.projectlombok lombok 1.18.38 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/lombok_jdk25_linkage_error/src/main/java/sample/App.java ================================================ package sample; import lombok.Data; import lombok.Builder; import lombok.With; @Data @Builder public class App { @With private String name; private int count; private boolean active; } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/lombok_jdk25_linkage_error/src/test/java/sample/AppTest.java ================================================ package sample; public class AppTest { void testApp() { // GIVEN var name = "test"; var count = 1; // WHEN var app = App.builder().name(name).count(count).active(true).build(); // THEN assert app.getName().equals(name); } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_main_source_sets_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_main_source_sets_project 1.0 jar 1.8 1.8 UTF-8 org.codehaus.mojo build-helper-maven-plugin 3.6.0 add additional main sources generate-sources add-source src/additional-main/java ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_main_source_sets_project/src/additional-main/java/sample/AdditionalMainClass.java ================================================ package sample; public class AdditionalMainClass { //This is a test class public void method() { System.out.println("Additional main source set"); } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_main_source_sets_project/src/main/java/sample/MainClass.java ================================================ package sample; public class MainClass { //This is a test class public void method() { System.out.println("Main source set"); } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/a/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 a ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/a/src/main/java/sample/MyInterface.java ================================================ package sample; public interface MyInterface { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/a/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/b/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 b org.openrewrite.maven a 1.0 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/b/src/main/java/sample/EmptyBlockSample.java ================================================ package sample; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Random; public class EmptyBlockSample implements MyInterface { int n = sideEffect(); static { } int sideEffect() { return new Random().nextInt(); } boolean boolSideEffect() { return sideEffect() == 0; } public void lotsOfIfs() { if(sideEffect() == 1) {} if(sideEffect() == sideEffect()) {} int n; if((n = sideEffect()) == 1) {} if((n /= sideEffect()) == 1) {} if(new EmptyBlockSample().n == 1) {} if(!boolSideEffect()) {} if(1 == 2) {} } public void emptyTry() { try { Files.lines(Paths.get("somewhere")); } catch (Throwable t) { } finally { } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 pom a b 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteRunIT.CodeCleanup ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/rewrite.yml org.openrewrite.recipe rewrite-static-analysis 1.0.4 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteRunIT.CodeCleanup recipeList: - org.openrewrite.staticanalysis.SimplifyBooleanExpression - org.openrewrite.staticanalysis.SimplifyBooleanReturn - org.openrewrite.staticanalysis.UnnecessaryParentheses ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_resources/a/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_resources 1.0 a ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_resources/a/src/main/resources/example.xml ================================================ bar ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_resources/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_resources 1.0 pom a 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ bug.report.ChangeTag ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_resources/rewrite.yml org.openrewrite.recipe rewrite-static-analysis 1.0.4 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_resources/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: bug.report.ChangeTag displayName: Change XML tag name recipeList: - org.openrewrite.xml.ChangeTagName: elementName: /foo newName: bar ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_source_sets_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_source_sets_project 1.0 pom 1.8 1.8 UTF-8 org.junit.jupiter junit-jupiter 5.9.1 test org.junit.jupiter junit-jupiter-engine 5.9.1 test org.codehaus.mojo build-helper-maven-plugin 3.6.0 add integration test sources generate-test-sources add-test-source src/integration-test/java ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_source_sets_project/src/integration-test/java/sample/IntegrationTest.java ================================================ package sample; import org.junit.jupiter.api.Test; class IntegrationTest { @Test void testBar() {} } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_source_sets_project/src/test/java/sample/RegularTest.java ================================================ package sample; import org.junit.jupiter.api.Test; class RegularTest { @Test void testBar() {} } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/.in-root ================================================ findMe ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/from-default-list.py ================================================ findMe ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/in-root.ignored ================================================ findMe ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/pom.xml ================================================ 4.0.0 org.openrewrite.maven single_project 1.0 jar RewriteRunIT#plaintext_masks 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteRunIT.PlainTextMasks ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/rewrite.yml org.openrewrite.recipe rewrite-static-analysis 1.15.0 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteRunIT.PlainTextMasks recipeList: - org.openrewrite.text.FindAndReplace: find: findMe replace: replacedWith regex: false ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/src/main/java/sample/Dummy.java ================================================ package sample; public class Dummy { private static final String findMe = "findMe"; } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/plaintext_masks/src/main/java/sample/in-src.ext ================================================ findMe ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/recipe_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven recipe_project 1.0 jar RewriteRunIT#recipe_project 1.8 1.8 UTF-8 org.openrewrite rewrite-java 8.0.0 @project.groupId@ @project.artifactId@ @project.version@ sample.ThrowingRecipe org.openrewrite.maven recipe_project 1.0 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/recipe_project/src/main/java/sample/ThrowingRecipe.java ================================================ package sample; import org.openrewrite.ExecutionContext; import org.openrewrite.Recipe; import org.openrewrite.Tree; import org.openrewrite.TreeVisitor; import org.openrewrite.internal.lang.Nullable; import org.openrewrite.java.JavaVisitor; import org.openrewrite.java.tree.J; import java.nio.file.*; import java.util.Random; public class ThrowingRecipe extends Recipe { @Override public String getDisplayName() { return "Throws exception"; } @Override public String getDescription() { return "Throws exception."; } @Override public TreeVisitor getVisitor() { return new JavaVisitor() { @Override public J visitCompilationUnit(J.CompilationUnit cu, ExecutionContext ctx) { throw new RuntimeException("This recipe throws an exception."); } }; } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/single_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven single_project 1.0 jar RewriteRunIT#single_project 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ org.openrewrite.java.format.AutoFormat ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/single_project/src/main/java/sample/EmptyBlockSample.java ================================================ package sample; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Random; public class EmptyBlockSample { int n = sideEffect(); static { } int sideEffect() { return new Random().nextInt(); } boolean boolSideEffect() { return sideEffect() == 0; } public void lotsOfIfs() { if(sideEffect() == 1) {} if(sideEffect() == sideEffect()) {} int n; if((n = sideEffect()) == 1) {} if((n /= sideEffect()) == 1) {} if(new EmptyBlockSample().n == 1) {} if(!boolSideEffect()) {} if(1 == 2) {} } public void emptyTry() { try { Files.lines(Paths.get("somewhere")); } catch (Throwable t) { } finally { } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunIT/single_project/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/a/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 a org.apache.maven.plugins maven-antrun-plugin 3.0.0 simulate-sleep validate run ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/a/src/main/java/sample/MyInterface.java ================================================ package sample; public interface MyInterface { } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/a/src/main/java/sample/SimplifyBooleanSample.java ================================================ package sample; public class SimplifyBooleanSample { boolean ifNoElse() { if (isOddMillis()) { return true; } return false; } static boolean isOddMillis() { boolean even = System.currentTimeMillis() % 2 == 0; if (even == true) { return false; } else { return true; } } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/b/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 b ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/b/src/main/java/sample/EmptyBlockSample.java ================================================ package sample; import java.util.Random; public class EmptyBlockSample { int n = sideEffect(); static { } int sideEffect() { return new Random().nextInt(); } } ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/pom.xml ================================================ 4.0.0 org.openrewrite.maven multi_module_project 1.0 pom a b 1.8 1.8 UTF-8 @project.groupId@ @project.artifactId@ @project.version@ com.example.RewriteRunIT.CodeCleanup ${maven.multiModuleProjectDirectory}/src/test/resources-its/org/openrewrite/maven/RewriteRunIT/multi_module_project/rewrite.yml org.openrewrite.recipe rewrite-static-analysis 1.0.4 ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteRunParallelIT/multi_module_project/rewrite.yml ================================================ --- type: specs.openrewrite.org/v1beta/recipe name: com.example.RewriteRunIT.CodeCleanup recipeList: - org.openrewrite.staticanalysis.SimplifyBooleanExpression - org.openrewrite.staticanalysis.SimplifyBooleanReturn - org.openrewrite.staticanalysis.UnnecessaryParentheses ================================================ FILE: src/test/resources-its/org/openrewrite/maven/RewriteTypeTableIT/typetable_default/pom.xml ================================================ 4.0.0 org.openrewrite.maven typetable_default 1.0 jar RewriteTypeTableIT#typetable_default create-typetable @project.groupId@ @project.artifactId@ @project.version@ com.google.guava:guava:33.3.1-jre, com.google.guava:guava:32.0.0-jre, typetable generate-resources ================================================ FILE: suppressions.xml ================================================ ^pkg:maven/org\.codehaus\.plexus/plexus\-utils@.*$ CVE-2025-67030