fix tests for context and permalinks

This commit is contained in:
phernandez
2025-01-18 23:54:28 -06:00
parent 9af2f481b2
commit 32606d771d
41 changed files with 262 additions and 250 deletions
+49 -1
View File
@@ -1,8 +1,10 @@
"""Utility functions for basic-memory."""
import os
import re
import unicodedata
from unidecode import unidecode
def sanitize_name(name: str) -> str:
"""
@@ -27,3 +29,49 @@ def sanitize_name(name: str) -> str:
name = re.sub(r"_+", "_", name).strip("_")
return name
def generate_permalink(file_path: str) -> str:
"""Generate a stable permalink from a file path.
Args:
file_path: Original file path
Returns:
Normalized permalink that matches validation rules. Converts spaces and underscores
to hyphens for consistency.
Examples:
>>> generate_permalink("docs/My Feature.md")
'docs/my-feature'
>>> generate_permalink("specs/API (v2).md")
'specs/api-v2'
>>> generate_permalink("design/unified_model_refactor.md")
'design/unified-model-refactor'
"""
# Remove extension
base = os.path.splitext(file_path)[0]
# Transliterate unicode to ascii
ascii_text = unidecode(base)
# Insert dash between camelCase
ascii_text = re.sub(r"([a-z0-9])([A-Z])", r"\1-\2", ascii_text)
# Convert to lowercase
lower_text = ascii_text.lower()
# replace underscores with hyphens
text_with_hyphens = lower_text.replace('_', '-')
# Replace remaining invalid chars with hyphens
clean_text = re.sub(r'[^a-z0-9/\-]', '-', text_with_hyphens)
# Collapse multiple hyphens
clean_text = re.sub(r'-+', '-', clean_text)
# Clean each path segment
segments = clean_text.split('/')
clean_segments = [s.strip('-') for s in segments]
return '/'.join(clean_segments)