File size: 3,337 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""Shared validation, response, and identifier helpers for the filesystem simulator."""

from __future__ import annotations

import copy
import hashlib
import re
from datetime import datetime
from typing import Any, Dict, Iterable, Optional


ID_PREFIXES: Dict[str, str] = {
    "workspace": "workspace",
    "user": "user",
    "team": "team",
    "node": "node",
    "file_content": "content",
    "operation": "op",
    "snapshot": "snapshot",
    "manifest": "manifest",
}

LEGACY_ID_PREFIXES: Dict[str, str] = {
    "workspace": "WSP",
    "user": "USR",
    "team": "TEM",
    "node": "NOD",
    "file_content": "CNT",
    "operation": "OPR",
    "snapshot": "SNP",
    "manifest": "MNF",
}


def success_response(data: Dict[str, Any], message: str = "") -> Dict[str, Any]:
    return {"status": "success", "data": data, "message": message}


def error_response(error_code: str, message: str) -> Dict[str, Any]:
    return {"status": "error", "data": {}, "message": f"{error_code}: {message}"}


def now_iso() -> str:
    return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")


def safe_copy(value: Any) -> Any:
    return copy.deepcopy(value)


def slugify(value: Any, *, fallback: str = "item") -> str:
    text = str(value or "").strip().lower()
    text = re.sub(r"[^a-z0-9]+", "-", text)
    text = re.sub(r"-+", "-", text).strip("-")
    return text or fallback


def generate_id(entity_type: str, sequence: int) -> str:
    prefix = ID_PREFIXES.get(entity_type, entity_type.strip().lower() or "entity")
    return f"{prefix}-generated-{int(sequence):04d}"


def validate_id_format(value: str, entity_type: str) -> bool:
    prefix = ID_PREFIXES.get(entity_type)
    if prefix is None:
        return False
    return bool(re.match(rf"^{re.escape(prefix)}-[a-z0-9][a-z0-9-]*$", str(value or "")))


def extract_id_sequence(value: Any, entity_type: Optional[str] = None) -> Optional[int]:
    text = str(value or "")
    match = re.search(r"-(\d{4,})$", text)
    if match:
        return int(match.group(1))
    if entity_type:
        legacy = LEGACY_ID_PREFIXES.get(entity_type)
        if legacy:
            legacy_match = re.fullmatch(rf"{re.escape(legacy)}_(\d+)", text)
            if legacy_match:
                return int(legacy_match.group(1))
    return None


def build_humanized_id(
    entity_type: str,
    record: Dict[str, Any],
    *,
    existing_ids: Optional[Iterable[str]] = None,
) -> str:
    existing = set(existing_ids or [])
    prefix = ID_PREFIXES.get(entity_type, entity_type)
    fields = [
        record.get("workspace_id"),
        record.get("path"),
        record.get("name"),
        record.get("reason"),
        record.get("action"),
    ]
    parts = [slugify(value) for value in fields if value]
    base = f"{prefix}-" + "-".join(parts[:3]) if parts else f"{prefix}-generated"
    base = re.sub(r"-+", "-", base).strip("-")
    candidate = base
    index = 2
    while candidate in existing:
        candidate = f"{base}-{index}"
        index += 1
    return candidate


def checksum_text(text: str) -> str:
    return "sha256:" + hashlib.sha256(str(text).encode("utf-8")).hexdigest()


def byte_len(text: str) -> int:
    return len(str(text).encode("utf-8"))


def line_count(text: str) -> int:
    if text == "":
        return 0
    return len(str(text).splitlines()) or 1