Debian Codegraph @

dist/scripts/upgrade-check.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """htmx 2 → 4 migration checker.
3
4 Scans HTML template files for upgrade issues and prints clickable
5 file:line references with suggested fixes.
6
7 Usage:
8 python htmx-upgrade-check.py [--ext .html,.php] [paths ...]
9 """
10
11 import argparse
12 import os
13 import re
14 import sys
15 from html.parser import HTMLParser
16
17 # ---------------------------------------------------------------------------
18 # Migration rules
19 # ---------------------------------------------------------------------------
20
21 REMOVED_ATTRS = {
22 "hx-vars": "use hx-vals with js: prefix",
23 "hx-params": "use htmx:config:request event",
24 "hx-prompt": "load the hx-prompt extension to keep the same syntax",
25 "hx-ext": "include extension scripts directly (no attribute needed in v4)",
26 "hx-disinherit": "not needed (inheritance is explicit in v4)",
27 "hx-inherit": "not needed (inheritance is explicit in v4)",
28 "hx-request": "use hx-config",
29 "hx-history": "removed (no localStorage cache in v4)",
30 "hx-history-elt": "removed",
31 }
32
33 RENAMED_ATTRS = {
34 "hx-disable": "rename to hx-ignore (hx-disable now means 'disable during request')",
35 "hx-disabled-elt": "rename to hx-disable",
36 }
37
38 # Attributes that were implicitly inherited in htmx 2 (via getClosestAttributeValue,
39 # findAttributeTargets, or getValuesForElement walking up the tree).
40 INHERITABLE_ATTRS = {
41 "hx-boost", "hx-confirm", "hx-encoding", "hx-headers", "hx-include",
42 "hx-indicator", "hx-push-url", "hx-replace-url", "hx-select",
43 "hx-select-oob", "hx-swap", "hx-sync", "hx-target", "hx-vals",
44 # These are removed/renamed in v4 but we still flag inheritance patterns
45 # so the user sees the full picture:
46 "hx-disabled-elt",
47 }
48
49 REQUEST_ATTRS = {"hx-get", "hx-post", "hx-put", "hx-patch", "hx-delete"}
50
51 # htmx 2 event → htmx 4 event
52 EVENT_RENAMES = {
53 "htmx:afterOnLoad": "htmx:after:init",
54 "htmx:afterProcessNode": "htmx:after:init",
55 "htmx:afterRequest": "htmx:after:request",
56 "htmx:afterSettle": "htmx:after:swap",
57 "htmx:afterSwap": "htmx:after:swap",
58 "htmx:beforeCleanupElement": "htmx:before:cleanup",
59 "htmx:beforeHistorySave": "htmx:before:history:update",
60 "htmx:beforeOnLoad": "htmx:before:init",
61 "htmx:beforeProcessNode": "htmx:before:process",
62 "htmx:beforeRequest": "htmx:before:request",
63 "htmx:beforeSwap": "htmx:before:swap",
64 "htmx:configRequest": "htmx:config:request",
65 "htmx:historyCacheMiss": "htmx:before:history:restore",
66 "htmx:historyRestore": "htmx:before:history:restore",
67 "htmx:load": "htmx:after:init",
68 "htmx:oobAfterSwap": "htmx:after:swap",
69 "htmx:oobBeforeSwap": "htmx:before:swap",
70 "htmx:pushedIntoHistory": "htmx:after:history:push",
71 "htmx:replacedInHistory": "htmx:after:history:replace",
72 "htmx:responseError": "htmx:response:error",
73 "htmx:sendError": "htmx:error",
74 "htmx:swapError": "htmx:error",
75 "htmx:targetError": "htmx:error",
76 "htmx:timeout": "htmx:error",
77 }
78
79 REMOVED_EVENTS = {
80 "htmx:validation:validate", "htmx:validation:failed",
81 "htmx:validation:halted", "htmx:xhr:loadstart",
82 "htmx:xhr:loadend", "htmx:xhr:progress", "htmx:xhr:abort",
83 }
84
85 SSE_EVENT_RENAMES = {
86 "htmx:sseOpen": "htmx:after:sse:connection",
87 "htmx:sseError": "htmx:sse:error",
88 "htmx:sseBeforeMessage": "htmx:before:sse:message",
89 "htmx:sseMessage": "htmx:after:sse:message",
90 "htmx:sseClose": "htmx:sse:close",
91 }
92
93 WS_EVENT_RENAMES = {
94 "htmx:wsOpen": "htmx:after:ws:connection",
95 "htmx:wsClose": "htmx:ws:close",
96 "htmx:wsConfigSend": "htmx:before:ws:request",
97 "htmx:wsBeforeSend": "htmx:before:ws:request",
98 "htmx:wsAfterSend": "htmx:after:ws:request",
99 "htmx:wsBeforeMessage": "htmx:before:ws:message",
100 "htmx:wsAfterMessage": "htmx:after:ws:message",
101 }
102
103 # Extension attribute renames
104 EXT_ATTR_RENAMES = {
105 "sse-connect": "rename to hx-sse:connect",
106 "sse-swap": "removed — SSE now integrates with standard htmx request pipeline",
107 "ws-connect": "rename to hx-ws:connect",
108 "ws-send": "rename to hx-ws:send",
109 }
110
111 # Old JS API calls
112 REMOVED_JS_API = {
113 "htmx.addClass": "use element.classList.add()",
114 "htmx.removeClass": "use element.classList.remove()",
115 "htmx.toggleClass": "use element.classList.toggle()",
116 "htmx.closest": "use element.closest()",
117 "htmx.remove": "use element.remove()",
118 "htmx.off": "use removeEventListener() (htmx.on() returns the callback)",
119 "htmx.location": "use htmx.ajax()",
120 "htmx.takeClass": (
121 "removed from core. To restore the htmx 2 behavior verbatim, paste:\n"
122 " htmx.takeClass = (elt, cls) => {\n"
123 " elt = typeof elt === 'string' ? document.querySelector(elt) : elt;\n"
124 " for (let c of elt.parentElement.children) c.classList.remove(cls);\n"
125 " elt.classList.add(cls);\n"
126 " };\n"
127 " For a fully featured replacement (polymorphic targets/sources, selector strings, "
128 "iterable inputs, q-proxy chaining), load the hx-live extension and use htmx.live.take()."
129 ),
130 "htmx.logAll": "use htmx.config.logAll = true",
131 "htmx.logNone": "use htmx.config.logAll = false (errors/warnings flow to console.* directly)",
132 "htmx.logger": "removed; htmx logs to console.error / console.warn / console.log directly. Observability tools (Sentry, DataDog RUM, etc.) capture console.* automatically",
133 "htmx.defineExtension": "use htmx.registerExtension()",
134 }
135
136 # Old config key → new config key
137 CONFIG_RENAMES = {
138 "defaultSwapStyle": "defaultSwap",
139 "globalViewTransitions": "transitions",
140 "historyEnabled": "history",
141 "includeIndicatorStyles": "includeIndicatorCSS",
142 }
143
144 REMOVED_CONFIG = {
145 "addedClass", "allowEval", "allowNestedOobSwaps", "allowScriptTags",
146 "attributesToSettle", "defaultSwapDelay", "disableSelector",
147 "getCacheBusterParam", "historyCacheSize", "methodsThatUseUrlParams",
148 "refreshOnHistoryMiss", "responseHandling", "scrollBehavior",
149 "scrollIntoViewOnBoost", "selfRequestsOnly", "settlingClass",
150 "swappingClass", "triggerSpecsCache", "useTemplateFragments",
151 "withCredentials", "wsBinaryType", "wsReconnectDelay",
152 }
153
154 # Old hx-swap show/scroll combined syntax: show:#selector:position
155 SWAP_OLD_SYNTAX = re.compile(r"(show|scroll):([^:\s]+):(top|bottom)")
156
157 # All old event names for text scanning
158 ALL_OLD_EVENTS = {**EVENT_RENAMES, **SSE_EVENT_RENAMES, **WS_EVENT_RENAMES}
159
160 # Lowercase lookup for hx-on attribute matching (html.parser lowercases attr names)
161 ALL_OLD_EVENTS_LOWER = {k.lower(): (k, v) for k, v in ALL_OLD_EVENTS.items()}
162 REMOVED_EVENTS_LOWER = {e.lower(): e for e in REMOVED_EVENTS}
163
164 # Removed response headers (flag if found in templates/JS)
165 REMOVED_RESPONSE_HEADERS = {
166 "HX-Trigger-After-Swap": "use HX-Trigger or JavaScript instead",
167 "HX-Trigger-After-Settle": "use HX-Trigger or JavaScript instead",
168 }
169
170 # ---------------------------------------------------------------------------
171 # Simple DOM tree
172 # ---------------------------------------------------------------------------
173
174 class Node:
175 __slots__ = ("tag", "attrs", "line", "children", "parent")
176
177 def __init__(self, tag, attrs, line):
178 self.tag = tag
179 self.attrs = attrs # dict {name: value}
180 self.line = line
181 self.children = []
182 self.parent = None
183
184 def descendants(self):
185 """Yield all descendant nodes (depth-first)."""
186 for child in self.children:
187 yield child
188 yield from child.descendants()
189
190 def has_request_attr(self):
191 return bool(REQUEST_ATTRS & set(self.attrs))
192
193
194 VOID_ELEMENTS = frozenset({
195 "area", "base", "br", "col", "embed", "hr", "img", "input",
196 "link", "meta", "param", "source", "track", "wbr",
197 })
198
199
200 class TreeBuilder(HTMLParser):
201 """Lenient HTML parser that builds a simple DOM tree with line numbers."""
202
203 def __init__(self):
204 super().__init__(convert_charrefs=False)
205 self.root = Node("root", {}, 0)
206 self.current = self.root
207
208 def handle_starttag(self, tag, attrs):
209 line, _ = self.getpos()
210 node = Node(tag, dict(attrs), line)
211 node.parent = self.current
212 self.current.children.append(node)
213 if tag.lower() not in VOID_ELEMENTS:
214 self.current = node
215
216 def handle_startendtag(self, tag, attrs):
217 line, _ = self.getpos()
218 node = Node(tag, dict(attrs), line)
219 node.parent = self.current
220 self.current.children.append(node)
221
222 def handle_endtag(self, tag):
223 node = self.current
224 while node.parent and node.tag != tag:
225 node = node.parent
226 if node.parent:
227 self.current = node.parent
228
229 def error(self, message):
230 pass
231
232
233 # ---------------------------------------------------------------------------
234 # Template syntax stripping
235 # ---------------------------------------------------------------------------
236
237 def _keep_newlines(match):
238 return "\n" * match.group().count("\n")
239
240
241 def strip_template_syntax(text):
242 """Replace template tags with whitespace, preserving line numbers."""
243 # Django / Jinja2
244 text = re.sub(r"\{%.*?%\}", _keep_newlines, text, flags=re.DOTALL)
245 text = re.sub(r"\{\{.*?\}\}", lambda m: "X" + _keep_newlines(m), text, flags=re.DOTALL)
246 # PHP
247 text = re.sub(r"<\?(?:php)?.*?\?>", _keep_newlines, text, flags=re.DOTALL)
248 # ERB
249 text = re.sub(r"<%.*?%>", _keep_newlines, text, flags=re.DOTALL)
250 return text
251
252
253 # ---------------------------------------------------------------------------
254 # Issue collection
255 # ---------------------------------------------------------------------------
256
257 class Issue:
258 __slots__ = ("file", "line", "category", "message")
259
260 def __init__(self, file, line, category, message):
261 self.file = file
262 self.line = line
263 self.category = category
264 self.message = message
265
266 def __str__(self):
267 return f"{self.file}:{self.line}: [{self.category}] {self.message}"
268
269
270 # ---------------------------------------------------------------------------
271 # Tree-based checks
272 # ---------------------------------------------------------------------------
273
274 def check_node(node, filepath, issues):
275 """Check a single node for migration issues, then recurse into children."""
276 attrs = node.attrs
277
278 for attr_name in attrs:
279 name_lower = attr_name.lower()
280
281 # Removed attributes
282 if name_lower in REMOVED_ATTRS:
283 issues.append(Issue(filepath, node.line, "removed-attr",
284 f"{attr_name} is removed → {REMOVED_ATTRS[name_lower]}"))
285
286 # Renamed attributes
287 if name_lower in RENAMED_ATTRS:
288 issues.append(Issue(filepath, node.line, "renamed-attr",
289 f"{attr_name} → {RENAMED_ATTRS[name_lower]}"))
290
291 # Extension attributes (SSE / WS)
292 if name_lower in EXT_ATTR_RENAMES:
293 issues.append(Issue(filepath, node.line, "ext",
294 f"{attr_name} → {EXT_ATTR_RENAMES[name_lower]}"))
295
296 # Old event names in hx-on attributes
297 if name_lower.startswith("hx-on:") or name_lower.startswith("hx-on::"):
298 check_hx_on_event(node, attr_name, filepath, issues)
299
300 # Old hx-swap show/scroll combined syntax
301 if name_lower == "hx-swap" and attrs[attr_name]:
302 check_swap_syntax(node, attrs[attr_name], filepath, issues)
303
304 for child in node.children:
305 check_node(child, filepath, issues)
306
307
308 def check_hx_on_event(node, attr_name, filepath, issues):
309 """Check if an hx-on: attribute references an old event name."""
310 lower = attr_name.lower()
311 if lower.startswith("hx-on::"):
312 event_lower = "htmx:" + lower[7:]
313 elif lower.startswith("hx-on:"):
314 event_lower = lower[6:]
315 else:
316 return
317
318 if event_lower in ALL_OLD_EVENTS_LOWER:
319 original, new_name = ALL_OLD_EVENTS_LOWER[event_lower]
320 issues.append(Issue(filepath, node.line, "renamed-event",
321 f'{attr_name} uses old event name "{original}" → '
322 f'use hx-on:{new_name}'))
323 elif event_lower in REMOVED_EVENTS_LOWER:
324 issues.append(Issue(filepath, node.line, "removed-event",
325 f'{attr_name} uses removed event '
326 f'{REMOVED_EVENTS_LOWER[event_lower]}'))
327
328
329 def check_swap_syntax(node, value, filepath, issues):
330 """Check for old show:#selector:position syntax in hx-swap."""
331 m = SWAP_OLD_SYNTAX.search(value)
332 if m:
333 kind, selector, position = m.groups()
334 target_key = f"{kind}Target"
335 issues.append(Issue(filepath, node.line, "swap-syntax",
336 f'old {kind}:{selector}:{position} syntax → '
337 f'use {kind}:{position} {target_key}:{selector}'))
338
339
340 def check_inheritance(root, filepath, issues):
341 """Detect implicit inheritance patterns: inheritable attr on ancestor,
342 request attr on descendant."""
343 def walk(node):
344 for attr_name in node.attrs:
345 name_lower = attr_name.lower()
346 if name_lower not in INHERITABLE_ATTRS:
347 continue
348 # Already has :inherited suffix — nothing to flag
349 if ":inherited" in attr_name:
350 continue
351
352 # For hx-boost, any descendant <a> or <form> is affected
353 if name_lower == "hx-boost":
354 for desc in node.descendants():
355 if desc.tag in ("a", "form"):
356 issues.append(Issue(filepath, node.line, "inheritance",
357 f'{attr_name} needs :inherited suffix '
358 f'(descendant <{desc.tag}> on line {desc.line} '
359 f'will no longer inherit it)'))
360 break # one warning per attr is enough
361 continue
362
363 # For other attrs, check for descendants that make requests
364 for desc in node.descendants():
365 if desc.has_request_attr():
366 issues.append(Issue(filepath, node.line, "inheritance",
367 f'{attr_name} needs :inherited suffix '
368 f'(descendant on line {desc.line} has '
369 f'{next(a for a in desc.attrs if a in REQUEST_ATTRS)})'))
370 break
371
372 for child in node.children:
373 walk(child)
374
375 walk(root)
376
377
378 # ---------------------------------------------------------------------------
379 # Text-based checks (JS / script / config)
380 # ---------------------------------------------------------------------------
381
382 def check_text(raw_text, filepath, issues):
383 """Scan raw file text line-by-line for old event names, JS API, and config."""
384 for lineno, line in enumerate(raw_text.splitlines(), 1):
385 # Old event names in JS strings (addEventListener, htmx.on, etc.)
386 for old_event, new_event in ALL_OLD_EVENTS.items():
387 if old_event in line:
388 # Skip if this is inside an hx-on attribute (handled by tree check)
389 if re.search(r'hx-on\S*=', line):
390 continue
391 issues.append(Issue(filepath, lineno, "old-event",
392 f'old event name "{old_event}" → "{new_event}"'))
393
394 for removed_event in REMOVED_EVENTS:
395 if removed_event in line:
396 if re.search(r'hx-on\S*=', line):
397 continue
398 issues.append(Issue(filepath, lineno, "removed-event",
399 f'removed event "{removed_event}"'))
400
401 # Old JS API methods
402 for old_api, replacement in REMOVED_JS_API.items():
403 # Match htmx.methodName( to avoid false positives
404 if re.search(re.escape(old_api) + r"\s*\(", line):
405 issues.append(Issue(filepath, lineno, "old-api",
406 f"{old_api}() is removed → {replacement}"))
407
408 # Old config key names
409 for old_cfg, new_cfg in CONFIG_RENAMES.items():
410 if re.search(r"(?:config\.|['\"])" + re.escape(old_cfg) + r"(?:['\"]|\s*[=:])", line):
411 issues.append(Issue(filepath, lineno, "renamed-config",
412 f'config "{old_cfg}" → "{new_cfg}"'))
413
414 for removed_cfg in REMOVED_CONFIG:
415 if re.search(r"(?:config\.|['\"])" + re.escape(removed_cfg) + r"(?:['\"]|\s*[=:])", line):
416 issues.append(Issue(filepath, lineno, "removed-config",
417 f'config "{removed_cfg}" is removed'))
418
419 # Removed response headers in JS
420 for header, fix in REMOVED_RESPONSE_HEADERS.items():
421 if header in line:
422 issues.append(Issue(filepath, lineno, "removed-header",
423 f'"{header}" is removed → {fix}'))
424
425
426 # ---------------------------------------------------------------------------
427 # File processing
428 # ---------------------------------------------------------------------------
429
430 JS_EXTENSIONS = frozenset({".js", ".mjs", ".cjs", ".ts", ".mts", ".cts", ".jsx", ".tsx"})
431
432
433 def check_file(filepath):
434 """Check a single file for all migration issues."""
435 try:
436 with open(filepath, "r", encoding="utf-8", errors="replace") as f:
437 raw_text = f.read()
438 except OSError as e:
439 print(f"warning: cannot read {filepath}: {e}", file=sys.stderr)
440 return []
441
442 issues = []
443 _, ext = os.path.splitext(filepath)
444
445 # HTML tree-based checks (skip for pure JS/TS files)
446 if ext.lower() not in JS_EXTENSIONS:
447 cleaned = strip_template_syntax(raw_text)
448 builder = TreeBuilder()
449 try:
450 builder.feed(cleaned)
451 except Exception:
452 pass
453 check_node(builder.root, filepath, issues)
454 check_inheritance(builder.root, filepath, issues)
455
456 # Text-based checks (JS patterns — applies to all file types)
457 check_text(raw_text, filepath, issues)
458
459 # Deduplicate (same file+line+category+message)
460 seen = set()
461 deduped = []
462 for issue in issues:
463 key = (issue.line, issue.category, issue.message)
464 if key not in seen:
465 seen.add(key)
466 deduped.append(issue)
467
468 deduped.sort(key=lambda i: i.line)
469 return deduped
470
471
472 def collect_files(paths, extensions):
473 """Collect files matching the given extensions from paths."""
474 files = []
475 for path in paths:
476 if os.path.isfile(path):
477 files.append(path)
478 elif os.path.isdir(path):
479 for dirpath, _, filenames in os.walk(path):
480 for fn in filenames:
481 if any(fn.endswith(ext) for ext in extensions):
482 files.append(os.path.join(dirpath, fn))
483 files.sort()
484 return files
485
486
487 # ---------------------------------------------------------------------------
488 # CLI
489 # ---------------------------------------------------------------------------
490
491 COLORS = {
492 "removed-attr": "\033[31m", # red
493 "renamed-attr": "\033[33m", # yellow
494 "inheritance": "\033[35m", # magenta
495 "renamed-event": "\033[33m", # yellow
496 "removed-event": "\033[31m", # red
497 "swap-syntax": "\033[33m", # yellow
498 "ext": "\033[36m", # cyan
499 "old-event": "\033[33m", # yellow
500 "old-api": "\033[31m", # red
501 "renamed-config": "\033[33m", # yellow
502 "removed-config": "\033[31m", # red
503 "removed-header": "\033[31m", # red
504 }
505 RESET = "\033[0m"
506
507
508 DEFAULT_EXTENSIONS = [".html", ".php", ".js", ".ts", ".jinja", ".jinja2", ".j2", ".erb", ".hbs"]
509
510
511 def main():
512 parser = argparse.ArgumentParser(
513 description="Scan HTML templates for htmx 2 → 4 migration issues.")
514 parser.add_argument("paths", nargs="*", default=["."],
515 help="Files or directories to scan (default: current directory)")
516 parser.add_argument("--ext", action="append", default=[],
517 help="Additional file extensions to scan (can be used multiple times, "
518 "e.g. --ext .vue --ext .svelte)")
519 parser.add_argument("--no-color", action="store_true",
520 help="Disable colored output")
521 args = parser.parse_args()
522
523 extensions = list(DEFAULT_EXTENSIONS)
524 for ext in args.ext:
525 for e in ext.split(","):
526 e = e.strip()
527 if not e.startswith("."):
528 e = "." + e
529 if e not in extensions:
530 extensions.append(e)
531
532 use_color = not args.no_color and sys.stdout.isatty()
533
534 ext_list = ", ".join(extensions)
535 print(f"File extensions: {ext_list}", file=sys.stderr)
536 print(f"Use --ext to add more (e.g. --ext .vue --ext .svelte)\n", file=sys.stderr)
537
538 files = collect_files(args.paths, extensions)
539 if not files:
540 print(f"No files found with extensions: {ext_list}", file=sys.stderr)
541 return
542
543 print(f"Scanning {len(files)} file(s)...\n", file=sys.stderr)
544
545 total_issues = 0
546 files_with_issues = 0
547
548 for filepath in files:
549 issues = check_file(filepath)
550 if issues:
551 files_with_issues += 1
552 total_issues += len(issues)
553 for issue in issues:
554 if use_color:
555 color = COLORS.get(issue.category, "")
556 print(f"{issue.file}:{issue.line}: {color}[{issue.category}]{RESET} {issue.message}")
557 else:
558 print(issue)
559
560 print(f"\nFound {total_issues} issue(s) in {files_with_issues} of {len(files)} file(s).",
561 file=sys.stderr)
562 sys.exit(1 if total_issues > 0 else 0)
563
564
565 if __name__ == "__main__":
566 main()