mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-16 19:33:11 +02:00
🤖 format everything with pre-commit by stirlingbot (#5144)
Auto-generated by [create-pull-request][1] with **stirlingbot** [1]: https://github.com/peter-evans/create-pull-request Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com> Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
parent
e6d3f20c36
commit
c990ab3216
@@ -15,7 +15,6 @@ Usage:
|
||||
import sys
|
||||
import argparse
|
||||
import glob
|
||||
from pathlib import Path
|
||||
|
||||
import tomllib
|
||||
|
||||
@@ -23,7 +22,7 @@ import tomllib
|
||||
def get_line_context(file_path, line_num, context_lines=3):
|
||||
"""Get lines around the error for context"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
start = max(0, line_num - context_lines - 1)
|
||||
@@ -32,7 +31,7 @@ def get_line_context(file_path, line_num, context_lines=3):
|
||||
context = []
|
||||
for i in range(start, end):
|
||||
marker = ">>> " if i == line_num - 1 else " "
|
||||
context.append(f"{marker}{i+1:4d}: {lines[i].rstrip()}")
|
||||
context.append(f"{marker}{i + 1:4d}: {lines[i].rstrip()}")
|
||||
|
||||
return "\n".join(context)
|
||||
except Exception as e:
|
||||
@@ -42,7 +41,7 @@ def get_line_context(file_path, line_num, context_lines=3):
|
||||
def get_character_context(file_path, char_pos, context_chars=100):
|
||||
"""Get characters around the error position"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
start = max(0, char_pos - context_chars)
|
||||
@@ -50,19 +49,19 @@ def get_character_context(file_path, char_pos, context_chars=100):
|
||||
|
||||
before = content[start:char_pos]
|
||||
error_char = content[char_pos] if char_pos < len(content) else "EOF"
|
||||
after = content[char_pos+1:end]
|
||||
after = content[char_pos + 1 : end]
|
||||
|
||||
return {
|
||||
'before': before,
|
||||
'error_char': error_char,
|
||||
'after': after,
|
||||
'display': f"{before}[{error_char}]{after}"
|
||||
"before": before,
|
||||
"error_char": error_char,
|
||||
"after": after,
|
||||
"display": f"{before}[{error_char}]{after}",
|
||||
}
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def count_keys(data, prefix=''):
|
||||
def count_keys(data, prefix=""):
|
||||
"""Recursively count all keys in nested TOML structure"""
|
||||
count = 0
|
||||
if isinstance(data, dict):
|
||||
@@ -77,42 +76,43 @@ def count_keys(data, prefix=''):
|
||||
def validate_toml_file(file_path):
|
||||
"""Validate a single TOML file and return detailed error info"""
|
||||
result = {
|
||||
'file': str(file_path),
|
||||
'valid': False,
|
||||
'error': None,
|
||||
'line': None,
|
||||
'context': None,
|
||||
'entry_count': 0
|
||||
"file": str(file_path),
|
||||
"valid": False,
|
||||
"error": None,
|
||||
"line": None,
|
||||
"context": None,
|
||||
"entry_count": 0,
|
||||
}
|
||||
|
||||
try:
|
||||
with open(file_path, 'rb') as f:
|
||||
with open(file_path, "rb") as f:
|
||||
data = tomllib.load(f)
|
||||
|
||||
result['valid'] = True
|
||||
result['entry_count'] = count_keys(data)
|
||||
result["valid"] = True
|
||||
result["entry_count"] = count_keys(data)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
result['error'] = error_msg
|
||||
result["error"] = error_msg
|
||||
|
||||
# Try to extract line number from error message
|
||||
import re
|
||||
line_match = re.search(r'line (\d+)', error_msg, re.IGNORECASE)
|
||||
|
||||
line_match = re.search(r"line (\d+)", error_msg, re.IGNORECASE)
|
||||
if line_match:
|
||||
line_num = int(line_match.group(1))
|
||||
result['line'] = line_num
|
||||
result['context'] = get_line_context(file_path, line_num)
|
||||
result["line"] = line_num
|
||||
result["context"] = get_line_context(file_path, line_num)
|
||||
|
||||
except FileNotFoundError:
|
||||
result['error'] = "File not found"
|
||||
result["error"] = "File not found"
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def print_validation_result(result, brief=False, quiet=False):
|
||||
"""Print validation result in human-readable format"""
|
||||
if result['valid']:
|
||||
if result["valid"]:
|
||||
if not quiet:
|
||||
print(f"✓ {result['file']}")
|
||||
if not brief:
|
||||
@@ -121,30 +121,35 @@ def print_validation_result(result, brief=False, quiet=False):
|
||||
print(f"✗ {result['file']}")
|
||||
print(f" Error: {result['error']}")
|
||||
|
||||
if result['line']:
|
||||
if result["line"]:
|
||||
print(f" Line: {result['line']}")
|
||||
|
||||
if result['context'] and not brief:
|
||||
print(f"\n Context:")
|
||||
if result["context"] and not brief:
|
||||
print("\n Context:")
|
||||
print(f" {result['context'].replace(chr(10), chr(10) + ' ')}")
|
||||
|
||||
if not brief:
|
||||
print(f"\n Common fixes:")
|
||||
print(f" - Check for missing quotes around keys or values")
|
||||
print(f" - Ensure proper escaping of special characters")
|
||||
print(f" - Verify table header syntax: [section.subsection]")
|
||||
print(f" - Check for duplicate keys in the same table")
|
||||
print("\n Common fixes:")
|
||||
print(" - Check for missing quotes around keys or values")
|
||||
print(" - Ensure proper escaping of special characters")
|
||||
print(" - Verify table header syntax: [section.subsection]")
|
||||
print(" - Check for duplicate keys in the same table")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Validate TOML translation files')
|
||||
parser.add_argument('files', nargs='*', help='TOML file(s) or pattern to validate')
|
||||
parser.add_argument('--all-batches', metavar='LANG',
|
||||
help='Validate all batch files for a language (e.g., ar_AR)')
|
||||
parser.add_argument('--brief', action='store_true',
|
||||
help='Show brief output without context')
|
||||
parser.add_argument('--quiet', action='store_true',
|
||||
help='Only show files with errors')
|
||||
parser = argparse.ArgumentParser(description="Validate TOML translation files")
|
||||
parser.add_argument("files", nargs="*", help="TOML file(s) or pattern to validate")
|
||||
parser.add_argument(
|
||||
"--all-batches",
|
||||
metavar="LANG",
|
||||
help="Validate all batch files for a language (e.g., ar_AR)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--brief", action="store_true", help="Show brief output without context"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--quiet", action="store_true", help="Only show files with errors"
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -181,11 +186,11 @@ def main():
|
||||
|
||||
# Summary
|
||||
total = len(results)
|
||||
valid = sum(1 for r in results if r['valid'])
|
||||
valid = sum(1 for r in results if r["valid"])
|
||||
invalid = total - valid
|
||||
|
||||
if not args.quiet:
|
||||
print(f"\n{'='*60}")
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f"Summary: {valid}/{total} files valid")
|
||||
if invalid > 0:
|
||||
print(f" {invalid} file(s) with errors")
|
||||
@@ -194,5 +199,5 @@ def main():
|
||||
sys.exit(0 if invalid == 0 else 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user