diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index d2098cb06f63..89c3a53132d5 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -30,7 +30,6 @@ jobs: matrix: check: [ "check_format", - "check_newlines", "validate_module_configs", "shellcheck_all", "module_documentation", diff --git a/Makefile b/Makefile index 38ba2eb9835e..1ad0c5ffbd40 100644 --- a/Makefile +++ b/Makefile @@ -413,27 +413,25 @@ px4_metadata: parameters_metadata airframe_metadata module_documentation extract # Style # -------------------------------------------------------------------- -.PHONY: check_format format format_changed check_newlines +.PHONY: check_format format format_changed check_format: $(call colorecho,'Checking formatting with astyle') @"$(SRC_DIR)"/Tools/astyle/check_code_style_all.sh @"$(SRC_DIR)"/Tools/astyle/check_param_names.py + @"$(SRC_DIR)"/Tools/astyle/check_newlines.py @cd "$(SRC_DIR)" && git diff --check format: $(call colorecho,'Formatting with astyle') @"$(SRC_DIR)"/Tools/astyle/check_param_names.py --fix + @"$(SRC_DIR)"/Tools/astyle/check_newlines.py --fix @"$(SRC_DIR)"/Tools/astyle/check_code_style_all.sh --fix format_changed: $(call colorecho,'Formatting changed files with astyle') @"$(SRC_DIR)"/Tools/astyle/check_code_style_all.sh --fix --diff-only -check_newlines: - $(call colorecho,'Checking for missing or duplicate newlines at the end of files') - @"$(SRC_DIR)"/Tools/astyle/check_newlines.sh - # Testing # -------------------------------------------------------------------- .PHONY: tests tests_daa_crosstrack tests_vtest_moving tests_neural tests_nocache tests_coverage tests_mission tests_mission_coverage tests_offboard diff --git a/Tools/astyle/check_newlines.py b/Tools/astyle/check_newlines.py new file mode 100755 index 000000000000..8994a8135bda --- /dev/null +++ b/Tools/astyle/check_newlines.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +""" +Check that tracked text files end in exactly one newline: a missing one breaks +the POSIX definition of a line, more than one fails trailing whitespace checks. + +Usage: + check_newlines.py check all tracked text files outside docs/ + check_newlines.py FILE... check only the given files + check_newlines.py --fix [FILE...] add a missing or remove extra newlines + +Only the last bytes of each file are read, so checking the whole tree is fast +enough to run as part of make format. +""" + +import argparse +import os +import subprocess +import sys + + +def text_files(): + """Tracked files git does not consider binary, excluding docs/, relative to the repository root.""" + result = subprocess.run(['git', 'grep', '--cached', '-Il', '-z', '', '--', ':!docs/*'], + capture_output=True, check=False) + + if result.returncode not in (0, 1): # 1: no match + sys.stderr.write(result.stderr.decode(errors='replace')) + sys.exit(result.returncode) + + return [p.decode() for p in result.stdout.split(b'\0') if p] + + +def line_ending(f, size): + """Trailing '\\r' and '\\n' bytes at the end of the file.""" + ending = b'' + position = size + + while position > 0: + chunk = min(position, 64) + position -= chunk + f.seek(position) + data = f.read(chunk) + stripped = data.rstrip(b'\r\n') + ending = data[len(stripped):] + ending + + if stripped: + break + + return ending + + +def check(path, fix): + try: + with open(path, 'rb+' if fix else 'rb') as f: + size = os.fstat(f.fileno()).st_size + ending = line_ending(f, size) + newlines = ending.count(b'\n') + + if size == 0 or (newlines == 1 and ending.endswith(b'\n')): + return True + + if not fix: + print(f'{"Multiple newlines" if newlines > 1 else "No new line"} at the end of {path}') + return False + + if newlines == 0: # replace stray '\r' bytes, if any, by a newline + f.truncate(size - len(ending)) + f.seek(0, os.SEEK_END) + f.write(b'\n') + + elif len(ending) == size: # file contains only line endings + f.truncate(0) + + else: # keep the first line ending (including a possible '\r'), drop the rest + f.truncate(size - len(ending) + ending.index(b'\n') + 1) + + print(f'Fixed newlines at the end of {path}') + return True + + except (FileNotFoundError, IsADirectoryError): # deleted or replaced in the working tree + return True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--fix', action='store_true', help='fix the files in place') + parser.add_argument('files', nargs='*', help='files to check (default: all tracked text files outside docs/)') + args = parser.parse_args() + + if args.files: + files = args.files + + else: + top = subprocess.run(['git', 'rev-parse', '--show-toplevel'], + capture_output=True, text=True, check=True).stdout.strip() + os.chdir(top) + files = text_files() + + ok = all([check(path, args.fix) for path in files]) + return 0 if ok else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/Tools/astyle/check_newlines.sh b/Tools/astyle/check_newlines.sh deleted file mode 100755 index 27bae971126b..000000000000 --- a/Tools/astyle/check_newlines.sh +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env bash - -return_value=0 - -# Check if there are files checked in that don't end in a newline (POSIX requirement) -git grep --cached -Il '' -- ':!docs/*' | xargs -L1 bash -c 'if test "$(tail -c 1 "$0")"; then echo "No new line at end of $0"; exit 1; fi' - -if [ $? -ne 0 ]; then - return_value=1 -fi - -# Check if there are files checked in that have duplicate newlines at the end (fail trailing whitespace checks) -git grep --cached -Il '' -- ':!docs/*' | xargs -L1 bash -c 'if tail -c 2 "$0" | ( read x && read y && [ x"$x" = x ] && [ x"$y" = x ]); then echo "Multiple newlines at the end of $0"; exit 1; fi' - -if [ $? -ne 0 ]; then - return_value=1 -fi - -exit $return_value diff --git a/Tools/astyle/pre-commit b/Tools/astyle/pre-commit index 2172e3bdc428..50927d13468b 100755 --- a/Tools/astyle/pre-commit +++ b/Tools/astyle/pre-commit @@ -1,4 +1,4 @@ -#!/bin/sh +#!/usr/bin/env bash # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should @@ -53,10 +53,27 @@ if [ $? -ne 0 ]; then exit 1 fi +# The following checks run on the staged content, exported into a temporary +# directory, so that unstaged changes neither hide nor cause errors. +REPO=$(git rev-parse --show-toplevel) +STAGED_DIR=$(mktemp -d) +trap 'rm -rf "$STAGED_DIR"' EXIT +git diff --cached --name-only --diff-filter=ACM -z | git checkout-index --stdin -z --prefix="$STAGED_DIR/" + +# Check for missing or duplicate newlines at the end of changed text files +git diff --cached --name-only --diff-filter=ACM -z -- ':!docs/*' | xargs -0 -r git grep --cached -Il -z '' -- | + (cd "$STAGED_DIR" && xargs -0 -r "$REPO/Tools/astyle/check_newlines.py") +if [ $? -ne 0 ] +then + echo "Pre-commit style error: Missing or duplicate newlines at the end of files, fix with \"make format\" and stage the result" + exit 1 +fi + # Check for code style, only in changed files -bash -c "comm -12 <(./Tools/astyle/files_to_check_code_style.sh | sort) <(git diff --cached --name-only --diff-filter=ACM) | xargs ./Tools/astyle/check_code_style.sh" +comm -12 <(./Tools/astyle/files_to_check_code_style.sh | sort) <(git diff --cached --name-only --diff-filter=ACM | sort) | + (cd "$STAGED_DIR" && xargs -r "$REPO/Tools/astyle/check_code_style.sh") if [ $? -ne 0 ] then - echo "Pre-commit style error: Bad formatting according to astyle rules" + echo "Pre-commit style error: Bad formatting according to astyle rules, fix with \"make format\" and stage the result" exit 1 fi