Coverage for src/c2puml/utils.py: 54%

28 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-09-14 18:23 +0000

1#!/usr/bin/env python3 

2""" 

3Utility helpers used by the C to PlantUML converter. 

4 

5Currently, only file encoding detection is required at runtime. 

6""" 

7 

8import logging 

9from pathlib import Path 

10 

11# Try to import chardet, fallback to basic encoding detection if not available 

12try: 

13 import chardet 

14 

15 CHARDET_AVAILABLE = True 

16except ImportError: 

17 CHARDET_AVAILABLE = False 

18 

19 

20def detect_file_encoding(file_path: Path) -> str: 

21 """Detect file encoding with platform-aware fallbacks.""" 

22 try: 

23 if CHARDET_AVAILABLE: 

24 # Try to detect encoding with chardet 

25 with open(file_path, "rb") as f: 

26 raw_data = f.read(1024) # Read first 1KB for detection 

27 if raw_data: 

28 result = chardet.detect(raw_data) 

29 if result and result["confidence"] > 0.7: 

30 return result["encoding"] 

31 

32 # Fallback encodings in order of preference 

33 fallback_encodings = ["utf-8", "latin-1", "cp1252", "iso-8859-1"] 

34 

35 for encoding in fallback_encodings: 

36 try: 

37 with open(file_path, "r", encoding=encoding) as f: 

38 f.read(1024) # Test read 

39 return encoding 

40 except (UnicodeDecodeError, UnicodeError): 

41 continue 

42 

43 # Final fallback 

44 return "utf-8" 

45 

46 except Exception as e: 

47 logging.warning(f"Failed to detect encoding for {file_path}: {e}") 

48 return "utf-8" 

49