hooks: check_black: pass stdin argument and check returncode When checking file content from git via stdin, black requires '-' as an argument to read from standard input. In addition, black signals formatting issues or errors through its exit code (0 if formatted, non-zero if formatting is needed) rather than stdout. Update check_black to: - Pass '-q' and '-' to black to quietly check stdin. - Check result.returncode instead of result.stdout. - Provide a default error message when stdout is empty. Bug: 488338724 Test: python3 -m pytest rh/hooks_unittest.py Change-Id: Iee44d1153c3d793d65e81883e8418126a798ac39 Reviewed-on: https://gerrit-review.googlesource.com/c/git-repohooks/+/647263 Tested-by: Josh Wu <joshwu@google.com> Commit-Queue: Josh Wu <joshwu@google.com> Reviewed-by: Mike Frysinger <vapier@google.com>
diff --git a/rh/hooks.py b/rh/hooks.py index 9627ae8..bad744e 100644 --- a/rh/hooks.py +++ b/rh/hooks.py
@@ -440,20 +440,20 @@ tool = options.tool_path("black") tool_options = options.args((), filtered) - cmd = [tool, "--check"] + tool_options + cmd = [tool, "-q", "--check", "-"] + tool_options fixup_cmd = [tool] + tool_options + ["--"] ret = [] for d in filtered: data = rh.git.get_file_content(commit, d.file) result = _run(cmd, input=data) - if result.stdout: + if result.returncode: ret.append( rh.results.HookResult( "black", project, commit, - error=result.stdout, + error=result.stdout or "Files not formatted", files=(d.file,), fixup_cmd=fixup_cmd, )