Skip to content

Commit 9eb81c8

Browse files
committed
[clang-format] Fix a bug that always returns error for JSON
Fixes #108556.
1 parent d989c24 commit 9eb81c8

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// RUN: echo '{' > %t.json
2+
// RUN: echo ' "married": true' >> %t.json
3+
// RUN: echo '}' >> %t.json
4+
5+
// RUN: clang-format -n -style=LLVM %t.json 2>&1 | FileCheck %s -allow-empty
6+
// CHECK-NOT: warning
7+
8+
// RUN: clang-format -n -style=LLVM < %t.json 2>&1 \
9+
// RUN: | FileCheck %s -check-prefix=CHECK2 -strict-whitespace
10+
// CHECK2: warning: code should be clang-formatted
11+
12+
// RUN: rm %t.json

clang/tools/clang-format/ClangFormat.cpp

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -351,9 +351,6 @@ static void outputReplacementsXML(const Replacements &Replaces) {
351351
static bool
352352
emitReplacementWarnings(const Replacements &Replaces, StringRef AssumedFileName,
353353
const std::unique_ptr<llvm::MemoryBuffer> &Code) {
354-
if (Replaces.empty())
355-
return false;
356-
357354
unsigned Errors = 0;
358355
if (WarnFormat && !NoWarnFormat) {
359356
SourceMgr Mgr;
@@ -490,9 +487,11 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) {
490487
Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
491488
AssumedFileName, &CursorPosition);
492489

490+
const bool IsJson = FormatStyle->isJson();
491+
493492
// To format JSON insert a variable to trick the code into thinking its
494493
// JavaScript.
495-
if (FormatStyle->isJson() && !FormatStyle->DisableFormat) {
494+
if (IsJson && !FormatStyle->DisableFormat) {
496495
auto Err = Replaces.add(tooling::Replacement(
497496
tooling::Replacement(AssumedFileName, 0, 0, "x = ")));
498497
if (Err)
@@ -511,8 +510,10 @@ static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) {
511510
reformat(*FormatStyle, *ChangedCode, Ranges, AssumedFileName, &Status);
512511
Replaces = Replaces.merge(FormatChanges);
513512
if (OutputXML || DryRun) {
514-
if (DryRun)
515-
return emitReplacementWarnings(Replaces, AssumedFileName, Code);
513+
if (DryRun) {
514+
return (Replaces.size() > IsJson ? 1 : 0) &&
515+
emitReplacementWarnings(Replaces, AssumedFileName, Code);
516+
}
516517
outputXML(Replaces, FormatChanges, Status, Cursor, CursorPosition);
517518
} else {
518519
IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem(

0 commit comments

Comments
 (0)