### Install Cleanthat-maven-plugin locally Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Build and install the plugin into the local Maven repository. Use '-pl :cleanthat-maven-plugin' for the plugin itself, and add '-am' if core dependencies have changed. ```bash mvn install -pl :cleanthat-maven-plugin ``` ```bash mvn install -pl :cleanthat-maven-plugin -am -PskipStyle -DskipITs -DskipTests ``` -------------------------------- ### Compile Cleanthat Project Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Clone the repository and install the project. The `-Pfast` profile may be needed to avoid Cleanthat depending on itself. ```bash git clone git@github.com:solven-eu/cleanthat.git mvn install -Pfast -T 8 ``` ```bash mvn install ``` -------------------------------- ### Example .cleanthat/cleanthat.yaml Configuration Source: https://context7.com/solven-eu/cleanthat/llms.txt A representative YAML configuration file for CleanThat, specifying syntax version, meta-options, source code settings, and engine configurations. ```yaml syntax_version: "2023-01-09" meta: full_clean_on_configuration_change: true labels: - "cleanthat" refs: protected_patterns: - master source_code: encoding: "UTF-8" line_ending: "GIT" engines: - engine: "spotless" skip: false steps: - id: "spotless" parameters: configuration: "repository:/.cleanthat/spotless.yaml" ``` -------------------------------- ### CleanThat Configuration Example (YAML) Source: https://github.com/solven-eu/cleanthat/blob/master/github/README.MD Example cleanthat.json configuration file. Specifies syntax version, metadata, source code exclusions and inclusions, line endings, and language-specific processors for Java. ```yaml syntax_version: "2021-08-02" meta: labels: - "cleanthat" refs: branches: - "refs/heads/develop" - "refs/heads/main" - "refs/heads/master" source_code: excludes: - "regex:.*/generated/.*" encoding: "UTF-8" line_ending: "LF" languages: - language: "java" language_version: "11" source_code: includes: - "regex:.*\.java" processors: - engine: "rules" parameters: production_ready_only: true - engine: "revelc_imports" parameters: # Organize imports like in Eclipse remove_unused: true groups: "java.,javax.,org.,com." static_groups: "java,*" # Use Spring formatting convention - engine: "spring_formatter" parameters: {} ``` -------------------------------- ### Call installed Cleanthat plugin with SNAPSHOT version Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Execute CleanThat goals using a locally installed SNAPSHOT version of the plugin. Replace '2.7-SNAPSHOT' with the actual version. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:2.7-SNAPSHOT:init ``` ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:2.7-SNAPSHOT:eclipse_formatter-stylesheet ``` ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:2.7-SNAPSHOT:cleanthat ``` -------------------------------- ### CI/CD Integration with GitHub Actions Source: https://context7.com/solven-eu/cleanthat/llms.txt Example configuration for running CleanThat as a CI gate or auto-fix step within GitHub Actions. This setup uses Maven and Spotless for code checking and applying fixes. ```yaml # .github/workflows/cleanthat.yml name: CleanThat on: [push, pull_request] jobs: cleanthat: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: java-version: '11' distribution: 'temurin' # Option A: Check-only (fail if code is not clean) - name: Check code style run: ./mvnw spotless:check # Option B: Auto-fix and commit - name: Auto-fix and commit run: | ./mvnw spotless:check || \ (./mvnw spotless:apply && git commit -am "style: apply CleanThat/Spotless" && git push) ``` -------------------------------- ### Build Lambda with Root Dependencies Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Use this Maven command to install the Lambda module along with its dependencies from the root project. For a cleaner build, use 'mvn clean install'. ```bash mvn install -pl :lambda -am ``` ```bash mvn clean install -pl :lambda -am ``` -------------------------------- ### ArithmeticAssignment Mutator Examples in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Demonstrates the conversion of verbose arithmetic assignments to compound assignment operators. This applies to +, -, *, / for primitives and Strings, handling commutativity. ```java // BEFORE (pre): int i = 3; i = i + add; // → i += add long l = 3L; l = l - add; // → l -= add float f = 3f; f = factor * f; // → f *= factor (symmetric op: variable may be on right) double d = 3.0; d = d / factor; // → d /= factor String s = "initial"; s = s + add; // → s += add (suffix only; prefix is NOT transformed) // NOT transformed (variable on right of non-symmetric op): double d2 = 3.0; d2 = factor / d2; // stays as-is ``` -------------------------------- ### Custom Java AST Mutator Example Source: https://context7.com/solven-eu/cleanthat/llms.txt Implement a custom mutator by extending AJavaparserExprMutator. This example removes redundant .toString() calls on String variables. Ensure the scope resolves to a String type before replacement. ```java import com.github.javaparser.ast.expr.Expression; import eu.solven.cleanthat.engine.java.refactorer.AJavaparserExprMutator; import eu.solven.cleanthat.engine.java.refactorer.NodeAndSymbolSolver; /** * Example custom mutator: removes redundant .toString() calls on String variables. * (Equivalent to the built-in StringToString mutator.) */ public class MyStringToString extends AJavaparserExprMutator { @Override public String minimalJavaVersion() { return "1"; // compatible since JDK 1 } @Override public boolean isDraft() { return false; // set true to exclude from default runs } @Override protected boolean processExpression(NodeAndSymbolSolver expr) { if (!expr.getNode().isMethodCallExpr()) { return false; } var call = expr.getNode().asMethodCallExpr(); if (!"toString".equals(call.getNameAsString()) || call.getArguments().isNonEmpty()) { return false; } // Check the scope resolves to a String type var scope = call.getScope(); if (scope.isEmpty()) return false; // Replace str.toString() with str expr.getNode().replace(scope.get()); return true; } } // Test your mutator using the standard @CompareMethods pattern: // public class TestMyStringToStringCases extends AJavaparserRefactorerCases { // @Override public IJavaparserAstMutator getTransformer() { return new MyStringToString(); } // // @CompareMethods // public static class BasicCase { // public String pre(String s) { return s.toString(); } // public String post(String s) { return s; } // } // } ``` -------------------------------- ### OptionalNotEmpty Mutator Examples in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Normalizes negated Optional emptiness checks to their positive equivalents. This mutator does not affect non-Optional types. ```java // BEFORE → AFTER Optional opt = Optional.of("hello"); // !isEmpty() → isPresent() boolean a = !opt.isEmpty(); // → opt.isPresent() // !isPresent() → isEmpty() boolean b = !opt.isPresent(); // → opt.isEmpty() // NOT transformed: non-Optional types are left alone Map map = new HashMap<>(); boolean c = !map.isEmpty(); // stays as-is ``` -------------------------------- ### UseCollectionIsEmpty Mutator Examples in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Replaces collection size checks with isEmpty() for Collection, List, and Map types. Note that String uses .length() and is not transformed by this mutator. ```java // BEFORE → AFTER // Collection boolean empty = collection.size() == 0; // → collection.isEmpty() // List boolean listEmpty = list.size() == 0; // → list.isEmpty() // Map boolean mapEmpty = map.size() == 0; // → map.isEmpty() // NOT transformed: String uses .length(), not .size() boolean strEmpty = str.length() == 0; // stays as-is (use UseStringIsEmpty for String) ``` -------------------------------- ### StreamAnyMatch Mutator Examples in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Simplifies stream operations by converting `.filter(p).findAny().isPresent()` to `.anyMatch(p)` and `.findAny().isEmpty()` to `!.anyMatch(p)`. This applies to streams of any type. ```java List items = List.of("a", null, "b"); // BEFORE → AFTER // .findAny().isPresent() → .anyMatch() boolean hasNonNull = items.stream() .filter(o -> null != o) .findAny() .isPresent(); // becomes: boolean hasNonNull2 = items.stream().anyMatch(o -> null != o); // .findAny().isEmpty() → !.anyMatch() boolean allNull = items.stream() .filter(o -> null != o) .findAny() .isEmpty(); // becomes: boolean allNull2 = !items.stream().anyMatch(o -> null != o); ``` -------------------------------- ### AWS API Gateway Request Mapping - OK Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md A successful AWS API Gateway request mapping example that uses a hardcoded string value for a custom attribute. ```json {"CUSTOM-ATTRIBUTE-NAME": {"DataType": "String", "StringValue": "Hardcoded"}} ``` -------------------------------- ### LiteralsFirstInComparisons Mutator Examples in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Reorders comparisons to place string or enum literals first (Yoda style) when using `.equals()`. This prevents NullPointerExceptions when the variable might be null. ```java // BEFORE → AFTER String input = getInput(); // may be null // variable.equals(literal) → literal.equals(variable) boolean a = input.equals("hardcoded"); // → "hardcoded".equals(input) Object obj = getObject(); boolean b = obj.equals("hardcoded"); // → "hardcoded".equals(obj) // Already correct: no change boolean c = "hardcoded".equals("input"); // stays as-is ``` -------------------------------- ### AWS API Gateway Request Mapping - FAILS Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Example of a request mapping configuration for AWS API Gateway that is known to fail. It attempts to map request headers to message attributes. ```json {"X-GitHub-Event": {"DataType": "String", "StringValue": "$request.header.X-GitHub-Event"}, "X-GitHub-Delivery": {"DataType": "String", "StringValue": "$request.header.X-GitHub-Delivery"}, "X-GitHub-Hook-ID": {"DataType": "String", "StringValue": "$request.header.X-GitHub-Hook-ID"}, "User-Agent": {"DataType": "String", "StringValue": "$request.header.User-Agent"}} ``` -------------------------------- ### Full Spotless Configuration (`.cleanthat/spotless.yaml`) Source: https://context7.com/solven-eu/cleanthat/llms.txt Drives Spotless formatter steps for multiple file formats, including Java, Markdown, and POM files. This configuration specifies formatters, excludes, and specific steps like CleanThat mutators and import ordering. ```yaml syntax_version: "2023-01-14" encoding: "UTF-8" line_ending: "GIT_ATTRIBUTES" formatters: - format: "markdown" steps: - id: "flexmark" parameters: {} - format: "java" excludes: - "**/do_not_format_me/**" steps: - id: "cleanthat" parameters: source_jdk: "11.0" include_draft: true mutators: - SafeAndConsensual - SafeButNotConsensual - SafeButControversial - Guava excluded_mutators: - LocalVariableTypeInference # prefer explicit types - id: "removeUnusedImports" - id: "importOrder" parameters: file: "repository:/.cleanthat/eclipse.importorder" - id: "eclipse" parameters: file: "repository:/.cleanthat/eclipse_java_code_formatter.xml" - id: "licenseHeader" parameters: delimiter: "(package )|(import )" file: "repository:/.cleanthat/spotless.license" - format: "pom" includes: - "glob:**/pom.xml" steps: - id: "sortPom" parameters: expandEmptyElements: false nrOfIndentSpace: -1 ``` -------------------------------- ### Initialize CleanThat Configuration with Maven Source: https://github.com/solven-eu/cleanthat/blob/master/github/README.MD Command to generate the cleanthat.json configuration file into an existing repository using the CleanThat Maven plugin. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:init ``` -------------------------------- ### cleanthat:init Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Initializes CleanThat configuration by generating a standard `.cleanthat/cleanthat.yaml` file at the root of the repository. ```APIDOC ## cleanthat:init ### Description Initializes CleanThat configuration with a standard setup, creating a `.cleanthat/cleanthat.yaml` file. ### Method mvn ### Endpoint io.github.solven-eu.cleanthat:cleanthat-maven-plugin:init ``` -------------------------------- ### Configure Cleanthat with Spotless (Default) Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Basic Cleanthat configuration using Spotless, enabling the default 'SafeAndConsensualMutators'. ```java cleanthat() [...] .addMutator('SafeAndConsensual') ``` -------------------------------- ### Configure Cleanthat with Spotless (Customizations) Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Customizing Cleanthat configuration with Spotless, including adding specific mutators, excluding others, and enabling draft mutators. ```java cleanthat() [...] .addMutator('SafeAndConsensual') .includeMutator('StreamForEachNestingForLoopToFlatMap') .excludeMutator('UseCollectionIsEmpty') .includeDraft(true) ``` -------------------------------- ### Apply and Check with Spotless Maven Plugin Source: https://context7.com/solven-eu/cleanthat/llms.txt Commands to apply all configured Spotless steps, including CleanThat, or to check for violations without modifying files. Useful for CI environments. ```bash # Apply all configured Spotless steps (including CleanThat) mvn spotless:apply ``` ```bash # Only check without modifying (useful in CI) mvn spotless:check ``` -------------------------------- ### Deploy Lambda from CircleCI Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Instructions for deploying the Lambda function via Git push to the master branch for production deployment in CircleCI. ```bash git push origin master:deploy-prd ``` -------------------------------- ### Handle Source JDK Version with JavaVersion Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Demonstrates handling any source JDK version using the JavaVersion utility. This is useful for build tools and code analysis. ```java Handle any source JDK version (with the help of [JavaVersion](https://github.com/codehaus-plexus/plexus-languages/blob/master/plexus-java/src/main/java/org/codehaus/plexus/languages/java/version/JavaVersion.java)) ``` -------------------------------- ### Apply and Check with Spotless Gradle Plugin Source: https://context7.com/solven-eu/cleanthat/llms.txt Gradle commands to apply formatting and CleanThat refactoring, or to perform a check without making changes, suitable for CI gates. ```bash # Apply formatting + CleanThat refactoring ./gradlew spotlessApply ``` ```bash # Check only (CI gate) ./gradlew spotlessCheck ``` -------------------------------- ### Implement Spotless Utilities Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Implements generic utility functions like trimTrailingWhitespace, endWithNewline, and index, originally from Spotless. ```java Implemented generic `trimTrailingWhitespace`, `endWithNewline` and `index` from Spotless ``` -------------------------------- ### AWS API Gateway Request Mapping - FAILS Custom Attribute Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Another example of a failing AWS API Gateway request mapping, specifically when trying to map a custom attribute using a variable. ```json {"CUSTOM-ATTRIBUTE-NAME": {"DataType": "String", "StringValue": "$request.header.User-Agent"}} ``` -------------------------------- ### Release New Version Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Prepare and perform a release to deploy jars to Sonatype m2central. ```bash mvn release:clean release:prepare release:perform ``` -------------------------------- ### Configure Cleanthat with Spotless (All Mutators) Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Enabling all available mutators in Cleanthat configuration via Spotless, including draft mutators. ```java cleanthat() [...] .addMutator('SafeAndConsensual') .addMutator('SafeButNotConsensual') .addMutator('SafeButControversial') .includeDraft(true) ``` -------------------------------- ### Run Lambda JAR Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md A simplified command to execute the Lambda JAR file, useful for quick tests or when the exact handler path is not critical. ```bash java -jar lambda/target/*.jar ``` -------------------------------- ### Deploy Lambda from Localhost Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Command to deploy the Lambda function using the Maven Lambda plugin from your local machine. ```bash mvn lambda:deploy-lambda -pl :lambda ``` -------------------------------- ### Send GPG Key to Server Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Send your GPG public key to the Ubuntu keyserver. Replace the key ID with your actual key ID. ```bash gpg --keyserver https://keyserver.ubuntu.com/ --send-key 90A8________________________________AAB7 ``` -------------------------------- ### Run Javadoc Plugin Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Execute the Maven Javadoc plugin to generate Javadoc, ensuring it's not skipped and using the Sonatype profile. ```bash mvn org.apache.maven.plugins:maven-javadoc-plugin:3.4.1:jar -Dmaven.javadoc.skip=false -PSonatype ``` -------------------------------- ### Apply Spotless Maven Plugin Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Use this command to clean your codebase with the Spotless Maven plugin. ```bash mvn spotless:apply ``` -------------------------------- ### Configure Cleanthat with Spotless (SafeButControversialMutators) Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Further extending Cleanthat configuration with Spotless to include 'SafeButControversial' mutators, in addition to 'SafeAndConsensual' and 'SafeButNotConsensual'. ```java cleanthat() [...] .addMutator('SafeAndConsensual') .addMutator('SafeButNotConsensual') .addMutator('SafeButControversial') ``` -------------------------------- ### Configure Cleanthat with Spotless (SafeButNotConsensualMutators) Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Extending Cleanthat configuration with Spotless to include 'SafeButNotConsensual' mutators alongside the default 'SafeAndConsensual' mutators. ```java cleanthat() [...] .addMutator('SafeAndConsensual') .addMutator('SafeButNotConsensual') ``` -------------------------------- ### Export GPG Key Manually Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD If sending the GPG key to the server fails, export it manually in armor format. ```bash gpg --armor --export 90A8________________________________AAB7 ``` -------------------------------- ### Execute Cleanthat:apply goal Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Run a one-shot mutator over the current directory. This goal applies specified or all available CleanThat rules. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply ``` ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply -Dcleanthat.mutators=LocalVariableTypeInference ``` ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply -Dcleanthat.mutators=SafeAndConsensual -Dcleanthat.mutators=SafeButNotConsensual -Dcleanthat.includeDraft=true ``` -------------------------------- ### Spotless Engine Integration Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Integrates Spotless as a primary engine within CleanThat, enabling it to leverage Spotless's formatting and linting capabilities. ```java Added Spotless as an Engine ``` -------------------------------- ### Instantiate SafeAndConsensualMutators in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Demonstrates how to instantiate the `SafeAndConsensualMutators` composite for Java code formatting, targeting a specific JDK version. It also shows how to retrieve the mutator's ID and the IDs of its underlying rules. ```java import eu.solven.cleanthat.engine.java.refactorer.mutators.composite.SafeAndConsensualMutators; import org.codehaus.plexus.languages.java.version.JavaVersion; // Instantiate composite for JDK 11 targets var mutators = new SafeAndConsensualMutators(JavaVersion.parse("11")); // Included rules (representative list): // - ModifierOrder : enforces JLS modifier ordering (public static final → ...) // - UseCollectionIsEmpty : col.size() == 0 → col.isEmpty() // - UseStringIsEmpty : str.length() == 0 → str.isEmpty() // - OptionalNotEmpty : !opt.isEmpty() → opt.isPresent() // - StreamAnyMatch : stream.filter(p).findAny().isPresent() → stream.anyMatch(p) // - StringToString : str.toString() → str // - UnnecessaryBoxing : Integer.valueOf(i) → i (where autoboxing suffices) // - ArithmethicAssignment : i = i + 3 → i += 3 // - UseIndexOfChar : str.indexOf("x") → str.indexOf('x') System.out.println(mutators.getCleanthatId()); // "SafeAndConsensual" System.out.println(mutators.getUnderlyingIds()); // [ModifierOrder, UseIndexOfChar, ...] ``` -------------------------------- ### Run Cleanthat with Maven Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Execute Cleanthat using Maven's spotless plugin. This command checks for code style violations and applies fixes if found, committing the changes. ```bash ./mvnw spotless:check || ./mvnw spotless:apply && git commit -m"Spotless" && git push ``` -------------------------------- ### Configure Spotless YAML for Eclipse Formatter Source: https://context7.com/solven-eu/cleanthat/llms.txt Reference the generated Eclipse formatter stylesheet in your `.cleanthat/spotless.yaml` configuration file. ```yaml - id: "eclipse" parameters: file: "repository:/.cleanthat/eclipse_java_code_formatter.xml" ``` -------------------------------- ### Test Lambda Handler Locally Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Run the Lambda handler locally to troubleshoot startup issues. Ensure the JAR file is correctly built and the handler class is specified. ```bash java -jar target/lambda-1.0-SNAPSHOT-aws.jar eu.solven.cleanthat.lambda.step0_checkWebhook.CheckWebhooksHandler ``` -------------------------------- ### Configure Spotless Gradle Plugin with CleanThat Source: https://context7.com/solven-eu/cleanthat/llms.txt Integrate CleanThat into the Spotless Gradle plugin for Java projects. This configuration specifies mutator tiers, exclusions, and formatting rules. ```groovy // build.gradle plugins { id 'com.diffplug.spotless' version '6.25.0' } spotless { java { cleanthat() .version('2.24') .addMutator('SafeAndConsensual') .addMutator('SafeButNotConsensual') .excludeMutator('LocalVariableTypeInference') .includeDraft(false) removeUnusedImports() eclipse().configFile('.cleanthat/eclipse_java_code_formatter.xml') } } ``` -------------------------------- ### Execute Cleanthat:cleanthat goal Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Apply CleanThat linting logic over the entire directory. This goal performs a comprehensive code cleanup. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:cleanthat ``` -------------------------------- ### Apply CleanThat Maven Plugin Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Execute CleanThat's Maven plugin to apply full refactoring based on `.cleanthat` configuration, even without a pom.xml. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:cleanthat ``` ```bash mvn cleanthat:apply ``` -------------------------------- ### Configure Spotless Maven Plugin with CleanThat Source: https://context7.com/solven-eu/cleanthat/llms.txt Integrate CleanThat into the Spotless Maven plugin to apply refactoring rules and Eclipse formatting during `mvn spotless:apply`. Specify mutator tiers and exclusions. ```xml com.diffplug.spotless spotless-maven-plugin 2.43.0 2.24 SafeAndConsensual SafeButNotConsensual LocalVariableTypeInference false ${project.basedir}/.cleanthat/eclipse_java_code_formatter.xml ``` -------------------------------- ### Generate Eclipse Formatter Stylesheet Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Generate a default Eclipse stylesheet based on existing .java files. This can be a slow process and has a default timeout. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:eclipse_formatter-stylesheet ``` ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:eclipse_formatter-stylesheet -Dduration.limit=PT1H ``` -------------------------------- ### Full CleanThat Configuration (`.cleanthat/cleanthat.yaml`) Source: https://context7.com/solven-eu/cleanthat/llms.txt The central configuration file for both the GitHub App and the Maven plugin. It controls various aspects including source code exclusions, encoding, line endings, and engine configurations. ```yaml syntax_version: "2023-01-09" meta: full_clean_on_configuration_change: true labels: - "cleanthat" refs: protected_patterns: - master # never auto-push to master - deploy-prd excluded_patterns: - deploy-prd # never open PRs targeting deploy-prd source_code: excludes: - "regex:.*/generated/.*" # skip generated sources - "regex:.*/do_not_format_me/.*" # skip explicitly excluded dirs encoding: "UTF-8" line_ending: "GIT" # respect .gitattributes engines: - engine: "spotless" skip: false steps: - id: "spotless" parameters: configuration: "repository:/.cleanthat/spotless.yaml" ``` -------------------------------- ### Generate Eclipse Formatter Stylesheet with Maven Source: https://github.com/solven-eu/cleanthat/blob/master/README.md Use this Maven command to automatically generate an Eclipse Stylesheet. This is useful for minimizing changes to a clean repository. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:eclipse_formatter-stylesheet ``` -------------------------------- ### Generate New GPG Key Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Generate a new GPG key for signing releases, using RSA4096 for key algorithm. ```bash gpg --gen-key --default-new-key-algo=rsa4096/cert,sign+rsa4096/encr ``` -------------------------------- ### Run cleanthat-maven-plugin:apply Source: https://context7.com/solven-eu/cleanthat/llms.txt Execute CleanThat refactoring rules directly using the Maven plugin. Supports running default safe rules, specific mutators, or all tiers including drafts. ```bash # Run default safe rules over the project mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply ``` ```bash # Run a single specific mutator mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply \ -Dcleanthat.mutators=LocalVariableTypeInference ``` ```bash # Run all three tiers of mutators including drafts mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply \ -Dcleanthat.mutators=SafeAndConsensual \ -Dcleanthat.mutators=SafeButNotConsensual \ -Dcleanthat.mutators=SafeButControversial \ -Dcleanthat.includeDraft=true ``` ```bash # Shorthand (requires pluginGroup in ~/.m2/settings.xml) mvn cleanthat:apply ``` -------------------------------- ### cleanthat:apply Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Executes a one-shot run of a mutator over the current directory. This goal can be used to apply specific CleanThat rules or a set of rules. ```APIDOC ## cleanthat:apply ### Description This Mojo enables one-shot run of a mutator over current directory. ### Method mvn ### Endpoint io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply ### Parameters #### Query Parameters - **cleanthat.mutators** (string) - Optional - Specifies a specific rule or set of rules to apply. - **cleanthat.includeDraft** (boolean) - Optional - If true, includes draft rules in the execution. ``` ```APIDOC ## cleanthat:apply (Specific Rule) ### Description Applies a single, specific CleanThat mutator. ### Method mvn ### Endpoint io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply ### Parameters #### Query Parameters - **cleanthat.mutators** (string) - Required - The name of the mutator to apply, e.g., `LocalVariableTypeInference`. ``` ```APIDOC ## cleanthat:apply (Multiple Rules with Draft) ### Description Applies multiple CleanThat rules, including draft rules. ### Method mvn ### Endpoint io.github.solven-eu.cleanthat:cleanthat-maven-plugin:apply ### Parameters #### Query Parameters - **cleanthat.mutators** (string) - Required - A comma-separated list of mutator names, e.g., `SafeAndConsensual,SafeButNotConsensual`. - **cleanthat.includeDraft** (boolean) - Required - Set to `true` to include draft rules. ``` -------------------------------- ### cleanthat:cleanthat Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Applies CleanThat linting logic over the entire directory. ```APIDOC ## cleanthat:cleanthat ### Description Applies CleanThat linting logic over the whole directory. ### Method mvn ### Endpoint io.github.solven-eu.cleanthat:cleanthat-maven-plugin:cleanthat ``` -------------------------------- ### Configure Cleanthat-maven-plugin in pom.xml (Deprecated) Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD This configuration is no longer relevant as the plugin is now pom-less. It shows how the plugin was previously configured within a Maven project's pom.xml. ```xml io.github.solven-eu.cleanthat cleanthat-maven-plugin ${cleanthat.version} Clean the code cleanthat Check the code is clean check io.github.solven-eu.cleanthat cleanthat-maven-plugin false ``` -------------------------------- ### CleanThat Robot Review Request Naming Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD The CleanThat Robot now opens a single Review-Request per protected branch, using the naming convention `cleanthat/headfor-XXX-yyyy-MM-dd`. ```java CleanThat Robot will open a single Review-Request per protected-branch (instead of opening one for each dirty event, with a random). The naming convention is `cleanthat/headfor-XXX-yyyy-MM-dd` where `XXX` is the protected branch name and `yyyy-MM-dd` is current day. ``` -------------------------------- ### Engine Concept Replacement Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD POTENTIALLY BREAKING CHANGE: The concept of 'language' has been replaced by 'engine'. CleanThat now wires linter-engines like Spotless instead of implementing language-specific formatters. ```java The concept of language has been replaced by engine. Instead of implementing language-specific formatters, CleanThat now targets wiring linter-engines (like Spotless). ``` -------------------------------- ### Fix ImportOrderStep with ordersFile Parameter Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Addresses an issue with ImportOrderStep when the ordersFile parameter is utilized, ensuring correct import ordering. ```java Fixes ImportOrderStep when the ordersFile parameters is used. ``` -------------------------------- ### Add Cleanthat to Maven settings.xml Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Configure Maven to recognize the cleanthat plugin group for shorter commands. This is an optional step for convenience. ```xml io.github.solven-eu.cleanthat ``` -------------------------------- ### CleanThat GitHub App Configuration Source: https://context7.com/solven-eu/cleanthat/llms.txt Configuration for the CleanThat GitHub App to auto-clean repositories on push and PR events. Place this YAML file at the repository root. ```yaml # .cleanthat/cleanthat.yaml (place at repository root) syntax_version: "2023-01-09" meta: full_clean_on_configuration_change: true labels: - "cleanthat" refs: protected_patterns: - master # CleanThat will NOT push to master directly excluded_patterns: - deploy-prd # CleanThat will NOT open PRs targeting deploy-prd source_code: excludes: - "regex:.*/generated/.*" encoding: "UTF-8" line_ending: "GIT" engines: - engine: "spotless" skip: false steps: - id: "spotless" parameters: configuration: "repository:/.cleanthat/spotless.yaml" ``` -------------------------------- ### Generate GitHub App Private Key Source: https://github.com/solven-eu/cleanthat/blob/master/lambda/README.md Command to convert a PEM-encoded private key to DER format using OpenSSL, typically for use with GitHub App authentication. ```bash openssl pkcs8 -topk8 -inform PEM -outform DER -in ~/Dropbox/Solven/Dev/CleanThat/cleanthat.2020-05-19.private-key.pem -out ~/Dropbox/Solven/Dev/CleanThat/github-api-app.private-key.der -nocrypt ``` -------------------------------- ### Generate Eclipse Formatter Stylesheet with Maven Source: https://context7.com/solven-eu/cleanthat/llms.txt Use the CleanThat Maven plugin to automatically generate an Eclipse formatter XML stylesheet. You can override the default timeout using ISO-8601 duration syntax. ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:eclipse_formatter-stylesheet ``` ```bash mvn io.github.solven-eu.cleanthat:cleanthat-maven-plugin:eclipse_formatter-stylesheet \ -Dduration.limit=PT1H ``` -------------------------------- ### Default MarkdownFormatter Pattern Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD The default include pattern for MarkdownFormatterFactory is now set to `*.MD` and `*.md` for broader file matching. ```java `MarkdownFormatterFactory` includes pattern is now defaulted to `*.MD` and `*.md` ``` -------------------------------- ### Unit Test: Compilation Units Comparison Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Use `@CompareCompilationUnitsAsResources` to test rules against code that might not compile within the test module's classpath, specifying pre and post resource paths. ```java @CompareCompilationUnitsAsResources( pre = "/source/do_not_format_me/UnnecessaryModifier/Issue807.java", post = "/source/do_not_format_me/UnnecessaryModifier/Issue807.java") public static class Issue807 { } ``` -------------------------------- ### Revert Failed Release Tags Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD If a release fails, revert the local head, force push master, and delete the erroneous tags. ```bash git tag -d v2.XX.RELEASE git push --delete origin v2.XX.RELEASE ``` -------------------------------- ### Default JsonFormatter Pattern Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD The default include pattern for JsonFormatterFactory is now set to `*.json`. ```java `JsonFormatterFactory` includes pattern is now defaulted to `*.json` ``` -------------------------------- ### Replace isProductionReady with includeDraft Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD BREAKING CHANGE: The `isProductionReady` method has been removed and replaced by the fully-functional `includeDraft` option for managing draft states. ```java **BREAKING CHANGE** `isProductionReady` has been removed, and replaced by a fully-functional `includeDraft` ``` -------------------------------- ### Convert Lambdas to Method References (Java) Source: https://context7.com/solven-eu/cleanthat/llms.txt Converts single-dispatch lambdas to equivalent method references, as recommended by Sonar RSPEC-1612. This improves code readability by using `ClassName::method` syntax. ```java // BEFORE → AFTER List list = getList(); // b -> b.method() → ClassName::method list.stream() .filter(a -> a instanceof SomeClass) .map(a -> (SomeClass) a) // → SomeClass.class::cast .map(b -> b.getName()) // → SomeClass::getName .forEach(b -> System.out.println(b)); // → System.out::println // becomes: list.stream() .filter(SomeClass.class::isInstance) .map(SomeClass.class::cast) .map(SomeClass::getName) .forEach(System.out::println); ``` -------------------------------- ### cleanthat:eclipse_formatter-stylesheet Source: https://github.com/solven-eu/cleanthat/blob/master/maven/README.MD Generates an Eclipse Stylesheet based on existing .java files. This can be a slow process and has a default timeout of 1 minute, which can be overridden. ```APIDOC ## cleanthat:eclipse_formatter-stylesheet ### Description Generates an Eclipse Stylesheet for Java formatting based on existing .java files. ### Method mvn ### Endpoint io.github.solven-eu.cleanthat:cleanthat-maven-plugin:eclipse_formatter-stylesheet ### Parameters #### Query Parameters - **duration.limit** (string) - Optional - Overrides the default timeout for the stylesheet generation. Uses ISO 8601 duration format (e.g., `PT1H` for 1 hour). ``` -------------------------------- ### SafeButNotConsensualMutators in Java Source: https://context7.com/solven-eu/cleanthat/llms.txt Initializes the SafeButNotConsensualMutators with a specific Java version. This composite mutator includes rules that are generally safe but might be stylistically debated by a subset of developers. ```java import eu.solven.cleanthat.engine.java.refactorer.mutators.composite.SafeButNotConsensualMutators; import org.codehaus.plexus.languages.java.version.JavaVersion; var mutators = new SafeButNotConsensualMutators(JavaVersion.parse("11")); // Additional rules beyond SafeAndConsensual (representative list): // - LocalVariableTypeInference : String s = new String() → var s = new String() // - LambdaIsMethodReference : x -> x.toString() → Object::toString // - LiteralsFirstInComparisons : obj.equals("str") → "str".equals(obj) // - ArraysDotStream : Arrays.asList(...).stream() → Arrays.stream(...) // - EnumsWithoutEquals : myEnum.equals(OTHER) → myEnum == OTHER // - PrimitiveWrapperInstantiation: new Integer(42) → Integer.valueOf(42) // - UseTextBlocks : multi-line string concat → """...""" (JDK 15+) // - ThreadRunToThreadStart : thread.run() → thread.start() // - UnnecessaryImport : removes redundant import statements // - EmptyControlStatement : removes empty if/else/try/catch bodies System.out.println(mutators.getCleanthatId()); // "SafeButNotConsensual" ``` -------------------------------- ### Mutators by Fully-Qualified Name Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Allows mutators to be included in the configuration by their fully-qualified class name, providing more explicit control. ```java Mutators can be included by their fully-qualified class name ``` -------------------------------- ### Add CleanThat Maven Dependency Source: https://context7.com/solven-eu/cleanthat/llms.txt Include the CleanThat Java refactorer library as a Maven dependency to use its mutators programmatically or with Spotless. ```xml io.github.solven-eu.cleanthat java 2.24 ``` -------------------------------- ### Unit Test: Simple Code Comparison Source: https://github.com/solven-eu/cleanthat/blob/master/CONTRIBUTING.MD Use the `@CompareMethods` annotation on a nested class to check if code is modified as expected, comparing `pre` and `post` methods. ```java @CompareMethods public static class CaseStringEqualsIgnoreCaseEmpty { public Object pre(String input) { return input.equalsIgnoreCase(""); } public Object post(String input) { return input.isEmpty(); } } ``` -------------------------------- ### Promote OptionalNotEmpty Mutator Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD The OptionalNotEmpty mutator is now promoted within the SafeAndConsensual group, indicating its increased importance or stability. ```java `OptionalNotEmpty` is promoted in `SafeAndConsensual` ``` -------------------------------- ### Dynamic IMutators Detection Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Fixes an issue related to the dynamic detection of IMutators, ensuring all applicable mutators are correctly identified and applied. ```java Fix issue related to [dynamic IMutators detection](https://github.com/solven-eu/cleanthat/blob/master/java/src/main/java/eu/solven/cleanthat/engine/java/refactorer/MutatorsScanner.java) ``` -------------------------------- ### EmptyControlStatement Mutator Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Adds a new mutator, EmptyControlStatement, which transforms empty control blocks `{}` into empty strings ``. ```java Additional mutator: `EmptyControlStatement` turns `{}` into `` ``` -------------------------------- ### Use Text Blocks for Multi-line Strings (Java) Source: https://context7.com/solven-eu/cleanthat/llms.txt Replaces multi-line string concatenation with Java 15 text blocks for cleaner HTML, JSON, and SQL literals. This mutator is safe but may not always be consensual. It leaves regex patterns with escape sequences as-is to preserve semantics. ```java // BEFORE (multi-line string concatenation): String html = "\n" + " \n" + "

Hello, World!

\n" + " \n" + "\n"; // AFTER (text block): String html = """

Hello, World!

"""; // NOT transformed: regex patterns with escape sequences are left as-is String regex = "[\r\n]+"; // stays as-is to preserve escape semantics ``` -------------------------------- ### Composite Mutators Added Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Introduces new composite mutators: OptionalNotEmpty, PMDMutators, CheckStyleMutators, and SonarMutators, for enhanced code analysis and refactoring. ```java Additional composite mutators: `OptionalNotEmpty`, `PMDMutators`, `CheckStyleMutators` and `SonarMutators` ``` -------------------------------- ### Composite Mutators by Identifier Source: https://github.com/solven-eu/cleanthat/blob/master/CHANGES.MD Enables referencing Composite Mutators using one of their identifiers, simplifying configuration and usage. ```java Composite Mutators can now be referenced by one of their identifier ```