[clang] Add ability for clang-format-diff to exit with non-0 status (PR #70883)

Conrad Donahue via cfe-commits cfe-commits at lists.llvm.org
Tue Oct 31 18:58:34 PDT 2023


https://github.com/conrad-donahue created https://github.com/llvm/llvm-project/pull/70883

This patch adds the ability for the clang-format-diff script to exit with a non-zero status if it detects that formatting changes are necessary. This makes it easier to use clang-format-diff as part of a DevOps pipeline, since you could add a stage to run clang-format-diff and fail if the formatting needs to be fixed.

>From 646cabcf167facb63c78277b50ea62afbc61b3c0 Mon Sep 17 00:00:00 2001
From: Conrad Donahue <conradjdonahue at gmail.com>
Date: Tue, 31 Oct 2023 21:55:27 -0400
Subject: [PATCH] Add ability for clang-format-diff to exit with non-0 status

---
 clang/docs/ClangFormat.rst                    | 1 +
 clang/tools/clang-format/clang-format-diff.py | 8 ++++++++
 2 files changed, 9 insertions(+)

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index f52f35550d03eb6..42864b90e408037 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -325,6 +325,7 @@ output of a unified diff and reformats all contained lines with
                           The name of the predefined style used as a fallback in case clang-format is invoked with-style=file, but can not
                           find the .clang-formatfile to use.
     -binary BINARY        location of binary to use for clang-format
+    -non-zero-exit-code   exit with a non-zero status if formatting changes are necessary
 
 To reformat all the lines in the latest Mercurial/:program:`hg` commit, do:
 
diff --git a/clang/tools/clang-format/clang-format-diff.py b/clang/tools/clang-format/clang-format-diff.py
index 324ef5b7f6b35f6..755ef23649a2469 100755
--- a/clang/tools/clang-format/clang-format-diff.py
+++ b/clang/tools/clang-format/clang-format-diff.py
@@ -95,6 +95,12 @@ def main():
         default="clang-format",
         help="location of binary to use for clang-format",
     )
+    parser.add_argument(
+        "-non-zero-exit-code",
+        action="store_true",
+        default=False,
+        help="exit with a non-zero status if formatting changes are necessary"
+    )
     args = parser.parse_args()
 
     # Extract changed lines for each file.
@@ -185,6 +191,8 @@ def main():
             diff_string = "".join(diff)
             if len(diff_string) > 0:
                 sys.stdout.write(diff_string)
+                if args.non_zero_exit_code:
+                    sys.exit(1)
 
 
 if __name__ == "__main__":



More information about the cfe-commits mailing list