Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ jobs:
matrix:
check: [
"check_format",
"check_newlines",
"validate_module_configs",
"shellcheck_all",
"module_documentation",
Expand Down
8 changes: 3 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
104 changes: 104 additions & 0 deletions Tools/astyle/check_newlines.py
Original file line number Diff line number Diff line change
@@ -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 changes: 0 additions & 19 deletions Tools/astyle/check_newlines.sh

This file was deleted.

23 changes: 20 additions & 3 deletions Tools/astyle/pre-commit
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 '' -- |
Comment thread
MaEtUgR marked this conversation as resolved.
Resolved
(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
Loading