df2tables 0.3.4__tar.gz → 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: df2tables
3
- Version: 0.3.4
3
+ Version: 0.3.5
4
4
  Summary: df2tables: Pandas and Polars DataFrames to Interactive DataTables
5
5
  Project-URL: Homepage, https://github.com/ts-kontakt/df2tables
6
6
  Project-URL: Issues, https://github.com/ts-kontakt/df2tables/issues
@@ -1,5 +1,5 @@
1
1
  from .df2tables import *
2
- __version__ = "0.3.4"
2
+ __version__ = "0.3.5"
3
3
  __author__ = "Tomasz Slugocki"
4
4
  __license__ = "MIT"
5
5
 
@@ -0,0 +1,317 @@
1
+ #!/usr/bin/python
2
+ # coding=utf8
3
+ """
4
+ Comnt - template content using block-annotated comments
5
+
6
+ Template regions are marked with standard comment syntax, so the template
7
+ stays a valid file you can open in a browser as-is, placeholder included.
8
+
9
+ HTML/XML: <!--[tag_id--> ... <!--tag_id]-->
10
+ JS/CSS: /*[tag_id*/ ... /*tag_id]*/
11
+
12
+ Python values go in as JavaScript source -- no JSON.parse() round trip:
13
+
14
+ const data = /*[data*/ [0, 1] /*data]*/; <- js_value([1, 2, 3])
15
+
16
+ Rules
17
+ - ids are ASCII identifiers: a letter or _ first, then letters, digits
18
+ and _ (the same rule as Python/Jinja2 names, but ASCII only).
19
+ Opening and closing id must match.
20
+ - An id may repeat (same style): render() writes its value into every
21
+ occurrence; get_tag_content(..., occurrence=N) reads one of them.
22
+ - An id uses ONE comment style (use two ids for html and js).
23
+ - Tags may nest. Replacing an outer tag replaces everything inside it,
24
+ so a value given for an inner tag as well is ignored (and reported).
25
+ - A value of None leaves that tag untouched.
26
+ - Markers stay in the output: a rendered file is again a template.
27
+
28
+ Error model
29
+ Problems are detected per id and only matter for ids you actually pass:
30
+ unknown id, id in both comment styles, unbalanced or misordered markers,
31
+ inner tag swallowed by an outer one. A broken id is skipped, never
32
+ guessed. render() then issues one warnings.warn() listing everything;
33
+ strict=True raises a single ValueError instead. get_tag_content()
34
+ raises NotFoundError.
35
+
36
+ Guarantees
37
+ Markers are searched only in the template, in one linear pass, and the
38
+ output is built once, left to right. Values are opaque: marker-like text
39
+ inside a value is copied verbatim and never treated as a tag.
40
+
41
+ Escaping
42
+ Comnt does not escape. Use js_value() for JS (json.dumps plus '<'
43
+ escaping, so '</script>' in data cannot break out of the element) and
44
+ html.escape() for HTML text.
45
+
46
+ Web apps
47
+ render_file() returns a string and caches the scanned template (up to
48
+ 16 files, validated by mtime and size, thread-safe), so a large
49
+ template is not rescanned on every request:
50
+
51
+ @app.get("/")
52
+ def index():
53
+ return comnt.render_file("page.html", {"data": comnt.js_value(rows)})
54
+
55
+ Author: Tomasz Slugocki
56
+ Version: 2.0.0
57
+ """
58
+
59
+ import functools
60
+ import json
61
+ import os
62
+ import re
63
+ import secrets
64
+ import stat
65
+ import tempfile
66
+ import warnings
67
+ import webbrowser
68
+ from pathlib import Path
69
+
70
+ __all__ = ['render', 'render_file', 'write_from_template', 'get_tag_content',
71
+ 'js_value', 'clear_cache', 'example', 'NotFoundError']
72
+
73
+ __version__ = "2.0.0"
74
+
75
+
76
+ class NotFoundError(ValueError):
77
+ """A tag is missing, used in both comment styles, or its markers don't
78
+ pair up cleanly. Subclasses ValueError."""
79
+
80
+
81
+ _NAME = r'[A-Za-z_][A-Za-z0-9_]*'
82
+ _NAME_RE = re.compile(_NAME)
83
+
84
+ # One pattern for every marker. The name of the group that matched tells
85
+ # which one it was: h/j = html/js comment, o/c = opening/closing marker.
86
+ _MARKER = re.compile(
87
+ r'<!--(?:\[(?P<ho>' + _NAME + r')|(?P<hc>' + _NAME + r')\])-->'
88
+ r'|/\*(?:\[(?P<jo>' + _NAME + r')|(?P<jc>' + _NAME + r')\])\*/'
89
+ )
90
+
91
+
92
+ def _scan(text):
93
+ """Pair up all markers of `text` in one linear pass.
94
+
95
+ Returns (spans, conflicts, counts):
96
+ spans: {tag_id: [(block_start, body_start, body_end, block_end)]}
97
+ complete pairs in document order; markers of one id are
98
+ paired like brackets, so same-id nesting works
99
+ conflicts: ids that occur in both html and js comments
100
+ counts: {tag_id: (opening, closing)} raw marker counts
101
+
102
+ Never raises; problems are reported only for ids that get used.
103
+ """
104
+ spans, counts, kinds, stacks, conflicts = {}, {}, {}, {}, set()
105
+ for m in _MARKER.finditer(text):
106
+ group = m.lastgroup
107
+ tag_id = m.group(group)
108
+ kind, is_open = group[0], group[1] == 'o'
109
+ count = counts.setdefault(tag_id, [0, 0])
110
+ count[0 if is_open else 1] += 1
111
+ if kinds.setdefault(tag_id, kind) != kind:
112
+ conflicts.add(tag_id)
113
+ stack = stacks.setdefault(tag_id, [])
114
+ if is_open:
115
+ stack.append((m.start(), m.end()))
116
+ elif stack:
117
+ block_start, body_start = stack.pop()
118
+ spans.setdefault(tag_id, []).append(
119
+ (block_start, body_start, m.start(), m.end()))
120
+ for pairs in spans.values():
121
+ pairs.sort()
122
+ return spans, conflicts, {k: tuple(v) for k, v in counts.items()}
123
+
124
+
125
+ def _problem(tag_id, scan):
126
+ """Why `tag_id` can't be used, or None if it is fine."""
127
+ spans, conflicts, counts = scan
128
+ if tag_id in conflicts:
129
+ return f"'{tag_id}' is used in both html and js comments (use two ids)"
130
+ opening, closing = counts.get(tag_id, (0, 0))
131
+ if not (opening or closing):
132
+ hint = "" if _NAME_RE.fullmatch(tag_id) else \
133
+ " (ids must start with a letter or _ and use only letters, digits and _)"
134
+ return f"'{tag_id}' not found{hint}"
135
+ pairs = len(spans.get(tag_id, ()))
136
+ if pairs != opening or opening != closing:
137
+ return (f"'{tag_id}' has unbalanced or misordered markers "
138
+ f"({opening} opening, {closing} closing, "
139
+ f"{pairs} complete pair(s))")
140
+ return None
141
+
142
+
143
+ def _render_scanned(text, repldict, scan, strict):
144
+ """Substitution over an already scanned template (shared by render()
145
+ and render_file(), so a cached scan can be reused)."""
146
+ spans = scan[0]
147
+ problems, work = [], []
148
+ for tag_id, val in repldict.items():
149
+ if val is None:
150
+ continue
151
+ if not isinstance(val, str):
152
+ raise TypeError(
153
+ f"replacement for '{tag_id}' must be a str or None, "
154
+ f"got {type(val).__name__}")
155
+ problem = _problem(tag_id, scan)
156
+ if problem:
157
+ problems.append(problem)
158
+ else:
159
+ work.extend((*s, tag_id, val) for s in spans[tag_id])
160
+
161
+ work.sort(key=lambda w: w[0]) # outer / leftmost first
162
+ pieces, cursor, owner, ignored = [], 0, None, {}
163
+ for block_start, body_start, body_end, block_end, tag_id, val in work:
164
+ if block_start < cursor: # starts inside a replaced region
165
+ if tag_id != owner: # (an id inside itself is no news)
166
+ key = (tag_id, block_end > cursor) # True: crosses it
167
+ ignored[key] = ignored.get(key, 0) + 1
168
+ continue
169
+ pieces.append(text[cursor:body_start])
170
+ pieces.append(val)
171
+ cursor, owner = body_end, tag_id
172
+ pieces.append(text[cursor:])
173
+
174
+ for (tag_id, crossing), count in ignored.items():
175
+ what = ("crosses another replaced tag (misnested markers)" if crossing
176
+ else "lies inside another replaced tag")
177
+ problems.append(f"'{tag_id}' {what}, its value was ignored in "
178
+ f"{count} of {len(spans[tag_id])} occurrence(s)")
179
+ if problems:
180
+ message = "comnt: " + "; ".join(problems)
181
+ if strict:
182
+ raise ValueError(message)
183
+ warnings.warn(message, stacklevel=3)
184
+ return "".join(pieces)
185
+
186
+
187
+ def render(instr, repldict, strict=False):
188
+ """Replace the body of each tag named in `repldict` with its value.
189
+
190
+ A repeated id gets the value in every occurrence; None leaves the tag
191
+ untouched. Broken or unknown ids are skipped and reported (see the
192
+ module docstring); strict=True raises ValueError instead.
193
+ """
194
+ if not isinstance(repldict, dict):
195
+ raise TypeError("repldict must be a dict")
196
+ if not isinstance(instr, str):
197
+ raise TypeError(f"instr must be a str, got {type(instr).__name__}")
198
+ if not repldict:
199
+ return instr
200
+ return _render_scanned(instr, repldict, _scan(instr), strict)
201
+
202
+
203
+ def get_tag_content(tag, instr, occurrence=0):
204
+ """Return the current content of `tag` without modifying anything.
205
+ `occurrence` (0-based) picks which copy to read if the id repeats."""
206
+ if not isinstance(tag, str) or not tag:
207
+ raise TypeError("'tag' must be a non-empty str")
208
+ if not isinstance(instr, str):
209
+ raise TypeError(f"'instr' must be a str, got {type(instr).__name__}")
210
+ scan = _scan(instr)
211
+ problem = _problem(tag, scan)
212
+ if problem:
213
+ raise NotFoundError(problem)
214
+ pairs = scan[0][tag]
215
+ if not 0 <= occurrence < len(pairs):
216
+ raise IndexError(
217
+ f"tag '{tag}' has {len(pairs)} occurrence(s); "
218
+ f"requested occurrence index {occurrence}")
219
+ _, body_start, body_end, _ = pairs[occurrence]
220
+ return instr[body_start:body_end]
221
+
222
+
223
+ def js_value(obj):
224
+ """Python object -> JavaScript literal that is safe inside <script>."""
225
+ return json.dumps(obj).replace("<", "\\u003c")
226
+
227
+
228
+ def _normpath(path):
229
+ return os.path.normcase(os.path.realpath(path))
230
+
231
+
232
+ @functools.lru_cache(maxsize=16)
233
+ def _load(path, mtime_ns, size):
234
+ # mtime and size are not used in the body: they are part of the cache
235
+ # key, so an edited file is simply a cache miss.
236
+ with open(path, encoding="utf-8", newline="") as op_file:
237
+ text = op_file.read()
238
+ return text, _scan(text)
239
+
240
+
241
+ def clear_cache():
242
+ """Forget all cached templates (mostly useful in tests)."""
243
+ _load.cache_clear()
244
+
245
+
246
+ def render_file(template, repldict, strict=False):
247
+ """render() for a template file, returning a str. The text and its scan
248
+ are cached until the file's mtime or size changes."""
249
+ if not isinstance(repldict, dict):
250
+ raise TypeError("repldict must be a dict")
251
+ path = os.path.abspath(template)
252
+ st = os.stat(path)
253
+ text, scan = _load(path, st.st_mtime_ns, st.st_size)
254
+ return _render_scanned(text, repldict, scan, strict)
255
+
256
+
257
+ def write_from_template(template, newfile, repldict, strict=False):
258
+ """Render the file `template` and write the result to `newfile`.
259
+ Written atomically (temp file + os.replace), so a crash can never leave
260
+ a half-written file. newline="" keeps the original line endings.
261
+ A new file gets the usual umask-based permissions; an existing `newfile`
262
+ keeps its permissions."""
263
+ newfile = os.fspath(newfile)
264
+ if _normpath(template) == _normpath(newfile):
265
+ raise ValueError("template and newfile must be different paths")
266
+ replaced = render_file(template, repldict, strict)
267
+ try:
268
+ mode = stat.S_IMODE(os.stat(newfile).st_mode)
269
+ except FileNotFoundError:
270
+ mode = None
271
+ tmp = f"{newfile}.{secrets.token_hex(4)}.tmp"
272
+ try:
273
+ with open(tmp, "x", encoding="utf-8", newline="") as outfile:
274
+ if mode is not None:
275
+ os.chmod(tmp, mode) # before any data is written
276
+ outfile.write(replaced)
277
+ os.replace(tmp, newfile)
278
+ except BaseException:
279
+ try:
280
+ os.unlink(tmp)
281
+ except OSError:
282
+ pass
283
+ raise
284
+ return True
285
+
286
+
287
+ def example():
288
+ """Render a small demo page and open it in the default browser."""
289
+ template = """<!DOCTYPE html>
290
+ <html>
291
+ <head><meta charset="utf-8"><title>comnt example</title></head>
292
+ <body>
293
+ <h1><!--[title-->Welcome to our site!<!--title]--></h1>
294
+ <!--[content--><p>This is placeholder content.</p><!--content]-->
295
+ <pre id="out"></pre>
296
+ <p><small><!--[title-->Welcome to our site!<!--title]--></small></p>
297
+ <script>
298
+ // A Python dict, injected as a JS value
299
+ const data = /*[data*/ {"name": "Ada"} /*data]*/;
300
+ document.getElementById("out").textContent = JSON.stringify(data, null, 2);
301
+ </script>
302
+ </body>
303
+ </html>
304
+ """
305
+ page = render(template, {
306
+ "title": "Example rendered from Python",
307
+ "content": "<p>Below: a Python dict rendered as a JavaScript object.</p>",
308
+ "data": js_value({"name": "Ada", "age": 37, "roles": ["admin", "editor"]}),
309
+ })
310
+ path = os.path.join(tempfile.gettempdir(), "comnt_example.html")
311
+ with open(path, "w", encoding="utf-8") as outfile:
312
+ outfile.write(page)
313
+ webbrowser.open(Path(path).as_uri())
314
+
315
+
316
+ if __name__ == "__main__":
317
+ example()
@@ -411,7 +411,8 @@ table.dataTable td {
411
411
  const searchNote = document.createElement("span");
412
412
  searchNote.style.cssText = "margin: 0.5rem; font-size: 0.7rem; font-style: italic; display: inline-flex; color: #667";
413
413
  searchNote.textContent = search_msg;
414
- const searchInput = document.querySelector("#" + TABLE_ID + "_wrapper .dt-search input.dt-input");
414
+ const wrapper_el = document.getElementById(TABLE_ID + "_wrapper");
415
+ const searchInput = wrapper_el ? wrapper_el.querySelector(".dt-search input.dt-input") : null;
415
416
  if (searchInput) {
416
417
  searchInput.insertAdjacentElement("afterend", searchNote);
417
418
  }
@@ -586,20 +587,39 @@ table.dataTable td {
586
587
  }
587
588
 
588
589
  // The "copy" button writes the DISPLAYED text (with a '.'
589
- // decimal) to the clipboard. The radio next to the button picks
590
- // the decimal separator for numeric fields - dates, text and
591
- // other cells stay untouched.
592
- const copy_sep_form = '<span style="margin-left: 0.5rem; display: inline-flex; flex-direction: column; align-items: flex-start; gap: 0.1rem;">' +
593
- '<span style="font-size: 0.6rem; font-style: italic; color: #667;">Decimal separator</span>' +
594
- '<form title="Decimal separator in copied text" style="display: inline-flex; gap: 0.5rem; align-items: center; font-size: 11px;">' +
595
- '<label style="display: inline-flex; align-items: center; gap: 0.2rem; cursor: pointer;">' +
596
- '<input type="radio" name="copy_sep_' + TABLE_ID + '" value="." checked> (<span style="font-family: Consolas, monospace; font-size: 13px;">.</span>) dot</label>' +
597
- '<label style="display: inline-flex; align-items: center; gap: 0.2rem; cursor: pointer;">' +
598
- '<input type="radio" name="copy_sep_' + TABLE_ID + '" value=","> (<span style="font-family: Consolas, monospace; font-size: 13px;">,</span>) comma</label>' +
599
- "</form></span>";
600
-
601
- const add_copy_sep_form = function() {
602
- const copy_btn = document.querySelector("#" + TABLE_ID + "_wrapper button.buttons-copy");
590
+ // decimal) to the clipboard. The segmented control next to the
591
+ // button picks the decimal separator for numeric fields - dates,
592
+ // text and other cells stay untouched. It also carries the
593
+ // fragment-portable CSS (compact toolbar + hidden DataTables 3
594
+ // header sort arrows): the template stylesheet does NOT travel
595
+ // with render_inline, so the widget must look right in any host
596
+ // page without extra CSS.
597
+ const copy_sep_form =
598
+ '<style>' +
599
+ '.cs-wrap{margin-left:.5rem;display:inline-flex;align-items:center;gap:.4rem;font-size:.8rem;color:#667}' +
600
+ '.cs-seg{display:inline-flex;border:1px solid #ccc;border-radius:6px;overflow:hidden;background:#fff}' +
601
+ '.cs-seg label{position:relative;margin:0;cursor:pointer}' +
602
+ '.cs-seg input{position:absolute;opacity:0;pointer-events:none}' +
603
+ '.cs-seg span{display:block;padding:.2rem .6rem;font:13px/1.2 Consolas,monospace;color:#333;user-select:none}' +
604
+ '.cs-seg label+label span{border-left:1px solid #ccc}' +
605
+ '.cs-seg label:hover span{background:#f0f0f0}' +
606
+ '.cs-seg input:checked+span{background:#0d6efd;color:#fff}' +
607
+ '.cs-seg input:focus-visible+span{outline:2px solid #0d6efd;outline-offset:-2px}' +
608
+ 'div.dt-buttons{align-items:center!important}' +
609
+ 'button.dt-button{padding:.2rem .5rem!important}' +
610
+ '.dt-length select.dt-input{padding:.2rem .5rem!important;line-height:1.2!important}' +
611
+ 'table.dataTable .dt-column-order{display:none!important}' +
612
+ '</style>' +
613
+ '<span class="cs-wrap" title="Decimal separator in copied text">Decimal:' +
614
+ '<span class="cs-seg" role="radiogroup" aria-label="Decimal separator">' +
615
+ '<label><input type="radio" name="copy_sep_' + TABLE_ID + '" value="." checked><span>1.23</span></label>' +
616
+ '<label><input type="radio" name="copy_sep_' + TABLE_ID + '" value=","><span>1,23</span></label>' +
617
+ '</span></span>';
618
+
619
+
620
+ const setup_copy_toolbar = function() {
621
+ const wrapper_el = document.getElementById(TABLE_ID + "_wrapper");
622
+ const copy_btn = wrapper_el ? wrapper_el.querySelector("button.buttons-copy") : null;
603
623
  if (copy_btn) {
604
624
  copy_btn.insertAdjacentHTML("afterend", copy_sep_form);
605
625
  }
@@ -634,7 +654,7 @@ table.dataTable td {
634
654
  },
635
655
  initComplete: function() {
636
656
  search_info();
637
- add_copy_sep_form();
657
+ setup_copy_toolbar();
638
658
  }
639
659
  };
640
660
 
@@ -1,598 +0,0 @@
1
- #!/usr/bin/python
2
- # coding=utf8
3
- """
4
- Comnt3 - template content using block-annotated comments
5
-
6
- A dead-simple, human-friendly way to manage template regions using
7
- **standard comment syntax** -- no weird symbols, no broken files, no
8
- preprocessing to view your code in a browser.
9
-
10
- You can inject actual JavaScript-ready values from Python (not just
11
- quoted strings), or refer to JS functions defined elsewhere -- no
12
- `JSON.parse(...)` round-trip on the frontend, unlike the usual Jinja2
13
- approach. Note: `repr()` is only JS-valid for a narrow subset
14
- (int/float/str/list/dict); use `json.dumps(...)` for anything else.
15
-
16
- Supported tag/comment formats:
17
- HTML/XML: <!--[tag_name--> ... <!--tag_name]-->
18
- JS/CSS: /*[tag_name*/ ... /*tag_name]*/
19
-
20
- Tag names may contain letters, digits, '_', '.', ':' and '-'; opening
21
- and closing names must match exactly.
22
-
23
- Error model (uniform):
24
- The scan phase never raises. Tag problems -- missing tags,
25
- one-sided/malformed pairs, an id used in both comment styles,
26
- unbalanced duplicate markers, nested/overlapping replacements --
27
- are localized to the affected tag id:
28
- * render(): the id is skipped (unbalanced ids still replace their
29
- complete pairs), a note is printed, and the rest of the render
30
- proceeds. strict=True raises a single ValueError instead.
31
- * get_tag_content(): raises, but only for the requested id.
32
- An id that is never rendered is copied through byte-for-byte.
33
-
34
- Rendering guarantee:
35
- Markers are found only in the original template. The output is built
36
- once, left to right, from original text and replacement values. Every
37
- replacement value is opaque: marker-like text inside it is copied
38
- verbatim and is never treated as another tag. One render() call never
39
- substitutes into the output of an earlier substitution.
40
-
41
- This is not context-sensitive escaping. Callers must still encode data
42
- appropriately for its destination (for example json.dumps() plus
43
- script-safe '<' escaping for JSON in a <script> element).
44
-
45
- Behavior notes:
46
- - A tag id may repeat (same comment style): render() broadcasts its
47
- value into every occurrence; get_tag_content(tag, instr,
48
- occurrence=0) picks the 0-based occurrence to read.
49
- - Mixing html/js styles for one id is rejected -- use two distinct
50
- ids (the two contexts usually need different quoting).
51
- - Nested original regions are supported. Selecting both an outer
52
- and an inner region for replacement is rejected at occurrence
53
- level; selecting only one of them is safe.
54
- - write_from_template(..., cache=True) caches text + scan keyed by
55
- (path, st_mtime_ns) with LRU eviction (max 128); output is
56
- written atomically (temp file + os.replace).
57
-
58
- Author: Tomasz Slugocki
59
- Version: 3.0.0
60
- """
61
-
62
- import os
63
- import re
64
- import tempfile
65
-
66
- __all__ = ['render', 'get_tag_content', 'write_from_template',
67
- 'simple_example', 'example', 'NotFoundError']
68
-
69
- __version__ = "3.0.0"
70
-
71
-
72
- class NotFoundError(ValueError):
73
- """Raised when a tag's opening marker, closing marker, or both are
74
- missing or malformed. Subclasses ValueError so existing
75
- `except ValueError` call sites keep working unchanged."""
76
- pass
77
-
78
-
79
- _NAME = r'[A-Za-z0-9_.:-]+'
80
-
81
- # Matches every raw opening/closing marker of both styles in a single
82
- # pass (group 1: html open, 2: html close, 3: js open, 4: js close).
83
- # Used to detect ids whose raw marker counts don't add up to complete
84
- # pairs -- e.g. three "<!--[date-->" but only two "<!--date]-->".
85
- _ANY_MARKER_RE = re.compile(
86
- r'<!--\[(' + _NAME + r')-->'
87
- r'|<!--(' + _NAME + r')\]-->'
88
- r'|/\*\[(' + _NAME + r')\*/'
89
- r'|/\*(' + _NAME + r')\]\*/'
90
- )
91
- _IS_OPEN = (True, False, True, False)
92
-
93
-
94
- def _scan_tags(text):
95
- """
96
- One original-template marker pass plus per-tag marker pairing.
97
- Returns (spans, conflicts, unbalanced):
98
-
99
- spans: {tag_id: [(block_start, block_end, body_start,
100
- body_end, kind), ...]} -- complete pairs,
101
- in document order
102
- conflicts: set of ids with complete pairs in BOTH comment styles
103
- unbalanced: {tag_id: (raw_open_count, raw_close_count)} for ids
104
- that have at least one complete pair PLUS stray
105
- unmatched markers (e.g. 3 openers but 2 closers due
106
- to a typo)
107
-
108
- Never raises. A mixed-style or unbalanced id is an authoring error,
109
- but it is only *reported* (by render/get_tag_content) when that id
110
- is actually used -- an unrelated problem elsewhere in the template
111
- must not abort the whole render.
112
- """
113
- markers = {}
114
- id_kind = {}
115
- conflicts = set()
116
- raw = {}
117
- for match in _ANY_MARKER_RE.finditer(text):
118
- group_index = match.lastindex
119
- tag_id = match.group(group_index)
120
- kind = "html" if group_index <= 2 else "js"
121
- is_open = _IS_OPEN[group_index - 1]
122
- counts = raw.setdefault(tag_id, [0, 0])
123
- counts[0 if is_open else 1] += 1
124
- if id_kind.setdefault(tag_id, kind) != kind:
125
- conflicts.add(tag_id)
126
- markers.setdefault(tag_id, []).append(
127
- (match.start(), match.end(), is_open, kind)
128
- )
129
-
130
- spans = {}
131
- unbalanced = {}
132
- for tag_id, tag_markers in markers.items():
133
- stack = []
134
- tag_spans = []
135
- for start, end, is_open, kind in tag_markers:
136
- if is_open:
137
- stack.append((start, end, kind))
138
- continue
139
- if not stack:
140
- continue
141
- block_start, body_start, _ = stack.pop()
142
- tag_spans.append(
143
- (block_start, end, body_start, start, kind)
144
- )
145
- if tag_spans:
146
- spans[tag_id] = sorted(tag_spans)
147
- open_count, close_count = raw[tag_id]
148
- if (open_count != close_count or len(tag_spans) != open_count) \
149
- and tag_spans and tag_id not in conflicts:
150
- unbalanced[tag_id] = (open_count, close_count)
151
- return spans, conflicts, unbalanced
152
-
153
-
154
- def _diagnose_missing(text, tag_id):
155
- """
156
- Only called on the error path (tag_id has no complete pair at all).
157
- Re-derives the specific diagnostics -- which half of the pair is
158
- missing, how many, whether styles are mixed -- via cheap substring
159
- counts. Repeated ids are legal since 0.2.0, so this reports the
160
- opening/closing imbalance instead of the 0.0.1-era "more than one
161
- start tag" assertion. Always raises.
162
- """
163
- html_start, html_end = f"<!--[{tag_id}-->", f"<!--{tag_id}]-->"
164
- js_start, js_end = f"/*[{tag_id}*/", f"/*{tag_id}]*/"
165
-
166
- hs, he = text.count(html_start), text.count(html_end)
167
- js, je = text.count(js_start), text.count(js_end)
168
-
169
- if not any((hs, he, js, je)):
170
- raise NotFoundError(
171
- f"not found: tag id '{tag_id}' in either html or js form"
172
- )
173
- if (hs or he) and (js or je):
174
- raise NotFoundError(
175
- f"same tag id in javascript and html is not allowed: '{tag_id}'"
176
- )
177
-
178
- if hs or he:
179
- start_cnt, end_cnt, start_tag, end_tag = hs, he, html_start, html_end
180
- else:
181
- start_cnt, end_cnt, start_tag, end_tag = js, je, js_start, js_end
182
-
183
- if start_cnt > end_cnt:
184
- raise NotFoundError(
185
- f"unbalanced tags for '{tag_id}': {start_cnt} opening "
186
- f"'{start_tag}' vs {end_cnt} closing '{end_tag}' "
187
- f"-- {start_cnt - end_cnt} closing tag(s) missing"
188
- )
189
- if end_cnt > start_cnt:
190
- raise NotFoundError(
191
- f"unbalanced tags for '{tag_id}': {end_cnt} closing "
192
- f"'{end_tag}' vs {start_cnt} opening '{start_tag}' "
193
- f"-- {end_cnt - start_cnt} opening tag(s) missing"
194
- )
195
-
196
- # counts match but the regex still matched nothing --
197
- # e.g. the closing tag appears before the opening one
198
- raise NotFoundError(
199
- f"tags for '{tag_id}' exist but are malformed or out of order"
200
- )
201
-
202
-
203
- def _find_overlaps(replacements, spans):
204
- """
205
- Return the set of individual spans -- as (tag_id, index) pairs --
206
- whose replacement would corrupt the output by nesting inside or
207
- crossing another replaced span. The original-template marker stack
208
- supports same-style and cross-style nesting. Keeping the granularity
209
- at the span level means a non-overlapping duplicate occurrence of an
210
- otherwise-overlapping id is still replaced.
211
- """
212
- entries = sorted(
213
- ((span[2], span[3], span[0], tag_id, idx)
214
- for tag_id in replacements
215
- for idx, span in enumerate(spans[tag_id])),
216
- key=lambda t: t[0],
217
- )
218
- overlapping = set()
219
- cursor = 0
220
- cursor_owner = None
221
- for body_start, body_end, block_start, tag_id, idx in entries:
222
- if block_start < cursor:
223
- overlapping.add((tag_id, idx))
224
- if cursor_owner is not None:
225
- overlapping.add(cursor_owner)
226
- continue # rejected entry doesn't extend the cursor
227
- cursor = body_end
228
- cursor_owner = (tag_id, idx)
229
- return overlapping
230
-
231
-
232
- def _render_spans(instr, repldict, spans, conflicts, unbalanced, strict):
233
- """
234
- Substitution pass over an already-scanned document. Split out from
235
- render() so write_from_template(cache=True) can reuse a cached scan.
236
- """
237
- missing = []
238
- conflicted = []
239
- replacements = {}
240
- for key, val in repldict.items():
241
- if val is None:
242
- continue # "leave untouched" -- can't be dangerous, never errors
243
- if not isinstance(val, str):
244
- raise TypeError(
245
- f"replacement value for '{key}' must be a str or None, "
246
- f"got {type(val).__name__}"
247
- )
248
- if key in conflicts:
249
- conflicted.append(key) # never broadcast one literal into
250
- continue # two different quoting contexts
251
- if key not in spans:
252
- missing.append(key)
253
- continue
254
- replacements[key] = val
255
-
256
- # Overlapping/nested spans would corrupt the rebuild; drop only the
257
- # offending occurrences, keep non-overlapping duplicates of the same
258
- # id. _find_overlaps returns (tag_id, index) pairs, not bare ids.
259
- overlapping = _find_overlaps(replacements, spans)
260
- overlap_ids = {tag_id for tag_id, _ in overlapping}
261
-
262
- kept = {}
263
- for tag_id in replacements:
264
- kept_spans = [
265
- span for idx, span in enumerate(spans[tag_id])
266
- if (tag_id, idx) not in overlapping
267
- ]
268
- if kept_spans:
269
- kept[tag_id] = kept_spans
270
-
271
- # ids with complete pairs PLUS stray unmatched markers that are
272
- # still being replaced after overlap removal: the complete pairs are
273
- # rendered, but the author should hear about the strays.
274
- imbalanced = [k for k in kept if k in unbalanced]
275
-
276
- if strict and (missing or conflicted or imbalanced or overlap_ids):
277
- problems = []
278
- if missing:
279
- problems.append("not found: " + ", ".join(missing))
280
- if conflicted:
281
- problems.append(
282
- "used in both html and js comments: " + ", ".join(conflicted)
283
- )
284
- if imbalanced:
285
- problems.append(
286
- "unbalanced markers: " + ", ".join(
287
- f"'{k}' ({unbalanced[k][0]} opening vs "
288
- f"{unbalanced[k][1]} closing)"
289
- for k in imbalanced
290
- )
291
- )
292
- if overlap_ids:
293
- problems.append(
294
- "nested/overlapping with another replaced tag: "
295
- + ", ".join(sorted(overlap_ids))
296
- )
297
- raise ValueError(f"comnt: tag id(s) {'; '.join(problems)}")
298
-
299
- for key in conflicted:
300
- print(
301
- f"comnt: tag id '{key}' exists in both html and js comments; "
302
- f"skipped (use two distinct ids -- the two contexts usually "
303
- f"need different quoting)"
304
- )
305
- for key in missing:
306
- try:
307
- _diagnose_missing(instr, key)
308
- except Exception as exc:
309
- print(f"comnt: {exc}")
310
- for key in imbalanced:
311
- open_cnt, close_cnt = unbalanced[key]
312
- print(
313
- f"comnt: tag id '{key}' has {open_cnt} opening vs "
314
- f"{close_cnt} closing markers; replaced the "
315
- f"{len(kept[key])} complete pair(s), stray unmatched "
316
- f"marker(s) left untouched"
317
- )
318
- for key in sorted(overlap_ids):
319
- total = len(spans[key])
320
- n_kept = len(kept[key]) if key in kept else 0
321
- if n_kept:
322
- print(
323
- f"comnt: tag id '{key}' has {total - n_kept} of {total} "
324
- f"occurrence(s) nested inside / crossing another replaced "
325
- f"tag; skipped those, replaced the remaining {n_kept}"
326
- )
327
- else:
328
- print(
329
- f"comnt: tag id '{key}' is nested inside or crosses "
330
- f"another replaced tag; skipped -- replace only the "
331
- f"outermost one"
332
- )
333
-
334
- if not kept:
335
- return instr
336
-
337
- # Flatten every remaining occurrence into one left-to-right rebuild
338
- # pass. Overlaps were excluded above, so this cannot fail -- the
339
- # check stays as a defensive sanity net, not the primary path.
340
- ordered = sorted(
341
- ((span[2], span[3], span[0], tag_id, replacements[tag_id])
342
- for tag_id, spans_list in kept.items()
343
- for span in spans_list),
344
- key=lambda t: t[0],
345
- )
346
- pieces = []
347
- cursor = 0
348
- for body_start, body_end, block_start, tag_id, val in ordered:
349
- if block_start < cursor:
350
- raise AssertionError(
351
- f"internal error: '{tag_id}' should have been caught by "
352
- f"_find_overlaps -- please report this as a comnt bug"
353
- )
354
- pieces.append(instr[cursor:body_start])
355
- pieces.append(val)
356
- cursor = body_end
357
- pieces.append(instr[cursor:])
358
- return "".join(pieces)
359
-
360
-
361
- def render(instr, repldict, strict=False):
362
- """
363
- Replace the body of each tag named in `repldict` with its value.
364
-
365
- - Unknown/typo'd tag ids and ids used in both comment styles:
366
- reported (printed) and skipped, UNLESS strict=True, in which case
367
- a single ValueError listing every problem is raised instead.
368
- - Ids with complete pairs plus stray unmatched markers: the pairs
369
- are replaced, and a warning about the strays is printed (or
370
- raised in strict mode).
371
- - A value of None means "leave this tag's content untouched".
372
- - If a tag id occurs more than once in `instr` (same comment
373
- style), its value is broadcast into every occurrence.
374
- - Values are opaque. Tags are located in the original `instr`, not
375
- in replacement text, and the output is rebuilt only once.
376
-
377
- Returns the rendered string. Runs in O(len(instr) + total tag
378
- occurrences) regardless of how many keys are in `repldict`.
379
- """
380
- if not isinstance(repldict, dict):
381
- raise TypeError("repldict must be a dict")
382
- if not isinstance(instr, str):
383
- raise TypeError(f"instr must be a str, got {type(instr).__name__}")
384
- if not repldict:
385
- return instr
386
- spans, conflicts, unbalanced = _scan_tags(instr)
387
- return _render_spans(instr, repldict, spans, conflicts, unbalanced, strict)
388
-
389
-
390
- def get_tag_content(tag, instr, occurrence=0):
391
- """Return the current content between the opening/closing tag `tag`
392
- in `instr`, without modifying anything.
393
-
394
- If `tag` appears more than once, `occurrence` (0-based, in document
395
- order) picks which copy to read; it defaults to the first one, so
396
- existing calls on non-repeated tags are unaffected. Reading is
397
- non-destructive, so stray unmatched markers for the same id do not
398
- raise here -- complete pairs are still well-defined.
399
- """
400
- if not tag or not isinstance(tag, str):
401
- raise TypeError("'tag' must be a non-empty str")
402
- if not instr or not isinstance(instr, str):
403
- raise TypeError("'instr' must be a non-empty str")
404
-
405
- spans, conflicts, _ = _scan_tags(instr)
406
- if tag in conflicts:
407
- raise NotFoundError(
408
- f"same tag id in javascript and html is not allowed: '{tag}'"
409
- )
410
- if tag not in spans:
411
- _diagnose_missing(instr, tag) # always raises
412
-
413
- occurrences = spans[tag]
414
- if not (0 <= occurrence < len(occurrences)):
415
- raise IndexError(
416
- f"tag '{tag}' has {len(occurrences)} occurrence(s); "
417
- f"requested occurrence index {occurrence}"
418
- )
419
-
420
- _, _, body_start, body_end, _ = occurrences[occurrence]
421
- return instr[body_start:body_end]
422
-
423
-
424
- def _normpath(path):
425
- """Canonical identity key for a path: absolute, symlinks resolved,
426
- case-normalized on platforms where that applies. Not a perfect
427
- file-identity check (that would need st_dev/st_ino), but it covers
428
- relative paths, symlinked directories and Windows case differences.
429
- """
430
- return os.path.normcase(os.path.realpath(path))
431
-
432
-
433
- _template_cache = {}
434
- _CACHE_MAX_ENTRIES = 128
435
-
436
-
437
- def write_from_template(template, newfile, repldict, cache=False, strict=False):
438
- """
439
- Render `template` (a path) with `repldict` and write the result to
440
- `newfile` atomically (temp file + os.replace, so a crash can never
441
- leave a half-written output file).
442
-
443
- cache=False (default): read and scan the file fresh every call.
444
- cache=True: keep the file's text AND its tag scan in memory keyed
445
- by (normcase(realpath(path)), st_mtime_ns), so repeated renders of
446
- an unchanged on-disk template (e.g. a Flask endpoint hit on every
447
- request) skip both the disk read and the tag scan -- only the
448
- substitution pass runs per call. The cache holds at most 128
449
- templates with LRU eviction, so one extra template never
450
- invalidates the whole cache.
451
- """
452
- if not isinstance(repldict, dict):
453
- raise TypeError("repldict must be a dict")
454
- if _normpath(template) == _normpath(newfile):
455
- raise ValueError("template and newfile must be different paths")
456
-
457
- if cache:
458
- key = _normpath(template)
459
- mtime = os.stat(template).st_mtime_ns
460
- cached = _template_cache.get(key)
461
- if cached is not None and cached[0] == mtime:
462
- # LRU: move the hit to the end of the insertion-ordered dict
463
- _template_cache[key] = _template_cache.pop(key)
464
- _, instr, spans, conflicts, unbalanced = cached
465
- else:
466
- with open(template, encoding="utf-8", newline="") as op_file:
467
- instr = op_file.read()
468
- spans, conflicts, unbalanced = _scan_tags(instr)
469
- if len(_template_cache) >= _CACHE_MAX_ENTRIES:
470
- _template_cache.pop(next(iter(_template_cache))) # evict LRU
471
- _template_cache[key] = (mtime, instr, spans, conflicts, unbalanced)
472
- replaced = _render_spans(
473
- instr, repldict, spans, conflicts, unbalanced, strict)
474
- else:
475
- with open(template, encoding="utf-8", newline="") as op_file:
476
- instr = op_file.read()
477
- replaced = render(instr, repldict, strict=strict)
478
-
479
- tmp_dir = os.path.dirname(newfile) or "."
480
- tmp_prefix = os.path.basename(newfile) + "."
481
- fd, tmp = tempfile.mkstemp(prefix=tmp_prefix, suffix=".tmp", dir=tmp_dir)
482
- try:
483
- with os.fdopen(fd, "w", encoding="utf-8", newline="") as outfile:
484
- outfile.write(replaced)
485
- os.replace(tmp, newfile)
486
- except BaseException:
487
- try:
488
- os.unlink(tmp)
489
- except OSError:
490
- pass
491
- raise
492
- return True
493
-
494
-
495
- def _open_file(filename):
496
- import subprocess
497
- import sys
498
- if sys.platform.startswith("win"):
499
- os.startfile(filename)
500
- else:
501
- opener = "open" if sys.platform == "darwin" else "xdg-open"
502
- subprocess.call([opener, filename])
503
-
504
-
505
- def example():
506
- content = """
507
- <!DOCTYPE html>
508
- <html>
509
- <head>
510
- <title>
511
- Example comnt rendered page
512
- </title>
513
-
514
- </head>
515
- <body> <h3>
516
- <!--[title-->
517
- Welcome to our site!
518
- <!--title]--></h3>
519
- <!--[content-->
520
- <p>
521
- This is placeholder content that shows in the browser.
522
- </p>
523
- <!--content]-->
524
- <code id="data-display" style=
525
- "background-color: rgb(245, 245, 245); padding: 10px; border: 1px solid rgb(221, 221, 221);">
526
- </code>
527
- <code id="user-display" style=
528
- "background-color: rgb(245, 245, 245); padding: 10px; border: 1px solid rgb(221, 221, 221);">
529
- </code>
530
- <script>
531
- // A Python list and a Python dict, injected as JS values
532
- const data = /*[data_arr*/ [0, 1]
533
- /*data_arr]*/;
534
- const user = /*[user_obj*/ {name: "Ada", age: 37}
535
- /*user_obj]*/;
536
- document.addEventListener('DOMContentLoaded', function() {
537
- document.getElementById('data-display').textContent =
538
- JSON.stringify(data, null, 2);
539
- document.getElementById('user-display').textContent =
540
- JSON.stringify(user, null, 2);
541
- });
542
- </script>
543
- </body>
544
- </html>
545
- """
546
-
547
- outstr = render(
548
- content,
549
- {
550
- "title": "Example rendered python object",
551
- "content": "<p>Below python range rendered as javascript variable</p>",
552
- "data_arr": repr(list(range(10))), # a Python list -> JS array
553
- "user_obj": repr(
554
- {"name": "Ada", "age": 37, "roles": ["admin", "editor"]}
555
- ), # a Python dict -> JS object (single quotes are valid JS)
556
- },
557
- )
558
- file_name = os.path.join(os.getcwd(), "comnt_test.html")
559
- with open(file_name, "w", encoding="utf8") as outfile:
560
- outfile.write(outstr)
561
- _open_file(file_name)
562
-
563
-
564
- def simple_example():
565
- import json
566
-
567
- content = """
568
- <!DOCTYPE html>
569
- <p id="title"> </p>
570
- <div id="data_arr"></div>
571
- <script>
572
- const title = /*[title*/
573
- "Example title"
574
- /*title]*/;
575
- const data = /*[data_arr*/
576
- [0, 1]
577
- /*data_arr]*/;
578
-
579
- document.getElementById("data_arr").textContent = JSON.stringify(data);
580
- document.getElementById("title").textContent = title;
581
- </script>
582
- """
583
- outstr = render(
584
- content,
585
- {
586
- "title": json.dumps("Example rendered python object"),
587
- "data_arr": json.dumps(list(range(10))),
588
- },
589
- )
590
- file_name = os.path.join(os.getcwd(), "comnt_simple.html")
591
- with open(file_name, "w", encoding="utf8") as outfile:
592
- outfile.write(outstr)
593
- _open_file(file_name)
594
-
595
-
596
- if __name__ == "__main__":
597
- # simple_example()
598
- example()
File without changes
File without changes
File without changes
File without changes