|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Arduino Include Checker |
| 4 | +Scans .ino files and ensures they have #include <Arduino.h> before preprocessor directives |
| 5 | +""" |
| 6 | + |
| 7 | +import sys |
| 8 | +import re |
| 9 | +import argparse |
| 10 | +from pathlib import Path |
| 11 | +from typing import List, Tuple |
| 12 | + |
| 13 | + |
| 14 | +def has_arduino_include(content: str) -> bool: |
| 15 | + """Check if content already has Arduino.h include""" |
| 16 | + patterns = [ |
| 17 | + r'#include\s*<Arduino\.h>', |
| 18 | + r'#include\s*"Arduino\.h"' |
| 19 | + ] |
| 20 | + for pattern in patterns: |
| 21 | + if re.search(pattern, content): |
| 22 | + return True |
| 23 | + return False |
| 24 | + |
| 25 | + |
| 26 | +def find_first_preprocessor_line(lines: List[str]) -> int: |
| 27 | + """ |
| 28 | + Find the index of the first preprocessor directive (line starting with #) |
| 29 | + Returns -1 if no preprocessor directive found |
| 30 | + """ |
| 31 | + for i, line in enumerate(lines): |
| 32 | + stripped = line.lstrip() |
| 33 | + if stripped.startswith('#'): |
| 34 | + return i |
| 35 | + return -1 |
| 36 | + |
| 37 | + |
| 38 | +def add_arduino_include(filepath: Path, verbose: bool = False) -> Tuple[bool, str]: |
| 39 | + """ |
| 40 | + Add #include <Arduino.h> to the file before the first preprocessor directive |
| 41 | + Returns (success, message) |
| 42 | + """ |
| 43 | + try: |
| 44 | + with open(filepath, 'r', encoding='utf-8') as f: |
| 45 | + content = f.read() |
| 46 | + |
| 47 | + # Check if already has Arduino.h include |
| 48 | + if has_arduino_include(content): |
| 49 | + return True, "Already has Arduino.h include" |
| 50 | + |
| 51 | + lines = content.split('\n') |
| 52 | + first_directive_idx = find_first_preprocessor_line(lines) |
| 53 | + |
| 54 | + if first_directive_idx == -1: |
| 55 | + return False, "No preprocessor directive found" |
| 56 | + |
| 57 | + # Insert the include before the first directive |
| 58 | + lines.insert(first_directive_idx, '#include <Arduino.h>') |
| 59 | + |
| 60 | + # Write back to file |
| 61 | + with open(filepath, 'w', encoding='utf-8') as f: |
| 62 | + f.write('\n'.join(lines)) |
| 63 | + |
| 64 | + return True, "Added #include <Arduino.h>" |
| 65 | + |
| 66 | + except Exception as e: |
| 67 | + return False, f"Error processing file: {str(e)}" |
| 68 | + |
| 69 | + |
| 70 | +def scan_ino_files(root_dir: str, verbose: bool = False) -> Tuple[List[Path], List[Path], List[Tuple[Path, str]]]: |
| 71 | + """ |
| 72 | + Scan directory for .ino files and process them |
| 73 | + Returns (already_had_include, files_added, failed_files_with_reasons) |
| 74 | + """ |
| 75 | + already_had = [] |
| 76 | + added = [] |
| 77 | + failed = [] |
| 78 | + |
| 79 | + root_path = Path(root_dir) |
| 80 | + if not root_path.exists(): |
| 81 | + print(f"Error: Directory '{root_dir}' does not exist") |
| 82 | + sys.exit(1) |
| 83 | + |
| 84 | + # Find all .ino files |
| 85 | + ino_files = list(root_path.rglob('*.ino')) |
| 86 | + |
| 87 | + if not ino_files: |
| 88 | + if verbose: |
| 89 | + print(f"No .ino files found in '{root_dir}'") |
| 90 | + return already_had, added, failed |
| 91 | + |
| 92 | + if verbose: |
| 93 | + print(f"Found {len(ino_files)} .ino file(s)") |
| 94 | + print("-" * 60) |
| 95 | + |
| 96 | + for filepath in ino_files: |
| 97 | + if verbose: |
| 98 | + print(f"\nProcessing: {filepath.relative_to(root_path)}") |
| 99 | + |
| 100 | + success, message = add_arduino_include(filepath, verbose) |
| 101 | + |
| 102 | + if verbose: |
| 103 | + print(f" → {message}") |
| 104 | + |
| 105 | + if success: |
| 106 | + if "Already has" in message: |
| 107 | + already_had.append(filepath) |
| 108 | + else: |
| 109 | + added.append(filepath) |
| 110 | + else: |
| 111 | + failed.append((filepath, message)) |
| 112 | + |
| 113 | + return already_had, added, failed |
| 114 | + |
| 115 | + |
| 116 | +def process_individual_files(filepaths: List[str], verbose: bool = False) -> Tuple[List[Path], List[Path], List[Tuple[Path, str]]]: |
| 117 | + """ |
| 118 | + Process individual .ino files (used by pre-commit hooks) |
| 119 | + Returns (already_had_include, files_added, failed_files_with_reasons) |
| 120 | + """ |
| 121 | + already_had = [] |
| 122 | + added = [] |
| 123 | + failed = [] |
| 124 | + |
| 125 | + if verbose: |
| 126 | + print(f"Processing {len(filepaths)} file(s)") |
| 127 | + print("-" * 60) |
| 128 | + |
| 129 | + for filepath_str in filepaths: |
| 130 | + filepath = Path(filepath_str).resolve() |
| 131 | + |
| 132 | + if not filepath.exists(): |
| 133 | + if verbose: |
| 134 | + print(f"\n⚠️ File not found: {filepath}") |
| 135 | + failed.append((filepath, "File not found")) |
| 136 | + continue |
| 137 | + |
| 138 | + if not filepath.suffix == '.ino': |
| 139 | + if verbose: |
| 140 | + print(f"\n⚠️ Skipping non-.ino file: {filepath}") |
| 141 | + continue |
| 142 | + |
| 143 | + if verbose: |
| 144 | + print(f"\nProcessing: {filepath}") |
| 145 | + |
| 146 | + success, message = add_arduino_include(filepath, verbose) |
| 147 | + |
| 148 | + if verbose: |
| 149 | + print(f" → {message}") |
| 150 | + |
| 151 | + if success: |
| 152 | + if "Already has" in message: |
| 153 | + already_had.append(filepath) |
| 154 | + else: |
| 155 | + added.append(filepath) |
| 156 | + else: |
| 157 | + failed.append((filepath, message)) |
| 158 | + |
| 159 | + return already_had, added, failed |
| 160 | + |
| 161 | + |
| 162 | +def main(): |
| 163 | + parser = argparse.ArgumentParser( |
| 164 | + description='Check and fix Arduino.h includes in .ino files', |
| 165 | + epilog='Exit code 0: All files OK. Exit code 1: Files modified or failed.' |
| 166 | + ) |
| 167 | + parser.add_argument( |
| 168 | + 'paths', |
| 169 | + nargs='*', |
| 170 | + help='Directory to scan or specific .ino files to check (default: two levels up from script)' |
| 171 | + ) |
| 172 | + parser.add_argument( |
| 173 | + '-v', '--verbose', |
| 174 | + action='store_true', |
| 175 | + help='Show detailed processing information' |
| 176 | + ) |
| 177 | + |
| 178 | + args = parser.parse_args() |
| 179 | + |
| 180 | + # Determine what to process |
| 181 | + if not args.paths: |
| 182 | + # Default to project root (two levels up from script location) |
| 183 | + script_dir = Path(__file__).resolve().parent |
| 184 | + project_root = (script_dir / "../../").resolve() |
| 185 | + root_dir = str(project_root) |
| 186 | + if args.verbose: |
| 187 | + print(f"No directory specified, using default: {root_dir}") |
| 188 | + print(f"Scanning directory: {root_dir}") |
| 189 | + print("=" * 60) |
| 190 | + already_had, added, failed = scan_ino_files(root_dir, args.verbose) |
| 191 | + else: |
| 192 | + # Check if first argument is a directory or a file |
| 193 | + first_path = Path(args.paths[0]) |
| 194 | + |
| 195 | + if first_path.is_dir(): |
| 196 | + # Directory mode: scan directory |
| 197 | + root_dir = args.paths[0] |
| 198 | + if args.verbose: |
| 199 | + print(f"Scanning directory: {root_dir}") |
| 200 | + print("=" * 60) |
| 201 | + already_had, added, failed = scan_ino_files(root_dir, args.verbose) |
| 202 | + else: |
| 203 | + # File mode: process individual files (pre-commit hook mode) |
| 204 | + if args.verbose: |
| 205 | + print("Running in pre-commit hook mode") |
| 206 | + print("=" * 60) |
| 207 | + already_had, added, failed = process_individual_files(args.paths, args.verbose) |
| 208 | + |
| 209 | + # Only show summary in verbose mode or if there are issues |
| 210 | + if args.verbose: |
| 211 | + print("\n" + "=" * 60) |
| 212 | + print("SUMMARY") |
| 213 | + print("=" * 60) |
| 214 | + print(f"Total files found: {len(already_had) + len(added) + len(failed)}") |
| 215 | + print(f"Already had Arduino.h: {len(already_had)}") |
| 216 | + print(f"Arduino.h added: {len(added)}") |
| 217 | + print(f"Failed: {len(failed)}") |
| 218 | + |
| 219 | + # Always show files that were modified |
| 220 | + if added: |
| 221 | + if not args.verbose: |
| 222 | + print("Arduino.h was added to the following file(s):") |
| 223 | + else: |
| 224 | + print(f"\n✓ Arduino.h was added to {len(added)} file(s):") |
| 225 | + for filepath in added: |
| 226 | + print(f" • {filepath}") |
| 227 | + |
| 228 | + # Always show files that failed |
| 229 | + if failed: |
| 230 | + if not args.verbose: |
| 231 | + print("\nFailed to add include to the following file(s):") |
| 232 | + else: |
| 233 | + print(f"\n⚠️ Failed to add include to {len(failed)} file(s):") |
| 234 | + for filepath, reason in failed: |
| 235 | + print(f" • {filepath}") |
| 236 | + print(f" Reason: {reason}") |
| 237 | + |
| 238 | + # Exit with code 1 if any files were modified or failed |
| 239 | + if added or failed: |
| 240 | + sys.exit(1) |
| 241 | + else: |
| 242 | + if args.verbose: |
| 243 | + print("\n✓ All .ino files already have Arduino.h include!") |
| 244 | + sys.exit(0) |
| 245 | + |
| 246 | + |
| 247 | +if __name__ == "__main__": |
| 248 | + main() |
0 commit comments