Coverage for functions \ flipdare \ util \ slug_coder.py: 100%
24 statements
« prev ^ index » next coverage.py v7.13.0, created at 2026-05-08 12:22 +1000
« prev ^ index » next coverage.py v7.13.0, created at 2026-05-08 12:22 +1000
1#!/usr/bin/env python
2# Copyright (c) 2026 Flipdare Pty Ltd. All rights reserved.
3#
4# This file is part of Flipdare's proprietary software and contains
5# confidential and copyrighted material. Unauthorised copying,
6# modification, distribution, or use of this file is strictly
7# prohibited without prior written permission from Flipdare Pty Ltd.
8#
9# This software includes third-party components licensed under MIT,
10# BSD, and Apache 2.0 licences. See THIRD_PARTY_NOTICES for details.
11#
14import re
15import hashlib
17from flipdare.constants import SLUG_CODE_LENGTH
18from flipdare.util.user_util import UserUtil
20__all__ = ["SlugCoder"]
23class SlugCoder:
25 def __init__(self, length: int = SLUG_CODE_LENGTH) -> None:
26 self.length = length
28 def from_text(self, text: str) -> str:
29 return self._generate_readable_code(text, self.length)
31 def from_doc_id(self, doc_id: str) -> str:
32 return self._generate_readable_code(doc_id, self.length)
34 def from_user_info(
35 self,
36 email: str,
37 name: str | None = None,
38 display_name: str | None = None,
39 ) -> str:
40 if name is not None:
41 return self._generate_readable_code(name, self.length)
43 safe_name = UserUtil.safe_name(email, display_name, name)
44 return self._generate_readable_code(safe_name, self.length)
46 @staticmethod
47 def _generate_readable_code(text: str, length: int = 14) -> str:
48 # 1. Clean the text: remove non-alphanumeric, lowercase it
49 clean_text = re.sub(r"[^a-zA-Z0-9\s]", "", text).lower()
50 words = clean_text.split()
52 # 2. Grab the first 2-3 words and join with dashes
53 base_slug = "-".join(words[:3])[: length - 5] # Leave room for the hash
55 # 3. Create a tiny hash from the full text to prevent collisions
56 salt = hashlib.md5(text.encode()).hexdigest()[:4] # noqa: S324
58 # 4. Combine: "word-word-salt"
59 return f"{base_slug}-{salt}"