[llvm] code-format: Improve the code-format-helper to be able to run as a git hook (PR #73957)

Aiden Grossman via llvm-commits llvm-commits at lists.llvm.org
Wed Dec 6 13:09:55 PST 2023


================
@@ -205,7 +284,39 @@ def format_run(
 
 ALL_FORMATTERS = (DarkerFormatHelper(), ClangFormatHelper())
 
+
+def hook_main():
+    # fill out args
+    args = FormatArgs()
+    args.verbose = False
+
+    # find the changed files
+    cmd = ["git", "diff", "--cached", "--name-only", "--diff-filter=d"]
+    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    output = proc.stdout.decode("utf-8")
+    for line in output.splitlines():
+        args.changed_files.append(line)
+
+    failed_fmts = []
+    for fmt in ALL_FORMATTERS:
+        if fmt.has_tool():
+            if not fmt.run(args.changed_files, args):
+                failed_fmts.append(fmt.name)
+        else:
+            print(f"Couldn't find {fmt.name}, can't check " + fmt.friendly_name.lower())
+
+    if len(failed_fmts) > 0:
+        sys.exit(1)
+
+    sys.exit(0)
+
+
 if __name__ == "__main__":
+    script_path = os.path.abspath(__file__)
+    if ".git/hooks" in script_path:  # and "GIT_DIR" in os.environ:
----------------
boomanaiden154 wrote:

Is the comment here a leftover from testing?

https://github.com/llvm/llvm-project/pull/73957


More information about the llvm-commits mailing list