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/__init__.py +8 -0
- mdtoken/__version__.py +3 -0
- mdtoken/cli.py +53 -0
- mdtoken/config.py +273 -0
- mdtoken/counter.py +82 -0
- mdtoken/enforcer.py +189 -0
- mdtoken/matcher.py +146 -0
- mdtoken/reporter.py +189 -0
- mdtoken-1.0.0.dist-info/METADATA +562 -0
- mdtoken-1.0.0.dist-info/RECORD +14 -0
- mdtoken-1.0.0.dist-info/WHEEL +5 -0
- mdtoken-1.0.0.dist-info/entry_points.txt +2 -0
- mdtoken-1.0.0.dist-info/licenses/LICENSE +21 -0
- mdtoken-1.0.0.dist-info/top_level.txt +1 -0
mdtoken/__init__.py
ADDED
mdtoken/__version__.py
ADDED
mdtoken/cli.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Command-line interface for mdtoken."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from mdtoken.__version__ import __version__
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@click.group(invoke_without_command=True)
|
|
11
|
+
@click.option("--version", is_flag=True, help="Show version and exit")
|
|
12
|
+
@click.pass_context
|
|
13
|
+
def main(ctx, version):
|
|
14
|
+
"""
|
|
15
|
+
mdtoken - Markdown Token Limit Pre-commit Hook
|
|
16
|
+
|
|
17
|
+
Enforce token count limits on markdown files to prevent AI context window bloat.
|
|
18
|
+
|
|
19
|
+
Use 'mdtoken check' to validate markdown files against configured token limits.
|
|
20
|
+
"""
|
|
21
|
+
if version:
|
|
22
|
+
click.echo(f"mdtoken version {__version__}")
|
|
23
|
+
ctx.exit(0)
|
|
24
|
+
|
|
25
|
+
# If no command provided and not --version, show help
|
|
26
|
+
if ctx.invoked_subcommand is None:
|
|
27
|
+
click.echo(ctx.get_help())
|
|
28
|
+
ctx.exit(0)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@main.command()
|
|
32
|
+
@click.argument("files", nargs=-1, type=click.Path(exists=True))
|
|
33
|
+
@click.option("--config", default=".mdtokenrc.yaml", help="Path to configuration file")
|
|
34
|
+
@click.option("--dry-run", is_flag=True, help="Check files without failing on violations")
|
|
35
|
+
@click.option("--verbose", "-v", is_flag=True, help="Show detailed suggestions for violations")
|
|
36
|
+
def check(files, config, dry_run, verbose):
|
|
37
|
+
"""Check markdown files against token count limits.
|
|
38
|
+
|
|
39
|
+
FILES: Markdown files to check. If none provided, uses glob patterns from config.
|
|
40
|
+
"""
|
|
41
|
+
from mdtoken.commands.check import check_files
|
|
42
|
+
|
|
43
|
+
exit_code = check_files(
|
|
44
|
+
files=list(files) if files else None,
|
|
45
|
+
config_path=config,
|
|
46
|
+
dry_run=dry_run,
|
|
47
|
+
verbose=verbose,
|
|
48
|
+
)
|
|
49
|
+
sys.exit(exit_code)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
sys.exit(main())
|
mdtoken/config.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Configuration loading and validation for mdtoken."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ConfigError(Exception):
|
|
10
|
+
"""Raised when configuration is invalid or cannot be loaded."""
|
|
11
|
+
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Config:
|
|
16
|
+
"""Configuration for markdown token limit enforcement.
|
|
17
|
+
|
|
18
|
+
Attributes:
|
|
19
|
+
default_limit: Default token limit for all markdown files
|
|
20
|
+
limits: Per-file or per-pattern token limits (overrides default)
|
|
21
|
+
exclude: Glob patterns for files to exclude from checking
|
|
22
|
+
total_limit: Optional total token limit across all files
|
|
23
|
+
fail_on_exceed: Whether to fail (exit 1) when limits are exceeded
|
|
24
|
+
encoding: Tiktoken encoding name to use for token counting
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# Model name to tiktoken encoding mapping
|
|
28
|
+
MODEL_ENCODING_MAP = {
|
|
29
|
+
"gpt-4": "cl100k_base",
|
|
30
|
+
"gpt-4o": "o200k_base",
|
|
31
|
+
"gpt-3.5-turbo": "cl100k_base",
|
|
32
|
+
"claude-3": "cl100k_base", # Claude uses similar tokenization
|
|
33
|
+
"claude-3.5": "cl100k_base",
|
|
34
|
+
"codex": "p50k_base",
|
|
35
|
+
"text-davinci-003": "p50k_base",
|
|
36
|
+
"text-davinci-002": "p50k_base",
|
|
37
|
+
"gpt-3": "r50k_base",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
# Default configuration values
|
|
41
|
+
DEFAULT_CONFIG = {
|
|
42
|
+
"default_limit": 4000,
|
|
43
|
+
"limits": {},
|
|
44
|
+
"exclude": [
|
|
45
|
+
".git/**",
|
|
46
|
+
"node_modules/**",
|
|
47
|
+
"venv/**",
|
|
48
|
+
".venv/**",
|
|
49
|
+
"build/**",
|
|
50
|
+
"dist/**",
|
|
51
|
+
"__pycache__/**",
|
|
52
|
+
],
|
|
53
|
+
"total_limit": None,
|
|
54
|
+
"fail_on_exceed": True,
|
|
55
|
+
"encoding": "cl100k_base",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
default_limit: int = 4000,
|
|
61
|
+
limits: Optional[Dict[str, int]] = None,
|
|
62
|
+
exclude: Optional[List[str]] = None,
|
|
63
|
+
total_limit: Optional[int] = None,
|
|
64
|
+
fail_on_exceed: bool = True,
|
|
65
|
+
encoding: Optional[str] = None,
|
|
66
|
+
model: Optional[str] = None,
|
|
67
|
+
) -> None:
|
|
68
|
+
"""Initialize configuration.
|
|
69
|
+
|
|
70
|
+
Args:
|
|
71
|
+
default_limit: Default token limit for all markdown files
|
|
72
|
+
limits: Per-file or per-pattern token limits
|
|
73
|
+
exclude: Glob patterns for files to exclude
|
|
74
|
+
total_limit: Optional total token limit across all files
|
|
75
|
+
fail_on_exceed: Whether to fail when limits are exceeded
|
|
76
|
+
encoding: Tiktoken encoding name (e.g., "cl100k_base")
|
|
77
|
+
model: Model name for user-friendly config (e.g., "gpt-4")
|
|
78
|
+
If both encoding and model are provided, encoding takes precedence
|
|
79
|
+
"""
|
|
80
|
+
self.default_limit = default_limit
|
|
81
|
+
self.limits = limits or {}
|
|
82
|
+
self.exclude = exclude or self.DEFAULT_CONFIG["exclude"].copy() # type: ignore
|
|
83
|
+
self.total_limit = total_limit
|
|
84
|
+
self.fail_on_exceed = fail_on_exceed
|
|
85
|
+
|
|
86
|
+
# Handle encoding/model parameter
|
|
87
|
+
if encoding is not None:
|
|
88
|
+
self.encoding = encoding
|
|
89
|
+
elif model is not None:
|
|
90
|
+
# Translate model to encoding
|
|
91
|
+
self.encoding = self._resolve_model_encoding(model)
|
|
92
|
+
else:
|
|
93
|
+
self.encoding = self.DEFAULT_CONFIG["encoding"] # type: ignore
|
|
94
|
+
|
|
95
|
+
self._validate()
|
|
96
|
+
|
|
97
|
+
def _resolve_model_encoding(self, model: str) -> str:
|
|
98
|
+
"""Resolve model name to tiktoken encoding name.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
model: Model name (e.g., "gpt-4", "claude-3.5")
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Corresponding tiktoken encoding name
|
|
105
|
+
|
|
106
|
+
Raises:
|
|
107
|
+
ConfigError: If model is not recognized
|
|
108
|
+
"""
|
|
109
|
+
if model in self.MODEL_ENCODING_MAP:
|
|
110
|
+
return self.MODEL_ENCODING_MAP[model]
|
|
111
|
+
|
|
112
|
+
# Provide helpful error with available models
|
|
113
|
+
available = ", ".join(sorted(self.MODEL_ENCODING_MAP.keys()))
|
|
114
|
+
raise ConfigError(
|
|
115
|
+
f"Unknown model '{model}'. Available models: {available}. "
|
|
116
|
+
f"Or specify 'encoding' directly (e.g., 'cl100k_base')."
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
def _validate(self) -> None:
|
|
120
|
+
"""Validate configuration values.
|
|
121
|
+
|
|
122
|
+
Raises:
|
|
123
|
+
ConfigError: If configuration values are invalid
|
|
124
|
+
"""
|
|
125
|
+
if not isinstance(self.default_limit, int) or self.default_limit <= 0:
|
|
126
|
+
raise ConfigError(
|
|
127
|
+
f"default_limit must be a positive integer, got: {self.default_limit}"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
if not isinstance(self.limits, dict):
|
|
131
|
+
raise ConfigError(f"limits must be a dictionary, got: {type(self.limits).__name__}")
|
|
132
|
+
|
|
133
|
+
for pattern, limit in self.limits.items():
|
|
134
|
+
if not isinstance(limit, int) or limit <= 0:
|
|
135
|
+
raise ConfigError(
|
|
136
|
+
f"Limit for pattern '{pattern}' must be a positive integer, got: {limit}"
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
if not isinstance(self.exclude, list):
|
|
140
|
+
raise ConfigError(f"exclude must be a list, got: {type(self.exclude).__name__}")
|
|
141
|
+
|
|
142
|
+
if self.total_limit is not None:
|
|
143
|
+
if not isinstance(self.total_limit, int) or self.total_limit <= 0:
|
|
144
|
+
raise ConfigError(
|
|
145
|
+
f"total_limit must be a positive integer or null, got: {self.total_limit}"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
if not isinstance(self.fail_on_exceed, bool):
|
|
149
|
+
raise ConfigError(
|
|
150
|
+
f"fail_on_exceed must be a boolean, got: {type(self.fail_on_exceed).__name__}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
if not isinstance(self.encoding, str) or not self.encoding:
|
|
154
|
+
raise ConfigError(
|
|
155
|
+
f"encoding must be a non-empty string, got: {self.encoding}"
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
@classmethod
|
|
159
|
+
def from_file(cls, config_path: Optional[Path] = None) -> "Config":
|
|
160
|
+
"""Load configuration from a YAML file.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
config_path: Path to configuration file. If None, searches for
|
|
164
|
+
.mdtokenrc.yaml in current directory.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
Config instance with loaded configuration
|
|
168
|
+
|
|
169
|
+
Raises:
|
|
170
|
+
ConfigError: If file cannot be read or contains invalid YAML/config
|
|
171
|
+
"""
|
|
172
|
+
# Determine config file path
|
|
173
|
+
if config_path is None:
|
|
174
|
+
config_path = Path.cwd() / ".mdtokenrc.yaml"
|
|
175
|
+
else:
|
|
176
|
+
config_path = Path(config_path)
|
|
177
|
+
|
|
178
|
+
# If config file doesn't exist, use defaults
|
|
179
|
+
if not config_path.exists():
|
|
180
|
+
return cls()
|
|
181
|
+
|
|
182
|
+
# Load and parse YAML
|
|
183
|
+
try:
|
|
184
|
+
with config_path.open("r", encoding="utf-8") as f:
|
|
185
|
+
data = yaml.safe_load(f)
|
|
186
|
+
except yaml.YAMLError as e:
|
|
187
|
+
raise ConfigError(f"Invalid YAML in config file '{config_path}': {e}") from e
|
|
188
|
+
except Exception as e:
|
|
189
|
+
raise ConfigError(f"Failed to read config file '{config_path}': {e}") from e
|
|
190
|
+
|
|
191
|
+
# Handle empty YAML file
|
|
192
|
+
if data is None:
|
|
193
|
+
return cls()
|
|
194
|
+
|
|
195
|
+
if not isinstance(data, dict):
|
|
196
|
+
raise ConfigError(
|
|
197
|
+
f"Config file must contain a YAML dictionary, got: {type(data).__name__}"
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
# Merge with defaults (but handle encoding/model specially)
|
|
201
|
+
config_dict = cls.DEFAULT_CONFIG.copy()
|
|
202
|
+
config_dict.update(data)
|
|
203
|
+
|
|
204
|
+
# For encoding/model: only use from config_dict if explicitly in YAML
|
|
205
|
+
# Otherwise pass None to let __init__ handle defaults
|
|
206
|
+
encoding_param = data.get("encoding") if "encoding" in data else None
|
|
207
|
+
model_param = data.get("model") if "model" in data else None
|
|
208
|
+
|
|
209
|
+
# Create Config instance
|
|
210
|
+
try:
|
|
211
|
+
return cls(
|
|
212
|
+
default_limit=config_dict.get("default_limit", cls.DEFAULT_CONFIG["default_limit"]),
|
|
213
|
+
limits=config_dict.get("limits", {}),
|
|
214
|
+
exclude=config_dict.get("exclude", cls.DEFAULT_CONFIG["exclude"]),
|
|
215
|
+
total_limit=config_dict.get("total_limit"),
|
|
216
|
+
fail_on_exceed=config_dict.get("fail_on_exceed", True),
|
|
217
|
+
encoding=encoding_param,
|
|
218
|
+
model=model_param,
|
|
219
|
+
)
|
|
220
|
+
except ConfigError:
|
|
221
|
+
raise
|
|
222
|
+
except Exception as e:
|
|
223
|
+
raise ConfigError(f"Failed to create config from file '{config_path}': {e}") from e
|
|
224
|
+
|
|
225
|
+
def get_limit(self, file_path: str) -> int:
|
|
226
|
+
"""Get token limit for a specific file.
|
|
227
|
+
|
|
228
|
+
Checks file-specific limits first, then falls back to default.
|
|
229
|
+
|
|
230
|
+
Args:
|
|
231
|
+
file_path: Path to file (can be relative or absolute)
|
|
232
|
+
|
|
233
|
+
Returns:
|
|
234
|
+
Token limit for the file
|
|
235
|
+
"""
|
|
236
|
+
# Check if there's a specific limit for this exact path
|
|
237
|
+
if file_path in self.limits:
|
|
238
|
+
return self.limits[file_path]
|
|
239
|
+
|
|
240
|
+
# Check if any pattern matches (simple string matching for now)
|
|
241
|
+
# In the future, could use glob pattern matching here
|
|
242
|
+
for pattern, limit in self.limits.items():
|
|
243
|
+
if pattern in file_path or file_path.endswith(pattern):
|
|
244
|
+
return limit
|
|
245
|
+
|
|
246
|
+
# Fall back to default
|
|
247
|
+
return self.default_limit
|
|
248
|
+
|
|
249
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
250
|
+
"""Convert configuration to dictionary.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
Dictionary representation of configuration
|
|
254
|
+
"""
|
|
255
|
+
return {
|
|
256
|
+
"default_limit": self.default_limit,
|
|
257
|
+
"limits": self.limits,
|
|
258
|
+
"exclude": self.exclude,
|
|
259
|
+
"total_limit": self.total_limit,
|
|
260
|
+
"fail_on_exceed": self.fail_on_exceed,
|
|
261
|
+
"encoding": self.encoding,
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
def __repr__(self) -> str:
|
|
265
|
+
"""String representation of Config."""
|
|
266
|
+
return (
|
|
267
|
+
f"Config(default_limit={self.default_limit}, "
|
|
268
|
+
f"limits={self.limits}, "
|
|
269
|
+
f"exclude={self.exclude}, "
|
|
270
|
+
f"total_limit={self.total_limit}, "
|
|
271
|
+
f"fail_on_exceed={self.fail_on_exceed}, "
|
|
272
|
+
f"encoding={self.encoding})"
|
|
273
|
+
)
|
mdtoken/counter.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Token counting functionality using tiktoken library."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import tiktoken
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TokenCounter:
|
|
9
|
+
"""Count tokens in text and files using tiktoken's cl100k_base encoding.
|
|
10
|
+
|
|
11
|
+
This encoding is used by GPT-4 and GPT-3.5-turbo models.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, encoding_name: str = "cl100k_base") -> None:
|
|
15
|
+
"""Initialize token counter with specified encoding.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
encoding_name: Name of tiktoken encoding to use (default: cl100k_base)
|
|
19
|
+
"""
|
|
20
|
+
try:
|
|
21
|
+
self.encoding = tiktoken.get_encoding(encoding_name)
|
|
22
|
+
except Exception as e:
|
|
23
|
+
raise ValueError(f"Failed to load tiktoken encoding '{encoding_name}': {e}") from e
|
|
24
|
+
self.encoding_name = encoding_name
|
|
25
|
+
|
|
26
|
+
def count_tokens(self, text: str) -> int:
|
|
27
|
+
"""Count tokens in the given text.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
text: Text string to count tokens for
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Number of tokens in the text
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
ValueError: If text cannot be encoded
|
|
37
|
+
"""
|
|
38
|
+
if not isinstance(text, str):
|
|
39
|
+
raise TypeError(f"Expected str, got {type(text).__name__}")
|
|
40
|
+
|
|
41
|
+
try:
|
|
42
|
+
tokens = self.encoding.encode(text)
|
|
43
|
+
return len(tokens)
|
|
44
|
+
except Exception as e:
|
|
45
|
+
raise ValueError(f"Failed to encode text: {e}") from e
|
|
46
|
+
|
|
47
|
+
def count_file_tokens(self, path: Path, encoding: str = "utf-8") -> int:
|
|
48
|
+
"""Count tokens in a file.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
path: Path to file to count tokens for
|
|
52
|
+
encoding: Text encoding to use when reading file (default: utf-8)
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
Number of tokens in the file
|
|
56
|
+
|
|
57
|
+
Raises:
|
|
58
|
+
FileNotFoundError: If file does not exist
|
|
59
|
+
IOError: If file cannot be read
|
|
60
|
+
ValueError: If file content cannot be encoded to tokens
|
|
61
|
+
"""
|
|
62
|
+
if not isinstance(path, Path):
|
|
63
|
+
path = Path(path)
|
|
64
|
+
|
|
65
|
+
if not path.exists():
|
|
66
|
+
raise FileNotFoundError(f"File not found: {path}")
|
|
67
|
+
|
|
68
|
+
if not path.is_file():
|
|
69
|
+
raise OSError(f"Not a regular file: {path}")
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
text = path.read_text(encoding=encoding)
|
|
73
|
+
except UnicodeDecodeError as e:
|
|
74
|
+
raise OSError(f"Failed to read file '{path}' with encoding '{encoding}': {e}") from e
|
|
75
|
+
except Exception as e:
|
|
76
|
+
raise OSError(f"Failed to read file '{path}': {e}") from e
|
|
77
|
+
|
|
78
|
+
return self.count_tokens(text)
|
|
79
|
+
|
|
80
|
+
def __repr__(self) -> str:
|
|
81
|
+
"""String representation of the token counter."""
|
|
82
|
+
return f"TokenCounter(encoding='{self.encoding_name}')"
|
mdtoken/enforcer.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Limit enforcement logic for mdtoken."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import List, Optional
|
|
6
|
+
|
|
7
|
+
from mdtoken.config import Config
|
|
8
|
+
from mdtoken.counter import TokenCounter
|
|
9
|
+
from mdtoken.matcher import FileMatcher
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Violation:
|
|
14
|
+
"""Represents a token limit violation.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
file_path: Path to the file that violated the limit
|
|
18
|
+
actual_tokens: Actual number of tokens in the file
|
|
19
|
+
limit: Token limit that was exceeded
|
|
20
|
+
excess: Number of tokens over the limit
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
file_path: Path
|
|
24
|
+
actual_tokens: int
|
|
25
|
+
limit: int
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def excess(self) -> int:
|
|
29
|
+
"""Calculate tokens over the limit."""
|
|
30
|
+
return self.actual_tokens - self.limit
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def percentage_over(self) -> float:
|
|
34
|
+
"""Calculate percentage over the limit."""
|
|
35
|
+
return (self.excess / self.limit) * 100
|
|
36
|
+
|
|
37
|
+
def __str__(self) -> str:
|
|
38
|
+
"""String representation of violation."""
|
|
39
|
+
return (
|
|
40
|
+
f"{self.file_path}: {self.actual_tokens} tokens "
|
|
41
|
+
f"(limit: {self.limit}, over by {self.excess})"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class EnforcementResult:
|
|
47
|
+
"""Results from limit enforcement check.
|
|
48
|
+
|
|
49
|
+
Attributes:
|
|
50
|
+
passed: Whether all files passed the limits
|
|
51
|
+
total_files: Total number of files checked
|
|
52
|
+
total_tokens: Total tokens across all files
|
|
53
|
+
violations: List of limit violations
|
|
54
|
+
total_limit_exceeded: Whether total_limit was exceeded (if configured)
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
passed: bool
|
|
58
|
+
total_files: int
|
|
59
|
+
total_tokens: int
|
|
60
|
+
violations: List[Violation]
|
|
61
|
+
total_limit_exceeded: bool = False
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def violation_count(self) -> int:
|
|
65
|
+
"""Number of files with violations."""
|
|
66
|
+
return len(self.violations)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class LimitEnforcer:
|
|
70
|
+
"""Enforces token limits on markdown files.
|
|
71
|
+
|
|
72
|
+
Attributes:
|
|
73
|
+
config: Configuration with limits
|
|
74
|
+
counter: Token counter
|
|
75
|
+
matcher: File matcher
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
config: Config,
|
|
81
|
+
counter: Optional[TokenCounter] = None,
|
|
82
|
+
matcher: Optional[FileMatcher] = None,
|
|
83
|
+
) -> None:
|
|
84
|
+
"""Initialize limit enforcer.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
config: Configuration object
|
|
88
|
+
counter: Token counter (creates default if not provided)
|
|
89
|
+
matcher: File matcher (creates default if not provided)
|
|
90
|
+
"""
|
|
91
|
+
self.config = config
|
|
92
|
+
self.counter = counter or TokenCounter(encoding_name=config.encoding)
|
|
93
|
+
self.matcher = matcher or FileMatcher(config)
|
|
94
|
+
|
|
95
|
+
def check_files(
|
|
96
|
+
self, patterns: Optional[List[str]] = None, check_files: Optional[List[Path]] = None
|
|
97
|
+
) -> EnforcementResult:
|
|
98
|
+
"""Check files against token limits.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
patterns: Glob patterns to match (defaults to ["**/*.md"])
|
|
102
|
+
check_files: Specific files to check (used by pre-commit)
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
EnforcementResult with violations and statistics
|
|
106
|
+
"""
|
|
107
|
+
# Find files to check
|
|
108
|
+
files_with_limits = self.matcher.find_markdown_files(
|
|
109
|
+
patterns=patterns, check_files=check_files
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
violations: List[Violation] = []
|
|
113
|
+
total_tokens = 0
|
|
114
|
+
|
|
115
|
+
# Check each file
|
|
116
|
+
for file_path, limit in files_with_limits:
|
|
117
|
+
try:
|
|
118
|
+
token_count = self.counter.count_file_tokens(file_path)
|
|
119
|
+
total_tokens += token_count
|
|
120
|
+
|
|
121
|
+
# Check if file exceeds its limit
|
|
122
|
+
if token_count > limit:
|
|
123
|
+
violations.append(
|
|
124
|
+
Violation(file_path=file_path, actual_tokens=token_count, limit=limit)
|
|
125
|
+
)
|
|
126
|
+
except Exception:
|
|
127
|
+
# If we can't count tokens, treat as a violation
|
|
128
|
+
violations.append(
|
|
129
|
+
Violation(
|
|
130
|
+
file_path=file_path,
|
|
131
|
+
actual_tokens=0, # Unknown
|
|
132
|
+
limit=limit,
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# Check total limit if configured
|
|
137
|
+
total_limit_exceeded = False
|
|
138
|
+
if self.config.total_limit is not None:
|
|
139
|
+
if total_tokens > self.config.total_limit:
|
|
140
|
+
total_limit_exceeded = True
|
|
141
|
+
|
|
142
|
+
# Determine if check passed
|
|
143
|
+
passed = len(violations) == 0 and not total_limit_exceeded
|
|
144
|
+
|
|
145
|
+
return EnforcementResult(
|
|
146
|
+
passed=passed,
|
|
147
|
+
total_files=len(files_with_limits),
|
|
148
|
+
total_tokens=total_tokens,
|
|
149
|
+
violations=violations,
|
|
150
|
+
total_limit_exceeded=total_limit_exceeded,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
def get_suggestions(self, violation: Violation) -> List[str]:
|
|
154
|
+
"""Generate actionable suggestions for fixing a violation.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
violation: The violation to generate suggestions for
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
List of suggestion strings
|
|
161
|
+
"""
|
|
162
|
+
suggestions = []
|
|
163
|
+
excess = violation.excess
|
|
164
|
+
percentage = violation.percentage_over
|
|
165
|
+
|
|
166
|
+
# Suggest based on severity
|
|
167
|
+
if percentage > 50:
|
|
168
|
+
suggestions.append("Consider splitting this file into multiple smaller files")
|
|
169
|
+
suggestions.append(f"Target: reduce by ~{excess} tokens to get under the limit")
|
|
170
|
+
elif percentage > 20:
|
|
171
|
+
suggestions.append("Review content and remove unnecessary sections")
|
|
172
|
+
suggestions.append("Consider moving older content to an archived directory")
|
|
173
|
+
else:
|
|
174
|
+
suggestions.append("Minor reduction needed - review and tighten content")
|
|
175
|
+
|
|
176
|
+
# Generic suggestions
|
|
177
|
+
suggestions.append("Remove redundant explanations or examples")
|
|
178
|
+
suggestions.append("Consider using more concise language")
|
|
179
|
+
|
|
180
|
+
# File-specific suggestions
|
|
181
|
+
if "README" in str(violation.file_path):
|
|
182
|
+
suggestions.append("Move detailed documentation to separate docs/ files")
|
|
183
|
+
suggestions.append("Keep README high-level and link to detailed docs")
|
|
184
|
+
|
|
185
|
+
return suggestions
|
|
186
|
+
|
|
187
|
+
def __repr__(self) -> str:
|
|
188
|
+
"""String representation of LimitEnforcer."""
|
|
189
|
+
return f"LimitEnforcer(config={self.config})"
|