Draft
Show file tree
Hide file tree
Changes from 11 commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Failed to load files.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
/*
* Copyright 2022-2025 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.spotless.extra.middleware;

import java.util.List;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.Lint;

/**
* Utility class for generating ReviewDog compatible output in the rdjsonl format.
* This class provides methods to create diff and lint reports that can be used by ReviewDog.
*/
public final class ReviewDogGenerator {

private static final String SOURCE = "spotless";

private ReviewDogGenerator() {
// Prevent instantiation
}

/**
* Generates a ReviewDog compatible JSON line (rdjsonl) for a diff between
* the actual content and the formatted content of a file.
*
* @param path The file path
* @param actualContent The content as it currently exists in the file
* @param formattedContent The content after formatting is applied
* @return A string in rdjsonl format representing the diff
*/
public static String rdjsonlDiff(String path, String actualContent, String formattedContent) {
if (actualContent.equals(formattedContent)) {
return "";
}

String diff = createUnifiedDiff(path, actualContent, formattedContent);

return String.format(
"{\"message\":{\"path\":\"%s\",\"message\":\"File requires formatting\",\"diff\":\"%s\"}}",
escapeJson(path),
escapeJson(diff));
}

/**
* Generates ReviewDog compatible JSON lines (rdjsonl) for lint issues
* identified by formatting steps.
*
* @param path The file path
* @param steps The list of formatter steps applied
* @param lintsPerStep The list of lints produced by each step
* @return A string in rdjsonl format representing the lints
*/
public static String rdjsonlLints(String path, List<FormatterStep> steps, List<List<Lint>> lintsPerStep) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should formattedContent also be output in the ReviewDog format in rdjsonlLints?

if (lintsPerStep == null || lintsPerStep.isEmpty()) {
return "";
}

StringBuilder builder = new StringBuilder();

for (int i = 0; i < lintsPerStep.size(); i++) {
List<Lint> lints = lintsPerStep.get(i);
if (lints == null || lints.isEmpty()) {
continue;
}

String stepName = (i < steps.size()) ? steps.get(i).getName() : "unknown";
for (Lint lint : lints) {
builder.append(formatLintAsJson(path, lint, stepName)).append('\n');
}
}

return builder.toString().trim();
}

/**
* Creates a unified diff between two text contents.
*/
private static String createUnifiedDiff(String path, String actualContent, String formattedContent) {
String[] actualLines = actualContent.split("\\r?\\n", -1);
String[] formattedLines = formattedContent.split("\\r?\\n", -1);

StringBuilder diff = new StringBuilder();
diff.append("--- a/").append(path).append('\n');
diff.append("+++ b/").append(path).append('\n');
diff.append("@@ -1,").append(actualLines.length).append(" +1,").append(formattedLines.length).append(" @@\n");

for (String line : actualLines) {
diff.append('-').append(line).append('\n');
}

for (String line : formattedLines) {
diff.append('+').append(line).append('\n');
}

return diff.toString();
}

/**
* Formats a single lint issue as a JSON line.
*/
private static String formatLintAsJson(String path, Lint lint, String ruleCode) {
return String.format(
"{"
+ "\"source\":\"%s\","
+ "\"code\":\"%s\","
+ "\"level\":\"warning\","
+ "\"message\":\"%s\","
+ "\"path\":\"%s\","
+ "\"line\":%d,"
+ "\"column\":%d"
+ "}",
escapeJson(SOURCE),
escapeJson(ruleCode),
escapeJson(lint.getDetail()),
escapeJson(path),
lint.getLineStart(),
1);
}

/**
* Escapes special characters in a string for JSON compatibility.
*/
private static String escapeJson(String str) {
if (str == null) {
return "";
}
return str
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t")
.replace("\b", "\\b")
.replace("\f", "\\f");
}
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
@ParametersAreNonnullByDefault
@ReturnValuesAreNonnullByDefault
package com.diffplug.spotless.extra.middleware;

import javax.annotation.ParametersAreNonnullByDefault;

import com.diffplug.spotless.annotations.ReturnValuesAreNonnullByDefault;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
/*
* Copyright 2022-2025 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.diffplug.spotless.extra.middleware;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.Test;

import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.Lint;

public class ReviewDogGeneratorTest {

@Test
public void diffSingleLine() {
String result = ReviewDogGenerator.rdjsonlDiff("test.txt", "dirty", "clean");
assertNotNull(result);
assertTrue(result.contains("\"path\":\"test.txt\""));
assertTrue(result.contains("\"diff\":"));
assertTrue(result.contains("-dirty"));
assertTrue(result.contains("+clean"));
}

@Test
public void diffNoChange() {
String result = ReviewDogGenerator.rdjsonlDiff("test.txt", "same", "same");
assertEquals("", result);
}

@Test
public void diffMultipleLines() {
String actual = "Line 1\nLine 2\nDirty line\nLine 4";
String formatted = "Line 1\nLine 2\nClean line\nLine 4";

String result = ReviewDogGenerator.rdjsonlDiff("src/main.java", actual, formatted);

assertNotNull(result);
assertTrue(result.contains("\"path\":\"src/main.java\""));
assertTrue(result.contains("-Dirty line"));
assertTrue(result.contains("+Clean line"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of this, just do Selfie.expectSelfie(result).toBe_TODO(). When you run it, it will replace the TODO with the actual content. Makes the assertion easier to read, write, and maintain.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What a awesome feature!!!
Done in 5724b73 , 745810b !

}

@Test
public void lintsEmpty() {
List<FormatterStep> steps = new ArrayList<>();
List<List<Lint>> lintsPerStep = new ArrayList<>();

String result = ReviewDogGenerator.rdjsonlLints("test.txt", steps, lintsPerStep);
assertEquals("", result);
}

@Test
public void lintsSingleIssue() {
FormatterStep step = FormatterStep.create(
"testStep",
"formatter-state",
state -> rawUnix -> rawUnix);
List<FormatterStep> steps = Collections.singletonList(step);

Lint lint = Lint.atLine(1, "TEST001", "Test lint message");
List<List<Lint>> lintsPerStep = Collections.singletonList(Collections.singletonList(lint));

String result = ReviewDogGenerator.rdjsonlLints("src/main.java", steps, lintsPerStep);

assertNotNull(result);
assertTrue(result.contains("\"path\":\"src/main.java\""));
assertTrue(result.contains("\"line\":1"));
assertTrue(result.contains("\"message\":\"Test lint message\""));
assertTrue(result.contains("\"code\":\"testStep\""));
}

@Test
public void lintsMultipleIssues() {
FormatterStep step1 = new FormatterStep() {
@Override
public String getName() {
return "step1";
}

@Override
public String format(String rawUnix, File file) {
return rawUnix;
}

@Override
public void close() {}
};

FormatterStep step2 = FormatterStep.create(
"step2",
"formatter-state",
state -> rawUnix -> rawUnix);

List<FormatterStep> steps = Arrays.asList(step1, step2);

Lint lint1 = Lint.atLine(1, "RULE1", "First issue");
Lint lint2 = Lint.atLine(5, "RULE2", "Second issue");

List<List<Lint>> lintsPerStep = Arrays.asList(
Collections.singletonList(lint1),
Collections.singletonList(lint2));

String result = ReviewDogGenerator.rdjsonlLints("src/main.java", steps, lintsPerStep);

assertNotNull(result);
assertTrue(result.contains("\"code\":\"step1\""));
assertTrue(result.contains("\"code\":\"step2\""));
assertTrue(result.contains("\"message\":\"First issue\""));
assertTrue(result.contains("\"message\":\"Second issue\""));

String[] lines = result.split("\n");
assertEquals(2, lines.length);
}
}
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2024 DiffPlug
* Copyright 2024-2025 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,6 +6,8 @@ We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (
### Changed
* Bump default `eclipse` version to latest `4.34` -> `4.35`. ([#2458](https://.com/diffplug/spotless/pull/2458))
* Bump default `greclipse` version to latest `4.32` -> `4.35`. ([#2458](https://.com/diffplug/spotless/pull/2458))
### Added
* Implement conversion of diff content to ReviewDog format ([#2478](https://.com/diffplug/spotless/pull/2478))

## [7.0.3] - 2025-04-07
### Changed
Expand Down
Loading