CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-clang-format

Python distribution of the LLVM clang-format code formatting tool for C, C++, and CUDA

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

Clang-Format

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.

Package Information

  • Package Name: clang-format
  • Language: Python
  • Installation: pip install clang-format
  • Alternative Installation: pipx install clang-format (for isolated execution)

Core Imports

import clang_format

For accessing utility functions:

from clang_format import get_executable

For accessing git integration and diff-based formatting:

from clang_format import git_clang_format, clang_format_diff

Basic Usage

Command Line Usage

After 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.py

Python API Usage

import 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.stdout

Pre-commit Hook Usage

repos:
- repo: https://github.com/pre-commit/mirrors-clang-format
  rev: v21.1.0
  hooks:
  - id: clang-format
    types_or: [c++, c, cuda]

Architecture

The package uses a simple wrapper architecture:

  • Binary Distribution: Native clang-format binaries bundled in data/bin/ directory
  • Python Wrapper: Utility functions to locate and execute the bundled executable
  • Console Scripts: Entry points that bridge Python package to command-line tools
  • Build-time Integration: Additional utilities (git-clang-format, clang-format-diff.py) copied from LLVM project during build

Capabilities

Executable Path Resolution

Utility 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)

Main Entry Point

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 Integration Module

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_format

Programmatic 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}")

Diff-Based Formatting Module

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_diff

Programmatic 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_stdin

Console Script Integration

The package provides three console script entry points for different clang-format utilities:

clang-format

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 processed

git-clang-format

Git 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 changes
  • git clang-format HEAD~1: Format changes since last commit
  • git clang-format --diff: Show formatting changes without applying

clang-format-diff.py

Diff-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 diff
  • clang-format-diff.py -p1 < changes.patch: Apply formatting to patch

Integration Patterns

Common integration patterns for development workflows:

CI/CD Integration

# Install in CI environment
pip install clang-format

# Check formatting in CI
clang-format --dry-run --Werror *.cpp *.h

Development Workflow

# Install with pipx for isolated usage
pipx install clang-format

# Format before commit
git add .
git clang-format
git commit -m "Apply clang-format"

Python Script Integration

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()

Error Handling

The package handles common error scenarios:

  • Missing executable: If the bundled executable is not found, functions will raise FileNotFoundError
  • Invalid arguments: Command-line argument errors are passed through from the underlying clang-format tool
  • Permission errors: File permission issues are handled by the underlying subprocess calls

Platform Support

  • Cross-platform: Supports Windows, macOS, and Linux
  • Architecture support: Binary wheels available for common architectures
  • Python versions: Compatible with Python 3.x (check package metadata for specific version requirements)

Additional Notes

The 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.

Install with Tessl CLI

npx tessl i tessl/pypi-clang-format
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/clang-format@21.1.x
Publish Source
CLI
Badge
tessl/pypi-clang-format badge