I'll help you create a Python script to check indentation in files. Here's a comprehensive solution that meets all your requirements:
#!/usr/bin/env python3
"""
Indentation checker for files using tabs.
Detects space, mixed, empty, and alignment indentation issues.
"""
import argparse
import os
import sys
import re
from pathlib import Path
from typing import List, Optional, TextIO, Tuple
class IndentationChecker:
def __init__(self, tab_size: int = 4, ignore_alignment: bool = False,
alignment_pattern: Optional[str] = None,
ignore_cpp_comments: bool = False,
ignore_xml_comments: bool = False):
self.tab_size = tab_size
self.ignore_alignment = ignore_alignment
self.alignment_pattern = re.compile(alignment_pattern) if alignment_pattern else None
self.ignore_cpp_comments = ignore_cpp_comments
self.ignore_xml_comments = ignore_xml_comments
def check_line(self, line: str, line_num: int, filepath: str,
in_cpp_comment: bool, in_xml_comment: bool,
prev_line: Optional[str] = None) -> Optional[Tuple[str, str]]:
"""Check a single line for indentation issues."""
# Skip checks if we're inside a comment and ignoring is enabled
if (in_cpp_comment and self.ignore_cpp_comments) or \
(in_xml_comment and self.ignore_xml_comments):
return None
# Strip newline but preserve other whitespace
line_content = line.rstrip('\n\r')
# Find where non-whitespace starts
non_ws_match = re.search(r'\S', line_content)
if non_ws_match:
# Line has non-whitespace content
indentation = line_content[:non_ws_match.start()]
# Check for space-only indentation
if indentation and ' ' in indentation and '\t' not in indentation:
return ('Space Indentation', line_content)
# Check for mixed indentation
elif ' ' in indentation and '\t' in indentation:
return ('Mixed Indentation', line_content)
# Check for alignment indentation
elif self._is_alignment_indentation(indentation):
# Check if we should ignore this alignment
if self.ignore_alignment:
if self.alignment_pattern is None:
return None # Ignore all alignment
elif prev_line and self.alignment_pattern.search(prev_line):
return None # Ignore alignment when pattern matches previous line
return ('Alignment Indentation', line_content)
else:
# Line has only whitespace
if line_content: # Not completely empty (has tabs/spaces)
return ('Empty Indentation', line_content)
return None
def _is_alignment_indentation(self, indentation: str) -> bool:
"""Check if indentation represents alignment (tabs followed by spaces)."""
if not indentation:
return False
# Find the last tab
last_tab_idx = indentation.rfind('\t')
if last_tab_idx == -1:
return False
# Check if there are spaces after the last tab
spaces_after_tab = indentation[last_tab_idx + 1:]
if not spaces_after_tab or not all(c == ' ' for c in spaces_after_tab):
return False
# Check if number of spaces is less than tab size
return len(spaces_after_tab) < self.tab_size
def check_file(self, filepath: Path, output: TextIO) -> int:
"""Check a single file for indentation issues."""
issues_found = 0
try:
with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
lines = f.readlines()
except Exception as e:
print(f"Error reading {filepath}: {e}", file=sys.stderr)
return 0
in_cpp_comment = False
in_xml_comment = False
prev_line = None
for line_num, line in enumerate(lines, 1):
# Track comment state changes on this line
cpp_changes = self._track_cpp_comments(line, in_cpp_comment)
xml_changes = self._track_xml_comments(line, in_xml_comment)
# Determine if we should check this line
check_line = True
# For multi-line comments, ignore from the second line
if self.ignore_cpp_comments and in_cpp_comment and line_num > 1:
# Check if the comment started on a previous line
if not any(change[1] for change in cpp_changes if change[0] == 0):
check_line = False
if self.ignore_xml_comments and in_xml_comment and line_num > 1:
# Check if the comment started on a previous line
if not any(change[1] for change in xml_changes if change[0] == 0):
check_line = False
# Check the line if needed
if check_line:
result = self.check_line(line, line_num, str(filepath),
in_cpp_comment, in_xml_comment, prev_line)
if result:
issue_type, line_content = result
output.write(f"{filepath}:{line_num}: {issue_type}: '{line_content}'\n")
issues_found += 1
# Update comment states for next iteration
for _, is_start in cpp_changes:
in_cpp_comment = is_start
for _, is_start in xml_changes:
in_xml_comment = is_start
prev_line = line.rstrip('\n\r')
return issues_found
def _track_cpp_comments(self, line: str, currently_in_comment: bool) -> List[Tuple[int, bool]]:
"""Track C++ style comment state changes in a line."""
changes = []
in_comment = currently_in_comment
in_string = False
escape_next = False
i = 0
while i < len(line):
if escape_next:
escape_next = False
i += 1
continue
if line[i] == '\\' and not in_comment:
escape_next = True
i += 1
continue
# Handle strings (outside comments)
if not in_comment and line[i] in '"\'':
if not in_string:
in_string = line[i]
elif in_string == line[i]:
in_string = False
i += 1
continue
if in_string:
i += 1
continue
# Handle comments
if not in_comment:
# Check for // comment
if i + 1 < len(line) and line[i:i+2] == '//':
# Rest of line is comment, but single-line only
break
# Check for /* comment start
elif i + 1 < len(line) and line[i:i+2] == '/*':
changes.append((i, True))
in_comment = True
i += 2
continue
else:
# In comment, look for */
if i + 1 < len(line) and line[i:i+2] == '*/':
changes.append((i + 2, False))
in_comment = False
i += 2
continue
i += 1
return changes
def _track_xml_comments(self, line: str, currently_in_comment: bool) -> List[Tuple[int, bool]]:
"""Track XML style comment state changes in a line."""
changes = []
in_comment = currently_in_comment
i = 0
while i < len(line):
if not in_comment:
# Check for <!-- comment start
if i + 3 < len(line) and line[i:i+4] == '<!--':
changes.append((i, True))
in_comment = True
i += 4
continue
else:
# In comment, look for -->
if i + 2 < len(line) and line[i:i+3] == '-->':
changes.append((i + 3, False))
in_comment = False
i += 3
continue
i += 1
return changes
def match_filters(filepath: Path, include_filters: List[str],
exclude_filters: List[str]) -> bool:
"""Check if filepath matches include/exclude filters."""
filepath_str = str(filepath)
# If include filters are specified, file must match at least one
if include_filters:
if not any(filter_pattern in filepath_str for filter_pattern in include_filters):
return False
# File must not match any exclude filter
if exclude_filters:
if any(filter_pattern in filepath_str for filter_pattern in exclude_filters):
return False
return True
def process_path(path: Path, checker: IndentationChecker, output: TextIO,
include_filters: List[str], exclude_filters: List[str],
recurse: bool) -> int:
"""Process a file or directory."""
total_issues = 0
if path.is_file():
if match_filters(path, include_filters, exclude_filters):
total_issues += checker.check_file(path, output)
elif path.is_dir():
if recurse:
for item in path.rglob('*'):
if item.is_file() and match_filters(item, include_filters, exclude_filters):
total_issues += checker.check_file(item, output)
else:
for item in path.iterdir():
if item.is_file() and match_filters(item, include_filters, exclude_filters):
total_issues += checker.check_file(item, output)
else:
print(f"Warning: {path} is neither a file nor a directory", file=sys.stderr)
return total_issues
def main():
parser = argparse.ArgumentParser(
description="Check indentation in files (expecting tabs)"
)
parser.add_argument('paths', nargs='*', default=['.'],
help='Files or directories to check (default: current directory)')
parser.add_argument('--include', nargs='*', default=[],
help='Include filters for file paths')
parser.add_argument('--exclude', nargs='*', default=[],
help='Exclude filters for file paths')
parser.add_argument('--no-recurse', action='store_true',
help='Do not recurse into directories')
parser.add_argument('--tab-size', type=int, default=4,
help='Tab stop size (default: 4)')
parser.add_argument('--output', type=str, default=None,
help='Output file (default: stdout)')
parser.add_argument('--ignore-alignment', nargs='?', const='', default=None,
help='Ignore alignment indentation, optionally with pattern to match previous line')
parser.add_argument('--ignore-cpp-comments', action='store_true',
help='Ignore indentation inside C++ style /* */ comments')
parser.add_argument('--ignore-xml-comments', action='store_true',
help='Ignore indentation inside XML <!-- --> comments')
args = parser.parse_args()
# Set up output
if args.output:
try:
output_file = open(args.output, 'w', encoding='utf-8')
except Exception as e:
print(f"Error opening output file: {e}", file=sys.stderr)
return 1
else:
output_file = sys.stdout
try:
# Create checker
checker = IndentationChecker(
tab_size=args.tab_size,
ignore_alignment=(args.ignore_alignment is not None),
alignment_pattern=args.ignore_alignment if args.ignore_alignment else None,
ignore_cpp_comments=args.ignore_cpp_comments,
ignore_xml_comments=args.ignore_xml_comments
)
# Process all paths
total_issues = 0
for path_str in args.paths:
path = Path(path_str)
total_issues += process_path(
path, checker, output_file,
args.include, args.exclude,
not args.no_recurse
)
# Report summary to stderr
if total_issues > 0:
print(f"\nTotal issues found: {total_issues}", file=sys.stderr)
finally:
if args.output:
output_file.close()
return 0 if total_issues == 0 else 1
if __name__ == '__main__':
sys.exit(main())