mdtoken 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mdtoken/matcher.py ADDED
@@ -0,0 +1,146 @@
1
+ """File matching and discovery logic for mdtoken."""
2
+
3
+ from fnmatch import fnmatch
4
+ from pathlib import Path
5
+ from typing import List, Tuple
6
+
7
+ from mdtoken.config import Config
8
+
9
+
10
+ class FileMatcher:
11
+ """Discovers and filters markdown files based on patterns.
12
+
13
+ Attributes:
14
+ config: Configuration object with limits and exclusions
15
+ root: Root directory for file discovery
16
+ """
17
+
18
+ def __init__(self, config: Config, root: Path = None) -> None:
19
+ """Initialize file matcher.
20
+
21
+ Args:
22
+ config: Configuration object
23
+ root: Root directory for file discovery (defaults to current directory)
24
+ """
25
+ self.config = config
26
+ self.root = root or Path.cwd()
27
+
28
+ def _is_excluded(self, file_path: Path) -> bool:
29
+ """Check if a file should be excluded based on exclude patterns.
30
+
31
+ Args:
32
+ file_path: Path to check
33
+
34
+ Returns:
35
+ True if file should be excluded, False otherwise
36
+ """
37
+ # Convert to relative path from root for pattern matching
38
+ try:
39
+ rel_path = file_path.relative_to(self.root)
40
+ except ValueError:
41
+ # File is outside root, use absolute path
42
+ rel_path = file_path
43
+
44
+ # Convert to POSIX-style path for consistent pattern matching
45
+ path_str = rel_path.as_posix()
46
+
47
+ # Check each exclude pattern
48
+ for pattern in self.config.exclude:
49
+ # Handle directory patterns (ending with /**)
50
+ if pattern.endswith("/**"):
51
+ dir_pattern = pattern[:-3] # Remove /**
52
+ # Check if path starts with the directory
53
+ if path_str.startswith(dir_pattern + "/") or path_str == dir_pattern:
54
+ return True
55
+ # Also match the directory itself
56
+ parts = path_str.split("/")
57
+ if dir_pattern in parts:
58
+ return True
59
+
60
+ # Handle glob patterns
61
+ elif fnmatch(path_str, pattern):
62
+ return True
63
+
64
+ # Handle simple substring matching
65
+ elif pattern in path_str:
66
+ return True
67
+
68
+ return False
69
+
70
+ def find_markdown_files(
71
+ self, patterns: List[str] = None, check_files: List[Path] = None
72
+ ) -> List[Tuple[Path, int]]:
73
+ """Find markdown files matching patterns.
74
+
75
+ Args:
76
+ patterns: Glob patterns to match (defaults to ["**/*.md"])
77
+ check_files: Specific files to check instead of scanning (used by pre-commit)
78
+
79
+ Returns:
80
+ List of tuples (file_path, token_limit) for each matched file
81
+ """
82
+ if patterns is None:
83
+ patterns = ["**/*.md"]
84
+
85
+ results: List[Tuple[Path, int]] = []
86
+
87
+ # If specific files provided (pre-commit mode), check only those
88
+ if check_files:
89
+ for file_path in check_files:
90
+ # Ensure it's a Path object
91
+ if not isinstance(file_path, Path):
92
+ file_path = Path(file_path)
93
+
94
+ # Check if it's a markdown file
95
+ if not file_path.suffix == ".md":
96
+ continue
97
+
98
+ # Check if it exists
99
+ if not file_path.exists() or not file_path.is_file():
100
+ continue
101
+
102
+ # Check if excluded
103
+ if self._is_excluded(file_path):
104
+ continue
105
+
106
+ # Get limit for this file
107
+ limit = self.config.get_limit(str(file_path))
108
+ results.append((file_path, limit))
109
+
110
+ return results
111
+
112
+ # Otherwise, scan using glob patterns
113
+ seen_files = set()
114
+
115
+ for pattern in patterns:
116
+ # Use glob to find matching files
117
+ for file_path in self.root.glob(pattern):
118
+ # Skip if not a file
119
+ if not file_path.is_file():
120
+ continue
121
+
122
+ # Skip if not markdown
123
+ if file_path.suffix != ".md":
124
+ continue
125
+
126
+ # Skip if already seen
127
+ if file_path in seen_files:
128
+ continue
129
+
130
+ # Skip if excluded
131
+ if self._is_excluded(file_path):
132
+ continue
133
+
134
+ # Get limit for this file
135
+ limit = self.config.get_limit(str(file_path))
136
+ results.append((file_path, limit))
137
+ seen_files.add(file_path)
138
+
139
+ # Sort results by path for consistency
140
+ results.sort(key=lambda x: x[0])
141
+
142
+ return results
143
+
144
+ def __repr__(self) -> str:
145
+ """String representation of FileMatcher."""
146
+ return f"FileMatcher(config={self.config}, root={self.root})"
mdtoken/reporter.py ADDED
@@ -0,0 +1,189 @@
1
+ """Reporting and output formatting for mdtoken."""
2
+
3
+ import sys
4
+ from typing import TextIO
5
+
6
+ from mdtoken.enforcer import EnforcementResult, LimitEnforcer, Violation
7
+
8
+
9
+ class Reporter:
10
+ """Formats and displays enforcement results.
11
+
12
+ Attributes:
13
+ enforcer: LimitEnforcer for generating suggestions
14
+ output: Output stream (defaults to stdout)
15
+ use_color: Whether to use ANSI colors in output
16
+ """
17
+
18
+ # ANSI color codes
19
+ RED = "\033[91m"
20
+ GREEN = "\033[92m"
21
+ YELLOW = "\033[93m"
22
+ BLUE = "\033[94m"
23
+ BOLD = "\033[1m"
24
+ RESET = "\033[0m"
25
+
26
+ def __init__(
27
+ self,
28
+ enforcer: LimitEnforcer = None,
29
+ output: TextIO = None,
30
+ use_color: bool = True,
31
+ ) -> None:
32
+ """Initialize reporter.
33
+
34
+ Args:
35
+ enforcer: LimitEnforcer for generating suggestions
36
+ output: Output stream (defaults to stdout)
37
+ use_color: Whether to use ANSI colors (auto-detected if not specified)
38
+ """
39
+ self.enforcer = enforcer
40
+ self.output = output or sys.stdout
41
+ # Auto-detect color support
42
+ if use_color:
43
+ self.use_color = self.output.isatty()
44
+ else:
45
+ self.use_color = False
46
+
47
+ def _colorize(self, text: str, color: str) -> str:
48
+ """Apply color to text if color is enabled.
49
+
50
+ Args:
51
+ text: Text to colorize
52
+ color: ANSI color code
53
+
54
+ Returns:
55
+ Colorized text or plain text if colors disabled
56
+ """
57
+ if self.use_color:
58
+ return f"{color}{text}{self.RESET}"
59
+ return text
60
+
61
+ def report(self, result: EnforcementResult, verbose: bool = False) -> None:
62
+ """Display enforcement results.
63
+
64
+ Args:
65
+ result: Enforcement result to display
66
+ verbose: Whether to show detailed suggestions
67
+ """
68
+ # Header
69
+ if result.passed:
70
+ self._print_success(result)
71
+ else:
72
+ self._print_failures(result, verbose)
73
+
74
+ # Summary
75
+ self._print_summary(result)
76
+
77
+ def _print_success(self, result: EnforcementResult) -> None:
78
+ """Print success message."""
79
+ check_mark = self._colorize("✓", self.GREEN)
80
+ message = self._colorize("All files within token limits!", self.GREEN)
81
+ self.output.write(f"{check_mark} {message}\n")
82
+
83
+ def _print_failures(self, result: EnforcementResult, verbose: bool) -> None:
84
+ """Print failure messages with violations."""
85
+ # Header
86
+ cross = self._colorize("✗", self.RED)
87
+ message = self._colorize(
88
+ f"Found {result.violation_count} file(s) exceeding token limits:", self.RED
89
+ )
90
+ self.output.write(f"{cross} {message}\n\n")
91
+
92
+ # List each violation
93
+ for i, violation in enumerate(result.violations, 1):
94
+ self._print_violation(violation, i, verbose)
95
+
96
+ # Total limit violation if applicable
97
+ if result.total_limit_exceeded:
98
+ self._print_total_limit_violation(result)
99
+
100
+ def _print_violation(self, violation: Violation, number: int, verbose: bool) -> None:
101
+ """Print details for a single violation.
102
+
103
+ Args:
104
+ violation: The violation to print
105
+ number: Violation number
106
+ verbose: Whether to show suggestions
107
+ """
108
+ # File header
109
+ file_str = self._colorize(str(violation.file_path), self.BOLD)
110
+ self.output.write(f"{number}. {file_str}\n")
111
+
112
+ # Stats
113
+ actual = self._colorize(str(violation.actual_tokens), self.RED)
114
+ limit = self._colorize(str(violation.limit), self.YELLOW)
115
+ excess = self._colorize(str(violation.excess), self.RED)
116
+ percentage = self._colorize(f"{violation.percentage_over:.1f}%", self.RED)
117
+
118
+ self.output.write(f" Tokens: {actual} / {limit}\n")
119
+ self.output.write(f" Over by: {excess} tokens ({percentage})\n")
120
+
121
+ # Suggestions if verbose
122
+ if verbose and self.enforcer:
123
+ suggestions = self.enforcer.get_suggestions(violation)
124
+ if suggestions:
125
+ self.output.write(f"\n {self._colorize('Suggestions:', self.BLUE)}\n")
126
+ for suggestion in suggestions[:3]: # Show top 3
127
+ self.output.write(f" • {suggestion}\n")
128
+
129
+ self.output.write("\n")
130
+
131
+ def _print_total_limit_violation(self, result: EnforcementResult) -> None:
132
+ """Print total limit violation warning."""
133
+ warning = self._colorize("⚠", self.YELLOW)
134
+ message = self._colorize(
135
+ f"Total tokens ({result.total_tokens}) exceeds total_limit "
136
+ f"({self.enforcer.config.total_limit if self.enforcer else 'N/A'})",
137
+ self.YELLOW,
138
+ )
139
+ self.output.write(f"{warning} {message}\n\n")
140
+
141
+ def _print_summary(self, result: EnforcementResult) -> None:
142
+ """Print summary statistics."""
143
+ self.output.write(self._colorize("Summary:", self.BOLD) + "\n")
144
+ self.output.write(f" Files checked: {result.total_files}\n")
145
+ self.output.write(f" Total tokens: {result.total_tokens:,}\n")
146
+ self.output.write(f" Violations: {result.violation_count}\n")
147
+
148
+ if result.passed:
149
+ status = self._colorize("PASSED", self.GREEN)
150
+ else:
151
+ status = self._colorize("FAILED", self.RED)
152
+
153
+ self.output.write(f" Status: {status}\n")
154
+
155
+ def get_exit_code(self, result: EnforcementResult, fail_on_exceed: bool) -> int:
156
+ """Determine appropriate exit code.
157
+
158
+ Args:
159
+ result: Enforcement result
160
+ fail_on_exceed: Whether to exit with error on violations
161
+
162
+ Returns:
163
+ Exit code (0 for success, 1 for failure)
164
+ """
165
+ if result.passed:
166
+ return 0
167
+
168
+ if fail_on_exceed:
169
+ return 1
170
+
171
+ # If fail_on_exceed is False, we still warn but exit 0
172
+ return 0
173
+
174
+ def format_summary_line(self, result: EnforcementResult) -> str:
175
+ """Format a one-line summary of results.
176
+
177
+ Args:
178
+ result: Enforcement result
179
+
180
+ Returns:
181
+ One-line summary string
182
+ """
183
+ if result.passed:
184
+ return f"✓ {result.total_files} files checked, {result.total_tokens:,} tokens total"
185
+ else:
186
+ return (
187
+ f"✗ {result.violation_count}/{result.total_files} files over limit, "
188
+ f"{result.total_tokens:,} tokens total"
189
+ )