|
| 1 | +import os |
| 2 | +import re |
| 3 | + |
| 4 | +def count_comment_ratio(path): |
| 5 | + total_comments = 0 |
| 6 | + total_lines = 0 |
| 7 | + |
| 8 | + file_types = { |
| 9 | + '.py': {'single': [r'#'], 'multi': []}, |
| 10 | + '.js': {'single': [r'//'], 'multi': [('/*', '*/')]}, |
| 11 | + '.go': {'single': [r'//'], 'multi': [('/*', '*/')]}, |
| 12 | + '.rb': {'single': [r'#'], 'multi': []}, |
| 13 | + } |
| 14 | + |
| 15 | + def analyze_file(file_path, ext): |
| 16 | + nonlocal total_comments, total_lines |
| 17 | + single_patterns = [re.compile(pat) for pat in file_types[ext]['single']] |
| 18 | + multi_delims = file_types[ext]['multi'] |
| 19 | + in_multiline = False |
| 20 | + |
| 21 | + try: |
| 22 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 23 | + for line in f: |
| 24 | + stripped = line.strip() |
| 25 | + if not stripped: |
| 26 | + continue # ignora linha em branco |
| 27 | + total_lines += 1 |
| 28 | + |
| 29 | + # Dentro de comentário multilinha |
| 30 | + if in_multiline: |
| 31 | + total_comments += 1 |
| 32 | + for _, end in multi_delims: |
| 33 | + if end in stripped: |
| 34 | + in_multiline = False |
| 35 | + continue |
| 36 | + |
| 37 | + # Início de comentário multilinha |
| 38 | + found_multiline = False |
| 39 | + for start, end in multi_delims: |
| 40 | + if start in stripped: |
| 41 | + total_comments += 1 |
| 42 | + found_multiline = True |
| 43 | + if end not in stripped: |
| 44 | + in_multiline = True |
| 45 | + break |
| 46 | + if found_multiline: |
| 47 | + continue |
| 48 | + |
| 49 | + # Comentário de linha única (ou inline) |
| 50 | + if any(pat.search(line) for pat in single_patterns): |
| 51 | + total_comments += 1 |
| 52 | + except Exception as e: |
| 53 | + print(f"Erro ao ler arquivo: {file_path}, erro: {e}") |
| 54 | + |
| 55 | + if os.path.isfile(path): |
| 56 | + ext = os.path.splitext(path)[1] |
| 57 | + if ext in file_types: |
| 58 | + analyze_file(path, ext) |
| 59 | + else: |
| 60 | + for root, _, files in os.walk(path): |
| 61 | + for filename in files: |
| 62 | + ext = os.path.splitext(filename)[1] |
| 63 | + if ext in file_types: |
| 64 | + analyze_file(os.path.join(root, filename), ext) |
| 65 | + |
| 66 | + if total_lines == 0: |
| 67 | + return "0.00%" |
| 68 | + |
| 69 | + percentage = (total_comments / total_lines) * 100 |
| 70 | + return f"{percentage:.2f}%" |
0 commit comments