Coverage for requests_tracker/templatetags/format_tags.py: 100%
32 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-18 22:19 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-18 22:19 +0000
1import os
2import re
3from pprint import pformat
4from typing import Any, Dict, Optional
6from django import template
7from django.utils.safestring import mark_safe
9from requests_tracker.sql.sql_parser import parse_sql
11register = template.Library()
14@register.filter
15def split_and_last(value: str, splitter: str = ".") -> str:
16 """
17 Takes in a string and splits it and returns the last item in the split.
18 """
19 return value.split(splitter)[-1]
22@register.filter
23def dict_key_index(input_dict: Dict[str, Any], key: str) -> Optional[int]:
24 """
25 Takes in a string key and returns the list index of the key.
26 Returns None if key is not found.
27 """
28 return next(
29 (i for i, dict_key in enumerate(input_dict.keys()) if dict_key == key),
30 None,
31 )
34@register.filter
35def pprint_datastructure_values(value: Any) -> str:
36 return mark_safe(
37 f"<pre>{pformat(value)}</pre>"
38 if isinstance(value, (dict, list, tuple))
39 else str(value)
40 )
43@register.simple_tag
44def simplify_sql(sql: str) -> str:
45 """
46 Takes in sql string and reformats it for a collapsed view.
47 """
48 parsed_sql = parse_sql(sql, align_indent=False)
49 simplify_re = re.compile(r"SELECT</strong> (...........*?) <strong>FROM")
50 return simplify_re.sub(
51 r"SELECT</strong> ••• <strong>FROM", parsed_sql
52 )
55@register.simple_tag
56def format_sql(sql: str) -> str:
57 """
58 Reformats SQL with align indents and bolded keywords
59 """
60 return parse_sql(sql, align_indent=True)
63@register.filter
64def simplify_path(path: str) -> str:
65 """
66 Takes in python full path and returns it relative to the current running
67 django project or site_packages.
69 e.g.
70 "/Users/my_user/Documents/django-project/venv/lib/python3.10/
71 site-packages/django/contrib/staticfiles/handlers.py"
72 =>
73 ".../site-packages/django/contrib/staticfiles/handlers.py"
74 """
76 if "/site-packages" in path:
77 return f"...{ path[path.index('/site-packages'): ] }"
78 elif path.startswith(os.getcwd()):
79 # This should be the directory of the django project
80 return f"...{path[len(os.getcwd()): ] }"
82 return path