Python distribution of the LLVM clang-format code formatting tool for C, C++, and CUDA
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
A Python distribution of the LLVM clang-format code formatting tool for C, C++, and CUDA. This package provides convenient installation and usage of clang-format without requiring separate LLVM development tools, making it ideal for development workflows, CI/CD pipelines, and pre-commit hooks.
pip install clang-formatpipx install clang-format (for isolated execution)import clang_formatFor accessing utility functions:
from clang_format import get_executableFor accessing git integration and diff-based formatting:
from clang_format import git_clang_format, clang_format_diffAfter installation, use the console scripts directly:
# Format a single file
clang-format main.cpp
# Format with specific style
clang-format -style=Google main.cpp
# Format in-place
clang-format -i main.cpp
# Format multiple files
clang-format *.cpp *.h
# Git integration - format staged changes
git-clang-format
# Format specific lines from diff
clang-format-diff.pyimport clang_format
import subprocess
# Get path to clang-format executable
exe_path = clang_format.get_executable('clang-format')
print(f"clang-format executable: {exe_path}")
# Use subprocess to run clang-format programmatically
result = subprocess.run([
exe_path,
'-style=LLVM',
'source.cpp'
], capture_output=True, text=True)
formatted_code = result.stdoutrepos:
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v21.1.0
hooks:
- id: clang-format
types_or: [c++, c, cuda]The package uses a simple wrapper architecture:
data/bin/ directoryUtility function to get the full path to the bundled clang-format executable, enabling programmatic usage and integration with other tools.
def get_executable(name):
"""
Get the full path to the specified executable.
Parameters:
- name: str, name of the executable (e.g., "clang-format")
Returns:
str: Full path to the executable in the package's data/bin directory
"""Usage Example:
import clang_format
import subprocess
# Get executable path
exe_path = clang_format.get_executable('clang-format')
# Use with subprocess for custom formatting
result = subprocess.run([
exe_path,
'-style=file', # Use .clang-format file
'-i', # Format in-place
'source.cpp'
], check=True)Primary entry point function that executes clang-format with command-line arguments. This function replicates command-line behavior within Python scripts.
def clang_format():
"""
Execute clang-format with command-line arguments from sys.argv.
This function processes sys.argv[1:] as arguments and exits with
the subprocess return code. Intended for console script usage.
Raises:
SystemExit: Always exits with subprocess return code
"""Usage Example:
import sys
import clang_format
# Programmatically set arguments
sys.argv = ['clang-format', '-style=Google', 'main.cpp']
# Execute (will exit process)
clang_format.clang_format()Git-aware formatting that applies clang-format only to changed lines in commits or staging area, providing selective formatting for version-controlled codebases.
def main():
"""
Main entry point for git-clang-format integration.
Processes command-line arguments and executes git-aware formatting,
applying clang-format selectively to changed lines in git repositories.
Returns:
int: Exit code (0 for no changes, 1 for changes applied)
"""Module Import:
from clang_format import git_clang_formatProgrammatic Usage:
import sys
from clang_format import git_clang_format
# Set arguments for git integration
sys.argv = ['git-clang-format', '--diff', 'HEAD~1']
# Execute git-aware formatting
result = git_clang_format.main()
print(f"Exit code: {result}")Universal diff processor that applies clang-format to specific changed lines from unified diff input, compatible with any version control system.
def main():
"""
Main entry point for diff-based selective formatting.
Reads unified diff from stdin and applies clang-format only to
the changed lines, supporting selective formatting workflows.
Returns:
int: Status code (1 if differences found, subprocess return code on failure)
"""Module Import:
from clang_format import clang_format_diffProgrammatic Usage:
import sys
import io
from clang_format import clang_format_diff
# Prepare diff input
diff_content = """--- a/example.cpp
+++ b/example.cpp
@@ -1,3 +1,4 @@
int main() {
- return 0;
+ return 0;
+ // Comment
}
"""
# Redirect stdin and execute
old_stdin = sys.stdin
sys.stdin = io.StringIO(diff_content)
sys.argv = ['clang-format-diff.py', '-i']
result = clang_format_diff.main()
sys.stdin = old_stdinThe package provides three console script entry points for different clang-format utilities:
Main code formatting utility for C, C++, and CUDA source code.
Console Command:
clang-format [options] [files...]Entry Point: clang_format:clang_format
Common Options:
-style=<style>: Formatting style (LLVM, Google, Chromium, Mozilla, WebKit, Microsoft, GNU, file)-i: Format files in-place--dry-run: Don't write changes, just show what would be formatted--sort-includes: Sort #include directives--verbose: Show which files are being processedGit integration utility that formats only the lines changed in git commits or staging area.
Console Command:
git clang-format [git-options]Entry Point: clang_format.git_clang_format:main
Common Usage:
git clang-format: Format staged changesgit clang-format HEAD~1: Format changes since last commitgit clang-format --diff: Show formatting changes without applyingDiff-based formatting utility that applies clang-format to specific changed lines from unified diff format.
Console Command:
clang-format-diff.py [diff-options]Entry Point: clang_format.clang_format_diff:main
Common Usage:
git diff HEAD~1 | clang-format-diff.py -i: Format changes from diffclang-format-diff.py -p1 < changes.patch: Apply formatting to patchCommon integration patterns for development workflows:
# Install in CI environment
pip install clang-format
# Check formatting in CI
clang-format --dry-run --Werror *.cpp *.h# Install with pipx for isolated usage
pipx install clang-format
# Format before commit
git add .
git clang-format
git commit -m "Apply clang-format"import clang_format
import subprocess
import os
def format_project_files():
"""Format all C++ files in project."""
exe_path = clang_format.get_executable('clang-format')
for root, dirs, files in os.walk('.'):
for file in files:
if file.endswith(('.cpp', '.h', '.cc', '.hpp')):
filepath = os.path.join(root, file)
subprocess.run([exe_path, '-i', filepath], check=True)
print(f"Formatted: {filepath}")
# Usage
format_project_files()The package handles common error scenarios:
FileNotFoundErrorThe package includes internal helper functions that are not part of the public API. These functions handle the underlying process execution and are abstracted by the public interface.