build(style): fast newline check with --fix as part of make format

The end of file newline check spawned two processes per tracked file and
took ~85s, so it only ran as a separate CI job. Rewrite it in Python
reading only the last bytes of each file (~0.3s) and add --fix to append
a missing or drop duplicate newlines.

Run it in make format (--fix), make check_format and the pre-commit hook
(staged text files only), and drop the separate check_newlines CI job.
This commit is contained in:
Matthias Grob committed 2026-11-26 10:24:01 +01:00
1 parent 1c15438ec5
commit 0430d0d816
5 files changed
+115 -25

No files matched your search

-1
View File
@@ -30,7 +30,6 @@ jobs:
matrix:
check: [
"check_format",
"check_newlines",
"validate_module_configs",
"shellcheck_all",
"module_documentation",
+3 -5
View File
@@ -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
+104
View File
@@ -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())
-19
View File
@@ -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
+8
View File
@@ -53,6 +53,14 @@ if [ $? -ne 0 ]; then
exit 1
fi
# 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 '' -- | xargs -0 -r ./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 ./Tools/astyle/check_newlines.py --fix"
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"
if [ $? -ne 0 ]