Coverage for mcpgateway/utils/create_slug.py: 100%

12 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-07-09 11:03 +0100

1# -*- coding: utf-8 -*- 

2# Standard 

3import re 

4from unicodedata import normalize 

5 

6# Helper regex patterns 

7CONTRACTION_PATTERN = re.compile(r"(\w)[''](\w)") 

8NON_ALPHANUMERIC_PATTERN = re.compile(r"[\W_]+") 

9 

10# Special character replacements that normalize() doesn't handle well 

11SPECIAL_CHAR_MAP = { 

12 "æ": "ae", 

13 "ß": "ss", 

14 "ø": "o", 

15} 

16 

17 

18def slugify(text): 

19 """Make an ASCII slug of text. 

20 

21 Args: 

22 text(str): Input text 

23 

24 Returns: 

25 str: Slugified text 

26 """ 

27 # Make lower case and delete apostrophes from contractions 

28 slug = CONTRACTION_PATTERN.sub(r"\1\2", text.lower()) 

29 # Convert runs of non-alphanumeric characters to single hyphens, strip ends 

30 slug = NON_ALPHANUMERIC_PATTERN.sub("-", slug).strip("-") 

31 # Replace special characters from the map 

32 for special_char, replacement in SPECIAL_CHAR_MAP.items(): 

33 slug = slug.replace(special_char, replacement) 

34 # Normalize the non-ASCII text to ASCII 

35 slug = normalize("NFKD", slug).encode("ascii", "ignore").decode() 

36 return slug