Coverage for app / documents / visuals / mermaid / dates.py: 91%
148 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""Dates as a Gantt chart writes them: ``dateFormat`` in dayjs's tokens,
2durations in dayjs's units, ``axisFormat`` in d3's directives.
4Each is read strictly and deterministically (no locale, no time zone): a
5date that does not match the format is tried as ISO 8601, as Mermaid falls
6back to ``new Date``, and is refused otherwise.
7"""
9from __future__ import annotations
11import calendar
12import re
13from datetime import UTC, datetime, timedelta
15MONTHS = [calendar.month_name[i] for i in range(1, 13)]
16DAYS = [calendar.day_name[i] for i in range(7)] # Monday first, as datetime
18#: dayjs tokens, longest first: (token, pattern, field).
19_TOKENS: tuple[tuple[str, str, str], ...] = (
20 ("YYYY", r"\d{4}", "year"),
21 ("YY", r"\d{2}", "year2"),
22 ("MMMM", "|".join(MONTHS), "month_name"),
23 ("MMM", "|".join(m[:3] for m in MONTHS), "month_short"),
24 ("MM", r"\d{2}", "month"),
25 ("M", r"\d{1,2}", "month"),
26 ("DD", r"\d{2}", "day"),
27 ("D", r"\d{1,2}", "day"),
28 ("HH", r"\d{2}", "hour"),
29 ("H", r"\d{1,2}", "hour"),
30 ("hh", r"\d{2}", "hour12"),
31 ("h", r"\d{1,2}", "hour12"),
32 ("mm", r"\d{2}", "minute"),
33 ("m", r"\d{1,2}", "minute"),
34 ("ss", r"\d{2}", "second"),
35 ("s", r"\d{1,2}", "second"),
36 ("SSS", r"\d{3}", "millisecond"),
37 ("A", r"AM|PM", "ampm"),
38 ("a", r"am|pm", "ampm"),
39 ("X", r"-?\d+(?:\.\d+)?", "unix"),
40 ("x", r"-?\d+", "unix_ms"),
41)
42_ISO = re.compile(
43 r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,6}))?)?)?(?:Z)?$"
44)
45_DURATION = re.compile(r"^(\d+(?:\.\d+)?)\s*(ms|[smhdwMy])$")
46_UNITS = {
47 "ms": timedelta(milliseconds=1),
48 "s": timedelta(seconds=1),
49 "m": timedelta(minutes=1),
50 "h": timedelta(hours=1),
51 "d": timedelta(days=1),
52 "w": timedelta(weeks=1),
53}
56class DateFormat:
57 """A ``dateFormat`` compiled to a full-match pattern."""
59 def __init__(self, text: str) -> None:
60 self.text = text.strip() or "YYYY-MM-DD"
61 parts: list[str] = []
62 self.fields: dict[str, str] = {}
63 i, n = 0, 0
64 while i < len(self.text):
65 ch = self.text[i]
66 if ch == "[":
67 end = self.text.find("]", i)
68 end = len(self.text) if end < 0 else end
69 parts.append(re.escape(self.text[i + 1 : end]))
70 i = end + 1
71 continue
72 for token, pattern, name in _TOKENS:
73 if self.text.startswith(token, i):
74 group = f"g{n}"
75 n += 1
76 self.fields[group] = name
77 parts.append(f"(?P<{group}>{pattern})")
78 i += len(token)
79 break
80 else:
81 parts.append(re.escape(ch))
82 i += 1
83 self.pattern = re.compile("^" + "".join(parts) + "$", re.IGNORECASE)
85 def parse(self, value: str) -> datetime | None:
86 value = value.strip()
87 m = self.pattern.match(value)
88 if m:
89 return self._build(m)
90 iso = _ISO.match(value)
91 if iso:
92 y, mo, d, h, mi, s, frac = iso.groups()
93 try:
94 return datetime(
95 int(y), int(mo), int(d), int(h or 0), int(mi or 0), int(s or 0),
96 int((frac or "0").ljust(6, "0")),
97 ) # fmt: skip
98 except ValueError:
99 return None
100 return None
102 def _build(self, m: re.Match[str]) -> datetime | None:
103 got: dict[str, str] = {
104 self.fields[k]: v for k, v in m.groupdict().items() if v is not None
105 }
106 try:
107 if "unix" in got:
108 return datetime.fromtimestamp(float(got["unix"]), UTC).replace(
109 tzinfo=None
110 )
111 if "unix_ms" in got:
112 return datetime.fromtimestamp(int(got["unix_ms"]) / 1000, UTC).replace(
113 tzinfo=None
114 )
115 year = (
116 int(got["year"])
117 if "year" in got
118 else (2000 + int(got["year2"]) if "year2" in got else 1970)
119 )
120 if "month_name" in got:
121 month = [m.lower() for m in MONTHS].index(got["month_name"].lower()) + 1
122 elif "month_short" in got:
123 month = [m[:3].lower() for m in MONTHS].index(
124 got["month_short"].lower()
125 ) + 1
126 else:
127 month = int(got.get("month", 1))
128 hour = int(got.get("hour", 0))
129 if "hour12" in got:
130 hour = int(got["hour12"]) % 12 + (
131 12 if got.get("ampm", "").lower() == "pm" else 0
132 )
133 return datetime(
134 year, month, int(got.get("day", 1)), hour, int(got.get("minute", 0)),
135 int(got.get("second", 0)), int(got.get("millisecond", 0)) * 1000,
136 ) # fmt: skip
137 except (ValueError, OverflowError, OSError):
138 return None
141def add_months(value: datetime, months: int) -> datetime:
142 """dayjs's ``add(n, "month")``: the day kept, or the month's last."""
143 index = value.month - 1 + months
144 year, month = value.year + index // 12, index % 12 + 1
145 day = min(value.day, calendar.monthrange(year, month)[1])
146 return value.replace(year=year, month=month, day=day)
149def duration_end(start: datetime, text: str) -> datetime | None:
150 """``start`` plus a duration such as ``3d``, ``1.5w`` or ``2M``."""
151 m = _DURATION.match(text.strip())
152 if not m:
153 return None
154 amount, unit = float(m.group(1)), m.group(2)
155 try:
156 if unit == "M":
157 return add_months(start, round(amount))
158 if unit == "y":
159 return add_months(start, 12 * round(amount))
160 return start + _UNITS[unit] * amount
161 except (OverflowError, ValueError):
162 return None
165def strftime(value: datetime, pattern: str) -> str:
166 """d3's ``timeFormat``: ``%Y-%m-%d``, ``%b %e``, ``%-d`` … Unknown
167 directives are written as they stand."""
168 out: list[str] = []
169 i = 0
170 while i < len(pattern):
171 ch = pattern[i]
172 if ch != "%" or i + 1 >= len(pattern):
173 out.append(ch)
174 i += 1
175 continue
176 pad = None
177 j = i + 1
178 if pattern[j] in "-_0" and j + 1 < len(pattern):
179 pad, j = pattern[j], j + 1
180 out.append(_directive(value, pattern[j], pad) or pattern[i : j + 1])
181 i = j + 1
182 return "".join(out)
185def _padded(number: int, width: int, pad: str | None, default: str = "0") -> str:
186 if pad == "-":
187 return str(number)
188 fill = " " if (pad == "_" or (pad is None and default == " ")) else "0"
189 return str(number).rjust(width, fill)
192def _directive(value: datetime, code: str, pad: str | None) -> str | None:
193 if code == "Y":
194 return str(value.year)
195 if code == "y":
196 return _padded(value.year % 100, 2, pad)
197 if code == "m":
198 return _padded(value.month, 2, pad)
199 if code == "d":
200 return _padded(value.day, 2, pad)
201 if code == "e":
202 return _padded(value.day, 2, pad, " ")
203 if code == "H":
204 return _padded(value.hour, 2, pad)
205 if code == "I":
206 return _padded(value.hour % 12 or 12, 2, pad)
207 if code == "M":
208 return _padded(value.minute, 2, pad)
209 if code == "S":
210 return _padded(value.second, 2, pad)
211 if code == "L":
212 return _padded(value.microsecond // 1000, 3, pad)
213 if code == "p":
214 return "PM" if value.hour >= 12 else "AM"
215 if code == "b":
216 return MONTHS[value.month - 1][:3]
217 if code == "B":
218 return MONTHS[value.month - 1]
219 if code == "a":
220 return DAYS[value.weekday()][:3]
221 if code == "A":
222 return DAYS[value.weekday()]
223 if code == "j":
224 return _padded(value.timetuple().tm_yday, 3, pad)
225 if code == "V":
226 return _padded(value.isocalendar()[1], 2, pad)
227 if code == "U":
228 return _padded(int(value.strftime("%U")), 2, pad)
229 if code == "w":
230 return str((value.weekday() + 1) % 7)
231 if code == "%":
232 return "%"
233 return None