Skip to content
Draft
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
4 changes: 4 additions & 0 deletions SerialPrograms/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ add_custom_target(build-time-make-directory ALL
# Internal repo or not, we're always building from the SerialPrograms folder
set(REPO_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../")

# Optional development targets; do not build or link the application.
include(cmake/Formatting.cmake)
pa_add_format_targets("${REPO_ROOT_DIR}")

# Determine environment
if(DEFINED ENV{GITHUB_ACTIONS})
message(STATUS "Detected CI environment, skipping qt deployment")
Expand Down
29 changes: 29 additions & 0 deletions SerialPrograms/cmake/Formatting.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Incremental C++ formatting, with no application build dependency.
# cmake --build /path/to/build --target format # apply eligible edited-line spacing
# cmake --build /path/to/build --target format-check # non-writing check
include_guard(GLOBAL)

# Add explicit targets; defer Python/tool discovery until a formatting target is run.
function(pa_add_format_targets repo_root)
get_filename_component(format_repo "${repo_root}" ABSOLUTE)
set(PA_FORMAT_BASE "HEAD" CACHE STRING "Git parent ref for incremental formatting (merge base with HEAD)")
set(PA_FORMAT_PYTHON "" CACHE FILEPATH "Optional Python 3.8+ interpreter for formatting only")
foreach(format_target IN ITEMS format format-check)
if(format_target STREQUAL "format")
set(format_mode --write)
else()
set(format_mode --check)
endif()
add_custom_target(${format_target}
COMMAND "${CMAKE_COMMAND}"
"-DPA_FORMAT_REPO=${format_repo}"
"-DPA_FORMAT_BASE=${PA_FORMAT_BASE}"
"-DPA_FORMAT_MODE=${format_mode}"
"-DPA_FORMAT_PYTHON=${PA_FORMAT_PYTHON}"
-P "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/RunFormatting.cmake"
COMMENT "Incremental C++ ${format_target}: Git-edited lines only"
USES_TERMINAL
VERBATIM
)
endforeach()
endfunction()
25 changes: 25 additions & 0 deletions SerialPrograms/cmake/RunFormatting.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Target-time adapter; invoked by Formatting.cmake, not during application configure.
# cmake --build /path/to/build --target format-check
cmake_minimum_required(VERSION 3.24)

if(NOT PA_FORMAT_MODE STREQUAL "--write" AND NOT PA_FORMAT_MODE STREQUAL "--check")
message(FATAL_ERROR "Use the format or format-check build target.")
endif()
if(PA_FORMAT_PYTHON)
set(Python3_EXECUTABLE "${PA_FORMAT_PYTHON}")
endif()
find_package(Python3 3.8 QUIET COMPONENTS Interpreter)
if(NOT Python3_Interpreter_FOUND)
message(FATAL_ERROR "Formatting needs Python 3.8+. Install it or configure PA_FORMAT_PYTHON=/path/to/python3.")
endif()
execute_process(
COMMAND "${Python3_EXECUTABLE}" "${PA_FORMAT_REPO}/devtools/format/format_changed.py"
--repo "${PA_FORMAT_REPO}" --base "${PA_FORMAT_BASE}" "${PA_FORMAT_MODE}"
RESULT_VARIABLE format_result
)
if(NOT format_result STREQUAL "0")
if(PA_FORMAT_MODE STREQUAL "--check" AND format_result STREQUAL "1")
message(FATAL_ERROR "Edited-line formatting remains. Run the format target, then review and stage its changes.")
endif()
message(FATAL_ERROR "Incremental formatter failed (${format_result}); see its diagnostic above. Requires Uncrustify 0.83.0 and Clang; clang-format is not used.")
endif()
58 changes: 58 additions & 0 deletions devtools/format/CMAKE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# CMake formatting targets

After this integration is present in the configured source checkout:

```sh
cmake --build /path/to/build --target format-check
cmake --build /path/to/build --target format
```

`format-check` previews eligible changes and fails if any remain. `format`
applies them. Neither target builds or links the app. They use the
[edited-line formatter](INCREMENTAL.md), not clang-format: tracked staged and
unstaged changes against HEAD, with all original leading columns/newlines kept.
They skip block reflows, preprocessor definitions and declaration lines. Review
the output and stage changes yourself; the index is never changed automatically.

The target belongs to the build directory's **configured source checkout**.
Running a lab build's target formats that lab checkout, not a different feature
worktree in the terminal's current directory. Use a build configured from your
feature worktree, or invoke the Python command with `--repo` to choose another.
An old build does not gain targets until its source picks up this integration
and CMake reconfigures.

Python 3.8+, Uncrustify 0.83.0 and Clang are needed when formatting eligible
changes. Python discovery happens only when a format target runs; it does not
add a Python/formatter requirement to normal app configuration. No dependency
is downloaded automatically and no clang-format installation is required.

Optional settings:

```sh
cmake -S SerialPrograms -B /path/to/build \
-DPA_FORMAT_BASE=origin/main \
-DPA_FORMAT_PYTHON=/path/to/python3
```

`PA_FORMAT_BASE` defaults to HEAD; another ref selects its merge base with HEAD
for whole-branch formatting. Use the actual parent for a stacked branch. Leave
`PA_FORMAT_PYTHON` empty to discover Python at target time. `UNCRUSTIFY` and
`CLANG` environment variables select non-PATH executables as with the CLI.

To configure a tools-only build without Qt/OpenCV or application dependencies:

```sh
cmake -S SerialPrograms -B /path/to/tools-build \
-DPA_CORE_ONLY=ON -DCOMMAND_LINE_EXE=OFF
cmake --build /path/to/tools-build --target format-check
```

This still performs normal CMake compiler/thread checks but compiles no app
when the explicit formatting target is requested. There is no `cmake --format`
flag; formatting is a project-defined build target. CTest registration for the
native application tests is a separate integration.

Tests live in `test_cmake.py` beside the formatter tests and include the actual
CMake module. They check source/build paths with spaces, a committed parent ref,
index preservation, useful missing-Python diagnostics, and that explicit format
targets do not run an unrelated ALL/application target.
78 changes: 78 additions & 0 deletions devtools/format/test_cmake.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""CMake format targets: python3 -m unittest discover -s devtools/format -p test_cmake.py -v."""

from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest


ROOT = Path(__file__).resolve().parents[2]


class CMakeFormattingTests(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory(prefix='format targets ')
self.addCleanup(self.directory.cleanup)
root = Path(self.directory.name)
self.repo, self.build, self.project = root / 'code tree', root / 'build tree', root / 'project'
self.project.mkdir()
(self.repo / 'Common').mkdir(parents=True)
(self.repo / 'devtools/format').mkdir(parents=True)
shutil.copy2(ROOT / '.uncrustify.cfg', self.repo / '.uncrustify.cfg')
shutil.copy2(ROOT / 'devtools/format/format_changed.py', self.repo / 'devtools/format/format_changed.py')
self.source = self.repo / 'Common/example.cpp'
self.source.write_bytes(b'void f(){\n int untouched=1;\n int changed=2;\n}\n')
self.git('init', '-q')
self.git('add', '.')
self.git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid',
'-c', 'commit.gpgSign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'base')
self.marker = root / 'app-was-built'
self.project.joinpath('CMakeLists.txt').write_text(
'cmake_minimum_required(VERSION 3.24)\nproject(FormatTargets NONE)\n'
f'include("{(ROOT / "SerialPrograms/cmake/Formatting.cmake").as_posix()}")\n'
f'pa_add_format_targets("{self.repo.as_posix()}")\n'
f'add_custom_target(app ALL COMMAND "${{CMAKE_COMMAND}}" -E touch "{self.marker.as_posix()}")\n'
)

def git(self, *args):
return subprocess.check_output(['git', '-C', str(self.repo), *args])

def configure(self, *args):
subprocess.run(['cmake', '-S', str(self.project), '-B', str(self.build),
'-DPA_FORMAT_PYTHON=' + sys.executable, *args],
capture_output=True, check=True)

def target(self, name):
return subprocess.run(['cmake', '--build', str(self.build), '--target', name], capture_output=True)

def test_check_write_and_no_application_dependency(self):
self.configure()
self.source.write_bytes(b'void f(){\n int untouched=1;\n int changed=3;\n}\n')
staged = self.git('diff', '--cached', '--binary')
self.assertNotEqual(0, self.target('format-check').returncode)
result = self.target('format')
self.assertEqual(0, result.returncode, result.stderr.decode())
self.assertEqual(b'void f(){\n int untouched=1;\n int changed = 3;\n}\n', self.source.read_bytes())
self.assertEqual(0, self.target('format-check').returncode)
self.assertEqual(staged, self.git('diff', '--cached', '--binary'))
self.assertFalse(self.marker.exists())

def test_missing_python_does_not_break_configure(self):
self.configure('-DPA_FORMAT_PYTHON=' + str(self.repo / 'missing-python'))
result = self.target('format')
self.assertNotEqual(0, result.returncode)
self.assertIn(b'Formatting needs Python 3.8+', result.stderr)
self.assertFalse(self.marker.exists())

def test_configured_parent_includes_committed_edits(self):
base = self.git('rev-parse', 'HEAD').decode().strip()
self.source.write_bytes(b'void f(){\n int untouched=1;\n int changed=3;\n}\n')
self.git('add', '.')
self.git('-c', 'user.name=Test', '-c', 'user.email=test@example.invalid',
'-c', 'commit.gpgSign=false', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'edit')
self.configure('-DPA_FORMAT_BASE=' + base)
self.assertEqual(0, self.target('format').returncode)
self.assertIn(b'int changed = 3;', self.source.read_bytes())
self.assertIn(b'int untouched=1;', self.source.read_bytes())
Loading