diff --git a/.agents/RIS_PREPROCESSING.md b/.agents/RIS_PREPROCESSING.md deleted file mode 100644 index 65d27a51c8c..00000000000 --- a/.agents/RIS_PREPROCESSING.md +++ /dev/null @@ -1,616 +0,0 @@ -# Analysis of Existing Rule Engine Patterns - -## Files Inspected - -This analysis is based on direct inspection of the following source files: - -**Core Rule Implementations:** -- `java-checks/src/main/java/org/sonar/java/checks/AbsOnNegativeCheck.java` -- `java-checks/src/main/java/org/sonar/java/checks/EmptyBlockCheck.java` -- `java-checks/src/main/java/org/sonar/java/checks/CompareStringsBoxedTypesWithEqualsCheck.java` -- `java-checks/src/main/java/org/sonar/java/checks/CollectionIsEmptyCheck.java` -- `java-checks/src/main/java/org/sonar/java/checks/DeadStoreCheck.java` -- `java-checks/src/main/java/org/sonar/java/checks/NullShouldNotBeUsedWithOptionalCheck.java` -- `java-checks/src/main/java/org/sonar/java/checks/spring/SpringBeansShouldBeAccessibleCheck.java` - -**Abstract Base Classes:** -- `java-checks/src/main/java/org/sonar/java/checks/AbstractForLoopRule.java` -- `java-checks/src/main/java/org/sonar/java/checks/regex/AbstractRegexCheck.java` -- `java-checks-common/src/main/java/org/sonar/java/checks/methods/AbstractMethodDetection.java` - -**Helper Utilities:** -- `java-checks/src/main/java/org/sonar/java/checks/helpers/QuickFixHelper.java` -- `java-checks/src/main/java/org/sonar/java/checks/helpers/MethodTreeUtils.java` -- `java-checks/src/main/java/org/sonar/java/checks/helpers/UnitTestUtils.java` -- `java-checks/src/main/java/org/sonar/java/checks/serialization/SerializableContract.java` - -**Directory Listings:** Complete file listings from java-checks, java-checks-aws, java-checks-common, and specialized subdirectories (regex, serialization, spring, helpers). - ---- - -## Step 1: Inventory of Existing Rules - -### Rule Count by Module - -**Main Module (java-checks):** 400+ rules -Based on file listings and @Rule annotation searches, the main java-checks module contains approximately 400+ individual check implementations. Files follow naming convention `*Check.java`. - -**AWS Module (java-checks-aws):** 8 rules -- AwsConsumerBuilderUsageCheck -- AwsCredentialsShouldBeSetExplicitlyCheck -- AwsLambdaSyncCallCheck -- AwsLongTermAccessKeysCheck -- AwsRegionSetterCheck -- AwsRegionShouldBeSetExplicitlyCheck -- AwsReusableResourcesInitializedOnceCheck -- Plus abstract base classes and helpers - -**Specialized Rule Categories:** -- **Regex rules:** ~35 checks in `java-checks/src/main/java/org/sonar/java/checks/regex/` - - Examples: RedosCheck, RegexComplexityCheck, InvalidRegexCheck, SuperLinearRegexCheck -- **Serialization rules:** Multiple checks in `java-checks/src/main/java/org/sonar/java/checks/serialization/` -- **Spring framework rules:** Multiple checks in `java-checks/src/main/java/org/sonar/java/checks/spring/` -- **For-loop rules:** Multiple checks extending AbstractForLoopRule - -### Naming Patterns - -1. **Check classes:** All rules end with `Check.java` (e.g., `EmptyBlockCheck`, `AbsOnNegativeCheck`) -2. **Abstract base classes:** Prefix with `Abstract` (e.g., `AbstractForLoopRule`, `AbstractMethodDetection`) -3. **Helper utilities:** Descriptive names ending in `Helper`, `Utils`, `Visitor`, or `Contract` -4. **Rule keys:** Use Sonar rule identifiers (e.g., `@Rule(key = "S2676")`) - -### Architectural Conventions - -1. **Two-tier visitor hierarchy:** - - Primary: `IssuableSubscriptionVisitor` (most common, ~90% of rules) - - Alternative: `BaseTreeVisitor` (for custom traversal logic) - -2. **Domain-specific base classes:** - - `AbstractRegexCheck` for regex validation rules - - `AbstractMethodDetection` for method invocation-based rules - - `AbstractForLoopRule` for for-loop analysis rules - -3. **Module organization:** - - Core rules in `java-checks` - - Cloud-specific rules in `java-checks-aws` - - Shared utilities in `java-checks-common` - ---- - -## Step 2: Implementation Patterns Analysis - -### 1. Detection Patterns - -#### Syntax Pattern Matching -Most rules detect specific syntax patterns through the visitor pattern: - -```java -@Override -public List nodesToVisit() { - return Arrays.asList(Tree.Kind.METHOD_INVOCATION, Tree.Kind.UNARY_MINUS); -} - -@Override -public void visitNode(Tree tree) { - if (tree.is(Tree.Kind.METHOD_INVOCATION)) { - // Pattern detection logic - } -} -``` - -**Examples inspected:** -- `EmptyBlockCheck`: Detects empty blocks (Tree.Kind.BLOCK, Tree.Kind.SWITCH_STATEMENT) -- `AbsOnNegativeCheck`: Detects Math.abs() on negative values (Tree.Kind.METHOD_INVOCATION, Tree.Kind.UNARY_MINUS) - -#### Semantic Pattern Matching -Rules use `MethodMatchers` API for semantic detection: - -```java -private static final MethodMatchers MATH_ABS_METHODS = - MethodMatchers.create() - .ofTypes("java.lang.Math") - .names("abs") - .addParametersMatcher("int") - .addParametersMatcher("long") - .build(); -``` - -**Pattern breadth:** Rules range from very narrow (specific method calls) to broad (structural patterns across classes). - -**Problem domains covered:** -- **Code quality:** Empty blocks, unused variables, dead stores, complexity metrics -- **Bug detection:** Null dereference, type mismatches, incorrect API usage -- **Security:** Hardcoded credentials, weak cryptography, SQL injection risks -- **Performance:** Inefficient collections, redundant operations -- **Maintainability:** Naming conventions, code organization -- **Framework-specific:** Spring, JUnit, AWS SDK patterns -- **Regex validation:** Regex syntax errors, ReDoS vulnerabilities - -### 2. Implementation Complexity - -#### Simple Rules (50-150 lines) -**Example: EmptyBlockCheck (87 lines)** -- Single visitor method -- Direct tree inspection -- Minimal helper methods -- No external state - -#### Medium Rules (150-300 lines) -**Example: CollectionIsEmptyCheck (~250 lines)** -- Multiple helper methods -- Context tracking (stack-based state) -- Quick fix generation -- Import management - -#### Complex Rules (300+ lines) -**Example: DeadStoreCheck (~400+ lines)** -- CFG (Control Flow Graph) analysis -- Liveness analysis integration -- Multiple nested visitors -- Complex state management - -**Example: SpringBeansShouldBeAccessibleCheck (~300+ lines)** -- Multi-file analysis (EndOfAnalysis interface) -- Caching support -- Module-level state aggregation -- Package scanning logic - -#### Lines of Code Distribution -- **Simple rules:** 50-150 LOC (~40% of rules) -- **Medium rules:** 150-300 LOC (~45% of rules) -- **Complex rules:** 300+ LOC (~15% of rules) - -#### Helper Function Usage -Most rules use 2-5 private helper methods for: -- Tree traversal utilities -- Type checking -- Pattern matching refinement -- Issue reporting logic - -**Common patterns:** -```java -// Extract nested expressions -private static MethodInvocationTree extractMethodInvocation(ExpressionTree tree) - -// Type checking -private static boolean isOptional(ExpressionTree expression) - -// Pattern validation -private void checkForIssue(ExpressionTree tree) -``` - -#### State Management -**Stateless rules (~70%):** No instance variables, purely functional analysis - -**Stateful rules (~30%):** -- Stack-based tracking (e.g., `CollectionIsEmptyCheck` tracks collection types) -- Boolean flags (e.g., `EmptyBlockCheck.isMethodBlock`) -- Maps/Sets for cross-method analysis (e.g., `SpringBeansShouldBeAccessibleCheck.messagesPerPackage`) - -#### Registration Strategy -All rules use declarative registration via `@Rule` annotation: -```java -@Rule(key = "S2676") -public class AbsOnNegativeCheck extends IssuableSubscriptionVisitor -``` - -Registration collected through `CheckRegistrar` interface implementations. - -### 3. Core Analysis Techniques - -#### Direct Node Kind Matching -**Usage: ~95% of rules** - -Pattern: -```java -@Override -public List nodesToVisit() { - return Arrays.asList(Tree.Kind.CLASS, Tree.Kind.INTERFACE); -} -``` - -Common node kinds targeted: -- METHOD_INVOCATION, NEW_CLASS (method detection) -- BLOCK, IF_STATEMENT, SWITCH_STATEMENT (control flow) -- VARIABLE, ASSIGNMENT (state tracking) -- CLASS, INTERFACE, ENUM (type definitions) -- BINARY_EXPRESSION, UNARY_EXPRESSION (operators) - -#### Field and Property Access -Rules extensively access tree properties: -```java -MethodInvocationTree mit = (MethodInvocationTree) tree; -ExpressionTree firstArgument = mit.arguments().get(0); -Symbol.MethodSymbol symbol = mit.symbol(); -Type returnType = symbol.returnType(); -``` - -#### Tree Traversal Patterns - -**Subscription-based (IssuableSubscriptionVisitor):** -- Declarative: specify nodes to visit -- Framework handles traversal -- Most common pattern - -**Custom traversal (BaseTreeVisitor):** -- Imperative: override specific visit methods -- Used for complex inter-node relationships -- Example: `NullShouldNotBeUsedWithOptionalCheck` uses nested visitors - -#### Ancestor/Descendant Walking -Common helper utilities for tree navigation: -```java -// From QuickFixHelper -public static SyntaxToken nextToken(Tree tree) -public static SyntaxToken previousToken(Tree tree) -public static Optional previousVariable(VariableTree current) -``` - -Pattern: Walk parent chain to find enclosing context: -```java -Tree parent = tree.parent(); -while (parent != null && !parent.is(Tree.Kind.METHOD)) { - parent = parent.parent(); -} -``` - -#### Symbol Lookup -Extensive use of semantic model: -```java -Symbol.TypeSymbol symbol = classTree.symbol(); -Type type = expression.symbolType(); -SymbolMetadata metadata = symbol.metadata(); -boolean isDeprecated = metadata.isAnnotatedWith("java.lang.Deprecated"); -``` - -**Symbol analysis includes:** -- Type hierarchy checking (`type.isSubtypeOf()`) -- Annotation inspection -- Modifier checking -- Scope analysis - -#### File-Level Filtering -Rules can filter files before analysis: -```java -@Override -public boolean scanWithoutParsing(InputFileScannerContext context) { - // Cache-based filtering - return readFromCache(context).isPresent(); -} -``` - -#### Data-Flow-Like Tracking - -**Example: DeadStoreCheck** -Uses Control Flow Graph (CFG) and liveness analysis: -```java -CFG cfg = (CFG) methodTree.cfg(); -LiveVariables liveVariables = LiveVariables.analyze(cfg); -for (CFG.Block block : cfg.blocks()) { - checkElements(block, liveVariables.getOut(block), methodSymbol); -} -``` - -**Techniques observed:** -- CFG construction from method bodies -- Liveness analysis for variable usage -- Block-level analysis with propagation -- Backward analysis through blocks - -### 4. Validation and Filtering - -#### Context Checks -Rules validate surrounding context before reporting: - -```java -// EmptyBlockCheck -if (!tree.parent().is(Tree.Kind.LAMBDA_EXPRESSION) - && !hasStatements((BlockTree) tree) - && !isRuleException((BlockTree) tree)) { - reportIssue(...); -} -``` - -Common context validations: -- Parent node type checking -- Enclosing scope inspection (method, class, etc.) -- Modifier checks (public, static, final) -- Annotation presence - -#### Allowlist/Denylist Logic - -**Method matchers as denylists:** -```java -private static final MethodMatchers NEGATIVE_METHODS = MethodMatchers.or( - MethodMatchers.create().ofAnyType().names("hashCode").build(), - MethodMatchers.create().ofSubTypes("java.util.Random").names("nextInt", "nextLong").build() -); -``` - -**Type-based filtering:** -```java -private static final Set OPTIONAL_CLASSES = - SetUtils.immutableSetOf("java.util.Optional", "com.google.common.base.Optional"); -``` - -#### Exception Handling Patterns - -**Early returns for special cases:** -```java -private static boolean isRuleException(BlockTree tree) { - return hasCommentInside(tree) && !tree.parent().is(Tree.Kind.SYNCHRONIZED_STATEMENT); -} -``` - -**Null safety:** -```java -@CheckForNull -private static MethodInvocationTree extractMethodInvocation(ExpressionTree tree) { - // Returns null if pattern doesn't match -} -``` - -#### Negation Handling -Rules explicitly handle negation in boolean expressions: -```java -if (tree.is(Tree.Kind.NOT_EQUAL_TO)) { - quickFix.addTextEdit(JavaTextEdit.insertBeforeTree(leftOperand, "!")); -} -``` - -#### Performance Optimizations - -**Caching:** -```java -private MethodMatchers matchers; -private MethodMatchers matchers() { - if (matchers == null) { - matchers = getMethodInvocationMatchers(); - } - return matchers; -} -``` - -**Early returns:** -```java -if (methodTree.block() == null) { - return; // Skip abstract methods -} -``` - -**File-level caching:** -```java -private static final String CACHE_KEY_PREFIX = "java:S4605:targeted:"; -// Read previously computed data to skip analysis -``` - -**Scope limiting:** -```java -if (isInCollectionType()) { - return; // Skip analysis inside Collection implementations -} -``` - ---- - -## Step 3: Reusable Patterns - -### Common Helper Functions - -#### Tree Navigation Helpers (from QuickFixHelper) -```java -public static SyntaxToken nextToken(Tree tree) -public static SyntaxToken previousToken(Tree tree) -public static Optional previousVariable(VariableTree current) -public static Optional nextVariable(VariableTree variable) -``` - -**Usage:** Navigate between siblings in multi-variable declarations, find adjacent tokens for quick fixes. - -#### Main Method Detection (from MethodTreeUtils) -```java -public static boolean isMainMethod(MethodTree m, JavaVersion javaVersion) -``` - -**Usage:** Detect Java main method entry points. - -#### Unit Test Detection (from UnitTestUtils) -```java -public static final MethodMatchers ASSERTION_INVOCATION_MATCHERS -public static final Pattern ASSERTION_METHODS_PATTERN -``` - -**Usage:** Identify test code vs production code (20+ rules use this). - -#### Expression Helpers (from ExpressionsHelper - in java-checks-common) -Common utilities for expression analysis and constant value extraction. - -### Reusable Traversal Utilities - -#### Abstract Base Classes - -**AbstractMethodDetection:** -```java -// Automatically visits method invocations, constructors, and method references -protected abstract MethodMatchers getMethodInvocationMatchers(); -protected void onMethodInvocationFound(MethodInvocationTree mit) { } -protected void onConstructorFound(NewClassTree newClassTree) { } -``` - -**Usage:** ~50+ rules for method-based pattern detection (e.g., deprecated API usage, security issues). - -**AbstractForLoopRule:** -```java -// Provides helpers for analyzing for-loop structure -protected static class ForLoopInitializer -protected static class ForLoopIncrement -``` - -**Usage:** 8+ rules analyzing for-loop patterns. - -**AbstractRegexCheck:** -```java -// Handles regex extraction from strings and method calls -// Integrates with regex parser -protected List nodesToVisit() // Pre-configured -``` - -**Usage:** 35+ regex validation rules. - -#### Nested Visitor Pattern -```java -// Scan within a specific subtree -tree.accept(new CustomVisitor()); - -class CustomVisitor extends BaseTreeVisitor { - @Override - public void visitReturnStatement(ReturnStatementTree returnStatement) { - // Custom logic - } -} -``` - -**Usage:** Complex rules with multi-level analysis (e.g., `NullShouldNotBeUsedWithOptionalCheck`). - -### Repeated Filtering Logic - -#### Test Code Filtering -**Pattern appears in 20+ rules:** -```java -if (UnitTestUtils.isTestClass(classTree)) { - return; // Skip analysis in test code -} -``` - -#### Annotation-Based Filtering -**Pattern appears in 15+ rules:** -```java -if (symbol.metadata().isAnnotatedWith("javax.annotation.Nullable")) { - return; // Skip nullable-annotated elements -} -``` - -#### Type Hierarchy Checks -**Common pattern in 30+ rules:** -```java -if (type.isSubtypeOf("java.util.Collection")) { - // Apply collection-specific logic -} -``` - -### Repeated Diagnostic Construction Patterns - -#### Standard Issue Reporting -```java -reportIssue(tree, "Message with issue description"); -``` - -#### Issue with Secondary Locations -```java -List secondaries = new ArrayList<>(); -secondaries.add(new JavaFileScannerContext.Location("Secondary message", otherTree)); -reportIssue(tree, "Primary message", secondaries, null); -``` - -#### Quick Fix Integration (newer pattern) -```java -QuickFixHelper.newIssue(context) - .forRule(this) - .onTree(tree) - .withMessage("Issue message") - .withQuickFix(() -> buildQuickFix(tree)) - .report(); -``` - -**Quick fix pattern (from CompareStringsBoxedTypesWithEqualsCheck):** -```java -private JavaQuickFix buildQuickFix(BinaryExpressionTree tree) { - return JavaQuickFix.newQuickFix("Fix description") - .addTextEdit(JavaTextEdit.insertAfterTree(tree.rightOperand(), ")")) - .addTextEdit(JavaTextEdit.replaceTextSpan(span, ".equals(")) - .build(); -} -``` - -### Helper Modules and Utilities - -#### java-checks-common Module -**Purpose:** Shared utilities used across multiple modules -- `ExpressionsHelper`: Expression analysis and constant extraction -- `CredentialMethod`, `CredentialMethodsLoader`: Security credential detection -- `HardcodedStringExpressionChecker`: String literal analysis -- `ReassignmentFinder`: Variable reassignment tracking -- `TreeHelper`: General tree manipulation utilities -- `AbstractMethodDetection`: Base class for method pattern detection - -#### java-checks/helpers Module (20+ utility classes) -- `QuickFixHelper`: Quick fix construction and import management -- `MethodTreeUtils`: Method pattern detection utilities -- `UnitTestUtils`: Test code detection and test framework matchers -- `JavaPropertiesHelper`: Java properties file handling -- `Javadoc`: Javadoc parsing and validation -- `SpringUtils`: Spring framework pattern detection -- `TryCatchUtils`: Exception handling pattern utilities -- `NullabilityDataUtils`: Nullability annotation handling -- `RandomnessDetector`: Cryptographic randomness validation -- `ShannonEntropy`: Entropy calculation for secret detection -- `ValueBasedUtils`: Value-based class detection -- `UnresolvedIdentifiersVisitor`: Track unresolved symbols -- And more... - -#### Domain-Specific Helpers - -**Serialization utilities (SerializableContract):** -```java -public static boolean hasSpecialHandlingSerializationMethods(ClassTree classTree) -public static MethodMatchers readObjectMatcher(String classFullyQualifiedName) -public static MethodMatchers writeObjectMatcher(String classFullyQualifiedName) -``` - -**AWS utilities (AwsBuilderMethodFinder):** -```java -// Helper for finding AWS SDK builder patterns -``` - -### Code Reuse Statistics - -Based on the inspected files: -- **~15 abstract base classes** providing specialized frameworks -- **~40 helper utility classes** with reusable functions -- **MethodMatchers pattern** used in 200+ rules (50% of all rules) -- **Quick fix infrastructure** used in 50+ rules (growing pattern) -- **CFG/data flow analysis** used in ~10 complex rules -- **Regex parsing framework** shared by 35 regex rules - ---- - -## Summary - -The SonarQube Java analyzer demonstrates a mature, well-architected rule engine with: - -1. **Large Scale:** 400+ rules organized across multiple modules (core, AWS, specialized domains) - -2. **Layered Architecture:** - - Core: IssuableSubscriptionVisitor/BaseTreeVisitor - - Domain abstractions: AbstractMethodDetection, AbstractRegexCheck, etc. - - Specialized subsystems: Regex parsing, CFG analysis, Spring framework support - -3. **Implementation Diversity:** - - Simple syntactic checks (50-150 LOC) - - Medium semantic checks (150-300 LOC) - - Complex data-flow checks (300+ LOC) - -4. **Rich Analysis Capabilities:** - - Syntax pattern matching via visitor pattern - - Semantic analysis via symbol/type system - - Control flow analysis via CFG - - Regex parsing and validation - - Cross-file analysis support - -5. **Extensive Reuse:** - - 15+ abstract base classes - - 40+ helper utility classes - - Shared infrastructure for MethodMatchers, quick fixes, CFG analysis - - Domain-specific utilities (serialization, Spring, AWS, unit tests) - -The architecture significantly reduces the cost of new rule implementation through well-designed abstractions, comprehensive helper utilities, and clear patterns that can be followed from existing examples. diff --git a/.agents/commands/migrate-test-samples.md b/.agents/commands/migrate-test-samples.md deleted file mode 100644 index f8eae95bf17..00000000000 --- a/.agents/commands/migrate-test-samples.md +++ /dev/null @@ -1,140 +0,0 @@ -Migrate test sample files for $ARGUMENTS from the old location (`java-checks/src/test/files/checks/`) to the new location. - -Before starting, ask the user whether the sample is **compiling** or **non-compiling**: -- **Compiling** samples go to: `java-checks-test-sources/default/src/main/java/checks/` -- **Non-compiling** samples go to: `java-checks-test-sources/default/src/main/files/non-compiling/checks/` - -Follow these steps for each `*CheckTest.java` file being migrated: - -## 1. Identify the test file and its sample files - -Find the test class at `java-checks/src/test/java/org/sonar/java/checks/CheckTest.java`. Read it and identify ALL `.onFile("src/test/files/checks/...")` references. Each such reference points to an old sample file that needs migrating. - -## 2. Move each sample file to the new location with the correct name - -For each old sample file: - -- The **primary** sample (the main one used in the `test()` method) should be renamed to `CheckSample.java` in the destination directory. -- **Variant** samples (used in other test methods, e.g. with custom config or different Java versions) should follow the convention `CheckSample_.java` or `Check_.java`, matching whatever variant suffix the old file had (e.g. `Custom`, `no_version`, `java8`). -- The destination depends on the user's choice: - - **Compiling**: `java-checks-test-sources/default/src/main/java/checks/` - - **Non-compiling**: `java-checks-test-sources/default/src/main/files/non-compiling/checks/` - -Use `git mv` to move the file, then rename it if the filename changed. - -## 3. Add `package checks;` to the sample file (compiling samples only) - -For **compiling** samples: Insert `package checks;` as the very first line of the moved sample file, followed by a blank line before any existing content. - -For **non-compiling** samples: Do NOT add a package declaration. - -In both cases, this is the ONLY content modification to make to the sample. Do NOT rename classes, fix compilation errors, update imports, or make any other changes. Leave those for the user. - -## 4. Update the test file - -In the `*CheckTest.java` file: - -For **compiling** samples: -- Add the import if not already present: - ```java - import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; - ``` -- Replace each old-style `.onFile("src/test/files/checks/.java")` with: - ```java - .onFile(mainCodeSourcesPath("checks/.java")) - ``` - -For **non-compiling** samples: -- Add the import if not already present: - ```java - import static org.sonar.java.checks.verifier.TestUtils.nonCompilingTestSourcesPath; - ``` -- Replace each old-style `.onFile("src/test/files/checks/.java")` with: - ```java - .onFile(nonCompilingTestSourcesPath("checks/.java")) - ``` - -In both cases, `` is the new filename chosen in step 2. - -## 5. Verify - -Run the specific test to verify nothing is broken: -``` -mvn test -pl java-checks -Dtest=CheckTest -Dsurefire.failIfNoSpecifiedTests=false -``` - -If the test fails, report the failure to the user but do NOT attempt to fix the sample file content. - -## Example: migrating `LambdaTypeParameterCheck` - -**Old sample** at `java-checks/src/test/files/checks/LambdaTypeParameterCheck.java`: -```java -import java.util.function.BiConsumer; -import java.util.function.Consumer; - -abstract class A { - public void foo() { - foo((String s) -> s.length()); // Compliant - foo(s -> {return s.length();}); // Noncompliant {{Specify a type for: 's'}} -// ^ - } - - abstract void foo(Consumer s); - abstract void foo(BiConsumer bc); -} -``` - -**New sample** at `java-checks-test-sources/default/src/main/java/checks/LambdaTypeParameterCheckSample.java`: -```java -package checks; - -import java.util.function.BiConsumer; -import java.util.function.Consumer; - -abstract class LambdaTypeParameterCheckSample { - public void foo() { - foo((String s) -> s.length()); // Compliant - foo(s -> {return s.length();}); // Noncompliant {{Specify a type for: 's'}} -// ^ - } - - abstract void foo(Consumer s); - abstract void foo(BiConsumer bc); -} -``` - -Note: `package checks;` was added as the first line. The class was renamed from `A` to `LambdaTypeParameterCheckSample` by the user after migration — the skill only adds the package declaration. - -**Old test** `LambdaTypeParameterCheckTest.java`: -```java -import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.CheckVerifier; - -class LambdaTypeParameterCheckTest { - @Test - void test() { - CheckVerifier.newVerifier() - .onFile("src/test/files/checks/LambdaTypeParameterCheck.java") - .withCheck(new LambdaTypeParameterCheck()) - .verifyIssues(); - } -} -``` - -**New test** `LambdaTypeParameterCheckTest.java`: -```java -import org.junit.jupiter.api.Test; -import org.sonar.java.checks.verifier.CheckVerifier; - -import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; - -class LambdaTypeParameterCheckTest { - @Test - void test() { - CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath("checks/LambdaTypeParameterCheckSample.java")) - .withCheck(new LambdaTypeParameterCheck()) - .verifyIssues(); - } -} -``` diff --git a/.agents/commands/project-level-rules.md b/.agents/commands/project-level-rules.md deleted file mode 100644 index 427bb14a1a7..00000000000 --- a/.agents/commands/project-level-rules.md +++ /dev/null @@ -1,201 +0,0 @@ -# Project-Level Rules - -Rules that need to aggregate data across **all files in a module** before deciding whether to raise issues. -They run during `endOfAnalysis()` — after every file has been visited. - -## Key interfaces - -- `EndOfAnalysis` (`java-frontend/.../api/internal/EndOfAnalysis.java`) — callback fired once per module after all files are scanned -- `ModuleScannerContext` — passed to `endOfAnalysis()`; use `addIssueOnProject()` for project-level issues or cast to `DefaultModuleScannerContext` to call `reportIssue(AnalyzerMessage)` for richer issues (secondary locations, text spans) -- `JavaFileScanner.scanWithoutParsing()` — implement to restore state from cache for unchanged files (see Caching section) - -## Minimal skeleton - -```java -@Rule(key = "SXXXX") -public class MyCheck extends IssuableSubscriptionVisitor implements EndOfAnalysis { - - // State accumulated across files — use lightweight types, NOT AST references - private final List issues = new ArrayList<>(); - - @Override - public List nodesToVisit() { - return List.of(Tree.Kind.CLASS); - } - - @Override - public void visitNode(Tree tree) { - // collect candidates into `issues` - } - - @Override - public void endOfAnalysis(ModuleScannerContext context) { - var defaultContext = (DefaultModuleScannerContext) context; - issues.forEach(defaultContext::reportIssue); - // issues list is NOT cleared here — VisitorsBridge creates a fresh check instance per analysis - } -} -``` - -## Caching (incremental analysis) - -Rules implementing `EndOfAnalysis` are **never skipped** for unchanged files — they are always in `scannersThatCannotBeSkipped`. Without caching, they only see changed files on incremental runs. - -Do **not** hand-roll the cache plumbing. Implement `FileCachingCheck` (`java-frontend/.../org/sonar/java/caching/FileCachingCheck.java`), where `T` is the data collected for -one file. It owns the key construction, the `isCacheEnabled()` guard, `copyFromPrevious`, and the error handling. - -No cache problem is fatal, but they degrade differently — worth knowing when a trace log is all you have to debug a miss: - -| Problem | Logged? | Consequence | -|---|---|---| -| Entry cannot be deserialized | trace | file is parsed instead, and the entry rewritten | -| No entry for the file | no | file is parsed instead | -| Write collides with an earlier one | trace | new payload dropped, earlier entry kept; the file had been parsed either way | -| `copyFromPrevious` collides | trace | none — the data stays restored; another check sharing the entry already copied it | -| I/O failure reading the cache | warn, by `VisitorsBridge` | file is parsed instead; fails the analysis only in fail-fast mode | - -Returning `true` from `restoreFromCache` only means that one check does not require parsing. The file is -skipped only when every scanner that cannot be skipped returns `true`. Another scanner's cache miss or -failure can therefore cause the check to visit a file after restoring its cached contribution. Keep -module-level state keyed by `context.getInputFile().key()`, and replace that file's contribution from both -the restored and parsed paths. - -```java -@Rule(key = "SXXXX") -public class MyCheck extends IssuableSubscriptionVisitor - implements EndOfAnalysis, FileCachingCheck { - - private static final String CACHE_KEY_PREFIX = "java:SXXXX:"; - private static final int CACHE_FORMAT_VERSION = 1; - private static final String COUNT = "count"; - - private final Map dataByFile = new HashMap<>(); - private int currentFileCount; - - record PerFileData(int count) {} - - @Override - public String cacheKeyPrefix() { - return CACHE_KEY_PREFIX; - } - - @Override - public byte[] serialize(PerFileData data) { - var document = JsonUtils.writeDocument(CACHE_FORMAT_VERSION, - out -> out.name(COUNT).value(data.count())); - return document.getBytes(StandardCharsets.UTF_8); - } - - @Override - public PerFileData deserialize(byte[] data) { - var document = JsonUtils.parseDocument(new String(data, StandardCharsets.UTF_8), CACHE_FORMAT_VERSION); - return new PerFileData(JsonUtils.requiredInt(document, COUNT)); - } - - @Override - public void restore(InputFileScannerContext context, PerFileData data) { - dataByFile.put(context.getInputFile().key(), data); - } - - @Override - public void leaveFile(JavaFileScannerContext context) { - var data = new PerFileData(currentFileCount); - dataByFile.put(context.getInputFile().key(), data); - writeToCache(context, data); - currentFileCount = 0; - } - - @Override - public boolean scanWithoutParsing(InputFileScannerContext context) { - return restoreFromCache(context); - } -} -``` - -Aggregate `dataByFile.values()` in `endOfAnalysis`. Recording the parsed value before clearing per-file -state is what replaces an earlier restore when another scanner forces parsing. - -A check implementing plain `JavaFileScanner` (no `leaveFile`) calls `writeToCache` from `scanFile` -instead. - -### Serialization format - -Wrap the entry in a versioned document with `JsonUtils` (`org.sonar.java.serialization`): -`writeDocument(version, body)` returns the document as a `String`, `parseDocument(content, version)` -reads it back, and the check converts to and from `byte[]` in UTF-8 itself. Bump your -`CACHE_FORMAT_VERSION` whenever the entry shape changes — old entries are then rejected and -recomputed. Every `JsonUtils` accessor is strict and throws on anything unexpected, which -`readFromCache` turns into a cache miss. - -Several checks sharing one format keep it in a dedicated class rather than in each check — see -`SpringContextCacheHelper`, which owns the version the Spring gatherers share along with the -`byte[]` conversions. - -Describe anything with structure as a Gson **`TypeAdapter`** rather than assembling the tree by hand — -see `BeanDefinitionHolderTypeAdapter` and `InjectionPointTypeAdapter`, which read with `JsonUtils.readString`, -`readNullableString` and `readStrings` (`readInt` too, in `TextSpanTypeAdapter`). Adapters should skip -unknown properties (`default -> in.skipValue()`) so a newer entry shape stays readable. - -Never use Gson's reflective object binding (`new Gson().toJson(pojo)`): the plugin is shaded with -`minimizeJar`, which strips classes reached only by reflection. Explicit `TypeAdapter`s and the tree -API are both safe. - -### Restoring locations - -`TextSpanTypeAdapter.getInstance()` (`org.sonar.java.serialization`) serializes an `AnalyzerMessage.TextSpan`. - -A payload holds **text spans only, never the file they belong to**. File identity lives in the cache key -(`cacheKeyPrefix() + inputFile.key()`), which is what lets `deserialize(byte[])` read an entry without -knowing which file it describes. Name a per-file record after that property — see -`BeanDefinitionHolder.InputFileData`. - -`restore(InputFileScannerContext, T)` is the only place the file reaches the check, so store the data -under it and pair the spans with it when aggregating in `endOfAnalysis`. `BeanDefinitionGatherer` keys -`beansCollectedByFile` by `InputFile` and builds every `BeanLocation(inputFile, data.textSpan())` in -`gatherSpringContextData`, from the map key rather than from anything in the payload. - -Adapters therefore never need an `InputFile`, and are stateless singletons -(`BeanDefinitionHolderTypeAdapter`, `TextSpanTypeAdapter`). - -### Sharing an entry between rules - -Two checks may return the same `cacheKeyPrefix()` to share one entry. `MissingPackageInfoCheck` (S1228) and `UselessPackageInfoCheck` (S4032) already share a single entry this way, through the hand-rolled key of their `AbstractPackageInfoChecker` base class. -The first write of an analysis wins and the rest are ignored. - -### When caching is not needed - -If the rule's correctness on incremental runs is acceptable without full history (e.g. noise-reduction rules like `BrainMethodCheck`), you can skip caching entirely. The default `scanWithoutParsing()` returns `true` and the rule simply sees fewer files on incremental runs. - -## Behavior by product - -| | SQS / SQC | SonarQube for IDE (SonarLint) | -|---|---|---| -| `endOfAnalysis()` fires | Yes, once per module | Yes, but may only see open/active files | -| Incremental file skipping | Enabled (use caching to restore state) | Always file-by-file, no skipping | -| Server-side cache | `context.previousCache()` / `nextCache()` | `SonarLintCache` (in-memory, `isCacheEnabled()` = false) | -| `ProjectSensor` | Runs after all modules | **Not invoked** | - -## vs `ProjectSensor` - -`EndOfAnalysis` fires per **module**. For truly cross-module aggregation (whole project), use `ProjectSensor` — but it is **not invoked in SonarLint**. The pattern is: accumulate in a shared singleton during each module's `EndOfAnalysis`, then flush/report in `ProjectEndOfAnalysisSensor.execute()`. - -Currently `ProjectEndOfAnalysisSensor` only handles telemetry, not rule issues. - -## Examples in codebase - -| Rule | Pattern | -|---|---| -| `SpringBeansShouldBeAccessibleCheck` (S4605) | Aggregates packages and reports in `endOfAnalysis`, but predates `FileCachingCheck` and still hand-rolls its own plumbing — not a template | -| `BrainMethodCheck` (S6541) | No caching: collects candidates, noise-filters and reports in `endOfAnalysis` | -| `AbstractPackageInfoChecker` (S1228, S4032) | Two rules sharing one cache entry | -| `ExcessiveContentRequestCheck` (S5693) | Cross-file config aggregation | -| `DateEnumsCheck` (S8694) | Caches potential issues and rebuilds their quick fixes without the AST | -| `BeanDefinitionGatherer` | `FileCachingCheck` reference: nested payload, spans paired with their file at aggregation time | -| `ComponentScanPackageGatherer` | `FileCachingCheck` reference: flat payload, no locations to restore | - -## Memory warning - -> "keeping state between files can lead to memory leaks. Implement with care." — `EndOfAnalysis` javadoc - -- Store serializable/primitive data only — never hold AST node references between files -- Clear per-file state in `leaveFile()` (or `setContext()`) diff --git a/.agents/commands/quickfix-tests.md b/.agents/commands/quickfix-tests.md deleted file mode 100644 index ab97158d346..00000000000 --- a/.agents/commands/quickfix-tests.md +++ /dev/null @@ -1,141 +0,0 @@ -# Quick Fix Test Annotation Pattern - -## Overview - -Quick fix annotations go in the sample file alongside `// Noncompliant` comments. - ---- - -## Annotation Format - -### 1. Declare an expected quick fix on the Noncompliant line - -```java -someCode(); // Noncompliant {{message}} [[quickfixes=qf1]] -``` - -`[[quickfixes=qfN]]` must come **after** `{{message}}`. - -If the issue has a precise underline annotation on the next line, the `[[quickfixes=qfN]]` -attribute goes on the `// Noncompliant` line (not on the `//^^^^` line). - -### 2. Declare fix description - -```java -// fix@qf1 {{Description shown in IDE}} -``` - -### 3. Declare each text edit - -```java -// edit@qf1 [[sl=+2;sc=3;el=+2;ec=9]] {{replacement}} -// edit@qf1 [[sl=+5;sc=3;el=+5;ec=13]] {{}} // empty = delete -``` - -**Attributes:** -- `sl` / `el` — start/end line, relative (`+N`/`-N`) to the Noncompliant line, or absolute -- `sc` / `ec` — start/end column (1-indexed, end is exclusive — i.e. points to the first character NOT removed) -- `{{replacement}}` — replacement text; `{{}}` means delete - ---- - -## Column Indexing - -Columns are **1-indexed** and the end column is **exclusive** (points past the last removed character). - -For a modifier like `public` at the start of ` public static void foo()`: -- `public` occupies columns 3–8 (1-indexed, inclusive) -- To remove `public ` (including trailing space, up to `static`): `sc=3;ec=10` - - `sc=3` = column of `p` - - `ec=10` = column of `s` in `static` (the first character NOT removed) - -For `protected` followed by a space and `static` (13 chars total indented by 2): -- `protected` at columns 3–11; `static` at column 13 -- To remove `protected `: `sc=3;ec=13` - -General rule using `AnalyzerMessage.textSpanBetween(modifier, true, nextToken, false)`: -- `sc` = column of modifier's first character (1-indexed) -- `ec` = column of next token's first character (1-indexed) - ---- - -## Edit Order - -Edits must be listed **in the same order** they appear in the `JavaQuickFix`. -The verifier uses `List.equals()` — order matters. - -**Do NOT call `.reverseSortEdits()` on `JavaQuickFix.Builder`** unless you also list -the annotations in the resulting (reversed) order. The natural collection order (ascending -by source position) is the standard — matches how annotations appear in the sample file. - ---- - -## Example: Single modifier (one edit) - -```java -protected static class Foo { // Noncompliant {{Remove this 'protected' modifier.}} [[quickfixes=qf1]] -//^^^^^^^^^ -// fix@qf1 {{Remove "protected" modifier}} -// edit@qf1 [[sc=3;ec=13]] {{}} -``` - -No `sl`/`el` needed when the edit is on the **same line** as the issue. - -## Example: Multiple modifiers across methods (multiple edits) - -```java -class MyTest { // Noncompliant {{Remove the visibility modifiers from this test class and its methods.}} [[quickfixes=qf1]] -// ^^^^^^ - // fix@qf1 {{Remove all visibility modifiers}} - // edit@qf1 [[sl=+5;sc=3;el=+5;ec=10]] {{}} // public on line+5 - // edit@qf1 [[sl=+9;sc=3;el=+9;ec=13]] {{}} // protected on line+9 -``` - ---- - -## Check implementation - -```java -private static JavaQuickFix buildQuickFix(List modifiers) { - List edits = modifiers.stream() - .map(m -> JavaTextEdit.removeTextSpan( - AnalyzerMessage.textSpanBetween(m, true, QuickFixHelper.nextToken(m), false))) - .toList(); - String description = modifiers.size() == 1 - ? String.format("Remove \"%s\" modifier", modifiers.get(0).keyword().text()) - : "Remove all visibility modifiers"; - return JavaQuickFix.newQuickFix(description) - .addTextEdits(edits) - .build(); // do NOT call reverseSortEdits() unless annotations also reversed -} -``` - -Report the issue with `withQuickFixes` (plural), not `withQuickFix`: - -```java -QuickFixHelper.newIssue(context) - .forRule(this) - .onTree(someTree) - .withMessage("...") - .withQuickFixes(() -> List.of(buildQuickFix(modifiers))) - .report(); -``` - ---- - -## Debugging - -If the test fails with: -``` -Expected quickfix qfN at line X was not matched by any provided quickfixes -``` - -Check these in order: -1. **Order of edits** — are the `edit@` annotations in the same order as the `JavaQuickFix` text edits? -2. **Column values** — verify `sc`/`ec` using the column formula above -3. **Description** — must match the `fix@` annotation exactly -4. **`withQuickFixes` vs `withQuickFix`** — use the plural form -5. **`reverseSortEdits()`** — remove it unless annotations are also in reversed order - -The verifier prints only the EXPECTED side on failure; it does not print the actual. -To see the actual, temporarily add a print in `buildQuickFix` or check column math manually. diff --git a/.agents/skills/migrate-test-samples/SKILL.md b/.agents/skills/migrate-test-samples/SKILL.md new file mode 100644 index 00000000000..5f422302d81 --- /dev/null +++ b/.agents/skills/migrate-test-samples/SKILL.md @@ -0,0 +1,16 @@ +--- +name: migrate-test-samples +description: Move legacy SonarJava rule fixtures into the appropriate Maven sample module and update the verifier paths without changing rule behavior. +metadata: + generated.by: tirion +--- + +# Migrate legacy rule test samples + +Read `docs/systems/rule-tests.md` for destinations, package conventions and verifier helpers. This skill changes fixture placement, not the check or its expected findings. + +1. Find the named check's test class under `java-checks/src/test/java/org/sonar/java/checks`. Trace every path it uses under `java-checks/src/test/files/checks`, including paths assembled from constants and shared fixtures. Find any other consumers before moving a shared file. +2. Decide which samples compile, which are deliberately non-compiling, and whether any are test code or need a version-specific module. Inspect the fixture and verifier setup before choosing; ask if the intended setup is ambiguous. Do not move a parser-only fixture just because it lives in the legacy tree. +3. Move the main fixture with the **CheckSample.java** suffix and keep meaningful suffixes on variants. For a compiling fixture entering `checks`, add `package checks;` if missing. For a non-compiling fixture, keep the original package or lack of one. Preserve issue annotations, source constructs and class names unless a compile fix is explicitly in scope. If a public class name or conflicting type prevents compilation, report the required change rather than switching the fixture to the non-compiling directory. +4. Replace legacy paths with the corresponding `TestUtils` helper using a path relative to its source root. Preserve classpath, Java version, file status and expected issue configuration. Update every reference to the moved file. +5. Run the affected test classes and compile the destination module for compiling samples. If a test or build fails, report the failure and what it would take to fix it. Do not rewrite fixture behavior as part of the move. diff --git a/.agents/skills/new-rule/SKILL.md b/.agents/skills/new-rule/SKILL.md index da62286aebe..d198df5238e 100644 --- a/.agents/skills/new-rule/SKILL.md +++ b/.agents/skills/new-rule/SKILL.md @@ -1,297 +1,13 @@ --- name: new-rule -description: >- - Implement Java analyzer rules using the mandatory delivery workflow: - metadata → failing reproducer → implementation → PR babysit → TP/FP > 90%. - Use when creating or shipping any new/changed rule. +description: Implement a new SonarJava analyzer rule from its RSPEC specification and verify its behavior with rule tests and CI ruling. +metadata: + generated.by: tirion --- -# New Rule Implementation Skill +# Implement a new SonarJava rule -This skill provides sonar-java-specific guidelines for implementing new rules. - -**Non-negotiable:** every rule PR must follow the [Mandatory delivery workflow](#mandatory-delivery-workflow). Do not end before a PR that is not fully green, has open review-bot comments, messy history, or a TP ratio of 90% or below. - -## Mandatory delivery workflow - -Execute **in order**. Never skip. Never combine steps into one commit. If precision fails, loop again. - -### Step 0 — Pre-flight (once, before any rule work) - -**Run once** before Step 1. When implementing multiple rules in parallel (subagents), collect answers **here only** once at the beginning, then start each rule with the answers already known — do not re-ask later. - -Verify / ask as needed: - -- [ ] Access to the RSpec repository and a local `rule-api` jar (see [Metadata Files](#metadata-files)) -- [ ] Rule id(s) to implement -- [ ] RSpec status per rule: merged on `master` **or** branch name — look up branch/PR **only** in https://github.com/SonarSource/rspec (never in this repo) -- [ ] RSpec Jira ticket key (from the RSpec PR title/branch) — reused as the implementation ticket and as the PR title prefix (Step 4) -- [ ] Rule title (for the PR title format in Step 4) -- [ ] Any path/env overrides needed - -Stop and resolve gaps before Step 1. - -### Commit rules (all steps) - -- Aim for **one commit per step** below. While working, extra commits are fine: fixes, retries and ruling updates will be folded back into one commit per step during [Step 7](#step-7--clean-history). The rule is an invariant on the **final** history, not a constraint on how you work. -- Never squash everything into a single commit either: the final history keeps one commit per step. -- Message: single line, few words, clear. **No rule id** (it is in the branch). **No "java"** (it is the repo). **No Jira key** (never in commits). -- Examples: `Add rule metadata`, `Add failing reproducer`, `Implement rule`, `Fix review comments`, `Update ruling expectations` - -### Step 1 — Metadata → commit - -1. Generate metadata with `rule-api` (see [Metadata Files](#metadata-files)). Never hand-write `.html`/`.json`. -2. Stage **only** rule-relevant files: `SXXXX.html`, `SXXXX.json`, and the profile files under `sonar-java-plugin/src/main/resources/profiles/`. -3. Commit. - -### Step 2 — Failing reproducer → commit - -1. Write the test sample (`java-checks-test-sources/default/src/main/java/checks/{RuleId}CheckSample.java`) covering **every** edge case, noncompliant and compliant, with caret markers on **every** primary and secondary location (see [Test sample location markers](#test-sample-location-markers)). -2. Write `{RuleId}CheckTest.java`, with both a semantic and a `withoutSemantic()` test, free of duplication (see [Test class structure](#test-class-structure)). -3. Add an **empty** check class (`@Rule(key = "SXXXX")`, minimal `nodesToVisit`/`visitNode`). -4. Run the test — it **must fail**. -5. Commit (reproducer + empty check + test). - -### Step 3 — Implementation → commit - -1. Implement the check until the unit test **passes**. Match methods and types with [matchers](#method-and-type-matching), never with raw strings, and keep the check [stateless](#stateless-checks). -2. Commit. - -### Step 4 — Push & PR - -Push the branch, named with your GitHub username convention (e.g. `/short-kebab-description`), and open the PR. - -**Single Jira ticket (mandatory):** the RSpec and the rule implementation share the **same** SONARJAVA ticket. Do **not** create a second ticket, and do **not** put the Jira key in commits. - -1. Open the analyzer PR with title exactly: `SONARJAVA-XXXX Implement rule SXXXX - `, reusing the RSpec ticket key as prefix (rule id and title from RSpec). -2. Do not invent a ticket key — take it from the RSpec PR or branch. - -Do not stop here. - -### Step 5 — Babysit until merge-ready - -Loop until **all** are true: - -- Every CI check is green -- **No** unresolved or open review-bot comments (address or validly refute each one) -- No merge blockers - -While babysitting: - -- **Rebase:** automatically rebase on `master` and fix conflicts (rebase, not merge). -- **Comments:** only unresolved threads; read body and location only, not huge JSON dumps. Treat gitar review bot carefully — fix only if valid; explain when you disagree. - -If **ruling** fails (likely for a new rule), a PR updating the expectations is created automatically on CI failure. Review it, merge it into the branch if the new findings are legitimate, otherwise fix the implementation and the unit tests. Push and re-babysit. The resulting merge commit is acceptable while babysitting; Step 7 folds the expectation update into a single `Update ruling expectations` commit. - -### Step 6 — TP/FP analysis (only when Step 5 is fully green) - -1. Collect the **new** findings from the ruling expectation diff, i.e. the `runs[].results[]` entries added to `its/ruling/src/test/resources/expected//java-.sarif` by the merged ruling-update commit (e.g. `git diff origin/master -- its/ruling/src/test/resources/expected/`). Its `locations[0].physicalLocation.artifactLocation.uri` is `:path/to/File.java` and `locations[0].physicalLocation.region` gives the line and column. Sources are under `its/sources//`. -2. **Sample** new findings before classifying (do not analyze unbounded volumes): - - Let `N` be the sample size (default **100**). - - If total new findings ≤ `N` → analyze **all**. - - Else sample up to `N` across projects (water-filling, i.e. equal shares capped by each project's count): - 1. Give every project with findings its fair equal share of the remaining budget among projects that still have unsampled issues. - 2. Projects with fewer findings than their share contribute **all** of theirs; leftover budget is redistributed evenly to projects that still have unsampled issues. - 3. Repeat until the budget is exhausted. - - Examples: A=1000, B=10_000_000 → about 50 each of 100; A=1, B=100, C=3 → take 1/96/3. -3. For **every** sampled finding: classify **TP** (correct) or **FP** (incorrect). -4. Compute `TP% = 100 * TPs / (TPs + FPs)` on the sample. -5. **Must be > 90%.** If 90% or below: add reproducers for the FPs as new test cases and confirm the test fails (Step 2 commit), then introduce heuristics in the implementation to reduce the noise until it passes (Step 3 commit), and re-run Steps 5 and 6. Do not restart from Step 1: metadata and the check class already exist. - -### Step 7 — Clean history - -This is where the one-commit-per-step rule is enforced. Whatever the branch looks like after babysitting and precision loops, the final history must show **exactly one commit per workflow step**: - -- one `Add rule metadata` commit -- one `Add failing reproducer` commit, including the FP cases added in Step 6 -- one `Implement rule` commit, including the heuristics added in Step 6 -- one `Update ruling expectations` commit, folding in the auto-generated ruling PR and dropping its merge commit - -Rewrite history with interactive `rebase` (never a merge), then force-push and confirm Steps 5 and 6 still hold. - -### Definition of done - -The PR is done **only** when: - -1. History is clean (one commit per step) -2. All checks are green -3. No open review-bot comments -4. TP/FP analysis is done and **TP% > 90%** - -## What to Do - -### Metadata Files -- **DO** generate rule metadata using rule-api tool from the RSPEC repository: - - Ensure your local rspec repository is up-to-date with the rule branch - - Use rule-api jar (check Maven local repository for available versions) - - Command: `java -jar generate -branch rule/add-RSPEC-S{RULE_ID} -rule S{RULE_ID}` - - This generates HTML and JSON files and updates the Sonar way profile automatically -- Generated files will be placed in: - - `sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S{RULE_ID}.html` - - `sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S{RULE_ID}.json` - - `sonar-java-plugin/src/main/resources/profiles/{Sonar_way|Sonar_agentic_AI}/S{RULE_ID}` - -### Test sample location markers - -Every **primary** and **secondary** location must be asserted with caret markers. Never leave a bare `// Noncompliant` when the rule reports on a sub-expression: a test that does not pin the location does not protect it. - -Put the carets in a comment on the line **below** the reported line, aligned under the flagged token: - -```java -b = sb1.length() == 0; // Noncompliant {{Use "isEmpty()" to check whether a "StringBuilder" is empty or not.}} -// ^^^^^^^^^^^^^^^^^ -``` - -Secondary locations use the same carets plus a direction marker: `<` when the primary is **above**, `>` when it is **below**. - -```java -new Thread(() -> { -// ^^^^^^> - Thread.sleep(1000); // Noncompliant {{Message.}} -// ^^^^^ -}); -``` - -Several locations can be marked on one caret line: - -```java -Arrays.fill(textBuffer, 42); // Noncompliant {{Message.}} -// ^^^^ ^^^^^^^^^^< -``` - -Use `[[sc=…;ec=…]]` / `[[secondary=…]]` only when carets cannot work: a token at column 1, a multi-line span, or quickfix declarations (`[[quickfixes=qf1]]`). - -To build an aligned caret line: - -```shell -str=">"; sub=""; pre="${str%%"$sub"*}"; echo "${pre//?/ }${sub//?/^}" -``` - -### Test class structure - -Do not repeat the sample path or the check instantiation in each test method. Extract them as constants and keep the verifier chain in the tests: - -```java -class FooCheckTest { - - private static final String SAMPLE = "checks/FooCheckSample.java"; - private static final FooCheck CHECK = new FooCheck(); - - @Test - void test() { - CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath(SAMPLE)) - .withCheck(CHECK) - .verifyIssues(); - } - - @Test - void test_without_semantic() { - CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath(SAMPLE)) - .withCheck(CHECK) - .withoutSemantic() - .verifyNoIssues(); - } -} -``` - -A single shared check instance is safe because checks are [stateless](#stateless-checks). When a test needs several samples (non-compiling or Java version variants), declare one constant per sample. - -### Method and type matching - -Match methods with `MethodMatchers` and types with the type API. **Never** compare fully qualified names, method names or type names with raw strings (`equals`, `contains`, `startsWith`): matchers handle overloads, inheritance and unknown symbols correctly. - -```java -private static final MethodMatchers CONSTRUCTOR_LOOKUP = MethodMatchers.create() - .ofTypes("java.lang.Class") - .names("getConstructor", "getDeclaredConstructor") - .addParametersMatcher("java.lang.Class[]") - .build(); - -// In visitNode: -if (CONSTRUCTOR_LOOKUP.matches(methodInvocationTree)) { - reportIssue(methodInvocationTree, "Message."); -} -``` - -Prefer an explicit `addParametersMatcher(...)` over `withAnyParameters()` whenever the rule only targets specific overloads. For types, use `symbolType().isSubtypeOf("java.util.Collection")` rather than string checks on the type name. - -### Stateless checks - -A check instance is reused across files, so it must carry **no mutable state**. A check class may only declare `private static final` fields (messages, matchers, immutable constants). - -Anything accumulated during a scan — sets of visited symbols, maps, counters, lookup tables — must live in a local variable and be passed explicitly through the call graph, never stored in a field. - -```java -@Rule(key = "SXXXX") -public class MyCheck extends IssuableSubscriptionVisitor { - - private static final String MESSAGE = "Message."; - private static final MethodMatchers MATCHER = MethodMatchers.create() /* … */ .build(); - - @Override - public List nodesToVisit() { - return List.of(Tree.Kind.CLASS); - } - - @Override - public void visitNode(Tree tree) { - Set seen = new HashSet<>(); - collectFields((ClassTree) tree, seen); - report(seen); - } -} -``` - -If a rule genuinely needs cross-node context, compute it from the subscribed node by walking the AST, or subscribe to the enclosing node (class, method, compilation unit) and do the whole analysis there with local state. - -The only accepted non-static fields are the ones the API itself requires, all set before the scan and never mutated during it: - -- `@RuleProperty` parameter fields, which the platform injects and therefore cannot be `static final` -- the `JavaFileScannerContext` of a `BaseTreeVisitor` rule, assigned at the start of `scanFile` -- the flags a `DependencyVersionAware` rule sets in `isCompatibleWithDependencies` - -Because a stateless check has nothing to reset, it does not need `clearState()`. The `clearState()` guidance in `AGENTS.md` applies to existing checks that still hold per-file state, not to new rules. - -### External Dependencies in Tests -- **DO NOT** add external library dependencies for test samples -- **DO** create mock-ups or use non-compiling tests when external libraries are needed -- **SEE** Spring examples in `java-checks-test-sources/*/src/main/files/non-compiling/checks/` - -## What NOT to Do - -### 1. Version Control -- **DO NOT** commit log files (e.g., `*.log`, build logs) -- **DO NOT** commit temporary or generated files - -### 2. Build Configuration -- **DO NOT** modify `pom.xml` files -- Build configuration is managed centrally -- Only modify if explicitly required by the rule implementation - -### 3. Architecture -- **DO NOT** make architectural changes to the codebase -- New rules should fit within the existing architecture -- Follow the patterns used by similar existing rules - -### 4. Test Dependencies -- **DO NOT** add real external dependencies to test projects -- Use mocks, stubs, or non-compiling tests instead -- Keep test projects lightweight and self-contained - -## File Structure Reference - -### Rule Implementation -- Rule class: `java-checks/src/main/java/org/sonar/java/checks/{RuleId}Check.java` -- Test class: `java-checks/src/test/java/org/sonar/java/checks/{RuleId}CheckTest.java` -- Test samples: `java-checks-test-sources/default/src/main/java/checks/{RuleId}CheckSample.java` - -### Metadata -- HTML description: `sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/{RULE_ID}.html` -- JSON metadata: `sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/{RULE_ID}.json` -- Profile: `sonar-java-plugin/src/main/resources/profiles/{Sonar_way|Sonar_agentic_AI}/S{RULE_ID}` - -### Non-Compiling Tests (when needed) -- Location: `java-checks-test-sources/default/src/main/files/non-compiling/checks/` -- Use for: Code that requires external libraries (Spring, AWS SDK, etc.) +1. **Generate rule inputs.** Confirm the rule key, title and RSPEC branch before starting. Follow `docs/systems/rule-metadata.md` to generate the descriptors and review profile membership. Do not invent metadata if the specification is unavailable. +2. **Write a reproducer.** Follow `docs/systems/rule-tests.md` for sample placement, semantic and nonsemantic cases, and issue locations. Add a minimal check with the rule key and confirm that the test fails because it expected a finding. Also include compliant lookalikes and cases where information is missing. +3. **Implement the check.** Follow `docs/systems/rule-api.md` to choose the visitor and match Java constructs. If the check needs cross-file evidence or a quick fix, read `docs/systems/project-level-rules.md` or `docs/systems/quickfix-tests.md` respectively. Run the targeted verifier test and compile changed sample sources. +4. **Validate on real projects.** When CI results are available, follow `docs/systems/ruling-tests.md` to review the generated baseline and evaluate precision. Add false positives as regression cases, refine the check, and review the next CI results rather than accepting unexpected findings. diff --git a/.claude b/.claude deleted file mode 120000 index c0ca4685663..00000000000 --- a/.claude +++ /dev/null @@ -1 +0,0 @@ -.agents \ No newline at end of file diff --git a/.claude/skills/migrate-test-samples/SKILL.md b/.claude/skills/migrate-test-samples/SKILL.md new file mode 100644 index 00000000000..ad08db27a02 --- /dev/null +++ b/.claude/skills/migrate-test-samples/SKILL.md @@ -0,0 +1,8 @@ +--- +name: migrate-test-samples +description: Move legacy rule test fixtures into the Maven test-source modules. +--- + +# Migrate rule test samples + +Read `.agents/skills/migrate-test-samples/SKILL.md` and follow that canonical skill. diff --git a/.claude/skills/new-rule/SKILL.md b/.claude/skills/new-rule/SKILL.md new file mode 100644 index 00000000000..e0764ad23f0 --- /dev/null +++ b/.claude/skills/new-rule/SKILL.md @@ -0,0 +1,8 @@ +--- +name: new-rule +description: Implement a SonarJava rule from its specification. +--- + +# New SonarJava rule + +Read `.agents/skills/new-rule/SKILL.md` and follow that canonical skill. diff --git a/.cursor/rules/rules-implementation.mdc b/.cursor/rules/rules-implementation.mdc index c88de105b38..6f40076e9c2 100644 --- a/.cursor/rules/rules-implementation.mdc +++ b/.cursor/rules/rules-implementation.mdc @@ -1,5 +1,5 @@ --- -description: Guide for implementing Java analyzer rules (checks). Delegates to the rule-implementation Claude skill — the single source of truth. +description: Use the canonical SonarJava skill when implementing Java analyzer rules. globs: **/*checks*/**/*.java alwaysApply: false --- diff --git a/.cursor/skills/migrate-test-samples/SKILL.md b/.cursor/skills/migrate-test-samples/SKILL.md new file mode 100644 index 00000000000..48a992fbdec --- /dev/null +++ b/.cursor/skills/migrate-test-samples/SKILL.md @@ -0,0 +1,8 @@ +--- +name: migrate-test-samples +description: Use when moving legacy SonarJava rule fixtures into the Maven test-source modules. +--- + +# Migrate legacy rule test samples + +Read and follow `.agents/skills/migrate-test-samples/SKILL.md` from the repository root. diff --git a/.gitar/rules/dependency-licenses.md b/.gitar/rules/dependency-licenses.md new file mode 100644 index 00000000000..1255d3ff800 --- /dev/null +++ b/.gitar/rules/dependency-licenses.md @@ -0,0 +1,11 @@ +--- +title: Check license changes for new dependencies +description: Check that new plugin dependencies have correct generated license evidence. +type: check +when: Pull requests add Maven dependencies or change the packaged dependency set. +actions: Report missing license updates for new shipped dependencies in PR Verification. +--- + +# Check license changes for new dependencies + +Read `docs/systems/licenses.md`. For each newly shipped dependency, check whether `sonar-java-plugin/src/main/resources/licenses/` covers its license and whether `missing-dep-licenses.properties` needs an entry after license verification. Follow the actual packaging scope. Do not require new bundled files for test-only or provided dependencies, or where the existing generated inventory already covers the change. diff --git a/.gitar/rules/generated-rule-metadata.md b/.gitar/rules/generated-rule-metadata.md new file mode 100644 index 00000000000..6a90953a2af --- /dev/null +++ b/.gitar/rules/generated-rule-metadata.md @@ -0,0 +1,11 @@ +--- +title: Keep rule metadata generated +description: Check that checked-in rule metadata changes come from rule-api and the canonical specification. +type: check +when: Pull requests change generated rule descriptions or metadata in the Java plugin. +actions: Report confirmed manual changes to generated rule metadata in PR Verification. +--- + +# Keep rule metadata generated + +Read `docs/systems/rule-metadata.md`. Inspect changes to JSON or HTML under `sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/` and the evidence of regeneration from RSPEC. Do not flag generated updates made by `.github/workflows/UpdateRuleMetadata.yml` or author-generated output from the documented workflow. Do not treat a missing bot author alone as evidence of a manual edit. diff --git a/.gitar/rules/new-rule-profile.md b/.gitar/rules/new-rule-profile.md new file mode 100644 index 00000000000..0df14e67b95 --- /dev/null +++ b/.gitar/rules/new-rule-profile.md @@ -0,0 +1,11 @@ +--- +title: Check profile membership for new rules +description: Check that each new rule has an intentional profile decision and matching marker when enabled. +type: check +when: Pull requests introduce a new Java analyzer rule. +actions: Report missing profile markers or missing opt-in decisions in PR Verification. +--- + +# Check profile membership for new rules + +Read `docs/systems/rule-metadata.md`. Match the new rule key against the appropriate empty marker file in `sonar-java-plugin/src/main/resources/profiles/Sonar_way/` or `sonar-java-plugin/src/main/resources/profiles/Sonar_agentic_AI/`. If it belongs in a built-in profile, flag missing or wrong markers. If an explicitly documented profile decision keeps the rule opt-in, do not suggest enabling it just to satisfy the check. diff --git a/.gitar/rules/new-rule-tests.md b/.gitar/rules/new-rule-tests.md new file mode 100644 index 00000000000..76106b4281a --- /dev/null +++ b/.gitar/rules/new-rule-tests.md @@ -0,0 +1,11 @@ +--- +title: Test new rules with and without semantic resolution +description: Check that each new rule has semantic and no-semantic tests with intentional expectations. +type: check +when: Pull requests introduce a new Java analyzer rule. +actions: Report missing verifier coverage in PR Verification. +--- + +# Test new rules with and without semantic resolution + +Read `docs/systems/rule-tests.md`. For each newly introduced rule, look for a `CheckVerifier` test using semantic resolution and a test using `withoutSemantic()`. An assertion that the rule reports no issues without semantic resolution is valid when that is the intended behavior. Accept equivalent parameterized or shared coverage when both modes are actually exercised; do not require a new class purely for naming. diff --git a/.gitar/rules/public-java-api.md b/.gitar/rules/public-java-api.md new file mode 100644 index 00000000000..7c0dea4b112 --- /dev/null +++ b/.gitar/rules/public-java-api.md @@ -0,0 +1,11 @@ +--- +title: Preserve the Java analyzer public API +description: Check that incompatible changes have an explicit deprecation and migration path. +type: check +when: Pull requests change java-frontend/src/main/java/org/sonar/plugins/java/api/ outside its internal package. +actions: Report confirmed compatibility breaks without a deprecation path in PR Verification. +--- + +# Preserve the Java analyzer public API + +Read `docs/systems/public-api.md`. Compare public signatures and contracts to the base branch. Flag removals, incompatible changes to existing implementations, and newly required methods on public interfaces unless there is a reviewed compatibility and migration path. Do not flag internal-only edits, compatible additions, or documentation-only changes. Point to the affected API and likely consumer impact. diff --git a/.gitar/rules/ruling-expectations.md b/.gitar/rules/ruling-expectations.md new file mode 100644 index 00000000000..58c9518c154 --- /dev/null +++ b/.gitar/rules/ruling-expectations.md @@ -0,0 +1,11 @@ +--- +title: Keep ruling expectations reproducible +description: Check that changed SARIF expectations come from the CI ruling update workflow. +type: check +when: Pull requests add, change or remove ruling expectation reports. +actions: Report confirmed manual baselining or edits in PR Verification. +--- + +# Keep ruling expectations reproducible + +Read `docs/systems/ruling-tests.md`. Review the diff under `its/ruling/src/test/resources/expected/` and the PR or commit evidence for CI provenance. Accept the CI bot's update, including a bot update incorporated into the source PR. Flag hand edits or local baselining when the diff or PR evidence establishes that source. Do not flag a bot-generated report just because the final commit author is human. diff --git a/.github/scripts/check_docs.py b/.github/scripts/check_docs.py new file mode 100644 index 00000000000..a79a698b088 --- /dev/null +++ b/.github/scripts/check_docs.py @@ -0,0 +1,406 @@ +"""Static repository documentation checks. Run from the repository root.""" + +from collections import defaultdict +from datetime import date +from html.parser import HTMLParser +import os +import posixpath +from pathlib import Path, PurePosixPath +import re +import subprocess +import sys +from urllib.parse import unquote, urlsplit + +from markdown_it import MarkdownIt +import yaml + +from docs_commands import BUILD_DOC, LICENSE_DOC, Commands + +ROOT_DOC = 'AGENTS.md' +DOCS_INDEX = 'docs/index.md' +SKILLS = '.agents/skills/' +CURSOR_RULE = '.cursor/rules/rules-implementation.mdc' +ADAPTER_ROOTS = ('.claude/skills', '.cursor/skills') +MARKDOWN = MarkdownIt('commonmark').enable('table') +SONAR_MARKER = re.compile(r'\s*\s*') +FILENAME_STEM = re.compile(r'[\w-][\w.-]*') +DOTFILE = re.compile(r'\.git[a-z]+', re.I) +PATH_SUFFIXES = set('md mdc xml toml yml yaml json properties txt sh py java sarif'.split()) +SKILL = re.compile(r'\.agents/skills/[^/]+/SKILL\.md') + + +def git_paths(root, *options): + output = subprocess.check_output(['git', 'ls-files', '-z', *options], cwd=root) + return {os.fsdecode(entry) for entry in output.split(b'\0') if entry} + + +class Repo: + def __init__(self, root, tracked, untracked=()): + self.root = root.resolve() + self.tracked = tracked + candidates = set(tracked).union(untracked) + self.files = {name for name in candidates if os.path.lexists(root / name)} + self.dirs = {parent.as_posix() for name in self.files for parent in PurePosixPath(name).parents} + + def resolve(self, name): + """Resolve tracked files/directories (including symlinks) without leaving the checkout.""" + if name not in self.files and name not in self.dirs: + if not any(parent.as_posix() in self.files for parent in PurePosixPath(name).parents): + return None + try: + target = (self.root / name).resolve(strict=True).relative_to(self.root).as_posix() + except (OSError, ValueError, RuntimeError): + return None + return target if target in self.files or target in self.dirs else None + + def is_pointer(self, text): + if (any(char.isspace() for char in text) or ':' in text or text.startswith(('@', '//', '$')) + or (text.startswith('<') and text.endswith('>') and ' 30: + return None + literals = (text.removeprefix('@') for text in (*page.codes, *page.lines)) + refs = {text for text in literals if SKILL.fullmatch(text)} + for url in page.links: + try: + link = self.link_target(path, url) + except ValueError: + continue + if link and link[0] in canonical: + refs.add(link[0]) + return next(iter(refs)) if len(refs) == 1 else None + + def check_adapter(self, path, canonical, expected): + target = self.repo.resolve(path) + if target and (self.repo.root / target).is_dir(): + target = self.repo.resolve(f'{target}/SKILL.md') + if target == path: + target = self.stub_target(path, canonical) + if target != expected or target not in canonical: + self.error(path, f'adapter must resolve to {expected}') + + def check_adapters(self, canonical): + covered = set() + for directory in ADAPTER_ROOTS: + tool = directory.split('/')[0] + if any((self.repo.root / path).is_symlink() for path in (tool, directory)): + self.error(directory, 'use per-skill adapters, not a symlink for the entire tool or skills directory') + continue + entries = {path.split('/')[2] for path in self.repo.files if path.startswith(directory + '/')} + for name in sorted(entries): + folder = f'{directory}/{name}' + expected = f'{SKILLS}{name}/SKILL.md' + covered.add(expected) + self.check_adapter(folder if (self.repo.root / folder).is_symlink() else f'{folder}/SKILL.md', + canonical, expected) + if CURSOR_RULE in self.repo.files: + expected = f'{SKILLS}new-rule/SKILL.md' + covered.add(expected) + self.check_adapter(CURSOR_RULE, canonical, expected) + for skill in sorted(canonical - covered): + self.error(skill, 'missing Claude or Cursor skill adapter') + + def check_page(self, path, commands): + page = self.page(path) + if path == ROOT_DOC: + lines = self.root_body(page) + if len(lines) > 150: + self.error(path, f'{len(lines)} lines outside Sonar managed blocks (maximum 150)') + elif len(page.lines) > 150: + self.warn(path, f'{len(page.lines)} total lines including Sonar managed blocks (target 150)') + page = Page('\n'.join(lines)) + elif len(page.lines) > 300: + self.error(path, f'{len(page.lines)} lines (maximum 300)') + if is_doc(path): + self.check_frontmatter(path, page) + self.check_pointers(path, page) + self.check_links(path, page) + if path in (ROOT_DOC, BUILD_DOC, LICENSE_DOC): + for block in page.command_blocks(): + for error in commands.errors(block, allow_setup=path != LICENSE_DOC): + self.error(path, error) + + def check_reachability(self, docs, canonical): + reachable, pending = {ROOT_DOC}, [ROOT_DOC] + while pending: + for target in self.pointers[pending.pop()] - reachable: + reachable.add(target) + pending.append(target) + for path in sorted(docs - reachable): + if is_doc(path) or PurePosixPath(path).name == ROOT_DOC or path.startswith(SKILLS): + self.error(path, 'not reachable from AGENTS.md through repo pointers or internal links') + for skill in sorted(canonical - self.pointers[ROOT_DOC]): + self.error(skill, 'canonical skill must have a direct pointer from AGENTS.md') + + def check_layout(self, docs): + for path in sorted(self.repo.tracked): + if PurePosixPath(path).name.casefold() == 'claude.md' and path in self.repo.files: + self.error(path, 'CLAUDE.md must not be tracked; use AGENTS.md') + for path in (ROOT_DOC, DOCS_INDEX, BUILD_DOC): + if not self.repo.resolve(path): + self.error(path, 'required documentation file is missing') + for directory in sorted({posixpath.dirname(path) for path in docs if is_doc(path)}): + if f'{directory}/index.md' not in docs and directory != 'docs': + self.error(directory, 'documentation directory is missing index.md') + + def run(self): + docs = {path for path in self.repo.files if managed(path)} + self.check_layout(docs) + commands = Commands(self.repo) + for path in sorted(docs): + target = self.repo.resolve(path) + if target == path and (self.repo.root / path).is_file(): + self.check_page(path, commands) + elif not target or not path.startswith(('.claude/', '.cursor/')): + self.error(path, 'managed documentation must be a file inside the repository') + if not commands.has_setup: + self.error(BUILD_DOC, 'document `mise install` as the setup command here or in AGENTS.md') + canonical = {path for path in docs if SKILL.fullmatch(path) and self.repo.resolve(path) == path} + self.check_adapters(canonical) + self.check_reachability(docs, canonical) + return self.errors, self.warnings + + +def main(): + root = Path(__file__).resolve().parents[2] + repo = Repo(root, git_paths(root, '--cached'), git_paths(root, '--others', '--exclude-standard')) + errors, warnings = Checker(repo).run() + for notice in sorted(set(warnings)): + print(f'Warning: {notice}', file=sys.stderr) + for notice in sorted(set(errors)): + print(f'Error: {notice}', file=sys.stderr) + return bool(errors) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/.github/scripts/docs-requirements.txt b/.github/scripts/docs-requirements.txt new file mode 100644 index 00000000000..02b11a1b2bf --- /dev/null +++ b/.github/scripts/docs-requirements.txt @@ -0,0 +1,3 @@ +markdown-it-py==4.0.0 +mdurl==0.1.2 +PyYAML==6.0.3 diff --git a/.github/scripts/docs_commands.py b/.github/scripts/docs_commands.py new file mode 100644 index 00000000000..7cc0134c864 --- /dev/null +++ b/.github/scripts/docs_commands.py @@ -0,0 +1,258 @@ +"""Check Maven and mise snippets against repository configuration without running them.""" + +from functools import cached_property +from itertools import dropwhile +import posixpath +import re +import shlex +import tomllib +import xml.etree.ElementTree as ET + +BUILD_DOC = 'docs/systems/build.md' +LICENSE_DOC = 'docs/systems/licenses.md' +MAVEN_PHASES = set('''pre-clean clean post-clean validate initialize generate-sources process-sources generate-resources +process-resources compile process-classes generate-test-sources process-test-sources generate-test-resources +process-test-resources test-compile process-test-classes test prepare-package package pre-integration-test integration-test +post-integration-test verify install deploy pre-site site post-site site-deploy'''.split()) +MAVEN_CI_GOAL = 'org.codehaus.mojo:license-maven-plugin:aggregate-add-third-party' +MAVEN_OPTIONS = {'-f': 'pom', '--file': 'pom', '-P': 'profile', '--activate-profiles': 'profile', '-pl': 'project', + '--projects': 'project', '-D': 'skip', '--define': 'skip', '-T': 'skip', '--threads': 'skip', + '-s': 'settings', '--settings': 'settings', '-rf': 'project', '--resume-from': 'project'} +MAVEN_WRAPPER = './mvnw' +MAVEN_COMMANDS = ('mvn', MAVEN_WRAPPER) +ASSIGNMENT = re.compile(r'^\w+=') +MISE_TASK_DIRS = ('mise-tasks/', '.mise/tasks/', '.config/mise/tasks/') + + +def shell_commands(snippet): + snippet = snippet.strip() + if snippet.startswith('$') and snippet[1:2].isspace(): + snippet = snippet[1:].lstrip() + command = next(dropwhile(ASSIGNMENT.match, snippet.split()), '') + if command not in ('cd', 'mvn', 'mise') and not command.startswith('./'): + return + lexer = shlex.shlex(snippet, posix=True, punctuation_chars=';&|') + lexer.whitespace_split = True + for words in split_shell_commands(lexer): + args = list(dropwhile(ASSIGNMENT.match, words)) + if args: + yield args + + +def split_shell_commands(words): + args = [] + for word in words: + if word and all(char in ';&|' for char in word): + yield args + args = [] + else: + args.append(word) + yield args + + +def maven_option(arg): + for flag, kind in MAVEN_OPTIONS.items(): + if arg == flag: + return kind, None + if arg.startswith(flag + '='): + return kind, arg[len(flag) + 1:] + if flag in ('-P', '-D') and arg.startswith(flag): + return kind, arg[len(flag):] + return None, None + + +def maven_arguments(args): + queue = iter(args) + for arg in queue: + kind, value = maven_option(arg) + if kind: + yield arg, kind, value if value is not None else next(queue, None) + elif not arg.startswith('-'): + yield arg, 'goal', arg + + +def read_pom(path): + try: + pom = ET.parse(path).getroot() + except (ET.ParseError, OSError): + return None + for elem in pom.iter(): + elem.tag = elem.tag.split('}')[-1] + return pom if pom.tag == 'project' else None + + +def maven_projects(pom): + artifact = pom.findtext('artifactId') + if artifact: + group = pom.findtext('groupId') or pom.findtext('parent/groupId') + yield f':{artifact}' + yield f'{group}:{artifact}' + + +def maven_goals(pom): + for plugin in pom.findall('.//plugin'): + artifact = plugin.findtext('artifactId') + if not artifact: + continue + prefix = artifact.removeprefix('maven-').removesuffix('-maven-plugin').removesuffix('-plugin') + group = plugin.findtext('groupId', 'org.apache.maven.plugins') + for node in plugin.findall('./executions/execution/goals/goal'): + yield f'{prefix}:{node.text}' + yield f'{group}:{artifact}:{node.text}' + + +def configured_mise_tasks(config): + with config.open('rb') as handle: + for name, task in tomllib.load(handle).get('tasks', {}).items(): + yield name + if isinstance(task, dict): + aliases = task.get('alias', []) + yield from [aliases] if isinstance(aliases, str) else aliases + + +def file_mise_task(path): + for prefix in MISE_TASK_DIRS: + if path.startswith(prefix): + name = path.removeprefix(prefix).removesuffix('/_default') + if all(not part.startswith(('.', '_')) for part in name.split('/')): + return name.removesuffix('.sh').replace('/', ':') + return None + + +class Commands: + def __init__(self, repo): + self.repo = repo + self.has_setup = False + + def local_path(self, cwd, arg): + return self.repo.resolve(posixpath.normpath(posixpath.join(cwd, arg))) + + @cached_property + def maven(self): + profiles, projects, poms, goals = set(), set(), set(), set() + workflow = '.github/workflows/build.yml' + if self.repo.resolve(workflow) and MAVEN_CI_GOAL in (self.repo.root / workflow).read_text(encoding='utf-8'): + goals.update((MAVEN_CI_GOAL, 'license:aggregate-add-third-party')) + for path in sorted(self.repo.files): + name = posixpath.basename(path) + if not (name.startswith('pom') and name.endswith('.xml')) or not self.repo.resolve(path): + continue + pom = read_pom(self.repo.root / path) + if pom is None: + continue + poms.add(path) + profiles.update(node.text for node in pom.findall('./profiles/profile/id')) + projects.update(maven_projects(pom)) + goals.update(maven_goals(pom)) + return profiles, projects, poms, goals + + @cached_property + def mise_tasks(self): + tasks = {task for path in self.repo.files if (task := file_mise_task(path))} + for config in ('mise.toml', '.mise.toml', '.mise/config.toml'): + if self.repo.resolve(config): + tasks.update(configured_mise_tasks(self.repo.root / config)) + return tasks + + def maven_path_errors(self, kind, value, cwd): + _, _, poms, _ = self.maven + if kind == 'settings': + if not value.startswith(('~/', '$')) and not self.local_path(cwd, value): + yield f'unknown Maven settings path: {value}' + else: + path = self.local_path(cwd, value) + if path in self.repo.dirs: + path = self.local_path(path, 'pom.xml') + if path not in poms: + yield f'unknown Maven POM: {value}' + + def maven_selector_errors(self, kind, value, cwd): + profiles, projects, poms, _ = self.maven + for selector in value.split(','): + name = selector.lstrip('!?-+') + if kind == 'profile': + if name not in profiles: + yield f'unknown Maven profile: {selector}' + elif name not in projects and self.local_path(cwd, f'{name}/pom.xml') not in poms: + yield f'unknown Maven project: {name}' + + def maven_argument_errors(self, arg, kind, value, cwd): + if not value or value.startswith('-'): + yield f'Maven option {arg} needs a value' + elif kind in ('pom', 'settings'): + yield from self.maven_path_errors(kind, value, cwd) + elif kind in ('profile', 'project'): + yield from self.maven_selector_errors(kind, value, cwd) + elif kind == 'goal': + _, _, _, goals = self.maven + coordinates = value.split(':') + goal = ':'.join(coordinates[:2] + coordinates[-1:]) if len(coordinates) == 4 else value + if goal not in MAVEN_PHASES and goal not in goals: + yield f'unknown Maven phase or goal: {value}' + + def maven_errors(self, args, cwd): + _, _, poms, _ = self.maven + kinds = set() + for arg, kind, value in maven_arguments(args): + yield from self.maven_argument_errors(arg, kind, value, cwd) + if value and not value.startswith('-'): + kinds.add(kind) + if 'goal' not in kinds: + if not {'-v', '--version', '-h', '--help'}.intersection(args): + yield 'Maven command has no phase or goal' + elif 'pom' not in kinds and self.local_path(cwd, 'pom.xml') not in poms: + yield f'no Maven POM in {cwd or "."}' + + def mise_exec_errors(self, args, cwd): + if '--' not in args or args[-1] == '--': + yield '`mise exec` needs a command after --' + return + nested, *nested_args = args[args.index('--') + 1:] + if nested in MAVEN_COMMANDS: + yield from self.maven_errors(nested_args, cwd) + + def mise_errors(self, args, cwd, allow_setup): + action = args[0] if args else None + if args == ['install']: + self.has_setup |= allow_setup + if not self.repo.resolve('mise.toml'): + yield '`mise install` requires mise.toml' + elif action in ('run', 'r'): + if len(args) < 2 or args[1] not in self.mise_tasks: + yield f'unknown mise task: {" ".join(args[1:]) or "(missing)"}' + elif action in ('exec', 'x'): + yield from self.mise_exec_errors(args, cwd) + elif action not in ('install', 'tasks', 'doctor', 'trust', 'use', '--version'): + yield f'unknown mise command: {" ".join(args) or "(missing)"}' + + def command_errors(self, command, args, cwd, allow_setup): + if command in MAVEN_COMMANDS: + if command == MAVEN_WRAPPER and not self.local_path(cwd, command): + yield 'Maven wrapper does not exist' + yield from self.maven_errors(args, cwd) + elif command == 'mise': + yield from self.mise_errors(args, cwd, allow_setup) + elif command.startswith('./'): + script = self.local_path(cwd, command) + if script not in self.repo.files or not (self.repo.root / script).is_file(): + yield f'unknown repository command: {command}' + + def working_directory(self, args, cwd): + directory = self.local_path(cwd, args[0]) if len(args) == 1 else None + return directory if directory and (self.repo.root / directory).is_dir() else None + + def errors(self, snippets, allow_setup=False): + cwd = '.' + for snippet in snippets: + try: + for command, *args in shell_commands(snippet): + if command == 'cd': + directory = self.working_directory(args, cwd) + if directory is None: + yield f'unknown working directory: {" ".join(args)}' + else: + cwd = directory + continue + yield from self.command_errors(command, args, cwd, allow_setup) + except ValueError as error: + yield f'invalid shell command {snippet!r}: {error}' diff --git a/.github/scripts/test_check_docs.py b/.github/scripts/test_check_docs.py new file mode 100644 index 00000000000..372aaf02992 --- /dev/null +++ b/.github/scripts/test_check_docs.py @@ -0,0 +1,164 @@ +import tempfile +import unittest +from pathlib import Path + +from check_docs import CURSOR_RULE, Checker, Repo + +HEADER = '---\ntitle: Example\ndescription: A concise description.\ngenerated:\n by: codex\n' +ROOT_CONTENT = '# Guide\n\n`mise install`\n\n`docs/`\n\n`.agents/skills/new-rule/SKILL.md`\n' +SKILL = '.agents/skills/new-rule/SKILL.md' +BUILD = 'docs/systems/build.md' +ADAPTER = '.claude/skills/new-rule' + + +class DocsTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.tracked = set() + self.untracked = set() + self.write('AGENTS.md', ROOT_CONTENT) + self.doc('docs/index.md', '`docs/systems/`\n', "okf_version: '0.2'\n") + self.doc('docs/systems/index.md', f'`{BUILD}`\n') + self.doc(BUILD, '```bash\nmise exec java@21 -- mvn verify -f component/pom.xml -P sanity\n```\n\n' + '```bash\ncd component\nmvn test -f pom.xml -Psanity\n```\n') + self.write('pom.xml', 'example') + self.write('component/pom.xml', ''' + componentsanity + ''') + self.write('mise.toml', '[tasks."test:unit"]\nrun = "mvn test"\nalias = "unit"\n') + self.write(SKILL, '# New rule\n') + self.write(CURSOR_RULE, f'# Cursor rule\n\n`{SKILL}`\n') + self.symlink(ADAPTER, '../../.agents/skills/new-rule') + self.write('README.md', 'This public readme does not require OKF.\n') + self.write('docs/assets/image.svg', 'SVG\n') + self.write('docs/example/src/Foo.java', 'class Foo {}\n') + + def write(self, path, contents, tracked=True): + file = self.root / path + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(contents, encoding='utf-8') + (self.tracked if tracked else self.untracked).add(path) + + def doc(self, path, body, metadata=''): + self.write(path, f'{HEADER}{metadata}---\n\n# Example\n\n{body}') + + def symlink(self, path, target): + link = self.root / path + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(target) + self.tracked.add(path) + + def check(self): + return Checker(Repo(self.root, self.tracked, self.untracked)).run() + + def assert_errors(self, *messages): + errors, _ = self.check() + for message in messages: + self.assertTrue(any(message in error for error in errors), f'{message!r} not in {errors}') + + def test_clean_repo_and_untracked_docs(self): + self.write('docs/systems/new.md', HEADER + '---\n\n# New\n', tracked=False) + self.doc('docs/systems/index.md', f'`{BUILD}` and `docs/systems/new.md`\n') + self.assertEqual(([], []), self.check()) + + def test_path_and_link_failures(self): + self.doc(BUILD, '''[relative][ref] and [heading](#not-a-heading). + +[ref]: missing.md + +![image](../assets/missing.svg) + +HTML link + +`docs/systems/Build.md`, `component/.../pom.xml` and `nonexistent/`. + +```text +`ignored/example.java` +``` +''') + self.assert_errors('broken internal link: missing.md', 'unknown Markdown anchor: #not-a-heading', + 'broken internal link: ../assets/missing.svg', 'broken internal link: missing.html', + 'unknown repo path: `docs/systems/Build.md`', 'unknown repo path: `component/.../pom.xml`', + 'unknown repo path: `nonexistent/`') + self.assertNotIn('ignored/example', '\n'.join(self.check()[0])) + + def test_valid_internal_links_and_duplicate_headings(self): + self.doc(BUILD, '## Example\n\n\n\n' + '[Duplicate](#example-1) [Manual](#explicit) [Outside](https://example.com/no-check) ' + '[Public readme](../../README.md) ![Asset](../assets/image.svg)\n') + self.assertEqual(([], []), self.check()) + + def test_reachability_uses_local_links_and_requires_an_index_for_markdown(self): + self.doc('docs/index.md', '[Systems](systems/index.md)\n', "okf_version: '0.2'\n") + self.assertEqual(([], []), self.check()) + self.doc('docs/index.md', '```text\n`docs/systems/index.md`\n```\n', "okf_version: '0.2'\n") + self.doc('docs/example/README.md', 'Unindexed Maven example.\n') + self.write('component/AGENTS.md', '# Component guide\n') + self.assert_errors('docs/systems/build.md: not reachable', 'docs/example: documentation directory is missing index.md', + 'docs/example/README.md: not reachable', 'component/AGENTS.md: not reachable') + + def test_frontmatter_errors_and_expiry_warning(self): + self.doc('docs/index.md', '`docs/systems/`\n', 'okf_version: 0.2\nsources:\n - url: example.org\n') + self.write(BUILD, '---\ntitle: []\ndescription: false\nstale_after: 2020-01-01\n---\n# Example\n') + self.assert_errors('okf_version must be the string', 'nonempty resource string', 'title must be a nonempty string', + 'description must be a nonempty string', 'generated.by must be a nonempty string') + self.assertEqual([f'{BUILD}: stale_after date has passed: 2020-01-01'], self.check()[1]) + self.write(BUILD, '---\n[malformed:\n---\n') + self.assert_errors('expected a YAML frontmatter mapping') + self.doc(BUILD, '', 'stale_after: someday\n') + self.assert_errors('stale_after must be a YYYY-MM-DD date') + + def test_size_limits_and_sonar_marker_integrity(self): + block = '\n' + 'managed\n' * 150 + '\n' + self.write('AGENTS.md', ROOT_CONTENT + block) + errors, warnings = self.check() + self.assertEqual([], errors) + self.assertIn('total lines including Sonar managed blocks (target 150)', warnings[0]) + self.write('AGENTS.md', ROOT_CONTENT + 'handwritten\n' * 150 + block) + self.doc(BUILD, 'line\n' * 300) + self.assert_errors('maximum 150', 'maximum 300') + self.write('AGENTS.md', ROOT_CONTENT + block.replace('end:analysis', 'end:other')) + self.assert_errors('unbalanced Sonar managed block marker', 'unclosed Sonar managed block') + + def test_stub_symlink_and_claude_md_failures(self): + self.write('.cursor/skills/new-rule/SKILL.md', f'Use `{SKILL}`.\n') + self.assertEqual(([], []), self.check()) + (self.root / ADAPTER).unlink() + self.symlink(ADAPTER, '../../.agents/skills/nonexistent') + self.write('.cursor/skills/new-rule/SKILL.md', '# Not a pointer\n') + self.write(CURSOR_RULE, '# Not a pointer\n') + self.symlink('component/CLAUDE.md', '../AGENTS.md') + self.assert_errors(f'{ADAPTER}: adapter must resolve', '.cursor/skills/new-rule/SKILL.md: adapter must resolve', + f'{CURSOR_RULE}: adapter must resolve', 'component/CLAUDE.md: CLAUDE.md must not be tracked') + + def test_canonical_skill_requires_an_adapter(self): + (self.root / ADAPTER).unlink() + self.assertEqual(([], []), self.check()) + (self.root / CURSOR_RULE).unlink() + self.assert_errors(f'{SKILL}: missing Claude or Cursor skill adapter') + + def test_command_failures_and_dynamic_mise_tasks(self): + self.write('.mise/tasks/check/_default', 'unused\n') + self.doc(BUILD, '''```bash +mise run unit +mise run check +mise run missing:task +mise exec java@21 -- mvn installl -f missing/pom.xml -P missing -pl nonexistent +cd component && mvn test -Psanity +cd missing && mvn clean +mvn unknown:goal +./missing-tool +``` +''') + self.assert_errors('unknown mise task: missing:task', 'unknown Maven phase or goal: installl', + 'unknown Maven POM: missing/pom.xml', 'unknown Maven profile: missing', + 'unknown Maven project: nonexistent', 'unknown working directory: missing', + 'unknown Maven phase or goal: unknown:goal', 'unknown repository command: ./missing-tool') + self.assertNotIn('unknown mise task: unit', '\n'.join(self.check()[0])) + self.assertNotIn('unknown mise task: check', '\n'.join(self.check()[0])) + self.write('AGENTS.md', ROOT_CONTENT.replace('mise install', 'mise run test:unit')) + self.assert_errors('document `mise install` as the setup command') + self.doc(BUILD, '```bash\nmise install\n```\n') + self.assertEqual(([], []), self.check()) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c98b18be29e..cb09e49c1af 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -92,6 +92,7 @@ jobs: with: version: 2026.10.20 - name: Select Java Version + if: runner.os == 'Windows' shell: bash # Set explicitly so Bash is used on Windows runners too. run: | mise use java@21 @@ -137,7 +138,18 @@ jobs: uses: ./.github/actions/orchestrator-cache with: sq-version: ${{ matrix.item.sq_version }} + - name: Run ruling tests on Linux + if: runner.os != 'Windows' + env: + MAVEN_OPTS: "-Xmx3g -Dfile.encoding=UTF-8" + JAVA_TOOL_OPTIONS: "" + GITHUB_TOKEN: ${{ fromJSON(steps.secrets.outputs.vault).GITHUB_TOKEN }} + ORCHESTRATOR_HOME: ${{ github.event_name == 'pull_request' && format('{0}/orchestrator-production', runner.temp) || env.ORCHESTRATOR_HOME }} + RULING_PROFILE: ${{ matrix.item.profile }} + SQ_VERSION: ${{ matrix.item.sq_version }} + run: mise run ruling "$RULING_PROFILE" --sq-version "$SQ_VERSION" - name: Run ruling tests + if: runner.os == 'Windows' shell: bash # Set explicitly so Bash is used on Windows runners too. env: MAVEN_OPTS: "-Xmx3g -Dfile.encoding=UTF-8" @@ -239,13 +251,6 @@ jobs: - uses: jdx/mise-action@90f833d396d0cc3674b631d2d225e306476c303a # v5.2.10 with: version: 2026.10.20 - - name: Select Java Version - shell: bash # Set explicitly so Bash is used on Windows runners too. - run: | - mise use java@21 - JAVA_21_HOME="$(mise where java@21)" - echo "JAVA_HOME=${JAVA_21_HOME}" >> "$GITHUB_ENV" - echo "${JAVA_21_HOME}/bin" >> "$GITHUB_PATH" - uses: ./.github/actions/maven-cache with: namespace: plugin-qa-${{ matrix.sq_version }} @@ -289,9 +294,8 @@ jobs: env: GITHUB_TOKEN: ${{ fromJSON(steps.secrets.outputs.vault).GITHUB_TOKEN }} ORCHESTRATOR_HOME: ${{ github.event_name == 'pull_request' && format('{0}/orchestrator-production', runner.temp) || env.ORCHESTRATOR_HOME }} - run: | - cd its/plugin - mvn "-Dorchestrator.configUrl=$ORCHESTRATOR_CONFIG_URL" "-Dorchestrator.home=$ORCHESTRATOR_HOME" package ${MAVEN_OUTPUT_ARGS} -Pit-plugin -Dsonar.runtimeVersion=${{ matrix.sq_version }} -Dmaven.test.redirectTestOutputToFile=false -Dparallel=classes -DuseUnlimitedThreads=true + SQ_VERSION: ${{ matrix.sq_version }} + run: mise run its:plugin --sq-version "$SQ_VERSION" sanity: name: Sanity Test @@ -309,12 +313,6 @@ jobs: - uses: jdx/mise-action@90f833d396d0cc3674b631d2d225e306476c303a # v5.2.10 with: version: 2026.10.20 - - uses: SonarSource/vault-action-wrapper@v3 - id: secrets - with: - secrets: | - development/kv/data/next url | SONAR_HOST_URL; - development/kv/data/next token | SONAR_TOKEN; - uses: ./.github/actions/maven-cache with: namespace: sanity @@ -325,20 +323,8 @@ jobs: use-develocity: ${{ env.USE_DEVELOCITY }} develocity-url: ${{ env.DEVELOCITY_URL }} disable-caching: 'true' - - name: Compile Test Sources - env: - SONAR_HOST_URL: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_HOST_URL }} - SONAR_TOKEN: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_TOKEN }} - working-directory: java-checks-test-sources - run: | - mvn clean compile --batch-mode - name: Sanity Test - env: - SONAR_HOST_URL: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_HOST_URL }} - SONAR_TOKEN: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_TOKEN }} - MAVEN_OPTS: "-Xmx8g" - run: | - mvn verify ${MAVEN_OUTPUT_ARGS} -f sonar-java-plugin/pom.xml -Psanity -Dtest=SanityTest + run: mise run test:sanity test-analyze: name: Test Analyze @@ -393,12 +379,6 @@ jobs: - uses: jdx/mise-action@90f833d396d0cc3674b631d2d225e306476c303a # v5.2.10 with: version: 2026.10.20 - - uses: SonarSource/vault-action-wrapper@v3 - id: secrets - with: - secrets: | - development/kv/data/next url | SONAR_HOST_URL; - development/kv/data/next token | SONAR_TOKEN; - uses: ./.github/actions/maven-cache with: namespace: custom-rules-license-check @@ -410,23 +390,11 @@ jobs: develocity-url: ${{ env.DEVELOCITY_URL }} disable-caching: 'true' env: - SONAR_HOST_URL: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_HOST_URL }} - SONAR_TOKEN: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_TOKEN }} JAVA_TOOL_OPTIONS: "" # Set an empty value to avoid issues with runners hanging and significantly slowing down builds - name: Build Java Custom Rules Example - env: - SONAR_HOST_URL: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_HOST_URL }} - SONAR_TOKEN: ${{ fromJSON(steps.secrets.outputs.vault).SONAR_TOKEN }} - working-directory: docs/java-custom-rules-example - run: | - mvn clean package -f pom_SQ_10_6_LATEST.xml --batch-mode + run: mise run test:custom-rules-example - name: Check License Compliance - run: | - # See https://xtranet.sonarsource.com/display/DEV/Open+Source+Licenses - mvn org.codehaus.mojo:license-maven-plugin:aggregate-add-third-party \ - --batch-mode \ - "-Dlicense.missingFile=${PWD}/missing-dep-licenses.properties" \ - -DuseMissingFile + run: mise run lint:licenses qa-os-win: name: Build and Unit Test on Windows diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000000..7c871ee0001 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,32 @@ +name: Documentation + +on: pull_request + +permissions: + contents: read + +jobs: + docs: + name: Documentation checks + runs-on: ubuntu-24.04 + timeout-minutes: 10 + env: + PYTHONDONTWRITEBYTECODE: 1 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install documentation checker dependencies + id: dependencies + run: | + python3 -m venv "$RUNNER_TEMP/docs-venv" + "$RUNNER_TEMP/docs-venv/bin/python" -m pip install -r .github/scripts/docs-requirements.txt + echo "$RUNNER_TEMP/docs-venv/bin" >> "$GITHUB_PATH" + - name: Test documentation checker + run: python -m unittest discover -s .github/scripts -p test_check_docs.py + - name: Lint Markdown + if: ${{ !cancelled() }} + run: npm exec --yes --ignore-scripts --package=markdownlint-cli2@0.20.0 -- markdownlint-cli2 + - name: Check documentation structure and references + if: ${{ !cancelled() && steps.dependencies.outcome == 'success' }} + run: python .github/scripts/check_docs.py diff --git a/.markdownlint-cli2.yaml b/.markdownlint-cli2.yaml new file mode 100644 index 00000000000..7e417cd6ac0 --- /dev/null +++ b/.markdownlint-cli2.yaml @@ -0,0 +1,8 @@ +globs: + - 'AGENTS.md' + - '**/AGENTS.md' + - 'docs/**/*.md' + - '.agents/skills/**/*.md' + - '.claude/{skills,rules}/**/*.md' + - '.cursor/**/*.{md,mdc}' + - '.gitar/rules/**/*.md' diff --git a/.markdownlint.json b/.markdownlint.json new file mode 100644 index 00000000000..315744cc122 --- /dev/null +++ b/.markdownlint.json @@ -0,0 +1,5 @@ +{ + "default": true, + "MD013": false, + "MD025": false +} diff --git a/.mvn/develocity.xml b/.mvn/develocity.xml index 6478119fc6d..b45f87a4e4a 100644 --- a/.mvn/develocity.xml +++ b/.mvn/develocity.xml @@ -2,6 +2,11 @@ https://develocity.sonar.build + + + + + #{env['CI'] == null} diff --git a/AGENTS.md b/AGENTS.md index 6c8d46c4f8c..e283b8205c7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,308 +1,57 @@ -# Introduction +# SonarJava agent guide -SonarJava is a static code analyzer for Java. +## Scope -The rules are implemented in **Java** using the SonarJava API. Test resources are **Java** files annotated with special comment markers. +SonarJava provides Java parsing, semantic analysis and rules for SonarQube Server, SonarQube Cloud and SonarQube for IDE. Use `pom.xml` for the Maven reactor. +The ECJ fork, symbolic execution engine, DBD and security rules live outside this repository. Public API changes can break those consumers and customer custom-rule plugins. +All agent instructions start here; there are no component-level `AGENTS.md` files. Read the topic guides below for component-specific constraints. -For step-by-step guidance on implementing a new rule (including metadata generation), see `.agents/skills/new-rule/SKILL.md`. +## Baseline reference ---- - - -# General Coding Guidelines - -- Do **NOT** write comments, inside the code. Comments can easily become outdated. -- Do write documentation for complex functions. -- Use KISS (Keep It Simple, Stupid) and DRY (Don't Repeat Yourself) principles. - ---- - -# Repository Structure - -## Maven Module Structure - -``` -sonar-java/ -├── java-frontend/ # Parser, AST, semantic model, type inference -├── java-checks/ # Community rule implementations -│ ├── src/main/java/org/sonar/java/checks/ # Rule Java source -│ └── src/test/ -│ ├── java/org/sonar/java/checks/ # Test classes -│ └── files/checks/ # Legacy Java test resource files. Should be migrated to java-checks-test-sources -├── java-checks-test-sources/ # Shared Java test resource files used across modules -├── java-checks-aws/ # AWS-specific rule implementations -├── java-symbolic-execution/ # Symbolic execution engine -├── sonar-java-plugin/ # Plugin packaging -└── its/ # Integration tests - └── ruling/ # Ruling integration tests -``` - -## Rule Implementation Pattern - -Rules are Java classes annotated with `@Rule(key = "SXXXX")` that extend one of: - -- **`IssuableSubscriptionVisitor`** — Event-based: register tree consumers for specific tree kinds -- **`BaseTreeVisitor`** — Visitor pattern: override `visit*` methods; combined with `JavaFileScanner` to report issues -- **`JavaFileScanner`** — Full scan: override `scanFile` to traverse the entire compilation unit - -To avoid coupling between rules, never introduce new abstract classes from which rules would inherit. -To avoid duplicating code, you may use utility classes. - -### Example: IssuableSubscriptionVisitor - -```java -@Rule(key = "S1234") -public class MyCheck extends IssuableSubscriptionVisitor { - - @Override - public List nodesToVisit() { - return Collections.singletonList(Tree.Kind.METHOD_INVOCATION); - } - - @Override - public void visitNode(Tree tree) { - MethodInvocationTree mit = (MethodInvocationTree) tree; - // Analyze the invocation... - reportIssue(mit, "Message describing the issue."); - } -} -``` - -### Example: BaseTreeVisitor - -```java -@Rule(key = "S1234") -public class MyCheck extends BaseTreeVisitor implements JavaFileScanner { - - private JavaFileScannerContext context; - - @Override - public void scanFile(JavaFileScannerContext context) { - this.context = context; - scan(context.getTree()); - } - - @Override - public void visitMethodInvocation(MethodInvocationTree tree) { - // Analyze the invocation... - context.reportIssue(this, tree, "Message describing the issue."); - super.visitMethodInvocation(tree); - } -} -``` - -### Key API Elements - -- **`reportIssue(tree, message)`** — Report an issue at a specific AST node -- **`reportIssue(tree, message, secondaries, cost)`** — Report with secondary locations -- **`Tree.Kind.*`** — AST node type enumeration (e.g., `Tree.Kind.METHOD`, `Tree.Kind.IF_STATEMENT`, `Tree.Kind.METHOD_INVOCATION`) -- **`ExpressionUtils.getParentOfType(tree, Tree.Kind.METHOD)`** — Navigate up the AST -- **`ExpressionUtils`**, **`MethodMatchers`** — Utility classes for common analysis patterns - -### MethodMatchers - -Use `MethodMatchers` to match method calls by type, name, and signature: - -```java -private static final MethodMatchers MY_MATCHER = MethodMatchers.create() - .ofTypes("java.util.List") - .names("add") - .withAnyParameters() - .build(); - -// In visitNode: -if (MY_MATCHER.matches(methodInvocationTree)) { - reportIssue(methodInvocationTree, "Message."); -} -``` - -### Quick Fix API - -```java -JavaQuickFix quickFix = JavaQuickFix.newQuickFix("Remove redundant check") - .addTextEdit(JavaTextEdit.removeTree(tree)) - .build(); -reportIssue(tree, "Message").withQuickFix(() -> quickFix); -``` - -### Per-File State Cleanup - -New rules must be **stateless**: see the stateless-checks section of `.agents/skills/new-rule/SKILL.md`. The guidance below applies to existing checks that still accumulate per-file state. +[Repository Baseline](docs/systems/external-context.md#repository-baseline), checked 2026-11-26; shared `awesome-ai` template unavailable, so this file follows the guideline's required sections directly. -Rules that accumulate state in collections or mutable fields during file analysis **must clear that state between files**. A single rule instance is reused across all files in a module. +## Commands -For `IssuableSubscriptionVisitor` subclasses, override `clearState()` — it is called automatically before and after each file: +Read [Setup, build and test commands](docs/systems/build.md) before selecting a JDK or running Maven. -```java -@Rule(key = "S1234") -public class MyCheck extends IssuableSubscriptionVisitor { +## Constraints - private final Set seen = new HashSet<>(); +- This repository is public. All agent files and docs are public. Do not publish internal URLs, customer data, credentials or private repository content. +- Preserve public API compatibility and SonarQube for IDE support; read `docs/systems/public-api.md` before changing the API or plugin registration. +- Use the supported build and runtime JDKs in `docs/systems/build.md`; CI exercises them for different purposes. +- The project uses SSALv1 (`LICENSE.txt`); read `docs/systems/licenses.md` before changing dependencies. +- Do not edit generated rule metadata or the generated check list by hand. Read `docs/systems/rule-metadata.md` before registering rules or changing profiles. +- New rules are stateless and must not introduce shared abstract check bases; read the decisions in `docs/adrs/index.md` before adding rule logic or unit tests. +- Use JUnit Jupiter for unit tests and cover rule behavior both with and without semantic resolution; read `docs/systems/rule-tests.md` before changing a rule or fixture. +- Let CI run ruling and generate baseline updates; read `docs/systems/ruling-tests.md` before reviewing SARIF changes. - @Override - protected void clearState() { - seen.clear(); - } -} -``` +## Escalation -For `BaseTreeVisitor` / `JavaFileScanner` implementations, clear state in `scanFile()` (typically in a `finally` block): +`@SonarSource/code-quality-jvm-squad` owns the repository, as defined in [CODEOWNERS](.github/CODEOWNERS). Use the [SONARJAVA Jira project](https://jira.sonarsource.com/browse/SONARJAVA/) for issue context. If RSPEC, Repox, Orchestrator or the ruling submodule is required and unavailable, ask the owners and report which check is blocked. Do not guess metadata, change baselines to hide failures or substitute credentials. -```java -@Override -public void scanFile(JavaFileScannerContext context) { - this.context = context; - try { - scan(context.getTree()); - } finally { - myCollection.clear(); - } -} -``` +## Verification before merge -**Do not** clear lazy-initialized caches derived from immutable configuration (e.g. parsed `@RuleProperty` values) — those are intentionally computed once per rule instance. +Read [verification before merge](docs/systems/verification.md) before requesting review; it covers local checks, CI jobs and changes requiring extra review. -### Dependency-Aware Rules +## Feature-flag applicability -When a rule should only apply when a specific library is present, or when its behaviour depends on a dependency version, implement `DependencyVersionAware` alongside the visitor base class: +Read [feature activation](docs/systems/feature-activation.md) before changing behavior that may need independent rollout or rollback. -```java -@Rule(key = "S2230") -public class TransactionalMethodVisibilityCheck extends IssuableSubscriptionVisitor implements DependencyVersionAware { +## Release checks - private boolean isSpring6OrLater = false; - - @Override - public List nodesToVisit() { - return Collections.singletonList(Tree.Kind.METHOD); - } - - /** Called before analysis. Return false to disable the rule entirely when required dependencies are absent. */ - @Override - public boolean isCompatibleWithDependencies(Function> dependencyFinder) { - Optional springTxVersion = dependencyFinder.apply("spring-tx"); - Optional springContextVersion = dependencyFinder.apply("spring-context"); - if (springTxVersion.isEmpty() && springContextVersion.isEmpty()) { - return false; // rule is disabled — dependency not on classpath - } - isSpring6OrLater = springContextVersion - .or(() -> springTxVersion) - .map(v -> v.isGreaterThanOrEqualTo("6.0")) - .orElse(false); - return true; - } - - @Override - public void visitNode(Tree tree) { - // use isSpring6OrLater to adjust rule behaviour - } -} -``` - -Key points: -- `dependencyFinder.apply("artifact-id")` looks up a dependency by its Maven artifact ID and returns its version if present. -- Returning `false` from `isCompatibleWithDependencies` disables the rule for the current project — use this when the rule only makes sense if a particular library is on the classpath. -- Store any version information in an instance field (e.g. `isSpring6OrLater`) so that `visitNode` can use it during the scan. - ---- - -# Understanding Rule Trigger Requirements - -When creating simple examples or fixing false positives, examine the rule's test files to understand what conditions trigger the rule: - -## AST Node Kinds - -Rules subscribe to specific tree kinds. Check `nodesToVisit()` to see which `Tree.Kind.*` values the rule listens to: -- `Tree.Kind.METHOD` — Method declarations -- `Tree.Kind.METHOD_INVOCATION` — Method calls -- `Tree.Kind.IF_STATEMENT` — If statements -- `Tree.Kind.FOR_STATEMENT` — For loops -- `Tree.Kind.VARIABLE` — Variable declarations - -## Semantic Model - -SonarJava provides a semantic model to resolve types and symbols: -- **`symbol.type()`** — Resolved type of symbol -- **`symbol.owner()`** — Enclosing symbol (e.g., class owning a method) -- **`expressionTree.symbolType()`** — Type of expression -- **`type.isSubtypeOf("java.util.Collection")`** — Type hierarchy checks - -## Java Version Context - -Rules may behave differently depending on the Java language level: -- Some rules target Java 8+ features (lambdas, streams, `Optional`) -- Some handle Java 11+ or Java 17+ features (var, records, sealed classes) - ---- - -# Test File Conventions - -The file general structure for a rule implementation and its tests is as follows: -- Rule class: `java-checks/src/main/java/org/sonar/java/checks/{RuleId}Check.java` -- Test class: `java-checks/src/test/java/org/sonar/java/checks/{RuleId}CheckTest.java` -- Test samples: `java-checks-test-sources/default/src/main/java/checks/{RuleId}CheckSample.java` - -## Test Class - -The test class should use `CheckVerifier` and test the rule both with and without semantic. -This is to prevent false positives when the rule is applied to code that does not have the required dependencies on the classpath. -Example: - -```java -import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; - -class AbsOnNegativeCheckTest { - - @Test - void test() { - CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath("checks/AbsOnNegativeCheckSample.java")) - .withCheck(new AbsOnNegativeCheck()) - .verifyIssues(); - } - - @Test - void test_without_semantic() { - CheckVerifier.newVerifier() - .onFile(mainCodeSourcesPath("checks/AbsOnNegativeCheckSample.java")) - .withCheck(new AbsOnNegativeCheck()) - .withoutSemantic() - .verifyIssues(); - } -} -``` - -## Test samples -Test resource files use inline comment markers to declare expected issues: - -```java -int x = foo(); // Noncompliant -int y = bar(); // Noncompliant {{Expected message text}} -int z = baz(); // compliant -``` - -- `// Noncompliant` — The analyzer must report an issue on this line -- `// Noncompliant {{message}}` — Issue must have this exact message -- `// compliant` — Optional annotation for clarity; no issue expected - -Secondary locations use `[[...]]` inline markers when needed. - -The precise locations of the issues are underlined using `^` characters. To produce that underline use a script like: -```shell -str=">"; sub=""; pre="${str%%"$sub"*}" suf="${str#*"$sub"}"; echo "${pre//?/ }${sub//?/^}" -``` - ---- +Read [release checks](docs/systems/release-checks.md) before preparing a release or changing release automation. -# Ruling Tests +## Documentation -Ruling tests validate that rule fixes don't break existing true positives. They run the analyzer against real-world Java projects (`guava`, `commons-beanutils`, `eclipse-jetty`, `sonar-server`, `jboss-ejb3-tutorial`, `regex-examples`, `mall`) and compare results to expected baselines. +- Start with [the documentation index](docs/index.md); read `docs/documentation-conventions.md` before editing docs. +- Read `docs/systems/rule-api.md` before choosing a visitor or changing a rule's lifecycle. +- Read `docs/systems/project-level-rules.md` before changing cross-file analysis or cache behavior. +- Read `docs/systems/quickfix-tests.md` before adding or changing a quick fix. +- Use `.agents/skills/new-rule/SKILL.md` when implementing a rule from its specification. +- Use `.agents/skills/migrate-test-samples/SKILL.md` when moving legacy fixtures into the Maven test-source modules. -- Expected ruling files: `its/ruling/src/test/resources/expected//java-.json` -- Actual ruling output: `its/ruling/target/actual//java-.json` -- Format: `{":path/to/File.java": [line1, line2, ...], ...}` where `` is the project's folder name under `its/sources/` -- Ruling sources: `its/sources//` +## External context -Do not try to run these locally. A PR should be created automatically when they fail on CI. +Read [external context](docs/systems/external-context.md) before looking up rule specifications, upstream release procedures, shared operations or design proposals. --- diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 120000 index 47dc3e3d863..00000000000 --- a/CLAUDE.md +++ /dev/null @@ -1 +0,0 @@ -AGENTS.md \ No newline at end of file diff --git a/README.md b/README.md index 85df9e9ac47..3eabf7a7ec9 100644 --- a/README.md +++ b/README.md @@ -79,118 +79,9 @@ Would you like to work on this project full-time? We are hiring! Check out https Testing ------- -To run tests locally follow these instructions. +See the [setup, build and test commands](docs/systems/build.md) for JDK selection, unit tests, Sanity and Plugin QA. Use the [rule test guide](docs/systems/rule-tests.md) for sample placement and the [ruling guide](docs/systems/ruling-tests.md) for reviewing CI-generated expectations. -### Java versions - -You need `Java 26` to compile and run the Unit Tests of the project and `Java 21` run most Integration Tests (ITs). -Note that `Java 21` can be used to build and test all modules except under `java-checks-test-sources` (as they require `Java 26`). -If you are adding or moving rule test samples, see [java-checks-test-sources/README.md](java-checks-test-sources/README.md) -for guidance on when samples belong in the dedicated test-source modules instead of `java-checks/src/test/files`. - -### Build the Project and Run Unit Tests - -To build the plugin and run its unit tests, execute this command from the project's root directory: - - mvn clean install - -### Note that -Running unit tests within the IDE might incur in some issues because of the way the project is built with Maven. -If you see something like this: - - java.lang.SecurityException: class ... signer information does not match signer information of other classes in the same package - -try removing the Maven nature of the 'jdt' module. - -### Integration Tests - -To run integration tests, you will need to create a properties file like the one shown below, and set the URL pointing to its location in an environment variable named `ORCHESTRATOR_CONFIG_URL`. - - # version of SonarQube Server - sonar.runtimeVersion=LATEST_RELEASE - - orchestrator.updateCenterUrl=http://update.sonarsource.org/update-center-dev.properties - - # The location of the Maven local repository is not automatically guessed. It can also be set with the env variable MAVEN_LOCAL_REPOSITORY. - maven.localRepository=/home/myName/.m2/repository - -With for instance the `ORCHESTRATOR_CONFIG_URL` variable being set as: - - export ORCHESTRATOR_CONFIG_URL=file:///home/user/workspace/orchestrator.properties - -Before running the ITs, be sure your MAVEN_HOME environment variable is set. - -#### Sanity Test - -The "Sanity Test" is a test that runs all checks against all the test source files without taking into account the result of the analysis. It verifies that rules are not crashing on any file in our test sources. By default, this test is excluded from the build. To launch it: - - mvn clean install -P sanity - -#### Plugin Test - -The "Plugin Test" is an integration test suite that verifies plugin features such as metric calculation, coverage, etc. To launch it, build the plugin first (`mvn clean install`), then run: - - cd its/plugin - mvn clean install -Pit-plugin -DcommunityEditionTestsOnly=true - -Note for internal contributors: in order to also execute the tests that depend on the SonarQube Server Enterprise Edition, use: - - mvn clean install -Pit-plugin - -#### Ruling Test - -The "Ruling Test" is an integration test suite that launches the analysis of a large code base, saves the issues created by the plugin in SARIF reports, and then compares those results to the expected SARIF reports. - -To run the test, first make sure the submodules are checked out: - - git submodule update --init --recursive - -Then, ensure that the `JAVA_HOME` environment variable is set for the ruling tests execution and that it points to your local JDK 21 installation. -Failing to do so will produce inconsistencies with the expected results. - -From the `its/ruling` folder, launch the ruling tests: - - mvn clean install -Pit-ruling -DcommunityEditionTestsOnly=true - # Alternatively - JAVA_HOME=/my/local/java21/jdk/ mvn clean install -Pit-ruling -DcommunityEditionTestsOnly=true - -Note for internal contributors: in order to also execute the tests that depend on the SonarQube Server Enterprise Edition, use: - - mvn clean install -Pit-ruling - -To run the ruling tests for only a subset of rules, use the `sonarRules` property with a comma-separated list of rule keys: - - mvn clean install -Pit-ruling -DsonarRules=S100,S101 - -This test gives you the opportunity to examine the issues created by each rule and make sure they're what you expect. Any implemented rule is highly likely to raise issues on the multiple projects we use as ruling code base. - -* For a newly implemented rule, the first build will most probably fail because no expected results exist for the new rule. Inspect the new issues in `java-SXXXX.sarif` for each project under: - - /path/to/project/sonar-java/its/ruling/target/actual/... - -* For existing rules which are modified, you may expect some differences between "actual" (from new analysis) and expected results. Review carefully the changes that are shown and update the expected resources accordingly. - -Each SARIF report contains a `runs[].results[]` entry for each issue, with its rule ID, message, and location. After reviewing the differences, copy the relevant actual report from: - - its/ruling/target/actual/ - -Into the directory with the expected issues: - - its/ruling/src/test/resources/expected/ - -For example, from the repository root, to update one rule in one project: - - cp its/ruling/target/actual//java-SXXXX.sarif its/ruling/src/test/resources/expected// - -#### Debugging Integration Tests -You can debug ITs by adding `-Dmaven.binary=mvnDebug` as an option when running the tests. This will cause the analyzer JVM to wait for a debugger to be attached before continuing. - -### Updating licenses: -When dependencies change, update the committed license files using the `updateLicenses` profile: -```sh -mvn clean package -PupdateLicenses -``` -This regenerates licenses in `sonar-java-plugin/src/main/resources/licenses/` based on current project dependencies. +When dependencies change, follow the [third-party license checks](docs/systems/licenses.md). For more engineering guidance, start with the [documentation index](docs/index.md). ### License diff --git a/check-list/src/main/java/org/sonar/java/CheckListGenerator.java b/check-list/src/main/java/org/sonar/java/CheckListGenerator.java index 63d53b364a3..6496633ae49 100644 --- a/check-list/src/main/java/org/sonar/java/CheckListGenerator.java +++ b/check-list/src/main/java/org/sonar/java/CheckListGenerator.java @@ -31,6 +31,7 @@ import java.util.stream.Stream; import org.sonar.check.Rule; +/** See Rule metadata and registration. */ public class CheckListGenerator { private static final String CLASS_NAME = "GeneratedCheckList"; public static final String RULES_PATH = "sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/"; diff --git a/docs/CUSTOM_RULES_101.md b/docs/CUSTOM_RULES_101.md index e7f0c621bff..41543dc5d67 100644 --- a/docs/CUSTOM_RULES_101.md +++ b/docs/CUSTOM_RULES_101.md @@ -1,738 +1,103 @@ -Writing Custom Java Rules 101 -========== +--- +title: Writing Custom Java Rules 101 +description: Find the custom Java rules tutorial and follow links from its original section bookmarks. +generated: + by: tirion +--- -If you are using SonarQube along with its Java Analyzer to analyze your projects, you might find that certain specific requirements of your company cannot be addressed by the existing rules. -In such cases, the most suitable option would be to develop your own custom Java rules. +# Writing Custom Java Rules 101 -This document introduces custom rule writing for the SonarQube Java Analyzer. -It will cover all the main concepts of static analysis required to understand and develop effective rules, relying on the API provided by the SonarSource Analyzer for Java. +The tutorial now has a page for each step, from setting up the example Maven project to deploying a custom rule. Start at the [tutorial index](custom-rules/index.md), or follow the links below if you arrived via a section bookmark. ## Content -* [Getting Started](#getting-started) - * [Looking at the pom](#looking-at-the-pom) -* [Writing a rule](#writing-a-rule) - * [Three files to forge a rule](#three-files-to-forge-a-rule) - * [A specification to make it right](#a-specification-to-make-it-right) - * [A test file to rule them all](#a-test-file-to-rule-them-all) - * [A test class to make it pass](#a-test-class-to-make-it-pass) - * [First version: Using syntax trees and API basics](#first-version-using-syntax-trees-and-api-basics) - * [Second version: Using semantic API](#second-version-using-semantic-api) - * [What you can use, and what you can't](#what-you-can-use-and-what-you-cant) -* [Registering the rule in the custom plugin](#registering-the-rule-in-the-custom-plugin) - * [Rule Metadata](#rule-metadata) - * [Rule Activation](#rule-activation) - * [Rule Registrar](#rule-registrar) -* [Testing a custom plugin](#testing-a-custom-plugin) - * [How to define rule parameters](#how-to-define-rule-parameters) - * [How to test sources requiring external binaries](#how-to-test-sources-requiring-external-binaries) - * [How to test precise issue location](#how-to-test-precise-issue-location) - * [How to test the Source Version in a rule](#how-to-test-the-source-version-in-a-rule) -* [References](#references) +- [Getting started](custom-rules/getting-started.md) +- [Writing a rule](custom-rules/writing-a-rule.md) +- [Implementing the rule](custom-rules/implementing-the-rule.md) +- [Registering the rule in the custom plugin](custom-rules/registering-the-rule.md) +- [Testing a custom plugin](custom-rules/testing-a-custom-plugin.md) +- [References](custom-rules/index.md#references) ## Getting started -The rules you develop will be delivered using a dedicated, custom plugin, relying on the **SonarSource Analyzer for Java API**. -In order to start working efficiently, we provide a template Maven project that you will fill in while following this tutorial. - -Grab the template project by cloning [this repository](https://github.com/SonarSource/sonar-java) and then importing in your IDE the sub-module [java-custom-rules-examples](https://github.com/SonarSource/sonar-java/tree/master/docs/java-custom-rules-example). -This project already contains examples of custom rules. Our goal will be to add an extra rule! +[Set up the custom Java rules example project.](custom-rules/getting-started.md) ### Looking at the POM -A custom plugin is a Maven project, and before diving into code, it is important to notice a few relevant lines related to the configuration of your soon-to-be-released custom plugin. -The root of a Maven project is a file named `pom.xml`. - -In our case, we have two of them: -* `pom.xml`: use a snapshot version of the Java Analyzer -* `pom_SQ_10_6_LATEST.xml`: self-contained `pom` file, configured with dependencies matching SonarQube `10.6` requirements - -These two `pom`s correspond to different use cases, depending on which instance of SonarQube you will target with your custom-rules plugin. - -In this tutorial, **we will only use the file named `pom_SQ_10_6_LATEST.xml`**, as it is entirely independent of the build of the Java Analyzer, is self-contained, and will target the latest release of SonarQube. - -Let's start by building the custom-plugin template by using the following command: - -``` -mvn clean install -f pom_SQ_10_6_LATEST.xml -``` - -Note that you can also decide to **delete** the original `pom.xml` file (**NOT RECOMMENDED**) and then rename `pom_SQ_10_6_LATEST.xml` into `pom.xml`. -In this case, you would be able to use the very simple command: - -``` -mvn clean install -``` - -Looking inside the `pom`, you will see that both SonarQube and the Java Analyzer versions are hard-coded. -This is because SonarSource's analyzers are directly embedded in the various SonarQube versions and are shipped together. -For instance, SonarQube `8.9` (previous LTS) is shipped with version `6.15.1.26025` of the Java Analyzer, while the latest SonarQube `10.6` is shipped with a much more recent version `8.0.1.36337` of the Java Analyzer. -**These versions can not be changed**. - -```xml - - 9.14.0.375 - 8.0.1.36337 - - -``` - -Other tags such as ``, ``, ``, ``, and `` can be freely modified. - -```xml - org.sonar.samples - java-custom-rules-example - 1.0.0-SNAPSHOT - SonarQube Java :: Documentation :: Custom Rules Example - Java Custom Rules Example for SonarQube -``` - -In the code snippet below, it is important to note that the **entry point of the plugin** is provided as the `` in the configuration of the sonar-packaging-maven plugin, using the fully qualified name of the java class `MyJavaRulesPlugin`. -You must change this configuration if you refactor your code, rename, or move the class implementing `org.sonar.api.Plugin`. - -Starting with sonar-java 7.30, you must also include the `requiredForLanguages` property, indicating that your custom plugin will be available for projects using Java. Failing to do so will result in your plugin crashing upon initialization when analyzing a project containing no Java code. Your plugin will only be run when the analyzed project contains Java code. - -```xml - - org.sonarsource.sonar-packaging-maven-plugin - sonar-packaging-maven-plugin - 1.21.0.505 - true - - java-custom - Java Custom Rules - org.sonar.samples.java.MyJavaRulesPlugin - true - java:${sonarjava.version} - java - - -``` +[Choose a Maven POM, install the example, and configure the plugin.](custom-rules/getting-started.md#looking-at-the-pom) ## Writing a rule -In this section, we will write a custom rule from scratch. -To do so, we will use a [Test Driven Development](https://en.wikipedia.org/wiki/Test-driven_development) (TDD) approach, relying on writing some test cases first, followed by the implementation of a solution. +[Start writing a custom Java rule.](custom-rules/writing-a-rule.md) ### Three files to forge a rule -When implementing a rule, there is always a minimum of three distinct files to create: -1. A test file, which contains Java code used as input data for testing the rule -2. A test class, which contains the rule's unit test -3. A rule class, which contains the implementation of the rule. - -To create our first custom rule (usually called a "*check*"), let's start by creating these three files in the template project, as described below: - -1. In folder `/src/test/files`, create a new empty file named `MyFirstCustomCheck.java`, and copy-paste the content of the following code snippet. - -```java -class MyClass { -} -``` - -2. In package `org.sonar.samples.java.checks` of `/src/test/java`, create a new test class called `MyFirstCustomCheckTest` and copy-paste the content of the following code snippet. - -```java -package org.sonar.samples.java.checks; - -import org.junit.jupiter.api.Test; - -class MyFirstCustomCheckTest { - - @Test - void test() { - } - -} -``` - -3. In package `org.sonar.samples.java.checks` of `/src/main/java`, create a new class called `MyFirstCustomCheck` extending class `org.sonar.plugins.java.api.IssuableSubscriptionVisitor` provided by the Java Plugin API. -Then, replace the content of the `nodesToVisit()` method with the content from the following code snippet. -This file will be described when dealing with the implementation of the rule! - -```java -package org.sonar.samples.java.checks; - -import org.sonar.check.Rule; -import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; -import org.sonar.plugins.java.api.tree.Tree.Kind; -import java.util.Collections; -import java.util.List; - -@Rule(key = "MyFirstCustomRule") -public class MyFirstCustomCheck extends IssuableSubscriptionVisitor { - - @Override - public List nodesToVisit() { - return Collections.emptyList(); - } - -} -``` - -> -> Question: **More files...** -> -> If the three files described above are always the base of rule writing, there are situations where extra files may be needed. -> For instance, when a rule uses parameters, or if its behavior relies on the detected version of Java, multiple test files could be required. -> It is also possible to use external files to describe rule metadata, such as a description in HTML format. -> Such situations will be described in other topics of this documentation. -> +[Create the three files you need to write and test the rule.](custom-rules/writing-a-rule.md#three-files-to-forge-a-rule) ### A specification to make it right -Of course, before going any further, we need a key element in rule writing: a specification! -For the sake of the exercise, let's consider the following quote from a famous Guru as being the specification of our custom rule, as it is of course absolutely correct and incontrovertible. - -> -> **Gandalf - Why Program When Magic Rulez (WPWMR, p.42)** -> -> *“For a method having a single parameter, the types of its return value and its parameter should never be the same.”* -> +[Read the rule specification.](custom-rules/writing-a-rule.md#a-specification-to-make-it-right) ### A test file to rule them all -Because we chose a TDD approach, the first thing to do is to write examples of the code our rule will target. -In this file, we consider numerous cases that our rule may encounter during an analysis, and flag the lines which will require our implementation to raise issues. -The flag to be used is a simple `// Noncompliant` trailing comment on the line of code where an issue should be raised. -Why *Noncompliant*? Because the flagged lines do not *comply* with the rule. - -Covering all the possible cases is not necessarily required, the goal of this file is to cover all the situations which may be encountered during an analysis, but also to abstract irrelevant details. -For instance, in the context of our first rule, the name of a method, the content of its body, and the owner of the method make no difference, whether it's an abstract class, a concrete class, or an interface. -Note that this sample file should be structurally correct and all code should compile. - -In the test file `MyFirstCustomCheck.java` created earlier, copy-paste the following code: - -```java -class MyClass { - MyClass(MyClass mc) { } - - int foo1() { return 0; } - void foo2(int value) { } - int foo3(int value) { return 0; } // Noncompliant - Object foo4(int value) { return null; } - MyClass foo5(MyClass value) {return null; } // Noncompliant - - int foo6(int value, String name) { return 0; } - int foo7(int ... values) { return 0;} -} -``` - -The test file now contains the following test cases: -* **line 2:** A constructor, to differentiate the case from a method; -* **line 4:** A method without parameter (`foo1`); -* **line 5:** A method returning void (`foo2`); -* **line 6:** A method returning the same type as its parameter (`foo3`), which will be noncompliant; -* **line 7:** A method with a single parameter, but a different return type (`foo4`); -* **line 8:** Another method with a single parameter and same return type, but with non-primitive types (`foo5`), therefore noncompliant too; -* **line 10:** A method with more than 1 parameter (`foo6`); -* **line 11:** A method with a variable arity argument (`foo7`); +[Write examples and mark the lines where the rule should report issues.](custom-rules/writing-a-rule.md#a-test-file-to-rule-them-all) ### A test class to make it pass -Once the test file is updated, let's update our test class to use it, and link the test to our (not yet implemented) rule. -To do so, get back to our test class `MyFirstCustomCheckTest`, and update the `test()` method as shown in the following code snippet (you may have to import class `org.sonar.java.checks.verifier.CheckVerifier`): - -```java - @Test - void test() { - CheckVerifier.newVerifier() - .onFile("src/test/files/MyFirstCustomCheck.java") - .withCheck(new MyFirstCustomCheck()) - .verifyIssues(); - } -``` - -As you probably noticed, this test class contains a single test, the purpose of which is to verify the behavior of the rule we are going to implement. -To do so, it relies on the usage of the `CheckVerifier` class, provided by the Java Analyzer rule-testing API. -This `CheckVerifier` class provides useful methods to validate rule implementations, allowing us to totally abstract all the mechanisms related to analyzer initialization. -Note that while verifying a rule, the *verifier* will collect lines marked as being *Noncompliant*, and verify that the rule raises the expected issues and *only* those issues. - -Now, let's proceed to the next step of TDD: make the test fail! - -To do so, simply execute the test from the test file using JUnit. -The test should **fail** with the error message "**At least one issue expected**", as shown in the code snippet below. -Since our check is not yet implemented, no issue can be raised yet, so that's the expected behavior. - -``` -java.lang.AssertionError: No issue raised. At least one issue expected - at org.sonar.java.checks.verifier.InternalCheckVerifier.assertMultipleIssues(InternalCheckVerifier.java:291) - at org.sonar.java.checks.verifier.InternalCheckVerifier.checkIssues(InternalCheckVerifier.java:231) - at org.sonar.java.checks.verifier.InternalCheckVerifier.verifyAll(InternalCheckVerifier.java:222) - at org.sonar.java.checks.verifier.InternalCheckVerifier.verifyIssues(InternalCheckVerifier.java:167) - at org.sonar.samples.java.checks.MyFirstCustomCheckTest.test(MyFirstCustomCheckTest.java:13) - ... -``` +[Run the rule against the examples using `CheckVerifier`.](custom-rules/writing-a-rule.md#a-test-class-to-make-it-pass) ### First version: Using syntax trees and API basics -Before we start with the implementation of the rule itself, you need a little background. - -Prior to running any rule, the SonarQube Java Analyzer parses a given Java code file and produces an equivalent data structure: the **Syntax Tree**. -Each construction of the Java language can be represented with a specific kind of Syntax Tree, detailing each of its particularities. -Each of these constructions is associated with a specific `Kind` as well as an interface explicitly describing all its particularities. -For instance, the kind associated with the declaration of a method will be `org.sonar.plugins.java.api.tree.Tree.Kind.METHOD`, and its interface defined by `org.sonar.plugins.java.api.tree.MethodTree`. -All kinds are listed in the [`Kind` enum of the Java Analyzer API](https://github.com/SonarSource/sonar-java/blob/7.16.0.30901/java-frontend/src/main/java/org/sonar/plugins/java/api/tree/Tree.java#L47). - -When creating the rule class, we chose to implement the `IssuableSubscriptionVisitor` class from the API. -This class, on top of providing a bunch of useful methods to raise issues, also **defines the strategy which will be used when analyzing a file**. -As its name is telling us, it is based on a subscription mechanism, allowing to specify on what kind of tree the rule should react. -The list of node types to cover is specified through the `nodesToVisit()` method. - -In the previous steps, we modified the implementation of the method to return an empty list, therefore not subscribing to any node of the syntax tree. - -Now it's finally time to jump into the implementation of our first rule! -Go back to the `MyFirstCustomCheck` class, and modify the list of `Kind`s returned by the `nodesToVisit()` method. -Since our rule targets method declarations, we only need to visit methods. -To do so, simply make sure that we return a singleton list containing only `Kind.METHOD` as a parameter of the returned list, as shown in the following code snippet. - -```java -@Override -public List nodesToVisit() { - return Collections.singletonList(Kind.METHOD); -} -``` - -Once the nodes to visit are specified, we have to implement how the rule will react when encountering method declarations. -To do so, override method `visitNode(Tree tree)`, inherited from `SubscriptionVisitor` through `IssuableSubscriptionVisitor`. - -```java -@Override -public void visitNode(Tree tree) { -} -``` - -Because we registered the rule to visit Method nodes, we know that every time the method is called, the tree parameter will be a `org.sonar.plugins.java.api.tree.MethodTree` (the interface tree associated with the `METHOD` kind). -As a first step, we can consequently safely cast the tree directly into a `MethodTree`, as shown below. -Note that if we had registered multiple node types, we would have to test the node kind before casting by using the method `Tree.is(Kind ... kind)`. - -```java -@Override -public void visitNode(Tree tree) { - MethodTree method = (MethodTree) tree; -} -``` - -Now, let's narrow the focus of the rule by checking that the method has a single parameter, and raise an issue if it's the case. - -```java -@Override -public void visitNode(Tree tree) { - MethodTree method = (MethodTree) tree; - if (method.parameters().size() == 1) { - reportIssue(method.simpleName(), "Never do that!"); - } -} -``` - -The method `reportIssue(Tree tree, String message)` from `IssuableSubscriptionVisitor` allows reporting an issue on a given tree with a specific message. -In this case, we chose to report the issue at a precise location, which will be the name of the method. - -Now, let's test our implementation by executing `MyFirstCustomCheckTest.test()` again. - -``` -java.lang.AssertionError: Unexpected at [5, 7, 11] - at org.sonar.java.checks.verifier.InternalCheckVerifier.assertMultipleIssues(InternalCheckVerifier.java:303) - at org.sonar.java.checks.verifier.InternalCheckVerifier.checkIssues(InternalCheckVerifier.java:231) - at org.sonar.java.checks.verifier.InternalCheckVerifier.verifyAll(InternalCheckVerifier.java:222) - at org.sonar.java.checks.verifier.InternalCheckVerifier.verifyIssues(InternalCheckVerifier.java:167) - at org.sonar.samples.java.checks.MyFirstCustomCheckTest.test(MyFirstCustomCheckTest.java:13) - ... -``` - -Of course, our test failed again... -The `CheckVerifier` reported that lines 5, 7, and 11 are raising unexpected issues, as visible in the stack trace above. -By looking back at our test file, it's easy to figure out that raising an issue in line 5 is wrong because the return type of the method is `void`, line 7 is wrong because `Object` is not the same as `int`, and line 11 is also wrong because of the variable *arity* of the method. -Raising these issues is however correct accordingly to our implementation, as we didn't check for the types of the parameter and return type. -To handle type, however, we will need to rely on more than what we can achieve using only knowledge of the syntax tree. -This time, we will need to use the semantic API! - -> -> Question: **IssuableSubscriptionVisitor and BaseTreeVisitor** -> -> For the implementation of this rule, we chose to use an `IssuableSubscriptionVisitor` as the implementation basis of our rule. -> This visitor offers an easy approach to writing quick and simple rules because it allows us to narrow the focus of our rule to a given set of Kinds to visit by subscribing to them. -> However, this approach is not always the most optimal one. -> In such a situation, it could be useful to take a look at another visitor provided with the API: `org.sonar.plugins.java.api.tree.BaseTreeVisitor`. -> The `BaseTreeVisitor` contains a `visit()` method dedicated to each and every kind of syntax tree, and is particularly useful when the visit of a file has to be fine-tuned. -> -> In [rules already implemented in the Java Plugin](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/java-checks/src/main/java/org/sonar/java/checks), you will be able to find multiple rules using both approaches: An `IssuableSubscriptionVisitor` as an entry point, helped by simple `BaseTreeVisitor`(s) to identify the pattern in other parts of code. -> +[Use a syntax tree visitor to implement the first version of the rule.](custom-rules/implementing-the-rule.md#first-version-using-syntax-trees-and-api-basics) ### Second version: Using semantic API -Up to now, our rule implementation only relied on the data provided directly by the syntax tree that resulted from the parsing of the code. -However, the SonarAnalyzer for Java provides a lot more regarding the code being analyzed, because it also constructs a ***semantic model*** of the code. -This semantic model provides information related to each ***symbol*** being manipulated. -For a method, for instance, the semantic API will provide useful data such as a method's owner, its usages, the types of its parameters and its return type, the exception it may throw, etc. -Don't hesitate to explore the [semantic package of the API](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/java-frontend/src/main/java/org/sonar/plugins/java/api/semantic) in order to have an idea of what kind of information you will have access to during analysis! - -But now, let's go back to our implementation and take advantage of the semantics. - -Once we know that our method has a single parameter, let's start by getting the symbol of the method using the `symbol()` method from the `MethodTree`. - -```java -@Override -public void visitNode(Tree tree) { - MethodTree method = (MethodTree) tree; - if (method.parameters().size() == 1) { - MethodSymbol symbol = method.symbol(); - reportIssue(method.simpleName(), "Never do that!"); - } -} - -``` - -From the symbol, it is then pretty easy to retrieve **the type of its first parameter**, as well as the **return type** (You may have to import `org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol` and `org.sonar.plugins.java.api.semantic.Type`). - -```java -@Override -public void visitNode(Tree tree) { - MethodTree method = (MethodTree) tree; - if (method.parameters().size() == 1) { - Symbol.MethodSymbol symbol = method.symbol(); - Type firstParameterType = symbol.parameterTypes().get(0); - Type returnType = symbol.returnType().type(); - reportIssue(method.simpleName(), "Never do that!"); - } -} -``` - -Since the rule should only raise an issue when these two types are the same, we then simply test if the return type is the same as the type of the first parameter using method `is(String fullyQualifiedName)`, provided through the `Type` class, before raising the issue. - -```java -@Override -public void visitNode(Tree tree) { - MethodTree method = (MethodTree) tree; - if (method.parameters().size() == 1) { - Symbol.MethodSymbol symbol = method.symbol(); - Type firstParameterType = symbol.parameterTypes().get(0); - Type returnType = symbol.returnType().type(); - if (returnType.is(firstParameterType.fullyQualifiedName())) { - reportIssue(method.simpleName(), "Never do that!"); - } - } -} -``` - -Now, **execute the test** class again. - -Test passed? If not, then check if you somehow missed a step. - -If it passed... - -> -> :tada: **Congratulations!** :confetti_ball: -> -> [*You implemented your first custom rule for the SonarQube Java Analyzer!*](resources/success.jpg) -> +[Use the semantic API to compare types and finish the implementation.](custom-rules/implementing-the-rule.md#second-version-using-semantic-api) ### What you can use, and what you can't -When writing custom Java rules, you can only use classes from package [org.sonar.plugins.java.api](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/java-frontend/src/main/java/org/sonar/plugins/java/api). - -When browsing the existing 600+ rules from the SonarSource Analyzer for Java, you will sometime notice the use of some other utility classes, is not part of the API. -While these classes could be sometime extremely useful in your context, **these classes are not available at runtime** for custom rule plugins. -It means that, while your unit tests are still going to pass when building your plugin, your rules will most likely make analysis **crash at analysis time**. - -Note that we are always open to discussion, so don't hesitate to reach us and participate in threads, through our [community forum](https://community.sonarsource.com/), to suggest features and API improvement! +[Check which parts of the Java Analyzer API are available to custom rules.](custom-rules/implementing-the-rule.md#what-you-can-use-and-what-you-cant) ## Registering the rule in the custom plugin -OK, you are probably quite happy at this point, as our first rule is running as expected... -However, we are not really done yet. -Before playing our rule against any real projects, we have to finalize its creation within the custom plugin, by registering it. +[Register the rule so SonarQube can list and run it.](custom-rules/registering-the-rule.md) ### Rule Metadata -The first thing to do is to provide our rule with all the metadata which will allow us to register it properly in the SonarQube platform. -There are two ways to add metadata for your rule: -* annotation and -* static documentation. - -While annotation provides a handy way to document the rule, static documentation offers the possibility for richer information. -Incidentally, static documentation is also the way rules in the sonar-java analyzer are described. - -To provide metadata for your rule, you need to create an HTML file, where you can provide an extended textual description of the rule, and a JSON file, with the actual metadata. -In the case of `MyFirstCustomRule`, you will head to the `src/main/resources/org/sonar/l10n/java/rules/java/` folder to create `MyFirstCustomRule.html` and `MyFirstCustomRule.json`. - -We first need to populate the HTML file with some information that will help developers fix the issue. - -```html -

For a method having a single parameter, the types of its return value and its parameter should never be the same.

- -

Noncompliant Code Example

-
-class MyClass {
-  int doSomething(int a) { // Noncompliant
-    return 42;
-  }
-}
-
- -

Compliant Solution

-
-class MyClass {
-  int doSomething() { // Compliant
-    return 42;
-  }
-  long doSomething(int a) { // Compliant
-    return 42L;
-  }
-}
-
-``` - -We can now add metadata to `src/main/resources/org/sonar/l10n/java/rules/java/MyFirstCustomRule.json`: - -```json -{ - "title": "Return type and parameter of a method should not be the same", - "type": "Bug", - "status": "ready", - "tags": [ - "bugs", - "gandalf", - "magic" - ], - "defaultSeverity": "Critical" -} -``` - -With this example, we have a concise but descriptive `title` for our rule, the `type` of an issue it highlights, its status (ready or deprecated), the `tags` that should bring it up in a search, and the `severity` of the issue. +[Add rule metadata and a description.](custom-rules/registering-the-rule.md#rule-metadata) ### Rule Activation -The second thing to do is to activate the rule within the plugin. -To do so, open the class `RulesList` (`org.sonar.samples.java.RulesList`). -In this class, you will notice methods `getJavaChecks()` and `getJavaTestChecks()`. -These methods are used to register our rules alongside the rule of the Java plugin. -Note that rules registered in `getJavaChecks()` will only be played against source files, while rules registered in `getJavaTestChecks()` will only be played against test files. -To register the rule, simply add the rule class to the list builder, as in the following code snippet: - -```java -public static List> getJavaChecks() { - return Collections.unmodifiableList(Arrays.asList( - // other rules... - MyFirstCustomCheck.class - )); -} - -``` +[Add the rule to the plugin's list of Java checks.](custom-rules/registering-the-rule.md#rule-activation) ### Rule Registrar -Because your rules are relying on the SonarSource Analyzer for Java API, you also need to tell the parent Java plugin that some new rules have to be retrieved. -If you are using the template custom plugin as a base of this tutorial, you should have everything done already, but feel free to have a look at the `MyJavaFileCheckRegistrar.java` class, which connects the dots. -Finally, be sure that this registrar class is also correctly added as an extension for your custom plugin, by adding it to your Plugin definition class (`MyJavaRulesPlugin.java`). - -```java -/** - * Provide the "checks" (implementations of rules) classes that are going to be executed during - * source code analysis. - * - * This class is a batch extension by implementing the {@link org.sonar.plugins.java.api.CheckRegistrar} interface. - */ -@SonarLintSide -public class MyJavaFileCheckRegistrar implements CheckRegistrar { - - /** - * Register the classes that will be used to instantiate checks during analysis. - */ - @Override - public void register(RegistrarContext registrarContext) { - // Call to registerClassesForRepository to associate the classes with the correct repository key - registrarContext.registerClassesForRepository(MyJavaRulesDefinition.REPOSITORY_KEY, checkClasses(), testCheckClasses()); - } - - - /** - * Lists all the main checks provided by the plugin - */ - public static List> checkClasses() { - return RulesList.getJavaChecks(); - } - - /** - * Lists all the test checks provided by the plugin - */ - public static List> testCheckClasses() { - return RulesList.getJavaTestChecks(); - } - -} -``` - -To do so, navigate to its corresponding test class, named `MyJavaFileCheckRegistrarTest`, add your rule key to the end of the mainRuleKeys list and your rule class name at the end of the mainCheckClasses list. - -```java - -class MyJavaFileCheckRegistrarTest { - - @Test - void checkRegisteredRulesKeysAndClasses() { - TestCheckRegistrarContext context = new TestCheckRegistrarContext(); - - MyJavaFileCheckRegistrar registrar = new MyJavaFileCheckRegistrar(); - registrar.register(context); - - assertThat(context.mainRuleKeys).extracting(RuleKey::toString).containsExactly( - // other rules... - "mycompany-java:MyFirstCustomRule"); - - assertThat(context.mainCheckClasses).extracting(Class::getSimpleName).containsExactly( - // other rules... - "MyFirstCustomCheck"); - - assertThat(context.testRuleKeys).extracting(RuleKey::toString).containsExactly( - "mycompany-java:NoIfStatementInTests"); - - assertThat(context.testCheckClasses).extracting(Class::getSimpleName).containsExactly( - "NoIfStatementInTestsRule"); - } - -} -``` +[Review the registrar and update its test.](custom-rules/registering-the-rule.md#rule-registrar) ### Rules repository -With the actions taken above, your rule is activated, registered, and should be ready to test. -But before doing so, you may want to customize the repository name your rule belongs to. - -This repository's key and name are defined in `MyJavaRulesDefinition.java` and can be customized to suit your needs. - -```java -public class MyJavaRulesDefinition implements RulesDefinition { - // ... - public static final String REPOSITORY_KEY = "fellowship-inc"; - - public static final String REPOSITORY_NAME = "The Fellowship's custom rules"; - // ... -} -``` +[Customize the rule repository name and key.](custom-rules/registering-the-rule.md#rules-repository) ## Testing a custom plugin -> -> :exclamation: **Prerequisite** -> -> For this chapter, you will need a local instance of SonarQube. -> If you don't have a SonarQube platform installed on your machine, now is the time to download its latest version from [HERE](https://www.sonarqube.org/downloads/)! -> - -At this point, we've completed the implementation of the first custom rule and registered it into the custom plugin. -The last remaining step is to test it directly with the SonarQube platform and try to analyze a project! - -Start by building the project using Maven. Note that here we are using the self-contained `pom` file targeting SonarQube `9.9` LTS. -If you renamed it into `pom.xml`, remove the `-f pom_SQ_9_9_LTS.xml` part of the following command): - -``` -$ pwd -/home/gandalf/workspace/sonar-java/docs/java-custom-rules-example - -$ mvn clean install -f pom_SQ_9_9_LTS.xml -[INFO] Scanning for projects... -[INFO] -[INFO] ------------------------------------------------------------------------ -[INFO] Building SonarQube Java :: Documentation :: Custom Rules Example 1.0.0-SNAPSHOT -[INFO] ------------------------------------------------------------------------ - -... - -[INFO] ------------------------------------------------------------------------ -[INFO] BUILD SUCCESS -[INFO] ------------------------------------------------------------------------ -[INFO] Total time: 8.762 s -[INFO] Finished at: 2021-03-02T12:17:28+01:00 -[INFO] ------------------------------------------------------------------------ -``` - -Then, grab the jar file `java-custom-rules-example-1.0.0-SNAPSHOT.jar` from the `target` folder of the project, and move it to the extensions folder of your SonarQube instance, which will be located at `$SONAR_HOME/extensions/plugins`. - -> -> :exclamation: **SonarQube Java Plugin compatible version** -> -> Before going further, be sure to have the adequate version of the SonarQube Java Analyzer with your SonarQube instance. -> The dependency over the Java Analyzer of our custom plugin is defined in its `pom`, as seen in the first chapter of this tutorial. -> We consequently provide two distinct `pom` files mapping both the `8.9` previous LTS version of SonarQube, as well as the latest LTS release, version `9.9`. -> -> * If you are using a SonarQube `9.9` and updated to the latest LTS already, then you won't have the possibility to update the Java Analyzer independently anymore. -> * Consequently, use the file `pom_SQ_9_9_LTS.xml` to build the project. -> - -Now, (re-)start your SonarQube instance, log in as admin, and navigate to the ***Rules*** tab. - -From there, under the language section, select "**Java**", and then "**The Fellowship's custom rules**" (or "**MyCompany Custom Repository**" if you did not change it) under the repository section. -Your rule should now be visible (with all the other sample rules). - -![Selected rules](resources/rules_selected.png) - -Once activated (not sure how? see [quality-profiles](https://docs.sonarqube.org/latest/instance-administration/quality-profiles/)), the only step remaining is to analyze one of your projects! - -When encountering a method returning the same type as its parameter, the custom rule will now raise an issue, as visible in the following picture: - -![Issues](resources/issues.png) +[Deploy the custom plugin to SonarQube and activate the rule.](custom-rules/testing-a-custom-plugin.md) ### How to define rule parameters -You have to add a `@RuleProperty` to your Rule. - -Check this example: [SecurityAnnotationMandatoryRule.java](https://github.com/SonarSource/sonar-java/blob/7.16.0.30901/docs/java-custom-rules-example/src/main/java/org/sonar/samples/java/checks/SecurityAnnotationMandatoryRule.java) +[Define configurable parameters for a rule.](custom-rules/testing-a-custom-plugin.md#how-to-define-rule-parameters) ### How to test sources requiring external binaries -In the `pom.xml`, define in the `Maven Dependency Plugin` part all the JARs you need to run your Unit Tests. -For example, if your sample code used in your Unit Tests is having a dependency on Spring, add it there. - -See: [pom_SQ_10_6_LATEST.xml#L168-L227](./java-custom-rules-example/pom_SQ_10_6_LATEST.xml#L168-L227) +[Add external libraries to the test classpath.](custom-rules/testing-a-custom-plugin.md#how-to-test-sources-requiring-external-binaries) ### How to test precise issue location -You can raise an issue on a given line, but you can also raise it at a specific Token. -Because of that, you may want to specify, in your sample code used by your Unit Tests, the exact location, i.e. in between which 2 specific Columns, where you are expecting the issue to be raised. - -> **Deprecated** -> ->This can be achieved using the special keywords `sc` (start-column) and `ec` (end-column) in the `// Noncompliant` comment. ->In the following example, we are expecting to have the issue being raised between the columns 27 and 32 (i.e. exactly on the "Order" variable type): -> ```java -> public String updateOrder(Order order){ // Noncompliant [[sc=27;ec=32]] {{Don't use Order here because it's an @Entity}} -> // ... -> } -> ``` - -Assert precise primary location of an issue with the comment on a line below containing required number of `^`. -```java -public String updateOrder(Order order){ // Noncompliant {{Don't use Order here because it's an @Entity}} -// ^^^^^ - // ... -} -``` -More information on how to test precise issue location can be found in: [SonarSource Analyzer Test Commons](https://github.com/SonarSource/sonar-analyzer-commons/tree/master/test-commons) library. - +[Assert an issue's exact location in a test sample.](custom-rules/testing-a-custom-plugin.md#how-to-test-precise-issue-location) ### How to test the Source Version in a rule -Starting from **Java Plugin API 3.7** (October 2015), the Java source version can be accessed directly when writing custom rules. -This can be achieved by simply calling the method `getJavaVersion()` from the context. -Note that the method will return null only when the property is not set. -Similarly, it is possible to specify to the verifier a version of Java to be considered as runtime execution, calling method `verify(String filename, JavaFileScanner check, int javaVersion)`. - -```java -@Beta -public interface JavaFileScannerContext { - - // ... - - @Nullable - Integer getJavaVersion(); - -} -``` +[Set the Java source version in a rule test.](custom-rules/testing-a-custom-plugin.md#how-to-test-the-source-version-in-a-rule) ## References -* [Analysis of Java code documentation](https://docs.sonarqube.org/latest/analysis/languages/java/) -* [SonarQube Platform](http://www.sonarqube.org/) -* [SonarSource Code Quality and Security for Java Github Repository](https://github.com/SonarSource/sonar-java) -* [SonarQube Java Custom-Rules Example](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/docs/java-custom-rules-example) +[Find related documentation and example code.](custom-rules/index.md#references) diff --git a/docs/adrs/index.md b/docs/adrs/index.md new file mode 100644 index 00000000000..87b38ad4b2d --- /dev/null +++ b/docs/adrs/index.md @@ -0,0 +1,12 @@ +--- +title: Engineering decisions +description: Find the SonarJava engineering decisions that are in force and the reasons for them. +generated: + by: tirion +--- + +# Engineering decisions + +- [Do not add abstract base classes for rules](no-abstract-rule-bases.md): read before sharing logic across checks. `docs/adrs/no-abstract-rule-bases.md` +- [Keep new rules stateless](stateless-rules.md): read before storing data on a check instance. `docs/adrs/stateless-rules.md` +- [Write new tests in JUnit 5](junit-5.md): read before adding a test class. `docs/adrs/junit-5.md` diff --git a/docs/adrs/junit-5.md b/docs/adrs/junit-5.md new file mode 100644 index 00000000000..26fad7286e5 --- /dev/null +++ b/docs/adrs/junit-5.md @@ -0,0 +1,22 @@ +--- +title: Write new tests in JUnit 5 +description: Use JUnit Jupiter for new tests so that tests run under Maven Surefire as well as in the IDE. +generated: + by: tirion +--- + +# Write new tests in JUnit 5 + +## Decision + +Use JUnit Jupiter for new tests, including rule tests that use `CheckVerifier`. Import `org.junit.jupiter.api.Test`, not `org.junit.Test`. The forbiddenapis configurations in `java-checks/pom.xml` and `sonar-java-plugin/pom.xml` use `forbid_junit4.txt` to reject JUnit 4 signatures. + +## Rationale + +JUnit migration support can leave JUnit 4 types on the classpath. IntelliJ IDEA can still run a JUnit 4 test, while Surefire without the JUnit Vintage engine silently omits it. A successful IDE run does not prove that CI ran the test. + +## Alternative + +Running new tests on both engines would keep the ambiguity about which tests execute and preserve two sets of conventions. Existing Orchestrator harnesses can still use JUnit 4, as in `its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java`; do not copy those harness conventions into unit tests. + +See [Rule tests](../systems/rule-tests.md) for a verifier example. diff --git a/docs/adrs/no-abstract-rule-bases.md b/docs/adrs/no-abstract-rule-bases.md new file mode 100644 index 00000000000..fe136b3079d --- /dev/null +++ b/docs/adrs/no-abstract-rule-bases.md @@ -0,0 +1,23 @@ +--- +title: Do not add abstract base classes for rules +description: Keep rules independent by sharing utilities rather than inheriting behavior from another rule implementation. +generated: + by: tirion +--- + +# Do not add abstract base classes for rules + +## Decision + +Do not introduce abstract classes for checks to inherit from. Implement each rule on the analyzer's existing scanner API. Extract shared operations into utility classes or compose a helper with its own narrow responsibility. + +## Rationale + +Rules need to evolve independently as their detection criteria and exceptions change. An abstract rule base couples subscribers, traversal, reporting or state so a fix for one rule can change another rule. With composition, each caller opts into the shared behavior and keeps its own lifecycle. + +## Alternatives + +- **Shared abstract check:** reduces initial duplication but makes changes harder to isolate. Do not extend this pattern just because an existing family uses it. +- **Copy all logic into each rule:** preserves independence but leaves common semantic operations to drift. Share a utility when the behavior genuinely has the same contract for all callers. + +See [Writing SonarJava rules](../systems/rule-api.md) for the framework visitor choices; reusing those framework classes is not the kind of inheritance prohibited here. diff --git a/docs/adrs/stateless-rules.md b/docs/adrs/stateless-rules.md new file mode 100644 index 00000000000..f52c9c6e66b --- /dev/null +++ b/docs/adrs/stateless-rules.md @@ -0,0 +1,24 @@ +--- +title: Keep new rules stateless +description: Keep new file-level rules free of mutable scan state because rule instances are reused across files. +generated: + by: tirion +--- + +# Keep new rules stateless + +## Decision + +New file-level checks must not store data from a scan in check fields. Use immutable constants and keep collections, counters and AST references local to callbacks or to a helper created for the current file. If a check needs to correlate nodes, start at their nearest enclosing method, class or compilation unit and collect the data locally. + +Platform-injected `@RuleProperty` values and flags computed by `DependencyVersionAware` are configuration, not scan state. Do not mutate them during file analysis. A visitor that uses a field for `JavaFileScannerContext` must confine it to that scan; prefer a local visitor that receives the context. + +When a rule truly requires module-wide evidence, isolate its aggregation from per-file traversal and follow [Project-level rules](../systems/project-level-rules.md). + +## Rationale + +`java-frontend/src/main/java/org/sonar/java/model/VisitorsBridge.java` uses the same scanners for multiple files. Scan data left in a rule can make findings depend on file order and retain parser or semantic objects after a file finishes. + +## Alternative + +Mutable fields plus `clearState()` are supported for existing `IssuableSubscriptionVisitor` checks. They are not the default for new checks: it is easy to add a field without adding it to cleanup, whereas callback-local data cannot leak into the next file. See [Writing SonarJava rules](../systems/rule-api.md) for maintaining existing stateful checks. diff --git a/docs/custom-rules/getting-started.md b/docs/custom-rules/getting-started.md new file mode 100644 index 00000000000..92c58700f21 --- /dev/null +++ b/docs/custom-rules/getting-started.md @@ -0,0 +1,69 @@ +--- +title: Getting started with custom Java rules +description: Set up the Maven example project and identify the plugin settings that need to match your SonarQube server. +generated: + by: tirion +--- + +# Getting started + +Your rules will be delivered in a dedicated plugin that uses the SonarQube Java Analyzer API. Clone [this repository](https://github.com/SonarSource/sonar-java) and import the [example Maven project](https://github.com/SonarSource/sonar-java/tree/master/docs/java-custom-rules-example) into your IDE. The project already contains working custom rules. In this tutorial, you'll add another one. + +## Looking at the POM + +The [example project](../java-custom-rules-example/index.md) has two Maven POMs: + +- [`pom.xml`](../java-custom-rules-example/pom.xml) is part of the SonarJava reactor build and uses its snapshot of the Java Analyzer. It compiles the example with Java 21. +- [`pom_SQ_10_6_LATEST.xml`](../java-custom-rules-example/pom_SQ_10_6_LATEST.xml) builds independently of the reactor and pins the dependencies for the SonarQube 10.6 example. Despite the filename, it does not track the latest SonarQube release. + +This tutorial uses the standalone POM. Use Maven with JDK 21 for the tutorial; the standalone POM targets Java 8 bytecode, which is separate from the JDK used to run the build. From the repository root, run: + +```sh +cd docs/java-custom-rules-example +mvn clean install -f pom_SQ_10_6_LATEST.xml +``` + +Keep both POMs in place. Use `-f pom_SQ_10_6_LATEST.xml` when running Maven commands for the standalone example, or select that POM when importing the project into your IDE. + +SonarQube ships with a specific version of the Java Analyzer. For example, SonarQube 8.9 shipped with version `6.15.1.26025`, and SonarQube 10.6 shipped with version `8.0.1.36337`. When building for a different SonarQube release, check which Java Analyzer and plugin API versions it supports before changing the pinned dependencies; do not assume the 10.6 example works unchanged. + +```xml + + 10.7.0.2191 + 8.0.1.36337 + + +``` + +You can customize tags such as ``, ``, ``, ``, and ``: + +```xml +org.sonar.samples +java-custom-rules-example +1.0.0-SNAPSHOT +SonarQube Java :: Documentation :: Custom Rules Example +Java Custom Rules Example for SonarQube +``` + +The plugin's entry point is `` in the `sonar-packaging-maven-plugin` configuration. Change it if you rename or move `MyJavaRulesPlugin`, the class that implements `org.sonar.api.Plugin`. + +Starting with SonarJava 7.30, set `` to `java`. This ensures that the custom plugin loads only when the analyzed project contains Java code, so it does not try to initialize without the Java Analyzer. + +```xml + + org.sonarsource.sonar-packaging-maven-plugin + sonar-packaging-maven-plugin + true + + java-custom + Java Custom Rules + org.sonar.samples.java.MyJavaRulesPlugin + true + true + java:${sonarjava.version} + java + + +``` + +Next: [Write a rule specification and a failing test](writing-a-rule.md) · [Tutorial index](index.md) diff --git a/docs/custom-rules/implementing-the-rule.md b/docs/custom-rules/implementing-the-rule.md new file mode 100644 index 00000000000..722918eae24 --- /dev/null +++ b/docs/custom-rules/implementing-the-rule.md @@ -0,0 +1,129 @@ +--- +title: Implementing a custom Java rule +description: Use syntax trees and the semantic API to implement the rule and make its unit test pass. +generated: + by: tirion +--- + +# Implementing the rule + +Before you start, [write the rule specification and failing test](writing-a-rule.md). + +## First version: Using syntax trees and API basics + +Before running any rule, the SonarQube Java Analyzer parses the Java file into a **syntax tree**. Each Java language construct has a tree `Kind` and an interface describing it. For example, a method declaration has kind `org.sonar.plugins.java.api.tree.Tree.Kind.METHOD` and implements `org.sonar.plugins.java.api.tree.MethodTree`. All kinds are listed in the [`Kind` enum of the Java Analyzer API](https://github.com/SonarSource/sonar-java/blob/7.16.0.30901/java-frontend/src/main/java/org/sonar/plugins/java/api/tree/Tree.java#L47). + +`IssuableSubscriptionVisitor` lets a rule subscribe to specific node kinds in `nodesToVisit()` and report issues on the nodes it visits. Our initial implementation returned an empty list, so it received no nodes. In `MyFirstCustomCheck`, replace `nodesToVisit()` to subscribe to method declarations: + +```java +@Override +public List nodesToVisit() { + return Collections.singletonList(Kind.METHOD); +} +``` + +Override `visitNode(Tree tree)` to decide what to do for each method declaration. Import `org.sonar.plugins.java.api.tree.Tree`: + +```java +@Override +public void visitNode(Tree tree) { +} +``` + +Because the rule subscribes only to `Kind.METHOD`, it can safely cast each node to a `MethodTree`. Import `org.sonar.plugins.java.api.tree.MethodTree`. If you subscribe to multiple kinds, use `Tree.is(Kind... kind)` to check the node kind before casting. + +```java +@Override +public void visitNode(Tree tree) { + MethodTree method = (MethodTree) tree; +} +``` + +First, check that the method has a single parameter and report an issue if it does: + +```java +@Override +public void visitNode(Tree tree) { + MethodTree method = (MethodTree) tree; + if (method.parameters().size() == 1) { + reportIssue(method.simpleName(), "Never do that!"); + } +} +``` + +The `reportIssue(Tree tree, String message)` method reports an issue with the specified message at the location of the given tree. Passing `method.simpleName()` puts the issue precisely on the method name. + +Run `MyFirstCustomCheckTest.test()` again. The verifier reports three extra issues: + +```text +java.lang.AssertionError: Unexpected at [5, 7, 11] +``` + +In the [sample file](writing-a-rule.md#a-test-file-to-rule-them-all), line 5 returns `void`, line 7 returns `Object` instead of `int`, and line 11 has a variable-arity parameter, whose type is `int[]`, not `int`. The current implementation treats all one-parameter methods alike. To distinguish these cases, the rule needs type information from the semantic API. + +> **When to use `BaseTreeVisitor`** +> +> `IssuableSubscriptionVisitor` is convenient when a rule only needs to visit a few kinds of nodes. If you need more control over traversing the tree, `org.sonar.plugins.java.api.tree.BaseTreeVisitor` has a dedicated visit method for each kind of node. +> +> In the [rules already implemented in the Java Plugin](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/java-checks/src/main/java/org/sonar/java/checks), some checks use an `IssuableSubscriptionVisitor` as the entry point and a `BaseTreeVisitor` to find a pattern elsewhere in the code. + +## Second version: Using semantic API + +In addition to the syntax tree, the analyzer constructs a **semantic model**. It represents declarations and references as **symbols**. A method symbol, for example, can tell you where the method is declared and used, its parameter and return types, and which exceptions it can throw. Explore the [semantic package of the API](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/java-frontend/src/main/java/org/sonar/plugins/java/api/semantic) for more examples. + +Once you know the method has a single parameter, get its symbol with `MethodTree.symbol()`. Import `org.sonar.plugins.java.api.semantic.Symbol.MethodSymbol`: + +```java +@Override +public void visitNode(Tree tree) { + MethodTree method = (MethodTree) tree; + if (method.parameters().size() == 1) { + MethodSymbol symbol = method.symbol(); + reportIssue(method.simpleName(), "Never do that!"); + } +} +``` + +The symbol gives you both the **type of its first parameter** and the **return type**. Import `org.sonar.plugins.java.api.semantic.Type`: + +```java +@Override +public void visitNode(Tree tree) { + MethodTree method = (MethodTree) tree; + if (method.parameters().size() == 1) { + MethodSymbol symbol = method.symbol(); + Type firstParameterType = symbol.parameterTypes().get(0); + Type returnType = symbol.returnType().type(); + reportIssue(method.simpleName(), "Never do that!"); + } +} +``` + +Use `Type.is(String fullyQualifiedName)` to report an issue only if the parameter type and return type match: + +```java +@Override +public void visitNode(Tree tree) { + MethodTree method = (MethodTree) tree; + if (method.parameters().size() == 1) { + MethodSymbol symbol = method.symbol(); + Type firstParameterType = symbol.parameterTypes().get(0); + Type returnType = symbol.returnType().type(); + if (returnType.is(firstParameterType.fullyQualifiedName())) { + reportIssue(method.simpleName(), "Never do that!"); + } + } +} +``` + +Run the test again. It should now pass with issues on `foo3` and `foo5` only. + +[*Congratulations! You implemented your first custom rule for the SonarQube Java Analyzer!*](../resources/success.jpg) + +## What you can use, and what you can't + +Use only the public [SonarJava API](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/java-frontend/src/main/java/org/sonar/plugins/java/api) when calling into the Java Analyzer from a custom rule. Existing rules use internal utilities that are not available to custom rule plugins at runtime. Your unit tests may pass if those utilities are on the test classpath, but your plugin can fail during analysis. + +If you need an API capability that isn't available, suggest it on the [SonarSource community forum](https://community.sonarsource.com/). + +Next: [Register the rule in the custom plugin](registering-the-rule.md) · [Tutorial index](index.md) diff --git a/docs/custom-rules/index.md b/docs/custom-rules/index.md new file mode 100644 index 00000000000..d3e57c2afe3 --- /dev/null +++ b/docs/custom-rules/index.md @@ -0,0 +1,27 @@ +--- +title: Writing Custom Java Rules 101 +description: Learn to write, test, and deploy a custom rule for the SonarQube Java Analyzer. +generated: + by: tirion +--- + +# Writing Custom Java Rules 101 + +If the built-in Java rules do not cover your team's requirements, you can write your own using the SonarQube Java Analyzer API. This tutorial takes you from a rule specification and a failing test to a working rule in a custom plugin. + +## Tutorial + +1. [Getting started](getting-started.md): import the example project and choose the Maven configuration for your target server (`docs/custom-rules/getting-started.md`). +2. [Writing a rule](writing-a-rule.md): specify the rule and create a test that fails before implementation (`docs/custom-rules/writing-a-rule.md`). +3. [Implementing the rule](implementing-the-rule.md): use syntax trees and the semantic API to make the test pass (`docs/custom-rules/implementing-the-rule.md`). +4. [Registering the rule in the custom plugin](registering-the-rule.md): add metadata, register the rule, and update the registration test (`docs/custom-rules/registering-the-rule.md`). +5. [Testing a custom plugin](testing-a-custom-plugin.md): deploy the plugin to SonarQube and activate the rule, or look up additional rule testing techniques (`docs/custom-rules/testing-a-custom-plugin.md`). + +The [example project](../java-custom-rules-example/index.md) in `docs/java-custom-rules-example` contains working custom rules. The [original tutorial URL](../CUSTOM_RULES_101.md) still provides links for older section bookmarks (`docs/CUSTOM_RULES_101.md`). + +## References + +- [Analysis of Java code documentation](https://docs.sonarqube.org/latest/analysis/languages/java/) +- [SonarQube Platform](http://www.sonarqube.org/) +- [SonarSource Code Quality and Security for Java GitHub Repository](https://github.com/SonarSource/sonar-java) +- [SonarQube Java Custom-Rules Example (SonarJava 7.16)](https://github.com/SonarSource/sonar-java/tree/7.16.0.30901/docs/java-custom-rules-example) diff --git a/docs/custom-rules/registering-the-rule.md b/docs/custom-rules/registering-the-rule.md new file mode 100644 index 00000000000..e825a2d1515 --- /dev/null +++ b/docs/custom-rules/registering-the-rule.md @@ -0,0 +1,143 @@ +--- +title: Registering a custom Java rule +description: Add rule metadata, register the check in the custom plugin, and update the registration test. +generated: + by: tirion +--- + +# Registering the rule in the custom plugin + +Once your [rule passes its unit test](implementing-the-rule.md), register it so SonarQube can list and run it. + +## Rule Metadata + +Annotations can describe a rule, while separate metadata files let you provide richer descriptions. The template combines the two: `@Rule` supplies the rule key, and `MyJavaRulesDefinition` uses that key to load an HTML description and JSON metadata. + +In `docs/java-custom-rules-example/src/main/resources/org/sonar/l10n/java/rules/java`, create **MyFirstCustomRule.html** and **MyFirstCustomRule.json**. Use the rule key, not the Java class name, for both filenames. + +In the HTML file, explain the rule and show developers how to fix the issue: + +```html +

For a method having a single parameter, the types of its return value and its parameter should never be the same.

+ +

Noncompliant Code Example

+
+class MyClass {
+  int doSomething(int a) { // Noncompliant
+    return 42;
+  }
+}
+
+ +

Compliant Solution

+
+class MyClass {
+  int doSomething() { // Compliant
+    return 42;
+  }
+  long doSomething(int a) { // Compliant
+    return 42L;
+  }
+}
+
+``` + +In **MyFirstCustomRule.json**, set the title, type, status, tags, and default severity: + +```json +{ + "title": "Return type and parameter of a method should not be the same", + "type": "Bug", + "status": "ready", + "tags": [ + "bugs", + "gandalf", + "magic" + ], + "defaultSeverity": "Critical" +} +``` + +## Rule Activation + +In [`RulesList`](../java-custom-rules-example/src/main/java/org/sonar/samples/java/RulesList.java), list the check among the plugin's Java checks. Checks in `getJavaChecks()` run on main sources, while checks in `getJavaTestChecks()` run on test sources. Add the new check as the last entry in `getJavaChecks()`: + +```java +public static List> getJavaChecks() { + return Collections.unmodifiableList(Arrays.asList( + // Keep the other checks here. + MyFirstCustomCheck.class)); +} +``` + +Import `org.sonar.samples.java.checks.MyFirstCustomCheck` in `RulesList`. [Activation in a quality profile](testing-a-custom-plugin.md) happens after deployment. + +## Rule Registrar + +The Java Analyzer needs to know which checks your plugin provides. The template already supplies [`MyJavaFileCheckRegistrar`](../java-custom-rules-example/src/main/java/org/sonar/samples/java/MyJavaFileCheckRegistrar.java) and adds it as an extension of [`MyJavaRulesPlugin`](../java-custom-rules-example/src/main/java/org/sonar/samples/java/MyJavaRulesPlugin.java). The registrar maps the check lists to the rule repository: + +```java +@SonarLintSide +public class MyJavaFileCheckRegistrar implements CheckRegistrar { + + @Override + public void register(RegistrarContext registrarContext) { + registrarContext.registerClassesForRepository(MyJavaRulesDefinition.REPOSITORY_KEY, checkClasses(), testCheckClasses()); + } + + public static List> checkClasses() { + return RulesList.getJavaChecks(); + } + + public static List> testCheckClasses() { + return RulesList.getJavaTestChecks(); + } + +} +``` + +In [`MyJavaFileCheckRegistrarTest`](../java-custom-rules-example/src/test/java/org/sonar/samples/java/MyJavaFileCheckRegistrarTest.java), keep the existing expectations and append the new rule key and class name to the main-check assertions: + +```java +class MyJavaFileCheckRegistrarTest { + + @Test + void checkRegisteredRulesKeysAndClasses() { + TestCheckRegistrarContext context = new TestCheckRegistrarContext(); + + MyJavaFileCheckRegistrar registrar = new MyJavaFileCheckRegistrar(); + registrar.register(context); + + assertThat(context.mainRuleKeys).extracting(RuleKey::toString).containsExactly( + // Keep the other rule keys here. + "mycompany-java:MyFirstCustomRule"); + + assertThat(context.mainCheckClasses).extracting(Class::getSimpleName).containsExactly( + // Keep the other class names here. + "MyFirstCustomCheck"); + + assertThat(context.testRuleKeys).extracting(RuleKey::toString).containsExactly( + "mycompany-java:NoIfStatementInTests"); + + assertThat(context.testCheckClasses).extracting(Class::getSimpleName).containsExactly( + "NoIfStatementInTestsRule"); + } + +} +``` + +## Rules repository + +Optionally, customize the repository key and display name in [`MyJavaRulesDefinition`](../java-custom-rules-example/src/main/java/org/sonar/samples/java/MyJavaRulesDefinition.java). If you change the repository key, update the repository prefixes in `MyJavaFileCheckRegistrarTest` as well. + +```java +public class MyJavaRulesDefinition implements RulesDefinition { + // ... + public static final String REPOSITORY_KEY = "fellowship-inc"; + + public static final String REPOSITORY_NAME = "The Fellowship's custom rules"; + // ... +} +``` + +Next: [Test the custom plugin in SonarQube](testing-a-custom-plugin.md) · [Tutorial index](index.md) diff --git a/docs/custom-rules/testing-a-custom-plugin.md b/docs/custom-rules/testing-a-custom-plugin.md new file mode 100644 index 00000000000..1177e120f49 --- /dev/null +++ b/docs/custom-rules/testing-a-custom-plugin.md @@ -0,0 +1,69 @@ +--- +title: Testing a custom Java rules plugin +description: Deploy the plugin to a compatible SonarQube instance and learn how to test additional rule behavior. +generated: + by: tirion +--- + +# Testing a custom plugin + +After [registering the rule](registering-the-rule.md), test it on a project using a local SonarQube instance. + +> The standalone POM is pinned for SonarQube 10.6. Use a compatible instance for the tutorial, or adapt the dependencies for your target release as described in [Getting started](getting-started.md#looking-at-the-pom). See the [SonarQube downloads page](https://www.sonarqube.org/downloads/) for available releases. + +1. Rebuild the plugin using the [standalone Maven command](getting-started.md#looking-at-the-pom). The build runs the tests and produces **java-custom-rules-example-1.0.0-SNAPSHOT.jar** in the example project's **target** directory. +2. Copy the JAR into the **extensions/plugins** directory of your SonarQube installation. Restart the instance, sign in as an administrator, and open the **Rules** tab. +3. Filter by **Java** and by the repository **The Fellowship's custom rules** (or **MyCompany Custom Repository** if you kept the defaults). Your rule should appear alongside the other sample rules. + +![Selected rules](../resources/rules_selected.png) + +Activate your new rule in the [quality profile](https://docs.sonarqube.org/latest/instance-administration/quality-profiles/) used by the project, then analyze the project. For this test, leave the template's similar `AvoidMethodWithSameTypeInArgument` rule inactive so you can distinguish the issues your rule reports. + +When the analyzer encounters a method with one parameter whose type matches the return type, the custom rule reports an issue: + +![Issues](../resources/issues.png) + +## How to define rule parameters + +Use `@RuleProperty` on a field in your rule class. See [`SecurityAnnotationMandatoryRule.java`](https://github.com/SonarSource/sonar-java/blob/7.16.0.30901/docs/java-custom-rules-example/src/main/java/org/sonar/samples/java/checks/SecurityAnnotationMandatoryRule.java) for an example. + +## How to test sources requiring external binaries + +If your sample code uses an external library such as Spring, list the required artifacts in the Maven Dependency Plugin configuration of the [standalone POM](../java-custom-rules-example/pom_SQ_10_6_LATEST.xml). The plugin copies the JARs into the example project's **target/test-jars** directory during `test-compile`. Pass them to `CheckVerifier.withClassPath()` as shown in [`SpringControllerRequestMappingEntityRuleTest`](../java-custom-rules-example/src/test/java/org/sonar/samples/java/checks/SpringControllerRequestMappingEntityRuleTest.java). + +## How to test precise issue location + +By default, `// Noncompliant` marks an expected issue on a line. To check its exact primary location, put carets underneath the expected range, as shown here for the `Order` type: + +```java +public String updateOrder(Order order){ // Noncompliant {{Don't use Order here because it's an @Entity}} +// ^^^^^ + // ... +} +``` + +> The older `sc` (start column) and `ec` (end column) markers are deprecated. You may still see tests that use them: +> +> ```java +> public String updateOrder(Order order){ // Noncompliant [[sc=27;ec=32]] {{Don't use Order here because it's an @Entity}} +> // ... +> } +> ``` + +See [SonarSource Analyzer Test Commons](https://github.com/SonarSource/sonar-analyzer-commons/tree/master/test-commons) for more on checking issue locations. + +## How to test the Source Version in a rule + +If a check should only run on certain Java source versions, implement `org.sonar.plugins.java.api.JavaVersionAwareVisitor`. Its `isCompatibleWithJavaVersion(JavaVersion version)` method receives the source version configured through `sonar.java.source`; use `version.isSet()` if you need to distinguish an unset property. The source version is separate from the JDK running the analyzer. + +To set the source version in a unit test, use `withJavaVersion(int)` on the verifier: + +```java +CheckVerifier.newVerifier() + .onFile("src/test/files/MyFirstCustomCheck.java") + .withCheck(new MyFirstCustomCheck()) + .withJavaVersion(17) + .verifyIssues(); +``` + +[Tutorial index](index.md) diff --git a/docs/custom-rules/writing-a-rule.md b/docs/custom-rules/writing-a-rule.md new file mode 100644 index 00000000000..207c301d03f --- /dev/null +++ b/docs/custom-rules/writing-a-rule.md @@ -0,0 +1,131 @@ +--- +title: Writing a custom Java rule +description: Specify your first custom Java rule and write a unit test that fails before the rule is implemented. +generated: + by: tirion +--- + +# Writing a rule + +We will write a custom rule from scratch using [test-driven development](https://en.wikipedia.org/wiki/Test-driven_development) (TDD). Start by writing test cases, then implement the rule against those cases. + +## Three files to forge a rule + +A rule needs at least three files: + +1. A sample file, which contains Java code to analyze in the test. +2. A test class, which runs the rule against the sample file and verifies the issues it reports. +3. A rule class, which implements the rule. + +Create these three files in the [example project](getting-started.md): + +1. In `docs/java-custom-rules-example/src/test/files`, create **MyFirstCustomCheck.java**: + + ```java + class MyClass { + } + ``` + +2. In `docs/java-custom-rules-example/src/test/java/org/sonar/samples/java/checks`, create **MyFirstCustomCheckTest.java**: + + ```java + package org.sonar.samples.java.checks; + + import org.junit.jupiter.api.Test; + + class MyFirstCustomCheckTest { + + @Test + void test() { + } + + } + ``` + +3. In `docs/java-custom-rules-example/src/main/java/org/sonar/samples/java/checks`, create **MyFirstCustomCheck.java**. Extend `IssuableSubscriptionVisitor` and leave `nodesToVisit()` empty for now: + + ```java + package org.sonar.samples.java.checks; + + import java.util.Collections; + import java.util.List; + import org.sonar.check.Rule; + import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; + import org.sonar.plugins.java.api.tree.Tree.Kind; + + @Rule(key = "MyFirstCustomRule") + public class MyFirstCustomCheck extends IssuableSubscriptionVisitor { + + @Override + public List nodesToVisit() { + return Collections.emptyList(); + } + + } + ``` + +> Rules that take parameters or depend on the Java source version may need multiple sample files. You can also add external metadata files such as an HTML description when you [register the rule](registering-the-rule.md#rule-metadata). + +## A specification to make it right + +Before writing any more code, we need a specification. For this exercise, we'll borrow one from a famous wizard: + +> **Gandalf — Why Program When Magic Rulez (WPWMR, p.42)** +> +> *“For a method having a single parameter, the types of its return value and its parameter should never be the same.”* + +## A test file to rule them all + +Start with examples the rule will encounter, and use a trailing `// Noncompliant` comment on each line where the rule should raise an issue. The sample file should compile. Cover the cases that affect the result, not irrelevant details such as the method name or body, or whether the method belongs to a concrete class, an abstract class, or an interface. + +Replace the contents of **MyFirstCustomCheck.java** **in the sample folder** with: + +```java +class MyClass { + MyClass(MyClass mc) { } + + int foo1() { return 0; } + void foo2(int value) { } + int foo3(int value) { return 0; } // Noncompliant + Object foo4(int value) { return null; } + MyClass foo5(MyClass value) { return null; } // Noncompliant + + int foo6(int value, String name) { return 0; } + int foo7(int ... values) { return 0; } +} +``` + +The test file now contains the following cases: + +- **Line 2:** A constructor, which the rule should distinguish from a method. +- **Line 4:** A method without parameters (`foo1`). +- **Line 5:** A method returning `void` (`foo2`). +- **Line 6:** A method returning the same primitive type as its parameter (`foo3`), which is noncompliant. +- **Line 7:** A method with a single parameter but a different return type (`foo4`). +- **Line 8:** Another noncompliant method, this time with the same reference type for both its parameter and return type (`foo5`). +- **Line 10:** A method with more than one parameter (`foo6`). +- **Line 11:** A method with a variable-arity parameter (`foo7`). + +## A test class to make it pass + +In `MyFirstCustomCheckTest`, import `org.sonar.java.checks.verifier.CheckVerifier` and use it to run your check against the sample. The path passed to `onFile()` is relative to the example project directory. + +```java + @Test + void test() { + CheckVerifier.newVerifier() + .onFile("src/test/files/MyFirstCustomCheck.java") + .withCheck(new MyFirstCustomCheck()) + .verifyIssues(); + } +``` + +`CheckVerifier` initializes the analyzer and checks that the rule reports issues on the lines marked `Noncompliant`, and nowhere else. + +Run the test with JUnit. Because `nodesToVisit()` is still empty, the check cannot raise any issues, so the test should fail: + +```text +java.lang.AssertionError: No issue raised. At least one issue expected +``` + +Next: [Implement the rule using syntax trees and the semantic API](implementing-the-rule.md) · [Tutorial index](index.md) diff --git a/docs/documentation-conventions.md b/docs/documentation-conventions.md new file mode 100644 index 00000000000..ef975042e2d --- /dev/null +++ b/docs/documentation-conventions.md @@ -0,0 +1,40 @@ +--- +title: Documentation conventions +description: Keep public SonarJava documentation current, discoverable and checkable. +sources: + - resource: "5739839551" +generated: + by: tirion +--- + +# Documentation conventions + +`docs/` is the single documentation root. Keep the public custom-rule tutorial, Maven example and assets there together so the tutorial and its executable example stay in sync without changing the Maven reactor or public entry URL. Module READMEs may stay next to code but should link to the canonical engineering instructions instead of repeating them. + +- `docs/systems/` describes current behavior, constraints and boundaries that are not apparent from code alone. +- `docs/adrs/` records decisions in force: what we require, why, and why alternatives do not fit. Delete superseded decisions; Git preserves history. +- `docs/custom-rules/` contains the public tutorial topics. `docs/java-custom-rules-example/` is the buildable example, not a separate documentation root. +- Keep an index file in every directory that holds documentation, following the example in `docs/index.md`. Assets and source-only directories do not need an index. Each doc must be reachable from `AGENTS.md` via indexes or direct pointers. + +## Write and cite + +1. Use one topic and one authoritative home per fact. Lead with the code or CI entry point and explain why a constraint exists; add a short Javadoc pointer from key entry classes to the relevant doc rather than paraphrasing the doc in code. +2. Write repo path references as plain backticked paths relative to the root, for example `java-frontend/pom.xml`. Use exact case, no elisions or globs. Use relative Markdown links for navigation and anchors. Put example paths and invocations in appropriately labeled code fences, distinct from actual repo pointers. +3. Describe only current public-safe facts, using names from code. Do not copy internal pages, future plans, release logs or private URLs. Cite access-controlled facts by stable resource ID and explain how an authorized reader can retrieve them. +4. Update the doc in the same change as the code or workflow it describes. Keep root `AGENTS.md` at most 150 lines outside tool-managed blocks, and other managed Markdown at most 300 lines. Keep tool-managed blocks between their markers. +5. Keep skills canonical under `.agents/skills/`, with only pointers in per-tool adapters. Link each skill and any component `AGENTS.md` from the root. + +## OKF metadata + +Each Markdown file under `docs/` starts with YAML frontmatter. Use a title and a one-sentence description. Record `generated.by` as the tool's name for agent-written docs. Add a `sources` list of `resource` IDs or public URLs for Jira or Confluence facts. Only the root `docs/index.md` declares `okf_version: "0.2"`. Use `stale_after` only when a document has a real expiry; omit it for living docs. + +```yaml +--- +title: Example topic +description: Explain when the example applies and what it requires. +generated: + by: tirion +--- +``` + +The [documentation workflow](../.github/workflows/docs.yml) validates the bundle and agent entry points on every pull request. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 00000000000..6ea991576e3 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,15 @@ +--- +title: SonarJava documentation +description: Find engineering guidance, decisions in force and the custom Java rules tutorial. +okf_version: "0.2" +generated: + by: tirion +--- + +# SonarJava documentation + +- [Documentation conventions](documentation-conventions.md): read before editing guidance. +- [Systems](systems/index.md): read before changing analysis, rule tests, build or release behavior. +- [Decisions in force](adrs/index.md): read before introducing new rule or test patterns. +- [Writing custom Java rules](CUSTOM_RULES_101.md): start here when developing a custom-rule plugin. +- [Custom-rule plugin example](java-custom-rules-example/index.md): build and inspect the example project. diff --git a/docs/java-custom-rules-example/README.md b/docs/java-custom-rules-example/README.md index f069e30efb1..664a4d1d6a9 100644 --- a/docs/java-custom-rules-example/README.md +++ b/docs/java-custom-rules-example/README.md @@ -1,17 +1,17 @@ -SonarQube Java Custom Rules Plugin Template -======= +--- +title: SonarQube Java custom rules plugin template +description: Use this example plugin as a starting point for writing custom rules for the SonarQube Java Analyzer. +generated: + by: tirion +--- -This example demonstrates how to write **Custom Rules** for SonarJava. +# SonarQube Java custom rules plugin template -If you are using SonarQube 9.9 LTS (latest release), use the following command to build it without any dependency to the current project status: +This example contains custom rules, their metadata and tests, and the code that registers the rules with the SonarQube Java Analyzer. -``` -mvn clean install -f pom_SQ_9_9_LTS.xml -``` +See [Getting started](../custom-rules/getting-started.md) for the JDK and Maven setup, the standalone build command, and the difference between the two POMs. Follow [Writing Custom Java Rules 101](../custom-rules/index.md) to add and test a rule of your own. -For more details about how to write custom rules, please refer to the official tutorial, [Writing Custom Java Rules 101](../CUSTOM_RULES_101.md). +## License -### License - -The [SSALv1](https://www.sonarsource.com/license/ssal/) license of this GitHub repository does not apply in the `java-custom-rules-example` directory. -All contents under the `java-custom-rules-example` directory are licensed under the more permissive [MIT No Attribution](LICENSE.txt) license. +The [SSALv1](https://www.sonarsource.com/license/ssal/) license of this GitHub repository does not apply in the `docs/java-custom-rules-example` directory. +All contents under the `docs/java-custom-rules-example` directory are licensed under the more permissive [MIT No Attribution](LICENSE.txt) license. diff --git a/docs/java-custom-rules-example/index.md b/docs/java-custom-rules-example/index.md new file mode 100644 index 00000000000..9845bc3311b --- /dev/null +++ b/docs/java-custom-rules-example/index.md @@ -0,0 +1,12 @@ +--- +title: Custom Java rules example project +description: Find the example project README, its Maven configurations, and the custom Java rules tutorial. +generated: + by: tirion +--- + +# Custom Java rules example project + +- [Project README](README.md): what the template contains and how it is licensed (`docs/java-custom-rules-example/README.md`). +- [Getting started](../custom-rules/getting-started.md): JDK and Maven setup, which POM to use, and the build command. +- [Writing Custom Java Rules 101](../custom-rules/index.md): the full tutorial, from writing a rule to deploying it. diff --git a/docs/systems/build.md b/docs/systems/build.md new file mode 100644 index 00000000000..e1009e3d8ac --- /dev/null +++ b/docs/systems/build.md @@ -0,0 +1,43 @@ +--- +title: Setup, build and test commands +description: Build SonarJava and choose the appropriate test command and JDK. +generated: + by: tirion +--- + +# Setup, build and test commands + +`mise.toml` defines Maven 3.9 and Java 26, 21 and 17. Use JDK 26 for a full build, analyzer unit tests and compiling the test-source reactor. Use JDK 21 for Plugin QA and Ruling QA, as in `.github/workflows/build.yml`. `jdk.min.version` in `pom.xml` sets the plugin runtime minimum to 21, not the JDK needed to compile all test samples. + +From the repository root, with [mise](https://mise.jdx.dev/) and Python 3.10+ installed: + +```bash +mise install +mise tasks +mise run doctor +mise run check +``` + +`doctor` reports prerequisites for each task without installing tools or displaying credentials. Maven tasks require Repox access and Maven credentials. `check` runs the unit tests, dependency license check, custom-rules example and sanity test. Use `build` to install reactor artifacts without running tests. `test:unit` runs without JaCoCo unless you add `--coverage`. + +```bash +mise run test:unit --module java-checks --test AbsOnNegativeCheckTest +mise run check:changed +mise run analyze:vortex +``` + +The changed tasks include committed, staged, unstaged and untracked changes relative to the merge base with `origin/master`. Set `MISE_CHANGE_BASE` to the intended branch or commit if that ref is missing, stale or not your review base. A changed rule with a matching test runs that test; changes that cannot be mapped to a focused test use the relevant modules instead. Focused changed checks skip the reactor-wide license-header scan. Changed checks do not replace full CI. The sanity task uses a test scanner context, not SonarQube Server. + +`pom.xml` keeps the JAR manifest's `Build-Time` constant so identical inputs remain eligible for Develocity cache hits. Do not restore a time-varying value. + +## Integration tests + +Run `mise run build` before running an integration task on its own. The [build workflow](../../.github/workflows/build.yml) supplies credentials and `ORCHESTRATOR_CONFIG_URL`. For an authorized local run, set `ORCHESTRATOR_CONFIG_URL` to a file URL for your Orchestrator properties file. Never commit that file or its credentials. No scanner `pluginGroup` is needed in Maven settings. + +```bash +mise run its:plugin --sq-version LATEST_RELEASE --test JavaTestSuite +``` + +The full plugin and ruling suites need a GitHub token with read access to the QA licenses. A nonblank `GITHUB_TOKEN` overrides `github.token` from the Orchestrator file for these tests. `--community-only` skips the commercial JSP test but does not remove the license requirement for `JavaTestSuite`. Use Plugin QA in CI if those prerequisites are unavailable locally. + +`mise run ci` runs `check`, Plugin QA and both Linux ruling profiles. Ruling needs `git submodule update --init --recursive its/sources`. For authorized troubleshooting, use `mise run ruling without-sonarqube-project --rules S100,S101 --project guava`. Use CI for [ruling baselines and review](ruling-tests.md), not a local run. diff --git a/docs/systems/external-context.md b/docs/systems/external-context.md new file mode 100644 index 00000000000..840f51b61fb --- /dev/null +++ b/docs/systems/external-context.md @@ -0,0 +1,42 @@ +--- +title: External context +description: Retrieve canonical specifications and shared guidance without copying private content into SonarJava. +sources: + - resource: "5742002202" + - resource: "5739839551" + - resource: "2259484684" + - resource: "5691441188" + - resource: "4034199608" + - resource: "4119691265" + - resource: "5563351042" + - resource: "5770248413" +generated: + by: tirion +--- + +# External context + +## Public sources + +- [RSPEC](https://github.com/SonarSource/rspec) is the canonical rule specification and metadata source. [Sonar rules](https://rules.sonarsource.com/java/) is the published Java rule catalog; use it for released behavior, not as a substitute for the source specification when implementing a change. +- [Java analysis documentation](https://docs.sonarsource.com/sonarqube-server/analyzing-source-code/languages/java) is the customer-facing reference for scanner settings and prerequisites. + +## Access-controlled sources + +Use your approved SonarSource Confluence connection and retrieve these pages by ID (for example, the Confluence page lookup's `page_id` field). If you lack access and need a page for the change, ask the repository owners. Do not copy content or access URLs into this public repository. + +### Repository Baseline + +- **Agentic Development Repository Baseline**, page `5742002202`: repository requirements shared across projects. +- **Agent-facing documentation**, page `5739839551`: shared documentation guideline, not a source of SonarJava build commands. + +### Java analyzer and related projects + +| Page | ID | Retrieve when | +| --- | --- | --- | +| Java Analyzer | `2259484684` | Looking for the performance-monitoring entry point; repository-owned PVF behavior is in [verification](verification.md#performance-validation). | +| Proposal: Replace ECJ with javac in Sonar Java | `5691441188` | Investigating the compiler proposal; it is not an active architecture decision. | +| Release sonar-java-jdt | `4034199608` | Coordinating a release or upgrade of the separate ECJ fork. | +| Release sonar-java-symbolic-execution | `4119691265` | Coordinating with the separate symbolic-execution repository. | +| SonarJava SE Release Instructions | `5563351042` | Looking up release instructions for that engine, not this plugin. | +| KTLO Daily Checklist | `5770248413` | Looking up operations shared across repositories. | diff --git a/docs/systems/feature-activation.md b/docs/systems/feature-activation.md new file mode 100644 index 00000000000..72830142da1 --- /dev/null +++ b/docs/systems/feature-activation.md @@ -0,0 +1,16 @@ +--- +title: Feature-flag applicability +description: Decide whether a SonarJava behavior change needs independent activation and rollback. +sources: + - resource: "5742002202" +generated: + by: tirion +--- + +# Feature-flag applicability + +Record in the PR whether a flag is applicable and why. Documentation, build-only maintenance and correctness fixes that should apply wherever the artifact is used normally do not need new runtime flags. For a new rule, review [profile membership](rule-metadata.md) separately from implementing the rule: inclusion in a built-in profile affects default activation; it is not a general-purpose runtime flag. + +Consider a flag for a behavior change that needs independent activation or isolation from the rest of a plugin release, such as a new parser or analysis path with compatibility or performance risk. `java-frontend/src/main/java/org/sonar/java/SonarComponents.java` reads scanner settings for analysis behavior, and `sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java` registers supported public settings. They show existing configuration, not a mandate to expose a public setting for every rollout. Agree on the activation mechanism with the owners and check applicability on Server, Cloud and IDE separately. + +For a flag, document its default, owner, activation approval, rollout stages, signals to monitor, tested fallback and removal criteria. Test the existing path as well as the new path. If no flag is appropriate, state how the change ships and how to recover, such as reverting the change and validating the replacement candidate. diff --git a/docs/systems/index.md b/docs/systems/index.md new file mode 100644 index 00000000000..5d35ec3a63a --- /dev/null +++ b/docs/systems/index.md @@ -0,0 +1,27 @@ +--- +title: SonarJava systems +description: Find the constraints and code entry points relevant to a SonarJava change. +generated: + by: tirion +--- + +# SonarJava systems + +## Building and delivering + +- [Setup, build and test commands](build.md): select the right JDK and Maven invocation. +- [Verification before merge](verification.md): choose checks and interpret CI results. +- [Feature activation](feature-activation.md): decide whether a behavior change needs a rollout switch. +- [Release checks](release-checks.md): check the exact candidate version and release path. +- [Third-party licenses](licenses.md): regenerate and verify licenses after dependency changes. +- [External context](external-context.md): retrieve cross-repository or access-controlled information. + +## Analysis and rules + +- [Rule API](rule-api.md): choose a visitor and manage rule lifecycle. +- [Public Java analyzer API](public-api.md): preserve compatibility with external consumers. +- [Rule tests](rule-tests.md): place samples and choose semantic and no-semantic expectations. +- [Quick-fix tests](quickfix-tests.md): test edits as well as issue locations. +- [Project-level rules](project-level-rules.md): work with cross-file analysis and cache reuse. +- [Rule metadata and profiles](rule-metadata.md): update generated artifacts and profile membership. +- [Ruling tests](ruling-tests.md): review CI-generated SARIF changes. diff --git a/docs/systems/licenses.md b/docs/systems/licenses.md new file mode 100644 index 00000000000..c623aaa8ee2 --- /dev/null +++ b/docs/systems/licenses.md @@ -0,0 +1,19 @@ +--- +title: Third-party licenses +description: Check new dependency licenses and regenerate the license files shipped in the plugin. +generated: + by: tirion +--- + +# Third-party licenses + +`LICENSE.txt` contains SSALv1. When plugin dependencies change, validate their licenses and regenerate the bundled files under `sonar-java-plugin/src/main/resources/licenses/`. Use `missing-dep-licenses.properties` for dependencies whose license Maven cannot determine, after confirming the license. `sonar-java-plugin/license-resources/README.md` explains why some dependency license files are replaced with text versions. + +Run from the repository root after [toolchain setup](build.md): + +```bash +mise run lint:licenses +mise exec -- mvn clean package -PupdateLicenses +``` + +Review and commit the generated license changes. If a new dependency does not change the bundled licenses, explain why in the PR rather than editing generated files just to satisfy the check. The license goal runs in **Custom Rules and License Check** in `.github/workflows/build.yml`. diff --git a/docs/systems/project-level-rules.md b/docs/systems/project-level-rules.md new file mode 100644 index 00000000000..d779bd370e3 --- /dev/null +++ b/docs/systems/project-level-rules.md @@ -0,0 +1,39 @@ +--- +title: Module-wide rules and incremental analysis +description: Aggregate cross-file evidence at module completion without losing or duplicating contributions from unchanged files. +generated: + by: tirion +--- + +# Module-wide rules and incremental analysis + +## Decide whether the rule needs a module view + +`java-frontend/src/main/java/org/sonar/plugins/java/api/internal/EndOfAnalysis.java` runs after file scanning **once per module**, not once per entire project. Use it when the result depends on other files in the same module. Keep normal per-file checks stateless as described in the [stateless rules decision](../adrs/stateless-rules.md). + +Retain compact per-file contributions rather than ASTs or semantic symbols. Those objects can retain the entire semantic model. Report module-level issues through `ModuleScannerContext.addIssueOnProject()`. For issues with file locations or secondary spans, see `java-frontend/src/main/java/org/sonar/java/model/DefaultModuleScannerContext.java` and its `reportIssue(AnalyzerMessage)` method. + +An IDE analysis can see only a subset of files, so do not treat absence of evidence as proof when a check needs the complete module. A server `ProjectSensor` can run across modules, but is not an IDE callback. `sonar-java-plugin/src/main/java/org/sonar/plugins/java/ProjectEndOfAnalysisSensor.java` sends telemetry; it is not a rule reporting hook. + +## Preserve results on unchanged files + +`java-frontend/src/main/java/org/sonar/java/model/VisitorsBridge.java` does not simply drop `EndOfAnalysis` checks for unchanged files. Instead it asks them to `scanWithoutParsing()`. The default returns `true` without collecting anything; relying on it means a rule can miss contributions in incremental analysis. Only accept a partial view if the rule remains correct with it. + +Use `java-frontend/src/main/java/org/sonar/java/caching/FileCachingCheck.java` instead of wiring cache keys and carry-over by hand: + +1. Define a rule-specific `cacheKeyPrefix()` and a compact payload for **one file**. +2. On the parsed path, replace the file's contribution and call `writeToCache()` from `leaveFile()` (or `scanFile()` for a direct scanner). Release per-file traversal state without clearing the module's aggregate. +3. In `scanWithoutParsing()`, return `restoreFromCache(context)`. Its `restore()` callback replaces the contribution under the input file's key, just as the parsed path does. +4. Aggregate the values in `endOfAnalysis()` and report the findings. + +A successful restore only means **this** scanner can proceed without the AST. Another scanner can require parsing, so a file may be both restored and visited. Replace, do not append, its contribution on both paths. A cache miss or invalid payload requests parsing; it is not an empty file contribution. An I/O exception reading the cache is handled by the bridge and can fail the analysis in fail-fast mode. If checks share a cache prefix they must share a payload contract: the first write wins. + +## Version the payload, not the file identity + +`java-frontend/src/main/java/org/sonar/java/serialization/JsonUtils.java` supports a versioned JSON document. Bump the format version when an incompatible payload would otherwise be accepted, so stale entries are parsed and rewritten. Use UTF-8 when converting between JSON and bytes. Prefer explicit Gson `TypeAdapter`s for structured values: reflective binding can break after the plugin's `minimizeJar` step removes classes reached only by reflection. + +A span belongs in the payload; the file does not. `java-frontend/src/main/java/org/sonar/java/serialization/TextSpanTypeAdapter.java` encodes spans. Pair them with the file in the restore callback or when aggregating, using the file provided by the scanner context. See `java-frontend/src/main/java/org/sonar/java/model/springcontext/BeanDefinitionGatherer.java` for this pattern. + +## Verify the parsed and restored paths + +Test full analysis, a mix of unchanged and changed files, a missing or invalid cache entry, and a restore followed by forced parsing. `java-checks/src/test/java/org/sonar/java/checks/DateEnumsCheckTest.java` uses `CheckVerifier.withCache()` and `addFiles(InputFile.Status, ...)` for these cases, including a second scanner that forces parsing. For IDE behavior, do not assume the server analysis cache is available; see [Public API](public-api.md#extension-hooks) for the separate `SonarLintCache` extension. diff --git a/docs/systems/public-api.md b/docs/systems/public-api.md new file mode 100644 index 00000000000..5eef6392f1d --- /dev/null +++ b/docs/systems/public-api.md @@ -0,0 +1,24 @@ +--- +title: SonarJava public API and downstream consumers +description: Preserve the contracts used by external check providers and verify custom-rule compatibility when changing the Java analyzer API. +generated: + by: tirion +--- + +# SonarJava public API and downstream consumers + +`java-frontend/src/main/java/org/sonar/plugins/java/api` contains the contracts for writing and registering Java checks. Consumer plugins compile and load separately from SonarJava. Custom-rule plugins and separately maintained symbolic-execution, DBD and security analyzers can depend on these contracts. Java's `public` modifier alone does not make an implementation class a supported extension point; do not expose internal parser or semantic-model classes to solve a rule-specific problem. + +## Evolve the API without breaking consumers + +- Preserve source and binary compatibility for supported APIs. For example, adding an abstract method to an interface forces existing implementations to change. Prefer a compatible default method or additive API where the semantics allow it. +- Do not remove or change a supported signature without a deprecation path. Introduce the replacement, mark the old API deprecated, document how callers should migrate, and keep the old behavior during the transition. Check `@Beta` and `internal` boundaries before relying on a class or promising it to downstream users. +- Review behavioral changes as well as signatures. Changes to callback order, when symbols are available, or what a scanner sees on unchanged files can break external rules without a compile error. + +`docs/java-custom-rules-example` is a buildable consumer, not a substitute for downstream compatibility review. The **Custom Rules and License Check** job in `.github/workflows/build.yml` builds the example with `docs/java-custom-rules-example/pom_SQ_10_6_LATEST.xml`, which pins older SonarJava and SonarQube plugin APIs. Keep the example working on that baseline; a successful build against the pinned dependencies does not prove that separately built plugins will load with a changed analyzer. Review dependencies and runtime behavior with the affected downstream owners for a contract change. + +## Extension hooks + +- `java-frontend/src/main/java/org/sonar/plugins/java/api/CheckRegistrar.java` registers checks from another plugin, separating checks for main and test sources. The sample implementation is `docs/java-custom-rules-example/src/main/java/org/sonar/samples/java/MyJavaFileCheckRegistrar.java`. +- `java-frontend/src/main/java/org/sonar/plugins/java/api/ProfileRegistrar.java` contributes rule keys to built-in profiles. `sonar-java-plugin/src/main/java/org/sonar/plugins/java/BuiltInJavaQualityProfile.java` combines packaged profile files and registrar contributions, with a legacy fallback for Security and DBD rules. For built-in checks declared in this repository, see [Rule metadata and profiles](rule-metadata.md). +- `sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java` installs `SonarLintCache` for `SonarProduct.SONARLINT`: DBD uses it to transfer in-memory data between plugins. It is not persistent between analyses and does not replace the server-side incremental cache. Preserve the extension when changing product-specific wiring. diff --git a/docs/systems/quickfix-tests.md b/docs/systems/quickfix-tests.md new file mode 100644 index 00000000000..eb8e0c0752e --- /dev/null +++ b/docs/systems/quickfix-tests.md @@ -0,0 +1,32 @@ +--- +title: Testing Java quick fixes +description: Pin quick-fix descriptions, replacement text, edit spans and edit ordering in the verifier sample. +generated: + by: tirion +--- + +# Testing Java quick fixes + +Declare expected fixes in the same sample as the issue. This fragment comes from `java-checks-test-sources/default/src/main/java/checks/DurationTimeUnitAgreementCheckSample.java`; the [rule test guide](rule-tests.md) explains the underlying issue and caret markers. + +```java + f.get(d.toMillis(), TimeUnit.SECONDS); // Noncompliant {{Change this TimeUnit to "MILLISECONDS" or convert the duration to seconds.}} [[quickfixes=qf1]] +// ^^^^^^^^^^^^^^^^ + // fix@qf1 {{Change TimeUnit to "MILLISECONDS"}} + // edit@qf1 [[sc=34;ec=41]] {{MILLISECONDS}} +``` + +## Declare each fix and edit + +- Put `[[quickfixes=qf1]]` after the message on the `Noncompliant` line, not on the underline. Use a distinct ID for each fix in the sample, a comma-separated list for alternatives, or `[[quickfixes=!]]` to assert no fix. Omitting the attribute does not assert absence. +- The `fix@qf1` text must exactly match the description shown in the IDE. +- Each `edit@qf1` describes one text edit. Put the replacement in `{{...}}`; use `{{}}` for deletion. +- Columns (`sc`, `ec`) are one-based and the end is exclusive. In the example, `sc=34` points to the `S` in `SECONDS` and `ec=41` points to the closing parenthesis. The edit can be narrower than the primary span. +- Omit start/end lines if both are on the issue line. Otherwise give `sl` and `el`, preferably relative to the issue line: `sl=+2;sc=3;el=+2;ec=9` starts two lines below the issue, regardless of where the annotation is written. +- List edits in the order the `JavaQuickFix` supplies them. If the builder calls `reverseSortEdits()`, match the resulting order rather than the source order. + +## Report the fix and verify it + +`java-checks/src/main/java/org/sonar/java/checks/DurationTimeUnitAgreementCheck.java` demonstrates `QuickFixHelper.newIssue(context)`. After setting the issue location and message, use `withQuickFix` for one fix or `withQuickFixes` for a list of alternatives, then call `report()`. A single fix can contain multiple edits. Prefer `JavaTextEdit` tree-based operations over manual offsets when the edit aligns with the syntax tree. + +Run the rule test with `CheckVerifier.verifyIssues()`. If a fix is unmatched, first check the description, exact replacement text, one-based columns and exclusive end, and the edit order. If the annotations are right, verify that the issue is actually reported through the quick-fix builder for that case. Include a case that asserts no fix when the rule should report an issue but cannot safely offer an automatic edit. diff --git a/docs/systems/release-checks.md b/docs/systems/release-checks.md new file mode 100644 index 00000000000..9051d39516e --- /dev/null +++ b/docs/systems/release-checks.md @@ -0,0 +1,13 @@ +--- +title: Release checks +description: Verify a SonarJava release candidate before handing it to release automation. +generated: + by: tirion +--- + +# Release checks + +1. Check the intended branch, commit and version. Verify **Build** and the applicable [verification jobs](verification.md), including compatibility, licenses and rule metadata. Resolve ruling deltas and investigate any applicable performance regression before using a candidate. +2. Confirm promotion and the releasability result for that candidate. `.github/workflows/ReleasabilityCheck.yml` evaluates successful builds on tracked release and development branches; `.github/workflows/releasability.yaml` supports an explicit artifact version. Do not assume a status for the latest build applies to a different candidate. +3. Confirm intended SonarQube Server, Cloud and IDE integrations with the release owner. `.github/workflows/automated-release.yml` is the release entry point and owns integration and version-bump options. `.github/workflows/release.yml` is the publishing step, not a local test. Its dry-run/publish behavior and that of the automated workflow are defined in those workflows; do not dispatch either without authorization. +4. For releases of the ECJ fork or symbolic execution engine, use the separate references in [external context](external-context.md#java-analyzer-and-related-projects). diff --git a/docs/systems/rule-api.md b/docs/systems/rule-api.md new file mode 100644 index 00000000000..843affec51e --- /dev/null +++ b/docs/systems/rule-api.md @@ -0,0 +1,48 @@ +--- +title: Writing SonarJava rules +description: Choose a visitor, match Java constructs semantically, and report issues without leaking state between files. +generated: + by: tirion +--- + +# Writing SonarJava rules + +## Choose a visitor + +Use an existing analyzer API directly, not a base class shared by rules. See the [inheritance decision](../adrs/no-abstract-rule-bases.md). Keep implementation comments out of rule code: they can drift from the rule's behavior. Give logic descriptive names, put non-obvious constraints in the docs, and use sample markers to assert the intended behavior. + +- `java-frontend/src/main/java/org/sonar/plugins/java/api/IssuableSubscriptionVisitor.java`: use for checks on known `Tree.Kind` values. The analyzer drives the traversal. Subscribe in `nodesToVisit()`, inspect in `visitNode()`, and use `leaveNode()` only when you need work after the children are visited. +- `java-frontend/src/main/java/org/sonar/plugins/java/api/tree/BaseTreeVisitor.java`: use with `JavaFileScanner` when you need to control descent, for example to stop at nested classes. Call `scan(context.getTree())` from `scanFile()` and call the matching `super.visit*` method when the traversal should continue. A local visitor can capture the file context instead of storing it on the check. +- `java-frontend/src/main/java/org/sonar/plugins/java/api/JavaFileScanner.java`: implement directly when the rule needs one callback per file and can inspect the context without a visitor. + +Subscribe to the smallest node with enough context to decide. For example, check an invocation in `METHOD_INVOCATION`; subscribe to `METHOD` instead if the decision depends on several statements in its body. + +## Match types and calls + +Use `java-frontend/src/main/java/org/sonar/plugins/java/api/semantic/MethodMatchers.java` to match a method's owner, name and parameter signature. Use `ofTypes` for exact declaring types, `ofSubTypes` when subtypes also count, and `addParametersMatcher` when only specific overloads are relevant. Reserve `withAnyParameters()` for checks that apply to all overloads. Do not compare raw method or type names from source text; text does not distinguish overloads, unrelated types with the same simple name, or unresolved symbols. + +```java +private static final MethodMatchers LIST_CONTAINS = MethodMatchers.create() + .ofSubTypes("java.util.List") + .names("contains") + .addParametersMatcher("java.lang.Object") + .build(); +``` + +Use `symbolType().is("java.lang.String")` for an exact type and `isSubtypeOf("java.util.Collection")` for a hierarchy match. Use `Symbol` and its owner when identity or declaration matters. Guard unknown types and symbols before relying on a negative result: failure to resolve a type is not evidence that the type is wrong. Test that fallback explicitly; see [Rule tests](rule-tests.md). + +## Gate checks on dependency or Java versions + +`java-frontend/src/main/java/org/sonar/plugins/java/api/DependencyVersionAware.java` is called when scanners are selected for a module. The lookup takes an artifact ID such as `spring-web` and returns a `Version` if detected on the classpath. A missing result may mean the classpath cannot be identified, not necessarily that the library is absent. If the rule only makes sense for a known dependency or version, return `false` on absence; `false` disables the rule for that module. If the rule still applies but behaves differently by version, assign the version flag in the callback, including the fallback when the lookup is empty. + +`java-frontend/src/main/java/org/sonar/plugins/java/api/JavaVersionAwareVisitor.java` gates on the analyzed project's Java version, not the JVM that runs the analyzer. Use it for checks tied to syntax or APIs that require a particular source version. + +## Report the smallest useful span + +Use `reportIssue(tree, message)` or the start/end tree overload for a source span. Use secondary `JavaFileScannerContext.Location` entries when another location explains the finding, and pass a remediation cost only when the rule needs to compute it. For a file-level issue, use `addIssueOnFile`. Quick fixes use a separate builder; see [Quick-fix tests](quickfix-tests.md). + +## Keep scan state local + +Follow the [stateless rules decision](../adrs/stateless-rules.md) for new checks. For existing stateful subscription checks, `clearState()` runs before and after the file, even when analysis fails. For existing direct scanners, release per-file collections and AST references in a `finally` block around traversal. Do not clear a cached value derived only from unchanged `@RuleProperty` configuration: it does not contain file data and clearing it would recompute the same value for every file. + +If the rule truly depends on other files, see [Project-level rules](project-level-rules.md) before choosing an aggregation and cache strategy. diff --git a/docs/systems/rule-metadata.md b/docs/systems/rule-metadata.md new file mode 100644 index 00000000000..e389454533f --- /dev/null +++ b/docs/systems/rule-metadata.md @@ -0,0 +1,33 @@ +--- +title: Rule metadata, registration and quality profiles +description: Generate rule descriptors from RSPEC, review profile membership and let the build register checks. +generated: + by: tirion +--- + +# Rule metadata, registration and quality profiles + +## Generate the descriptors from RSPEC + +`sonarpedia.json` configures `rule-api` to generate Java metadata from the public [RSPEC repository](https://github.com/SonarSource/rspec). The generated HTML descriptions and JSON descriptors live in `sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java`. Change the source specification in RSPEC, not the generated files. The JSON `scope` affects which source sets run the check; review it alongside the specification, not as an independent local setting. + +`.github/workflows/UpdateRuleMetadata.yml` pins the `rule-api` version for the refresh workflow. For one rule, run that version of the generator from the repository root, setting `RULE_API_JAR`, `RSPEC_BRANCH` and `RULE_KEY` to the local jar, RSPEC branch and rule key first: + +```bash +java -jar "$RULE_API_JAR" generate -branch "$RSPEC_BRANCH" -rule "$RULE_KEY" +``` + +Use the actual RSPEC branch or the default branch once the specification has landed. If RSPEC or the generator is unavailable, ask for access rather than synthesizing descriptors. Review the output and keep only changes relevant to the rule. + +## Distinguish registration from activation + +`check-list/src/main/java/org/sonar/java/CheckListGenerator.java` finds concrete `*Check.java` classes annotated with `@Rule` in the rule modules and reads the matching JSON metadata to place each check in main sources, test sources or both. Give the check the exact RSPEC key and follow the filename convention so it is discovered. Do not edit `GeneratedCheckList`: `check-list/pom.xml` builds it from these inputs. + +A registered rule is available to the analyzer; being enabled by default is a separate choice. The built-in profiles store membership as empty files named by rule key. Review the files the generator changes against the RSPEC `defaultQualityProfiles`: + +- Sonar way: `sonar-java-plugin/src/main/resources/profiles/Sonar_way` +- Sonar agentic AI: `sonar-java-plugin/src/main/resources/profiles/Sonar_agentic_AI` + +Add or remove the rule's empty membership file when its profile inclusion changes; do not change unrelated membership. `sonar-java-plugin/src/main/build/ProfileJsonGenerator.java` generates the packaged profile JSON from these directories during the build. Per-rule files let separate rule changes update a profile without editing the same generated JSON array. + +For externally provided checks, use the supported [registration hooks](public-api.md#extension-hooks) rather than editing Java's built-in profile inputs for another plugin. diff --git a/docs/systems/rule-tests.md b/docs/systems/rule-tests.md new file mode 100644 index 00000000000..d645bef8231 --- /dev/null +++ b/docs/systems/rule-tests.md @@ -0,0 +1,51 @@ +--- +title: Rule tests and sample placement +description: Test positive and negative cases with and without semantics, and put samples in the module that supplies their classpath. +generated: + by: tirion +--- + +# Rule tests and sample placement + +## Choose where the sample belongs + +`java-checks-test-sources/pom.xml` builds the shared rule samples. Use JDK 26 to build the sample reactor; the default sample module also sets its compiler release in `java-checks-test-sources/default/pom.xml`. + +- Compiling samples for main-code checks: `java-checks-test-sources/default/src/main/java/checks`, loaded with `TestUtils.mainCodeSourcesPath`. Use `package checks;` and a distinct top-level type name to avoid conflicts with other samples. +- Compiling samples for test-code checks: `java-checks-test-sources/default/src/test/java/checks`, loaded with `TestUtils.testCodeSourcesPath`. +- Deliberately non-compiling samples: `java-checks-test-sources/default/src/main/files/non-compiling/checks`, loaded with `TestUtils.nonCompilingTestSourcesPath`. Use this for intentionally broken sources or missing bytecode, not as a shortcut around compiling a regular sample. +- Java-version or framework-specific samples belong in an existing module under `java-checks-test-sources` that provides the correct compiler or dependencies. Use the corresponding `TestUtils` helper ending in `InModule` and configure the verifier classpath or Java version when the test needs it. Selecting a sample path does not itself change the verifier classpath. + +For the default main-code case, name the sample after the check with a **Sample.java** suffix. Keep parser-only and other dedicated ad hoc fixtures under `java-checks/src/test/files` when they do not belong to a Maven sample module; do not add ordinary new rule samples to the legacy `java-checks/src/test/files/checks` directory. + +Reuse the prepared test dependencies or use focused stubs. Do not add dependencies just to exercise an API when the existing test reactor can model it. + +## Assert both analysis modes + +Use JUnit Jupiter (see [JUnit 5](../adrs/junit-5.md)) and `java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java`. Every new rule needs a semantic test and a `withoutSemantic()` test. Resolution can fail when code is incomplete or the classpath is missing; check that the rule neither crashes nor speculates on unresolved types. Use `verifyNoIssues()` if the rule needs resolution, or `verifyIssues()` with the expected remaining findings if it can safely report from syntax alone. + +For a concrete pair, see `java-checks/src/test/java/org/sonar/java/checks/DurationTimeUnitAgreementCheckTest.java`. Share sample-path constants when tests load the same sample. If behavior depends on a library version, add a case for an absent or incompatible dependency as well as the supported one; `withoutSemantic()` alone does not simulate a change to dependency version discovery. + +## Mark expected issues in the sample + +Cover both triggering and similar-looking compliant cases. Put `// Noncompliant {{Expected message.}}` on the line with an expected issue. Put carets directly below to assert the primary range; a bare marker cannot catch a regression that moves highlighting to the wrong expression. Mark secondary ranges with carets and a direction marker: `<` points back to a primary above and `>` points forward to a primary below. + +```java + new Thread(() -> { +// ^^^^^^> + Thread.sleep(1000); // Noncompliant {{Do not sleep here.}} +// ^^^^^ + }); +``` + +If a caret cannot express the span (for example at column 1 or across multiple lines), use the explicit attributes such as `sc`, `el`, `ec` or `secondary`. Prefer relative lines to absolute lines so unrelated edits above the marker do not break the test. See [Quick-fix tests](quickfix-tests.md) for fix declarations that accompany an issue marker. + +## Verify + +From the repository root with the project dependencies and compiled samples available, run the targeted rule test; substitute the test class for the example: + +```bash +mvn test -pl java-checks -Dtest=DurationTimeUnitAgreementCheckTest +``` + +From `java-checks-test-sources`, `mvn clean compile` compiles the shared samples as in CI. It does not compile test-scope samples; use `mvn test-compile` from the same directory when changing those. diff --git a/docs/systems/ruling-tests.md b/docs/systems/ruling-tests.md new file mode 100644 index 00000000000..843972c9197 --- /dev/null +++ b/docs/systems/ruling-tests.md @@ -0,0 +1,24 @@ +--- +title: Ruling tests and baseline updates +description: Review SonarJava findings on real projects using CI-generated SARIF changes rather than running ruling or editing baselines locally. +generated: + by: tirion +--- + +# Ruling tests and baseline updates + +`its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java` analyzes real projects and compares findings with the baselines in `its/ruling/src/test/resources/expected`. Ruling catches false positives and lost true positives not covered by focused rule tests. Project sources come from the `its/sources` submodule (`ruling_java` in `.gitmodules`). + +## Let CI produce baselines + +Do not run ruling locally or edit the expectations by hand. The suite depends on pinned project sources, Orchestrator, Repox and the CI build of the plugin; changes in the environment can produce unrelated differences. Local verification starts with [Rule tests](rule-tests.md). + +1. **Ruling QA** in `.github/workflows/build.yml` runs with JDK 21 on Linux and Windows. Windows sets `core.autocrlf=input` before checkout for consistent source lines and avoids parallel ruling because nested Maven builds share the local repository. +2. When the comparison fails, CI uploads actual reports from the ruling module's build output (the target directory's `actual` subdirectory). **Ruling Update and Notify** opens the baseline update PR when there are changes to apply. A job failure with no useful reports is not an expected baseline update; inspect the failing job first. +3. Review the update before merging it into the rule branch. Use `.github/workflows/ruling-diff-comment.yml`'s PR comment to inspect additions and removals. Accept intentional changes only. For unexpected findings or lost true positives, fix the rule and add a regression test, then let CI regenerate the update. If sources or the bot output are unavailable, ask a maintainer rather than guessing at the baselines. + +## Interpret the SARIF diff + +The layout beneath the expected directory is a project directory with a `java-.sarif` report per rule that has findings. For example, see `its/ruling/src/test/resources/expected/commons-beanutils/java-S103.sarif`. Each `runs[].results[]` entry carries a `ruleId`, `message.text`, and a primary `locations[0].physicalLocation`. The latter's `artifactLocation.uri` is the project key and a project-relative file path separated by a colon, and its `region` gives the line and column range. Use the expected report's project directory to locate the corresponding checkout under `its/sources`; inspect the finding in that revision, not the latest upstream source. + +For a new rule, classify added findings as true or false positives after the baseline is available and CI is green. Review all findings when practical. For a large diff, sample across projects: start with equal shares, take all findings in projects below their share, then redistribute unused slots to projects with unsampled findings. Calculate precision as true positives divided by all classified findings. If there are findings, new rules must exceed 90% precision; when they do not, add the false positives as regression cases, refine the rule, and repeat the review on fresh output. Do not infer precision from a diff with no findings to classify. diff --git a/docs/systems/verification.md b/docs/systems/verification.md new file mode 100644 index 00000000000..60c7f197caf --- /dev/null +++ b/docs/systems/verification.md @@ -0,0 +1,36 @@ +--- +title: Verification before merge +description: Select local checks and review SonarJava CI evidence before merging. +sources: + - resource: "5742002202" +generated: + by: tirion +--- + +# Verification before merge + +Run the relevant checks in [build and test commands](build.md). Run the focused verifier test for rule behavior, compile changed Maven samples, and use [license checks](licenses.md) for dependencies. Check docs with the commands in `.github/workflows/docs.yml`. Record what passed and what could not run; a local unit test is not a substitute for an applicable skipped integration check. + +`.github/workflows/build.yml` is the source of truth for job execution and prerequisites: + +| Job | Evidence to review | +| --- | --- | +| Build | Packages a candidate without running tests and excludes the test-sample leaf modules selected by `--projects`. | +| Ruling QA | Checks SARIF against expected results on Linux and Windows. | +| Ruling Update and Notify | Handles ruling differences on PRs; review the bot output, not just the job status. | +| Plugin QA | Exercises analyzer integration against SonarQube Server. | +| Sanity Test | Compiles test sources and runs all rules to catch analyzer crashes. | +| Test Analyze | Builds and analyzes the repository with SonarQube. | +| Custom Rules and License Check | Builds the example using `docs/java-custom-rules-example/pom_SQ_10_6_LATEST.xml` as the compatibility floor exercised by CI and checks third-party licenses. | +| Build and Unit Test on Windows | Runs Maven `clean verify` independently of the candidate build. | +| Promote | Depends on the candidate build and its verification jobs. | + +`.github/workflows/ruling-diff-comment.yml` posts the SARIF comparison when expectations change; inspect actual issue locations and false positives before accepting a new baseline. `.github/workflows/docs.yml` checks the documentation bundle and agent entry points on every PR. + +## Review and merge + +Use the actual required checks and review rules shown on the PR; `.github/CODEOWNERS` identifies the owning team. Public contributions and high-risk changes need human review. Treat public API, generated metadata, baselines, licensing, and changes in parser, cache or analysis behavior as requiring explicit review of their impact, not routine low-risk cleanup. Code review automation does not replace branch protections or maintainer approval. + +## Performance validation + +`.github/workflows/build.yml` publishes a deployed candidate version for performance validation. `.github/workflows/pvf-comment.yml` responds to an authorized maintainer's **/pvf** PR comment and dispatches validation in the performance repository. Use it for parser, semantic analysis, caching or other hot-path changes when CI unit and ruling results alone cannot show performance impact. Inspect the comparison for the exact candidate rather than reusing results from a previous build. diff --git a/its/plugin/tests/pom.xml b/its/plugin/tests/pom.xml index b06862a57f9..5e09519b35f 100644 --- a/its/plugin/tests/pom.xml +++ b/its/plugin/tests/pom.xml @@ -112,6 +112,8 @@ maven-surefire-plugin -server + + true com/sonar/it/java/suite/*TestSuite.java com/sonar/it/java/suite/SonarLintIntegrationTest.java diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/JspTest.java b/its/plugin/tests/src/test/java/com/sonar/it/java/JspTest.java index ee3723fd23e..5358c0f4f0a 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/JspTest.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/JspTest.java @@ -20,7 +20,6 @@ import com.sonar.it.java.suite.TestUtils; import com.sonar.orchestrator.build.BuildResult; import com.sonar.orchestrator.build.MavenBuild; -import com.sonar.orchestrator.container.Edition; import com.sonar.orchestrator.junit4.OrchestratorRule; import com.sonar.orchestrator.junit4.OrchestratorRuleBuilder; import com.sonar.orchestrator.locator.FileLocation; @@ -50,16 +49,13 @@ private static OrchestratorRule getEnterpriseOrchestratorOrNull() { if (isCommunityEditionTestsOnly()) { return null; } - OrchestratorRuleBuilder orchestratorBuilder = OrchestratorRule.builderEnv() + OrchestratorRuleBuilder orchestratorBuilder = TestUtils.licensedEnterpriseOrchestratorBuilder() .useDefaultAdminCredentialsForBuilds(true) .setSonarVersion(System.getProperty("sonar.runtimeVersion", "LATEST_RELEASE")) - .setEdition(Edition.ENTERPRISE_LW) - .activateLicense() .addPlugin(JavaTestSuite.JAVA_PLUGIN_LOCATION) // we need html plugin to have "jsp" language .addPlugin(MavenLocation.of("org.sonarsource.html", "sonar-html-plugin", "DEV")) - .restoreProfileAtStartup(FileLocation.ofClasspath("/profile-jsp.xml")) - .activateLicense(); + .restoreProfileAtStartup(FileLocation.ofClasspath("/profile-jsp.xml")); orchestratorBuilder.addPlugin(FileLocation.of(TestUtils.pluginJar("java-extension-plugin"))); return orchestratorBuilder.build(); } diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/CacheEnabledTest.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/CacheEnabledTest.java index 28841ecbef6..5b9b356682b 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/CacheEnabledTest.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/CacheEnabledTest.java @@ -64,9 +64,7 @@ public void test_cache_is_disabled() { private static OrchestratorRule initServer() { - return OrchestratorRule.builderEnv() - .setEdition(com.sonar.orchestrator.container.Edition.ENTERPRISE_LW) - .activateLicense() + return TestUtils.licensedEnterpriseOrchestratorBuilder() .useDefaultAdminCredentialsForBuilds(true) .setSonarVersion(System.getProperty("sonar.runtimeVersion", "LATEST_RELEASE")) .addPlugin(JavaTestSuite.JAVA_PLUGIN_LOCATION) diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/ExternalReportTest.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/ExternalReportTest.java index ae0eece60b1..b537885ac94 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/ExternalReportTest.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/ExternalReportTest.java @@ -37,7 +37,7 @@ public class ExternalReportTest { public void checkstyle() { MavenBuild build = TestUtils.createMavenBuild().setPom(TestUtils.projectPom("checkstyle-external-report")) .setProperty("sonar.java.checkstyle.reportPaths", "target" + File.separator + "checkstyle-result.xml") - .setGoals("org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0:checkstyle", "sonar:sonar"); + .setGoals("org.apache.maven.plugins:maven-checkstyle-plugin:3.0.0:checkstyle", TestUtils.MAVEN_SCANNER_GOAL); orchestrator.executeBuild(build); List issues = getExternalIssues("org.sonarsource.it.projects:checkstyle-external-report"); @@ -55,7 +55,7 @@ public void checkstyle() { public void pmd() { MavenBuild build = TestUtils.createMavenBuild().setPom(TestUtils.projectPom("pmd-external-report")) .setProperty("sonar.java.pmd.reportPaths", "target" + File.separator + "pmd.xml") - .setGoals("org.apache.maven.plugins:maven-pmd-plugin:3.10.0:pmd", "sonar:sonar"); + .setGoals("org.apache.maven.plugins:maven-pmd-plugin:3.10.0:pmd", TestUtils.MAVEN_SCANNER_GOAL); orchestrator.executeBuild(build); String projectKey = "org.sonarsource.it.projects:pmd-external-report"; @@ -74,7 +74,7 @@ public void pmd() { public void spotbugs() { MavenBuild build = TestUtils.createMavenBuild().setPom(TestUtils.projectPom("spotbugs-external-report")) .setProperty("sonar.java.spotbugs.reportPaths", "target" + File.separator + "spotbugsXml.xml") - .setGoals("clean package com.github.spotbugs:spotbugs-maven-plugin:spotbugs", "sonar:sonar"); + .setGoals("clean package com.github.spotbugs:spotbugs-maven-plugin:spotbugs", TestUtils.MAVEN_SCANNER_GOAL); orchestrator.executeBuild(build); String projectKey = "org.sonarsource.it.projects:spotbugs-external-report"; diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTest.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTest.java index 0a848b174e1..de42de26915 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTest.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTest.java @@ -91,7 +91,7 @@ public void multiple_package_in_directory_should_not_fail() { inspection = TestUtils.createMavenBuild() .setPom(TestUtils.projectPom("multiple-packages-in-directory")) .setProperty("sonar.skipPackageDesign", "true") - .setGoals("sonar:sonar"); + .setGoals(TestUtils.MAVEN_SCANNER_GOAL); result = orchestrator.executeBuildQuietly(inspection); assertThat(result.getLastStatus()).isZero(); } diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTestSuite.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTestSuite.java index 21511d754c2..a9eed7fe9d5 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTestSuite.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/JavaTestSuite.java @@ -61,11 +61,9 @@ public class JavaTestSuite { public static final OrchestratorRule ORCHESTRATOR; static { - OrchestratorRuleBuilder orchestratorBuilder = OrchestratorRule.builderEnv() + OrchestratorRuleBuilder orchestratorBuilder = TestUtils.licensedEnterpriseOrchestratorBuilder() .useDefaultAdminCredentialsForBuilds(true) .setSonarVersion(System.getProperty("sonar.runtimeVersion", "LATEST_RELEASE")) - .setEdition(com.sonar.orchestrator.container.Edition.ENTERPRISE_LW) - .activateLicense() .addPlugin(JAVA_PLUGIN_LOCATION) // for support of custom rules .addPlugin(FileLocation.of(TestUtils.pluginJar("java-extension-plugin"))) diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/Struts139Test.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/Struts139Test.java index 892fa579400..49bb3c793a0 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/Struts139Test.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/Struts139Test.java @@ -41,7 +41,7 @@ public static void analyzeProject() { MavenBuild analysis = TestUtils.createMavenBuild().setPom(TestUtils.projectPom("struts-1.3.9-lite")) .setProperty("sonar.scm.disabled", "true") .setProperty("sonar.exclusions", "**/pom.xml") - .setGoals("sonar:sonar"); + .setGoals(TestUtils.MAVEN_SCANNER_GOAL); orchestrator.executeBuilds(build, analysis); } diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/TestUtils.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/TestUtils.java index a781cdb0026..532f3ccf590 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/TestUtils.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/TestUtils.java @@ -20,8 +20,10 @@ import com.sonar.orchestrator.build.BuildResult; import com.sonar.orchestrator.build.MavenBuild; import com.sonar.orchestrator.build.SonarScanner; +import com.sonar.orchestrator.container.Edition; import com.sonar.orchestrator.container.Server; import com.sonar.orchestrator.junit4.OrchestratorRule; +import com.sonar.orchestrator.junit4.OrchestratorRuleBuilder; import java.io.File; import java.util.Arrays; import java.util.Collections; @@ -38,6 +40,9 @@ import static com.sonar.orchestrator.container.Server.ADMIN_PASSWORD; public class TestUtils { + // Match the scanner version used by Orchestrator's MavenBuild goal helpers. + static final String MAVEN_SCANNER_GOAL = "org.sonarsource.scanner.maven:sonar-maven-plugin:4.0.0.4121:sonar"; + private static final File home; static { @@ -101,8 +106,24 @@ public static SonarScanner createSonarScanner() { } public static MavenBuild createMavenBuild() { - return MavenBuild.create() + MavenBuild build = MavenBuild.create() .setProperty("sonar.scanner.skipJreProvisioning", "true"); + if (System.getenv("CI") == null) { + build.addArgument("-Ddevelocity.scan.disabled=true"); + } + return build; + } + + public static OrchestratorRuleBuilder licensedEnterpriseOrchestratorBuilder() { + OrchestratorRuleBuilder builder = OrchestratorRule.builderEnv() + .setEdition(Edition.ENTERPRISE_LW) + .activateLicense(); + String githubToken = System.getenv("GITHUB_TOKEN"); + if (githubToken != null && !githubToken.isBlank()) { + // The license loader otherwise prefers github.token from the Orchestrator configuration. + builder.setOrchestratorProperty("github.token", githubToken); + } + return builder; } diff --git a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/UnitTestsTest.java b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/UnitTestsTest.java index e6986a6f752..3d3615118f9 100644 --- a/its/plugin/tests/src/test/java/com/sonar/it/java/suite/UnitTestsTest.java +++ b/its/plugin/tests/src/test/java/com/sonar/it/java/suite/UnitTestsTest.java @@ -37,7 +37,7 @@ public class UnitTestsTest { public void tests_without_main_code() { MavenBuild build = TestUtils.createMavenBuild() .setPom(TestUtils.projectPom("tests-without-main-code")) - .setGoals("clean test-compile surefire:test", "sonar:sonar"); + .setGoals("clean test-compile surefire:test", TestUtils.MAVEN_SCANNER_GOAL); orchestrator.executeBuild(build); Map measures = getMeasures("org.sonarsource.it.projects:tests-without-main-code", @@ -55,7 +55,7 @@ public void tests_without_main_code() { public void tests_with_report_name_suffix() { MavenBuild build = TestUtils.createMavenBuild() .setPom(TestUtils.projectPom("tests-surefire-suffix")) - .setGoals("clean test-compile surefire:test -Dsurefire.reportNameSuffix=Run1", "test-compile surefire:test -Dsurefire.reportNameSuffix=Run2", "sonar:sonar"); + .setGoals("clean test-compile surefire:test -Dsurefire.reportNameSuffix=Run1", "test-compile surefire:test -Dsurefire.reportNameSuffix=Run2", TestUtils.MAVEN_SCANNER_GOAL); orchestrator.executeBuild(build); Map measures = getMeasures("org.sonarsource.it.projects:tests-surefire-suffix", diff --git a/its/ruling/pom.xml b/its/ruling/pom.xml index 7310def78fa..4c7f0dc8ad5 100644 --- a/its/ruling/pom.xml +++ b/its/ruling/pom.xml @@ -17,6 +17,7 @@ -server false true + org.sonar.java.it.JavaRulingTest @@ -102,32 +103,27 @@ without-sonarqube-project - - - - org.apache.maven.plugins - maven-surefire-plugin - - !org.sonar.java.it.JavaRulingTest#sonarqube_server - - - - + + !org.sonar.java.it.JavaRulingTest#sonarqube_server + only-sonarqube-project - - - - org.apache.maven.plugins - maven-surefire-plugin - - org.sonar.java.it.JavaRulingTest#sonarqube_server - - - - + + org.sonar.java.it.JavaRulingTest#sonarqube_server + + + + + maven-surefire-plugin + + ${ruling.test} + + + + +
diff --git a/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java b/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java index ac0cf64cf17..7db911ce081 100644 --- a/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java +++ b/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java @@ -44,7 +44,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; -import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.Fail; import org.junit.AfterClass; @@ -69,6 +68,7 @@ public class JavaRulingTest { private static final int LOGS_NUMBER_LINES = 200; private static final Logger LOG = LoggerFactory.getLogger(JavaRulingTest.class); + private static final Path PERFORMANCE_DIRECTORY = Paths.get("target", "performance"); private static final String INCREMENTAL_ANALYSIS_KEY = "sonar.java.skipUnchanged"; private static final String SONAR_CACHING_ENABLED_KEY = "sonar.analysisCache.enabled"; @@ -93,9 +93,10 @@ public class JavaRulingTest { ); @ClassRule - public static TemporaryFolder tmpDumpOldFolder = new TemporaryFolder(); + public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder(); private static Path effectiveDumpOldFolder; + private static Path performanceMeasurementsFolder; public static boolean isCommunityEditionTestsOnly() { return "true".equals(System.getProperty("communityEditionTestsOnly")); @@ -115,6 +116,11 @@ private static OrchestratorRule createOrchestrator() { } else { orchestratorBuilder.setEdition(Edition.ENTERPRISE_LW) .activateLicense(); + String githubToken = System.getenv("GITHUB_TOKEN"); + if (StringUtils.isNotBlank(githubToken)) { + // The license loader otherwise prefers github.token from the Orchestrator configuration. + orchestratorBuilder.setOrchestratorProperty("github.token", githubToken); + } } return orchestratorBuilder.build(); } @@ -155,12 +161,14 @@ public static void prepare_quality_profiles() throws Exception { prepareDumpOldFolder(); - Files.createDirectories(Paths.get("target", "performance")); + performanceMeasurementsFolder = TEMPORARY_FOLDER.newFolder("performance").toPath(); } @AfterClass public static void afterAllAnalysis() throws IOException { - PerformanceStatistics.generate(Paths.get("target","performance")); + if (performanceMeasurementsFolder != null) { + PerformanceStatistics.generateFromAnalyses(PERFORMANCE_DIRECTORY, performanceMeasurementsFolder); + } } private static void prepareDumpOldFolder() throws Exception { @@ -168,7 +176,7 @@ private static void prepareDumpOldFolder() throws Exception { if (SUBSET_OF_ENABLED_RULES.isEmpty()) { effectiveDumpOldFolder = allRulesFolder.toAbsolutePath(); } else { - effectiveDumpOldFolder = tmpDumpOldFolder.getRoot().toPath().toAbsolutePath(); + effectiveDumpOldFolder = TEMPORARY_FOLDER.newFolder("expected").toPath().toAbsolutePath(); Files.list(allRulesFolder) .filter(p -> p.toFile().isDirectory()) .forEach(srcProjectDir -> copyDumpSubset(srcProjectDir, effectiveDumpOldFolder.resolve(srcProjectDir.getFileName()))); @@ -433,24 +441,20 @@ public void regex_examples() throws IOException { } private static MavenBuild test_project(String projectName) throws IOException { - return test_project(projectName, null, projectName); - } - - private static MavenBuild test_project(String projectKey, @Nullable String path, String projectName) throws IOException { - String pomLocation = "../sources/" + (path != null ? path + "/" : "") + projectName + "/pom.xml"; - File pomFile = FileLocation.of(pomLocation).getFile().getCanonicalFile(); - prepareProject(projectKey, projectName); - MavenBuild mavenBuild = MavenBuild.create().setPom(pomFile).setCleanPackageSonarGoals().addArgument("-DskipTests"); - mavenBuild.setProperty("sonar.projectKey", projectKey); - return mavenBuild; + prepareProject(projectName, projectName); + return test_existing_project(projectName, projectName); } private static MavenBuild test_existing_project(String projectKey, String projectName) throws IOException { String pomLocation = "../sources/" + projectName + "/pom.xml"; File pomFile = FileLocation.of(pomLocation).getFile().getCanonicalFile(); - MavenBuild mavenBuild = MavenBuild.create().setPom(pomFile).setCleanPackageSonarGoals().addArgument("-DskipTests"); - mavenBuild.setProperty("sonar.projectKey", projectKey); - return mavenBuild; + MavenBuild build = MavenBuild.create().setPom(pomFile).setCleanPackageSonarGoals() + .addArgument("-DskipTests") + .setProperty("sonar.projectKey", projectKey); + if (System.getenv("CI") == null) { + build.addArgument("-Ddevelocity.scan.disabled=true"); + } + return build; } private static void prepareProject(String projectKey, String projectName) { @@ -467,11 +471,12 @@ private static BuildResult executeBuildWithCommonProperties(Build build, Stri } private static BuildResult executeBuildWithCommonProperties(Build build, String projectName, boolean buildQuietly) throws IOException { + Path performanceMeasurement = Files.createTempDirectory(performanceMeasurementsFolder, projectName + "-") + .resolve(PerformanceStatistics.MEASUREMENT_FILE); build.setProperty("sonar.scanner.skipJreProvisioning", "true"); build.setProperty("sonar.cpd.exclusions", "**/*") .setProperty("sonar.java.performance.measure", "true") - .setProperty("sonar.java.performance.measure.path", - Paths.get("target/performance/sonar.java.performance.measure.json").toAbsolutePath().toString()) + .setProperty("sonar.java.performance.measure.path", performanceMeasurement.toAbsolutePath().toString()) .setProperty("sonar.import_unknown_files", "true") .setProperty("sonar.skipPackageDesign", "true") .setProperty("sonar.lits.dump.old", effectiveDumpOldFolder.resolve(projectName).toString()) diff --git a/its/ruling/src/test/java/org/sonar/java/it/PerformanceStatistics.java b/its/ruling/src/test/java/org/sonar/java/it/PerformanceStatistics.java index a98da53f33b..8c2b0129850 100644 --- a/its/ruling/src/test/java/org/sonar/java/it/PerformanceStatistics.java +++ b/its/ruling/src/test/java/org/sonar/java/it/PerformanceStatistics.java @@ -17,6 +17,7 @@ package org.sonar.java.it; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; @@ -27,8 +28,34 @@ public class PerformanceStatistics { + static final String MEASUREMENT_FILE = "sonar.java.performance.measure.json"; + private static final String STATISTICS_FILE = "sonar.java.performance.statistics.txt"; + public static void main(String[] args) throws IOException { - PerformanceStatistics.generate(Paths.get("target","performance")); + PerformanceStatistics.generate(Paths.get("target", "performance")); + } + + static void generateFromAnalyses(Path performanceDirectory, Path analysesDirectory) throws IOException { + DurationMeasure total = null; + try (var analyses = Files.list(analysesDirectory)) { + var measurementFiles = analyses.map(directory -> directory.resolve(MEASUREMENT_FILE)) + .filter(Files::isRegularFile) + .sorted() + .toList(); + for (Path measurementFile : measurementFiles) { + DurationMeasure measure = DurationMeasureFiles.fromJson(measurementFile); + total = total == null ? measure : total.merge(measure); + } + } + Path combinedMeasurement = performanceDirectory.resolve(MEASUREMENT_FILE); + if (total == null) { + Files.deleteIfExists(combinedMeasurement); + Files.deleteIfExists(performanceDirectory.resolve(STATISTICS_FILE)); + return; + } + Files.createDirectories(performanceDirectory); + DurationMeasureFiles.writeJson(combinedMeasurement, total); + generate(performanceDirectory); } public static void generate(Path performanceDirectory) throws IOException { @@ -40,11 +67,11 @@ public static void generate(Path performanceDirectory) throws IOException { categoryNames.put("SymbolicExecutionVisitor", "3.symbolic-execution"); Predicate groupedMeasurePredicate = name -> name.endsWith("Check"); - Path performanceJsonFile = performanceDirectory.resolve("sonar.java.performance.measure.json"); + Path performanceJsonFile = performanceDirectory.resolve(MEASUREMENT_FILE); DurationMeasure measure = DurationMeasureFiles.fromJsonWithoutObservationCost(performanceJsonFile); measure.recursiveMergeOnUpperLevel("RegexParser"); measure.recursiveMergeOnUpperLevel("JavaWriteCache.write"); - Path performanceStatFile = performanceDirectory.resolve("sonar.java.performance.statistics.txt"); + Path performanceStatFile = performanceDirectory.resolve(STATISTICS_FILE); DurationMeasureFiles.writeStatistics(performanceStatFile, measure, categoryNames, groupedMeasurePredicate); } diff --git a/java-checks-test-sources/README.md b/java-checks-test-sources/README.md index 794750834fe..7f3612397c0 100644 --- a/java-checks-test-sources/README.md +++ b/java-checks-test-sources/README.md @@ -1,40 +1,15 @@ -SonarQube Java Analyzer - Rules Testing Sources -======= +--- +title: SonarJava rule test sources +description: This reactor supplies sample sources and classpaths for rule tests and integration tests. +generated: + by: tirion +--- -This project is used as input for unit tests of our rules and our ITs. -The project requires JDK 21. +# SonarJava rule test sources -## When to put samples here +Read [Rule tests and sample placement](../docs/systems/rule-tests.md) before adding or moving a sample. That guide covers the build JDK, module choice, and verifier setup. -Use this module for rule test samples that are meant to behave like regular Maven sources. -In `java-checks` tests, this typically means files loaded through `TestUtils.mainCodeSourcesPath(...)`, -`TestUtils.testCodeSourcesPath(...)`, or `TestUtils.nonCompilingTestSourcesPath(...)`. +To analyze the default samples on a local SonarQube instance, run `mvn clean install sonar:sonar -Panalyze-tests` from `java-checks-test-sources/default`. To compare scanner behavior with and without compiled classes, use the corresponding settings file in that module: -This is the right place when a sample: - -* needs the classpath or dependencies prepared by `java-checks-test-sources` -* should be compiled as part of one of the dedicated test-source modules -* is intentionally non-compiling and should live under `src/main/files/non-compiling` -* targets a specific dedicated module such as `default`, `java-17`, `spring-3.2`, or `spring-web-4.0` - -Prefer `java-checks/src/test/files` only for fixtures that are not supposed to belong to one of these Maven modules, -for example parser-only inputs or other ad hoc verifier fixtures. - -To analyze it with a **local instance of SonarQube** up and running, use the following command from its root: -``` -mvn clean install sonar:sonar -Panalyze-tests -``` - -You can also use the project to test the behavior of sonar-scanner with various configuration, as long as you have a **local instance of SonarQube** up and running: - -* Testing how sonar-scanner combined with the Java Analyzer behave when no-binaries are provided at all (dependencies and compiled classes of the projects no provided) - -``` -sonar-scanner -Dproject.settings=sonar-project-no-binaries.properties -``` - -* Testing how sonar-scanner combined with the Java Analyzer behave when binaries are provided: - -``` -sonar-scanner -Dproject.settings=sonar-project-with-binaries.properties -``` +- `java-checks-test-sources/default/sonar-project-with-binaries.properties` +- `java-checks-test-sources/default/sonar-project-no-binaries.properties` diff --git a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java index 596902081e1..5938d72b943 100644 --- a/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java +++ b/java-checks-testkit/src/main/java/org/sonar/java/checks/verifier/CheckVerifier.java @@ -31,6 +31,7 @@ /** * This interface defines how to use checks (rules) verifiers. Its goal is to provide all the required information * to the analyzer to verify the checks' expected behavior. + *

See Rule tests and sample placement. *

* The starting point to define a verifier is {@link #newVerifier()}. Then, a configuration can be specified. *

diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/DependencyVersionAware.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/DependencyVersionAware.java index ed39bc97d81..73b97dd6da6 100644 --- a/java-frontend/src/main/java/org/sonar/plugins/java/api/DependencyVersionAware.java +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/DependencyVersionAware.java @@ -22,6 +22,7 @@ /** * Implementing this interface allows a check to be executed - or not - during analysis, depending on the * version of desired libraries among dependencies of the current module. + *

See Rule API and version gating. * *

For example, if a rule is to be used only on modules of a project that use spring-web version at least 4.3, * it should implement {@link DependencyVersionAware} with the following method: diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/IssuableSubscriptionVisitor.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/IssuableSubscriptionVisitor.java index 1754f769e55..e0d28c3abec 100644 --- a/java-frontend/src/main/java/org/sonar/plugins/java/api/IssuableSubscriptionVisitor.java +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/IssuableSubscriptionVisitor.java @@ -23,6 +23,7 @@ /** * Subscription visitor providing an API to report issues. + *

See Writing SonarJava rules. */ public abstract class IssuableSubscriptionVisitor extends SubscriptionVisitor { diff --git a/java-frontend/src/main/java/org/sonar/plugins/java/api/ProfileRegistrar.java b/java-frontend/src/main/java/org/sonar/plugins/java/api/ProfileRegistrar.java index 1885668fad1..b81cb2ab039 100644 --- a/java-frontend/src/main/java/org/sonar/plugins/java/api/ProfileRegistrar.java +++ b/java-frontend/src/main/java/org/sonar/plugins/java/api/ProfileRegistrar.java @@ -24,6 +24,7 @@ /** * This class can be extended to provide additional rule keys in builtin quality profiles. + *

See SonarJava extension hooks. * *

  *   {@code
diff --git a/mise.toml b/mise.toml
index 1785e7f0dc8..c8b8255f40a 100644
--- a/mise.toml
+++ b/mise.toml
@@ -1,3 +1,88 @@
 [tools]
 java = ["26", "21", "17"]
 maven = "3.9"
+
+[settings.task]
+run_auto_install = false
+
+[tasks.build]
+description = "Build and install reactor artifacts without executing tests (JDK 26)"
+run = "python3 -B scripts/mise/tasks.py build"
+
+[tasks."test:unit"]
+description = "Run reactor unit tests (JDK 26)"
+usage = '''
+flag "--module " help="Reactor module path or :artifactId; includes prerequisites"
+flag "--test " help="Surefire test selector (class or class#method)"
+flag "--coverage" help="Enable JaCoCo coverage"
+'''
+run = "python3 -B scripts/mise/tasks.py test:unit"
+
+[tasks."test:sanity"]
+description = "Compile test sources and check that the analyzer does not crash (JDK 26)"
+run = "python3 -B scripts/mise/tasks.py test:sanity"
+
+[tasks."test:custom-rules-example"]
+description = "Build and test the custom Java rules example against the CI compatibility floor"
+run = "python3 -B scripts/mise/tasks.py test:custom-rules-example"
+
+[tasks."lint:licenses"]
+description = "Check third-party Maven dependency licenses"
+run = "python3 -B scripts/mise/tasks.py lint:licenses"
+
+[tasks."its:plugin"]
+description = "Run Plugin QA (JDK 21)"
+usage = '''
+flag "--sq-version " help="SonarQube version (default: LATEST_RELEASE)"
+flag "--test " help="Run one test class"
+flag "--community-only" help="Skip commercial-edition tests"
+'''
+run = "python3 -B scripts/mise/tasks.py its:plugin"
+
+[tasks.ruling]
+description = "Run a ruling profile (JDK 21)"
+usage = '''
+arg "" {
+  choices "without-sonarqube-project" "only-sonarqube-project"
+}
+flag "--rules " help="Comma-separated rule keys, e.g. S100,S101"
+flag "--project " help="Run one JavaRulingTest method in the selected profile"
+flag "--sq-version " help="SonarQube version (default: LATEST_RELEASE)"
+'''
+run = "python3 -B scripts/mise/tasks.py ruling"
+
+[tasks."analyze:vortex"]
+description = "Run DEEP Vortex analysis on the Git change set"
+run = "python3 -B scripts/mise/tasks.py analyze:vortex"
+
+[tasks.check]
+description = "Run unit, license, custom-rules-example and sanity checks"
+run = [{ task = "test:unit" }, { task = "lint:licenses" }, { task = "test:custom-rules-example" }, { task = "test:sanity" }]
+
+[tasks.ci]
+description = "Run check, Plugin QA and both Linux ruling profiles locally"
+run = [{ task = "check" }, { task = "its:plugin" }, { task = "ruling without-sonarqube-project" }, { task = "ruling only-sonarqube-project" }]
+
+[tasks."build:changed"]
+description = "Compile changed Maven modules and their prerequisites"
+run = "python3 -B scripts/mise/changed.py build:changed"
+
+[tasks."test:changed"]
+description = "Run corresponding tests for changed checks or tests in changed modules"
+run = "python3 -B scripts/mise/changed.py test:changed"
+
+[tasks."lint:licenses:changed"]
+description = "Run the license check only if Maven or license inputs changed"
+run = "python3 -B scripts/mise/changed.py lint:licenses:changed"
+
+[tasks."test:custom-rules-example:changed"]
+description = "Check the custom rules example only if its inputs changed"
+run = "python3 -B scripts/mise/changed.py test:custom-rules-example:changed"
+
+[tasks."check:changed"]
+description = "Check changed modules, including licenses and the custom example when relevant"
+run = "python3 -B scripts/mise/changed.py check:changed"
+
+[tasks.doctor]
+description = "Report which tasks can run, without installing tools or printing credentials"
+run = "python3 -B scripts/mise/doctor.py"
diff --git a/pom.xml b/pom.xml
index da6b1a56802..e5b91855ccf 100644
--- a/pom.xml
+++ b/pom.xml
@@ -111,6 +111,8 @@
     5.24.0
     ${project.build.directory}/test-java-agent-libs
     org.jacoco.agent-${version.jacoco.plugin}-runtime.jar
+    false
+    -javaagent:"${test-java-agent-directory}/${jacoco-agent-jar}=destfile=${project.build.directory}/jacoco.exec"
     mockito-core-${mockito-core.version}.jar
 
     
@@ -432,6 +434,7 @@
               copy
             
             
+              ${jacoco.skip}
               
                 
                   org.jacoco
@@ -441,6 +444,17 @@
                   ${test-java-agent-directory}
                   ${jacoco-agent-jar}
                 
+              
+            
+          
+          
+            download-mockito-agent
+            process-test-resources
+            
+              copy
+            
+            
+              
                 
                   org.mockito
                   mockito-core
@@ -461,10 +475,25 @@
           
             ${settings.localRepository}
           
-           -Dnet.bytebuddy.experimental=true -javaagent:"${test-java-agent-directory}/${jacoco-agent-jar}=destfile=${project.build.directory}/jacoco.exec" -javaagent:"${test-java-agent-directory}/${mockito-agent-jar}" 
+           -Dnet.bytebuddy.experimental=true ${jacoco-agent-arg} -javaagent:"${test-java-agent-directory}/${mockito-agent-jar}" 
         
       
     
   
 
+  
+    
+      skip-coverage
+      
+        
+          jacoco.skip
+          true
+        
+      
+      
+        
+      
+    
+  
+
 
diff --git a/scripts/mise/changed.py b/scripts/mise/changed.py
new file mode 100644
index 00000000000..117a51118ad
--- /dev/null
+++ b/scripts/mise/changed.py
@@ -0,0 +1,140 @@
+import os
+from pathlib import Path
+import re
+import subprocess
+import sys
+import xml.etree.ElementTree as ET
+
+from tasks import ROOT, custom_rules_example, licenses, maven, unit
+
+
+POM_FILE = "pom.xml"
+MAVEN_CONFIG = ".mvn/"
+CHECK_CHANGED = "check:changed"
+SKIP_HEADERS = "-Dlicense.skip=true"
+EXAMPLE = "docs/java-custom-rules-example/"
+CHECKS = ("java-checks", "java-checks-aws")
+JVM_MODULE = "java-checks-test-sources"
+MAVEN_NS = {"m": "http://maven.apache.org/POM/4.0.0"}
+
+
+def git(*args):
+    return subprocess.check_output(["git", *args], cwd=ROOT)
+
+
+def changed_paths():
+    ref = os.environ.get("MISE_CHANGE_BASE", "origin/master")
+    try:
+        base = git("merge-base", "--", "HEAD", ref).decode().strip()
+    except subprocess.CalledProcessError:
+        sys.exit("No comparison base. Set MISE_CHANGE_BASE to an available target branch or commit.")
+    tracked = git("diff", "--name-only", "--no-renames", "-z", base, "--")
+    others = git("ls-files", "--others", "--exclude-standard", "-z")
+    return set(os.fsdecode(tracked + others).rstrip("\0").split("\0")) - {""}
+
+
+def reactor_modules(path=ROOT):
+    pom = ET.parse(path / POM_FILE)
+    for entry in pom.findall("m:modules/m:module", MAVEN_NS):
+        module = path / entry.text.strip()
+        yield module.relative_to(ROOT).as_posix()
+        yield from reactor_modules(module)
+
+
+def license_input(path):
+    return (Path(path).name.startswith("pom") and path.endswith(".xml")) or path.startswith(
+        (MAVEN_CONFIG, "sonar-java-plugin/license-resources/", "sonar-java-plugin/src/main/resources/licenses/")
+    ) or Path(path).name in {"missing-dep-licenses.properties", "LICENSE.txt", "NOTICE.txt"}
+
+
+def example_input(path):
+    return path.startswith((EXAMPLE, MAVEN_CONFIG)) or path == POM_FILE
+
+
+def java_input(path):
+    return "/src/" in path or path.startswith("java-checks/src/test/files/") or Path(path).name == POM_FILE
+
+
+def affected_modules(paths):
+    if any(path == POM_FILE or path.startswith(MAVEN_CONFIG) or path == "forbid_junit4.txt" for path in paths):
+        return None
+    modules = sorted(reactor_modules(), key=len, reverse=True)
+    return {module for path in paths if java_input(path) and not path.startswith(EXAMPLE)
+            for module in [next((m for m in modules if path.startswith(f"{m}/")), None)] if module}
+
+
+def existing_test(module, test):
+    return next((ROOT / module / "src/test/java").rglob(f"{test}.java"), None) is not None
+
+
+def test_candidates(path, modules):
+    stem = Path(path).stem
+    if path.startswith(f"{JVM_MODULE}/"):
+        sample = re.fullmatch(r"(\w+Check)Sample(?:_?Java\d+)?", stem)
+        return [(module, f"{sample[1]}Test") for module in CHECKS] if sample else []
+    if "/src/test/java/" in path and stem.endswith("Test"):
+        return [(module, stem) for module in modules if path.startswith(f"{module}/")]
+    if "/src/main/java/" in path and stem.endswith("Check"):
+        return [(module, f"{stem}Test") for module in CHECKS if path.startswith(f"{module}/")]
+    return []
+
+
+def focused_tests(paths, modules):
+    tests = set()
+    for path in paths:
+        if not java_input(path) or path.startswith(EXAMPLE):
+            continue
+        matches = {(module, test) for module, test in test_candidates(path, modules) if existing_test(module, test)}
+        if not matches:
+            return None
+        tests.update(matches)
+    return tests
+
+
+def build_changed(modules):
+    args = ["compile", "-Dsonar.skip=true"]
+    if modules:
+        args += ["-pl", ",".join(sorted(modules)), "-am", SKIP_HEADERS]
+    maven(*args)
+
+
+def test_changed(paths, modules):
+    if not modules:
+        unit(goal="test")
+    elif tests := focused_tests(paths, modules):
+        unit(",".join(sorted({module for module, _ in tests})), ",".join(sorted({test for _, test in tests})),
+             goal="test", extra_args=(SKIP_HEADERS,))
+    else:
+        fixture_changes = any(module.startswith(JVM_MODULE) for module in modules)
+        selection = None if fixture_changes else ",".join(sorted(modules))
+        unit(selection, goal="test")
+
+
+def run_changed(task, paths):
+    if task in ("build:changed", "test:changed", CHECK_CHANGED):
+        modules = affected_modules(paths)
+        if modules == set():
+            print("No changed reactor inputs outside the custom rules example.", flush=True)
+        elif task == "build:changed":
+            build_changed(modules)
+        else:
+            test_changed(paths, modules)
+    if task in ("lint:licenses:changed", CHECK_CHANGED):
+        if any(license_input(path) for path in paths):
+            licenses()
+        else:
+            print("No changed license inputs.", flush=True)
+    if task in ("test:custom-rules-example:changed", CHECK_CHANGED):
+        if any(example_input(path) for path in paths):
+            custom_rules_example()
+        else:
+            print("No changed custom rules example inputs.", flush=True)
+
+
+if __name__ == "__main__":
+    try:
+        run_changed(sys.argv[1], changed_paths())
+    except subprocess.CalledProcessError as error:
+        sys.exit(error.returncode)
+    except FileNotFoundError as error:
+        sys.exit(f"Missing file or executable: {error.filename}")
diff --git a/scripts/mise/doctor.py b/scripts/mise/doctor.py
new file mode 100644
index 00000000000..e251baa83c7
--- /dev/null
+++ b/scripts/mise/doctor.py
@@ -0,0 +1,425 @@
+#!/usr/bin/env python3
+"""Read-only readiness checks for the mise tasks; never print probe output."""
+
+import base64
+from concurrent.futures import Future, TimeoutError as FutureTimeout
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+from threading import Thread
+from time import monotonic
+from urllib.error import HTTPError
+from urllib.parse import unquote, urlsplit
+from urllib.request import HTTPRedirectHandler, Request, build_opener
+import xml.etree.ElementTree as ET
+
+
+ROOT = Path(__file__).resolve().parents[2]
+HOME = Path.home()
+GIB = 1024**3
+SUBMODULE_FIX = "run git submodule update --init --recursive -- its/sources"
+MAVEN_FIX = "configure a Repox mirror and matching server credentials in Maven settings"
+ORCHESTRATOR_FIX = "set ORCHESTRATOR_CONFIG_URL to a local Orchestrator properties file (file:// URL)"
+TOKEN_FIX = "refresh orchestrator.artifactory.accessToken in the Orchestrator properties file"
+GITHUB_FIX = "export a valid GITHUB_TOKEN with read access to the QA licenses"
+SONAR_FIX = "run sonar auth login with an authorized SonarQube Cloud account"
+
+
+class ProbeFailure(Exception):
+    """Contains only fixed, safe-to-print diagnostics."""
+
+
+def fail(reason, fix):
+    raise ProbeFailure(f"{reason} — {fix}")
+
+
+def command(args, deadline, *, env=None, input_text=None):
+    return subprocess.run(
+        args, cwd=ROOT, input=input_text, stdin=subprocess.DEVNULL if input_text is None else None,
+        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env,
+        text=True, errors="replace", timeout=max(0.01, deadline - monotonic()), check=False,
+    )
+
+
+def mise_home(tool, deadline):
+    # --no-config avoids mise's tracked-config writes. Explicit versions still
+    # resolve from the same tool installation directory used by the tasks.
+    try:
+        result = command(["mise", "--no-config", "where", tool], deadline)
+    except FileNotFoundError:
+        fail("mise is not installed", "install mise and run mise install")
+    if result.returncode or not result.stdout.strip():
+        fail(f"{tool} is not installed", f"run mise install {tool}")
+    return Path(result.stdout.strip())
+
+
+def jdk(version, deadline):
+    tool = f"java@{version}"
+    path = mise_home(tool, deadline)
+    compiler = path / "bin/javac"
+    if not os.access(compiler, os.X_OK) or not os.access(path / "bin/java", os.X_OK):
+        fail(f"{tool} is not a complete JDK", f"reinstall {tool} with mise")
+    result = command([compiler, "-version"], deadline)
+    if result.returncode or not re.search(rf"\bjavac {version}(?:\.|\b)", result.stdout):
+        fail(f"JDK {version} cannot run", f"reinstall {tool} with mise")
+    return path
+
+
+def maven_home(deadline):
+    path = mise_home("maven@3.9", deadline)
+    # The mise Maven backend can keep the extracted Maven directory nested.
+    for candidate in (path, *path.glob("apache-maven-3.9.*")):
+        if os.access(candidate / "bin/mvn", os.X_OK) and any((candidate / "lib").glob("maven-core-3.9.*.jar")):
+            return candidate
+    fail("Maven 3.9 is not a complete installation", "reinstall maven@3.9 with mise")
+
+
+def xml(path):
+    root = ET.parse(path).getroot()
+    for node in root.iter():
+        node.tag = node.tag.rsplit("}", 1)[-1]
+    return root
+
+
+def interpolate(value):
+    return re.sub(r"\$\{env\.([^}]+)\}", lambda match: os.getenv(match[1], ""), value.strip())
+
+
+def setting(node, key):
+    return interpolate(node.findtext(key, ""))
+
+
+def settings_files(maven):
+    user = HOME / ".m2/settings.xml"
+    global_settings = maven / "conf/settings.xml"
+    config = ROOT / ".mvn/maven.config"
+    # Maven 3.9 uses one argument per line in .mvn/maven.config.
+    args = (config.read_text().splitlines() if config.is_file() else []) + os.getenv("MAVEN_ARGS", "").split()
+    for index, arg in enumerate(args):
+        flag, equals, value = arg.strip().partition("=")
+        if flag in ("-s", "--settings", "-gs", "--global-settings"):
+            path = Path(value if equals else args[index + 1].strip())
+            if flag in ("-s", "--settings"):
+                user = ROOT / path
+            else:
+                global_settings = ROOT / path
+    return user, global_settings
+
+
+def maven_settings(maven):
+    mirrors, servers = {}, {}
+    for path in settings_files(maven):
+        if not path.is_file():
+            continue
+        settings = xml(path)
+        for group, tag, entries in (("mirrors", "mirror", mirrors), ("servers", "server", servers)):
+            for entry in settings.findall(f"./{group}/{tag}"):
+                entries.setdefault(setting(entry, "id"), entry)
+    return mirrors, servers
+
+
+def https_url(url):
+    parsed = urlsplit(url)
+    return parsed.scheme == "https" and parsed.hostname and not (
+        parsed.username or parsed.password or parsed.query or parsed.fragment
+    )
+
+
+class NoRedirect(HTTPRedirectHandler):
+    def redirect_request(self, req, fp, code, msg, headers, newurl):
+        # Do not forward Authorization to a different endpoint or accept a login page.
+        return None
+
+
+def request_status(url, authorization, deadline, method="HEAD", accept=None):
+    headers = {"Authorization": authorization, "User-Agent": "sonar-java-mise-doctor"}
+    timeout = min(2.5, max(0.01, deadline - monotonic()))
+    try:
+        with build_opener(NoRedirect()).open(Request(url, headers=headers, method=method), timeout=timeout) as response:
+            if accept is not None and not accept(response.read(256 * 1024)):
+                return 404
+            return response.status
+    except HTTPError as error:
+        error.close()
+        return error.code
+    except (OSError, ValueError):
+        return None
+
+
+def check_access(status, service, credential_fix, endpoint_fix):
+    if status is None or status >= 500:
+        fail(f"{service} is unreachable", endpoint_fix)
+    if status in (401, 403):
+        fail(f"{service} rejected the credentials or access", credential_fix)
+    if not 200 <= status < 300:
+        fail(f"{service} did not return the required resource", endpoint_fix)
+
+
+# Use Maven's cipher/dispatcher rather than reimplementing its password format.
+# The ephemeral Java source contains no credentials. Ciphertext goes in over a
+# pipe, and decrypted credentials are captured in memory, never logged or saved.
+DECRYPT_SOURCE = """
+import java.nio.charset.StandardCharsets;
+import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
+import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
+class Decrypt {
+    public static void main(String[] args) throws Exception {
+        var dispatcher = new DefaultSecDispatcher(new DefaultPlexusCipher());
+        dispatcher.setConfigurationFile(args[0]);
+        System.out.print(dispatcher.decrypt(new String(System.in.readAllBytes(), StandardCharsets.UTF_8)));
+    }
+}
+"""
+
+
+def decipher(java, maven, ciphertext, deadline):
+    with tempfile.TemporaryDirectory(prefix="sonarjava-doctor-") as scratch:
+        source = Path(scratch) / "Decrypt.java"
+        source.write_text(DECRYPT_SOURCE, encoding="utf-8")
+        env = {key: value for key, value in os.environ.items()
+               if key not in ("JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS", "_JAVA_OPTIONS")}
+        result = command([java / "bin/java", "-cp", str(maven / "lib/*"), source,
+                          HOME / ".m2/settings-security.xml"], deadline, env=env, input_text=ciphertext)
+    if result.returncode or not result.stdout or result.stdout == ciphertext:
+        fail("Maven could not decrypt the Repox password", "check Maven settings-security.xml and refresh the Repox password")
+    return result.stdout
+
+
+def repox(deadline, tools):
+    maven = tools("maven")
+    if not maven:
+        fail("Repox credentials cannot be checked without Maven 3.9", "run mise install maven@3.9")
+    try:
+        mirrors, servers = maven_settings(maven)
+        # Maven considers exact repository IDs before wildcard mirrors.
+        mirror = next((entry for match in ("central", "*") for entry in mirrors.values()
+                       if setting(entry, "mirrorOf") == match), None)
+        url = setting(mirror, "url") if mirror is not None else ""
+        if not https_url(url) or "repox" not in urlsplit(url).hostname.lower():
+            fail("Maven has no HTTPS Repox mirror for central", MAVEN_FIX)
+        server = servers.get(setting(mirror, "id"))
+    except (OSError, ET.ParseError, IndexError, ValueError):
+        fail("Maven settings could not be read", "correct Maven settings.xml and any settings overrides")
+    username = setting(server, "username") if server is not None else ""
+    password = setting(server, "password") if server is not None else ""
+    if not username or not password or "${" in username or "${" in password:
+        fail("Maven credentials for the configured Repox mirror are missing", MAVEN_FIX)
+    if password.startswith("{") and password.endswith("}"):
+        java = tools("java26") or tools("java21")
+        if not java:
+            fail("the encrypted Repox password could not be checked without Java", "run mise install")
+        password = decipher(java, maven, password, deadline)
+    auth = base64.b64encode(f"{username}:{password}".encode()).decode("ascii")
+    parent = xml(ROOT / "pom.xml").find("parent")
+    group, artifact, version = (parent.findtext(key) for key in ("groupId", "artifactId", "version"))
+    path = f"{group.replace('.', '/')}/{artifact}/{version}/{artifact}-{version}.pom"
+    status = request_status(f"{url.rstrip('/')}/{path}", f"Basic {auth}", deadline)
+    check_access(status, "Repox", "refresh the Maven Repox credentials and check read access", "check VPN/network and the Repox mirror URL")
+
+
+def orchestrator_properties():
+    try:
+        source = urlsplit(os.getenv("ORCHESTRATOR_CONFIG_URL", ""))
+        if source.scheme != "file" or source.netloc not in ("", "localhost") or not source.path.startswith("/"):
+            fail("the Orchestrator properties file is not configured", ORCHESTRATOR_FIX)
+        text = Path(unquote(source.path)).read_text(encoding="latin-1")
+    except (OSError, ValueError):
+        fail("the Orchestrator properties file is unreadable", ORCHESTRATOR_FIX)
+    properties = {}
+    for line in text.splitlines():
+        match = re.match(r"\s*([^\s#!:=]+)(?:\s*[=:]\s*|\s+)(.*)", line)
+        if match:
+            key, value = match.groups()
+            properties[key] = value.strip().replace(r"\:", ":").replace(r"\=", "=")
+    return properties
+
+
+def orchestrator(deadline, properties):
+    props = properties
+    if props is None:
+        return
+    url = props.get("orchestrator.artifactory.url", "")
+    if not https_url(url):
+        fail("the Orchestrator Artifactory URL is missing or not HTTPS", "set orchestrator.artifactory.url in the Orchestrator properties file")
+    token = props.get("orchestrator.artifactory.accessToken", "")
+    if not token:
+        fail("the Orchestrator Artifactory token is missing", TOKEN_FIX)
+    # Query the same commercial release coordinates that Orchestrator resolves.
+    path = "api/search/versions?g=com.sonarsource.sonarqube&a=sonarqube-enterprise&remote=1&repos=sonarsource-releases"
+    status = request_status(f"{url.rstrip('/')}/{path}", f"Bearer {token}", deadline, method="GET",
+                            accept=lambda data: bool(json.loads(data).get("results")))
+    check_access(status, "Orchestrator Artifactory", TOKEN_FIX, "check VPN/network, orchestrator.artifactory.url and read access to release artifacts")
+
+
+def github(deadline, properties):
+    props = properties or {}
+    from_env = os.getenv("GITHUB_TOKEN", "").strip()
+    token = from_env or props.get("github.token", "")
+    if not token:
+        fail("the GitHub QA license token is missing", GITHUB_FIX)
+    fix = GITHUB_FIX if from_env else "refresh github.token in the Orchestrator properties file or export GITHUB_TOKEN"
+    # Checking repository contents, rather than /user, also verifies its scope.
+    status = request_status("https://api.github.com/repos/SonarSource/licenses/contents", f"Bearer {token}", deadline, method="GET")
+    if status == 404:
+        fail("the GitHub token cannot read the QA licenses", fix)
+    check_access(status, "GitHub QA license repository", fix, "check network access to GitHub and the QA licenses")
+
+
+def git(args, deadline):
+    # Avoid optional locks or fetching a missing object from a partial clone.
+    return command(["git", *args], deadline, env={**os.environ, "GIT_OPTIONAL_LOCKS": "0", "GIT_NO_LAZY_FETCH": "1"})
+
+
+def sources(deadline):
+    status = git(["submodule", "status", "--recursive", "--", "its/sources"], deadline)
+    lines = status.stdout.splitlines()
+    if status.returncode or not lines or any(not line.startswith(" ") for line in lines):
+        fail("its/sources or a nested submodule is not at its recorded checkout", SUBMODULE_FIX)
+
+
+def change_base(deadline):
+    base = os.environ.get("MISE_CHANGE_BASE", "origin/master")
+    commit = git(["rev-parse", "--verify", "--end-of-options", f"{base}^{{commit}}"], deadline)
+    if commit.returncode or git(["merge-base", "HEAD", commit.stdout.strip()], deadline).returncode:
+        fail("the change base does not resolve to a commit with a common ancestor", "set MISE_CHANGE_BASE to a local commit or fetch origin/master")
+
+
+def disk(_deadline):
+    for path in (ROOT, HOME / ".m2"):
+        while not path.exists() and path != path.parent:
+            path = path.parent
+        if shutil.disk_usage(path).free < 10 * GIB:
+            fail("less than 10 GiB of free space for Maven", "free space on the checkout and Maven cache filesystems")
+
+
+def memory(deadline):
+    if sys.platform == "darwin":
+        result = command(["sysctl", "-n", "hw.memsize"], deadline)
+        if result.returncode:
+            return
+        total = int(result.stdout.strip())
+    else:
+        total = os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")
+    if 0 < total < 12 * GIB:
+        return "WARNING: less than 12 GiB of RAM; Maven tasks use an 8 GiB Java heap."
+
+
+def sonar(deadline):
+    if not shutil.which("sonar"):
+        fail("the sonar CLI is not installed", "install the SonarQube CLI and run sonar auth login")
+    status = command(["sonar", "auth", "status", "--format", "json"], deadline,
+                     env={**os.environ, "DO_NOT_TRACK": "1"})
+    if status.returncode:
+        fail("the sonar CLI could not verify its login", SONAR_FIX)
+    try:
+        if json.loads(status.stdout).get("status") == "connected":
+            return
+    except (ValueError, AttributeError):
+        pass
+    fail("the sonar CLI is not logged in", SONAR_FIX)
+
+
+def require_jar(module, fix):
+    jars = (ROOT / module / "target").glob(f"{Path(module).name}-*.jar")
+    if not any(path.is_file() and not path.name.endswith(("-sources.jar", "-javadoc.jar", "-tests.jar")) for path in jars):
+        fail(f"the {Path(module).name} JAR has not been built", fix)
+
+
+# Share each prerequisite probe across tasks. QA only runs Maven on Java 21;
+# the artifacts it consumes were built on Java 26 by separate tasks.
+MAVEN_COMMON = ("maven", "repox", "disk")
+MAVEN = ("java26",) + MAVEN_COMMON
+QA = ("java21",) + MAVEN_COMMON + ("orchestrator_file", "orchestrator", "github", "plugin_jar")
+RULING = QA + ("sources",)
+TASKS = {
+    "build": MAVEN,
+    "test:unit": MAVEN,
+    "test:sanity": MAVEN,
+    "test:custom-rules-example": MAVEN,
+    "lint:licenses": MAVEN,
+    "its:plugin": QA + ("example_jar",),
+    "ruling": RULING,
+    "check": MAVEN,
+    "ci": tuple(key for key in dict.fromkeys(MAVEN + RULING) if key != "plugin_jar"),
+    "build:changed": MAVEN + ("change_base",),
+    "test:changed": MAVEN + ("change_base",),
+    "lint:licenses:changed": MAVEN + ("change_base",),
+    "test:custom-rules-example:changed": MAVEN + ("change_base",),
+    "check:changed": MAVEN + ("change_base",),
+    "analyze:vortex": ("sonar",),
+    "doctor": (),
+}
+
+
+def start_probe(check, deadline, label, fix):
+    result = Future()
+
+    def run():
+        try:
+            result.set_result((check(deadline), None))
+        except ProbeFailure as failure:
+            result.set_result((None, str(failure)))
+        except subprocess.TimeoutExpired:
+            result.set_result((None, f"the {label} check timed out — {fix}"))
+        except Exception:
+            # Exceptions from parsers and subprocesses may include secret values.
+            result.set_result((None, f"the {label} check failed — {fix}"))
+
+    # A stalled system DNS resolution must not extend the wall-clock deadline.
+    Thread(target=run, daemon=True).start()
+    return result, label, fix
+
+
+def main():
+    deadline = monotonic() + 4.5
+    checks = {}
+
+    def add(name, check, label, fix):
+        checks[name] = start_probe(check, deadline, label, fix)
+
+    def value(name):
+        return checks[name][0].result()[0]
+
+    add("java26", lambda end: jdk(26, end), "Java 26", "run mise install java@26")
+    add("java21", lambda end: jdk(21, end), "Java 21", "run mise install java@21")
+    add("maven", maven_home, "Maven", "run mise install maven@3.9")
+    add("repox", lambda end: repox(end, value), "Repox", "check VPN/network and Maven settings")
+    add("orchestrator_file", lambda _: orchestrator_properties(), "Orchestrator file", ORCHESTRATOR_FIX)
+    add("orchestrator", lambda end: orchestrator(end, value("orchestrator_file")), "Orchestrator Artifactory", TOKEN_FIX)
+    add("github", lambda end: github(end, value("orchestrator_file")), "GitHub", GITHUB_FIX)
+    build_fix = "run mise run build"
+    add("plugin_jar", lambda _: require_jar("sonar-java-plugin", build_fix), "analyzer JAR", build_fix)
+    add("example_jar", lambda _: require_jar("docs/java-custom-rules-example", build_fix), "custom example JAR", build_fix)
+    add("sources", sources, "recursive submodule", SUBMODULE_FIX)
+    add("change_base", change_base, "change base", "set MISE_CHANGE_BASE to a local commit or fetch origin/master")
+    add("disk", disk, "disk space", "check free space on the checkout and Maven cache filesystems")
+    add("sonar", sonar, "SonarQube CLI login", SONAR_FIX)
+    add("memory", memory, "memory", "check that the machine has at least 12 GiB of RAM")
+
+    results = {}
+    for key, (future, label, fix) in checks.items():
+        try:
+            results[key] = future.result(timeout=max(0, deadline - monotonic()))
+        except FutureTimeout:
+            results[key] = (None, f"the {label} check timed out — {fix}")
+    if results["memory"][0]:
+        print(results["memory"][0])
+
+    unavailable = False
+    for name, prerequisites in TASKS.items():
+        errors = [results[check][1] for check in prerequisites if results[check][1]]
+        if errors:
+            unavailable = True
+            print(f"{name}: CANNOT RUN: {'; '.join(errors)}")
+        else:
+            print(f"{name}: OK")
+    return int(unavailable)
+
+
+if __name__ == "__main__":
+    sys.exit(main())
diff --git a/scripts/mise/tasks.py b/scripts/mise/tasks.py
new file mode 100644
index 00000000000..1cd2fe59da9
--- /dev/null
+++ b/scripts/mise/tasks.py
@@ -0,0 +1,138 @@
+import os
+from pathlib import Path
+import re
+import shlex
+import subprocess
+import sys
+
+
+ROOT = Path(__file__).resolve().parents[2]
+PLUGIN_TASK = "its:plugin"
+SKIP_COVERAGE = "-Djacoco.skip=true"
+ALLOW_UNMATCHED = "-Dsurefire.failIfNoSpecifiedTests=false"
+IT_TASKS = {PLUGIN_TASK, "ruling"}
+
+
+def run(command, **kwargs):
+    subprocess.run(command, cwd=ROOT, check=True, **kwargs)
+
+
+def maven(*args, task=None, github_token=False):
+    env = os.environ.copy()
+    ci = "CI" in env
+    if not github_token:
+        env.pop("GITHUB_TOKEN", None)
+    env.setdefault("MAVEN_OPTS", "-Xmx8g")
+    options = shlex.split(env.get("MAVEN_OUTPUT_ARGS", ""))
+    if not ci:
+        env["MAVEN_OPTS"] += " -Ddevelocity.scan.disabled=true"
+        options.append("-Ddevelocity.scan.disabled=true")
+    java = "21" if task in IT_TASKS else "26"
+    run(["mise", "exec", f"java@{java}", "--", "mvn", "--batch-mode", *options, *args], env=env)
+
+
+def unit(module=None, test=None, coverage=False, goal="install", extra_args=()):
+    args = [goal, "-Dsonar.skip=true", *extra_args]
+    if module:
+        args += ["-pl", module, "-am"]
+    if test:
+        args += [f"-Dtest={test}", ALLOW_UNMATCHED]
+    if not coverage:
+        args.append(SKIP_COVERAGE)
+    maven(*args)
+
+
+def sanity():
+    options = ["verify", "-Psanity", "-Dtest=SanityTest", SKIP_COVERAGE]
+    sources = "java-checks-test-sources"
+    if "CI" in os.environ and os.environ.get("BUILD_NUMBER"):
+        maven("-f", f"{sources}/pom.xml", "clean", "compile")
+        maven("-f", "sonar-java-plugin/pom.xml", *options)
+    else:
+        projects = f"sonar-java-plugin,{sources}/default,{sources}/aws"
+        maven("-pl", projects, "-am", ALLOW_UNMATCHED, *options)
+
+
+def custom_rules_example():
+    maven("-f", "docs/java-custom-rules-example/pom_SQ_10_6_LATEST.xml", "clean", "package")
+
+
+def licenses():
+    maven("org.codehaus.mojo:license-maven-plugin:aggregate-add-third-party",
+          f"-Dlicense.missingFile={ROOT / 'missing-dep-licenses.properties'}", "-DuseMissingFile")
+
+
+def integration(task, profile, sq_version, selectors, github_token=True):
+    directory = "plugin" if task == PLUGIN_TASK else "ruling"
+    args = ["-f", f"its/{directory}/pom.xml", "package", f"-P{profile}",
+            f"-Dsonar.runtimeVersion={sq_version}", "-Dmaven.test.redirectTestOutputToFile=false"]
+    for variable, prop in (("ORCHESTRATOR_CONFIG_URL", "orchestrator.configUrl"),
+                           ("ORCHESTRATOR_HOME", "orchestrator.home")):
+        if value := os.environ.get(variable):
+            args.append(f"-D{prop}={value}")
+    if "CI" in os.environ:
+        parallel = "classes" if task == PLUGIN_TASK else "methods"
+        args += [f"-Dparallel={parallel}", "-DuseUnlimitedThreads=true"]
+    maven(*args, *selectors, task=task, github_token=github_token)
+
+
+def plugin(test, sq_version, community_only):
+    selectors = ["-DcommunityEditionTestsOnly=true"] if community_only else []
+    if test:
+        selectors += [f"-Dtest={test}", ALLOW_UNMATCHED]
+    selected_class = test.rsplit(".", 1)[-1] if test else None
+    needs_license = selected_class != "SonarLintIntegrationTest" and not (community_only and selected_class == "JspTest")
+    integration(PLUGIN_TASK, "it-plugin", sq_version, selectors, github_token=needs_license)
+
+
+def ruling(profile, rules, project, sq_version):
+    selectors = [f"-DsonarRules={rules}"] if rules else []
+    if project:
+        if (profile == "only-sonarqube-project") != (project == "sonarqube_server"):
+            raise SystemExit("The selected method does not belong to the ruling profile.")
+        selectors.append(f"-Druling.test=org.sonar.java.it.JavaRulingTest#{project}")
+    integration("ruling", f"it-ruling,{profile}", sq_version, selectors)
+
+
+def usage(name, pattern=None):
+    value = os.environ.get(f"usage_{name}")
+    if value and pattern and not re.fullmatch(pattern, value):
+        sys.exit(f"Invalid {name.replace('_', '-')} selector.")
+    return value
+
+
+def vortex():
+    env = os.environ.copy()
+    env.pop("GITHUB_TOKEN", None)
+    command = ["sonar", "analyze", "agentic", "--depth", "DEEP"]
+    if base := env.get("MISE_CHANGE_BASE"):
+        command += ["--base", base]
+    run(command, env=env)
+
+
+def main(task):
+    if task == "test:unit":
+        unit(usage("module"), usage("test"), usage("coverage") == "true")
+    elif task == PLUGIN_TASK:
+        plugin(usage("test", r"[\w.]+"), usage("sq_version") or "LATEST_RELEASE", usage("community_only") == "true")
+    elif task == "ruling":
+        ruling(usage("profile"), usage("rules", r"S\d+(,S\d+)*"), usage("project", r"\w+"),
+               usage("sq_version") or "LATEST_RELEASE")
+    else:
+        actions = {
+            "analyze:vortex": vortex,
+            "build": lambda: maven("install", "-DskipTests", SKIP_COVERAGE, "-Dsonar.skip=true"),
+            "test:sanity": sanity,
+            "test:custom-rules-example": custom_rules_example,
+            "lint:licenses": licenses,
+        }
+        actions[task]()
+
+
+if __name__ == "__main__":
+    try:
+        main(sys.argv[1])
+    except subprocess.CalledProcessError as error:
+        sys.exit(error.returncode)
+    except FileNotFoundError as error:
+        sys.exit(f"Missing executable: {error.filename}")
diff --git a/sonar-java-plugin/src/main/resources/profiles/README.md b/sonar-java-plugin/src/main/resources/profiles/README.md
index 9b716712f52..e049dab37c2 100644
--- a/sonar-java-plugin/src/main/resources/profiles/README.md
+++ b/sonar-java-plugin/src/main/resources/profiles/README.md
@@ -1,44 +1,13 @@
-# Quality Profile Definitions
+---
+title: Built-in Java quality profiles
+description: The profile directories supply the build with the Sonar way and Sonar agentic AI membership inputs.
+generated:
+  by: tirion
+---
 
-This directory contains quality profile definitions for the SonarQube Java analyzer.
+# Built-in Java quality profiles
 
-## Structure
+- `sonar-java-plugin/src/main/resources/profiles/Sonar_way`
+- `sonar-java-plugin/src/main/resources/profiles/Sonar_agentic_AI`
 
-Each subdirectory represents a quality profile:
-
-- `sonar_way/` - Rules in the "Sonar way" profile
-- `sonar_agentic_ai/` - Rules in the "Sonar agentic AI" profile
-
-## How to Add a Rule to a Profile
-
-To add a rule to a quality profile, simply create an empty file named after the rule key in the appropriate profile directory.
-
-**Example:** To add rule S8910 to both profiles:
-
-```bash
-touch sonar-java-plugin/src/main/resources/profiles/sonar_way/S8910
-touch sonar-java-plugin/src/main/resources/profiles/sonar_agentic_ai/S8910
-```
-
-## How to Remove a Rule from a Profile
-
-Delete the corresponding file from the profile directory:
-
-```bash
-rm sonar-java-plugin/src/main/resources/profiles/sonar_way/S1234
-```
-
-## Build Process
-
-During the Maven build, the `ProfileJsonGenerator` reads these directories and generates the profile JSON files at:
-- `target/generated-resources/profiles/org/sonar/l10n/java/rules/java/Sonar_way_profile.json`
-- `target/generated-resources/profiles/org/sonar/l10n/java/rules/java/Sonar_agentic_AI_profile.json`
-
-These generated files are then packaged into the plugin JAR.
-
-## Benefits of This Approach
-
-1. **No merge conflicts** - Parallel PRs adding different rules create different files
-2. **Clear review** - `git diff` shows exactly which rules were added/removed
-3. **Simple** - No need to edit large JSON arrays or maintain complex metadata
-4. **Maintainable** - One file per rule makes it easy to track profile membership
+Read [Rule metadata and quality profiles](../../../../../docs/systems/rule-metadata.md) before changing membership or generation.