transcript.md 0.1.0__py3-none-any.whl
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.
- transcript/__init__.py +35 -0
- transcript/_rule/__init__.py +0 -0
- transcript/_rule/archive.py +128 -0
- transcript/_rule/conda.py +52 -0
- transcript/_rule/container.py +290 -0
- transcript/_rule/core.py +524 -0
- transcript/_rule/lambdas.py +120 -0
- transcript/_rule/registry.py +54 -0
- transcript/_rule/serialize.py +26 -0
- transcript/_rule/snakefile.py +81 -0
- transcript/_rule/wildcards.py +110 -0
- transcript/cli.py +363 -0
- transcript/document.py +56 -0
- transcript/execute.py +240 -0
- transcript/html/__init__.py +17 -0
- transcript/html/_assets/.frontend.sha256 +1 -0
- transcript/html/_assets/__init__.py +21 -0
- transcript/html/_assets/style.min.css +1 -0
- transcript/html/_assets/transcript.min.js +21 -0
- transcript/html/_island.py +72 -0
- transcript/html/_navigate.py +198 -0
- transcript/html/_output.py +100 -0
- transcript/html/_resources.py +171 -0
- transcript/html/_review.py +34 -0
- transcript/html/markup.py +26 -0
- transcript/html/page.py +107 -0
- transcript/output.py +308 -0
- transcript/parse.py +256 -0
- transcript/renderers/__init__.py +126 -0
- transcript/renderers/bitmap.py +166 -0
- transcript/renderers/compose.py +174 -0
- transcript/renderers/compose_runtime.js +233 -0
- transcript/renderers/datavzrd.py +321 -0
- transcript/renderers/datavzrd_runtime.js +362 -0
- transcript/renderers/label.py +211 -0
- transcript/renderers/markdown.py +45 -0
- transcript/renderers/table.py +32 -0
- transcript/renderers/vegalite.py +250 -0
- transcript/review/__init__.py +13 -0
- transcript/review/_block.py +167 -0
- transcript/review/_migrate.py +212 -0
- transcript/review/_records.py +238 -0
- transcript/review/_span.py +287 -0
- transcript/review/load.py +64 -0
- transcript/tmd.py +159 -0
- transcript_md-0.1.0.dist-info/METADATA +17 -0
- transcript_md-0.1.0.dist-info/RECORD +49 -0
- transcript_md-0.1.0.dist-info/WHEEL +4 -0
- transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Canonical literal serialization for rule declarations and fragments."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
|
|
7
|
+
from snakemake.exceptions import WorkflowError
|
|
8
|
+
|
|
9
|
+
from .lambdas import _StaticLambda
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _literal(value):
|
|
13
|
+
"""Serialize a static value, using canonical double quotes for strings."""
|
|
14
|
+
if isinstance(value, _StaticLambda):
|
|
15
|
+
if value.source is None:
|
|
16
|
+
raise WorkflowError(
|
|
17
|
+
"a lambda declared outside a document cannot be "
|
|
18
|
+
"serialized; run the document with transcript"
|
|
19
|
+
)
|
|
20
|
+
return value.source
|
|
21
|
+
return json.dumps(value) if isinstance(value, str) else repr(value)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _entry(name: str | None, value):
|
|
25
|
+
value = _literal(value)
|
|
26
|
+
return f"{name}={value}," if name else f"{value},"
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Generate the Snakefile rule fragment for a declared document rule."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from snakemake.exceptions import WorkflowError
|
|
10
|
+
|
|
11
|
+
from .serialize import _entry, _literal
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def make_snakemake_rule(rule, conda_path: Path | None = None, TAB=" "):
|
|
15
|
+
"""Return the Snakefile rule text for this declaration."""
|
|
16
|
+
name = rule._name
|
|
17
|
+
if "document" in rule._input:
|
|
18
|
+
raise WorkflowError("input.document is preserved in the rule declaration")
|
|
19
|
+
inputs = [*rule._input._raw_items()]
|
|
20
|
+
if rule._filename is not None:
|
|
21
|
+
document = rule._filename
|
|
22
|
+
inputs.append(("document", document))
|
|
23
|
+
if not name:
|
|
24
|
+
name = _rule_name(_document_stem(document))
|
|
25
|
+
if name:
|
|
26
|
+
lines = [f"rule {name}:"]
|
|
27
|
+
else:
|
|
28
|
+
lines = ["rule:"]
|
|
29
|
+
lines.extend(_block("input", inputs, TAB))
|
|
30
|
+
lines.extend(_block("output", rule._output._raw_items(), TAB))
|
|
31
|
+
lines.extend(_block("log", rule._log._raw_items(), TAB))
|
|
32
|
+
lines.extend(_block("params", rule._params._raw_items(), TAB))
|
|
33
|
+
if rule._threads is not None:
|
|
34
|
+
lines.append(f"{TAB}threads: {rule._threads}")
|
|
35
|
+
lines.extend(_block("resources", rule._resources.items(), TAB))
|
|
36
|
+
if conda_path is not None:
|
|
37
|
+
lines.append(f"{TAB}conda:")
|
|
38
|
+
lines.append(f"{TAB}{TAB}{_literal(str(conda_path))}")
|
|
39
|
+
wildcards = " ".join(
|
|
40
|
+
f"--wildcards {item}={{wildcards.{item}:q}}"
|
|
41
|
+
for item in sorted(rule.wildcard_names())
|
|
42
|
+
)
|
|
43
|
+
parts = ["transcript", "{input.document:q}"]
|
|
44
|
+
target_document = rule.smk_target_document
|
|
45
|
+
if target_document is not None:
|
|
46
|
+
kind, _ = target_document
|
|
47
|
+
parts.extend(("-o", f"{{{kind}.document:q}}"))
|
|
48
|
+
if wildcards:
|
|
49
|
+
parts.append(wildcards)
|
|
50
|
+
lines.append(f"{TAB}shell:")
|
|
51
|
+
lines.append(f"{TAB}{TAB}{_literal(' '.join(parts))}")
|
|
52
|
+
return "\n".join(lines) + "\n"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _document_stem(path: str):
|
|
56
|
+
"""The logical stem of a document: ``demo.tmd.py`` -> ``demo``."""
|
|
57
|
+
name = Path(path).name
|
|
58
|
+
if name.endswith(".tmd.py"):
|
|
59
|
+
return name[:-7] # len(".tmd.py")
|
|
60
|
+
return Path(path).stem
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _rule_name(name: str):
|
|
64
|
+
"""Replace characters that Snakemake does not accept in a rule name."""
|
|
65
|
+
if re.search(r"[A-Za-z0-9_]", name) is None:
|
|
66
|
+
return "transcript_document"
|
|
67
|
+
name = re.sub(r"[^A-Za-z0-9_]+", "_", name)
|
|
68
|
+
return "_" + name if name[0].isdigit() else name
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _block(keyword: str, entries: Iterable[tuple], TAB=" "):
|
|
72
|
+
entries = iter(entries)
|
|
73
|
+
for k, v in entries:
|
|
74
|
+
break
|
|
75
|
+
else:
|
|
76
|
+
return
|
|
77
|
+
yield f"{TAB}{keyword}:"
|
|
78
|
+
tab2 = TAB * 2
|
|
79
|
+
yield f"{tab2}{_entry(k, v)}"
|
|
80
|
+
for k, v in entries:
|
|
81
|
+
yield f"{tab2}{_entry(k, v)}"
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Wildcard matching, name extraction and value placeholdization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from snakemake.exceptions import WorkflowError
|
|
8
|
+
from snakemake.io import contains_wildcard, regex_from_filepattern
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class WildcardState:
|
|
12
|
+
"""One rule's wildcard bookkeeping.
|
|
13
|
+
|
|
14
|
+
Three layers are kept apart: ``defaults`` declared with
|
|
15
|
+
``r.wildcards(...)``, ``inferred`` captures learned from input patterns,
|
|
16
|
+
and ``job`` (the runtime ``--wildcards`` of the execution that created the
|
|
17
|
+
rule). ``declared`` is the script-side view used for inference and
|
|
18
|
+
consistency checks; ``effective`` adds the job values only for resolution
|
|
19
|
+
and lambda evaluation.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, job: dict[str, str] | None = None):
|
|
23
|
+
self.defaults: dict[str, str] | None = None
|
|
24
|
+
self.inferred: dict[str, str] = {}
|
|
25
|
+
self.job: dict[str, str] = dict(job or {})
|
|
26
|
+
|
|
27
|
+
def declared(self) -> dict[str, str]:
|
|
28
|
+
"""Script-side wildcard values: inferred captures plus declared defaults."""
|
|
29
|
+
return self.inferred | (self.defaults or {})
|
|
30
|
+
|
|
31
|
+
def effective(self, override: dict[str, str] | None = None) -> dict[str, str]:
|
|
32
|
+
"""Runtime values: declared, then the job's, then *override*."""
|
|
33
|
+
if override is None:
|
|
34
|
+
override = self.job
|
|
35
|
+
return self.declared() | override
|
|
36
|
+
|
|
37
|
+
def conflict(self, captured: dict[str, str]):
|
|
38
|
+
"""Return the first capture that contradicts a declared value, if any."""
|
|
39
|
+
declared = self.declared()
|
|
40
|
+
for name, value in captured.items():
|
|
41
|
+
if name in declared and declared[name] != value:
|
|
42
|
+
return name, value
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _matches(pattern, value):
|
|
47
|
+
"""Whether *value* matches the wildcard *pattern* (snakemake semantics)."""
|
|
48
|
+
if pattern == value:
|
|
49
|
+
return True
|
|
50
|
+
if not isinstance(pattern, str) or not isinstance(value, str):
|
|
51
|
+
return False
|
|
52
|
+
if not contains_wildcard(pattern):
|
|
53
|
+
return False
|
|
54
|
+
return re.match(regex_from_filepattern(pattern), value) is not None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _iter_str(value):
|
|
58
|
+
"""Return the string leaves of a declaration value (paths or params)."""
|
|
59
|
+
if isinstance(value, str):
|
|
60
|
+
yield value
|
|
61
|
+
elif isinstance(value, list):
|
|
62
|
+
for item in value:
|
|
63
|
+
if isinstance(item, str):
|
|
64
|
+
yield item
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _match_wildcards(pattern: str, value: str) -> dict[str, str] | None:
|
|
68
|
+
"""Return the wildcards captured when *value* matches *pattern*."""
|
|
69
|
+
match = re.match(regex_from_filepattern(pattern), value)
|
|
70
|
+
captured = match.groupdict() if match else {}
|
|
71
|
+
return captured or None
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _placeholderize(value: str, wildcards: dict[str, str]):
|
|
75
|
+
"""Replace known wildcard values in *value* with their placeholders.
|
|
76
|
+
|
|
77
|
+
A single left-to-right scan keeps the replacement well-defined when values
|
|
78
|
+
overlap or form a cycle. At each position the longest value wins, so with
|
|
79
|
+
``a="sth", b="sth2"`` the value ``"sth2.tsv"`` becomes ``"{b}.tsv"`` rather
|
|
80
|
+
than ``"{a}2.tsv"``; because inserted placeholders are never rescanned,
|
|
81
|
+
``ext="csv", csv="ext"`` maps ``"csv.ext"`` to ``"{ext}.{csv}"`` instead of
|
|
82
|
+
corrupting the placeholder. If two wildcards share a value that actually
|
|
83
|
+
occurs in *value*, the substitution is ambiguous and is rejected.
|
|
84
|
+
"""
|
|
85
|
+
by_value: dict[str, list[str]] = {}
|
|
86
|
+
for name, text in wildcards.items():
|
|
87
|
+
if text:
|
|
88
|
+
by_value.setdefault(text, []).append(name)
|
|
89
|
+
if not by_value:
|
|
90
|
+
return value
|
|
91
|
+
alternation = re.compile(
|
|
92
|
+
"|".join(re.escape(text) for text in sorted(by_value, key=len, reverse=True))
|
|
93
|
+
)
|
|
94
|
+
result: list[str] = []
|
|
95
|
+
i = 0
|
|
96
|
+
while i < len(value):
|
|
97
|
+
match = alternation.match(value, i)
|
|
98
|
+
if match is None:
|
|
99
|
+
result.append(value[i])
|
|
100
|
+
i += 1
|
|
101
|
+
continue
|
|
102
|
+
names = by_value[match.group(0)]
|
|
103
|
+
if len(names) > 1:
|
|
104
|
+
raise WorkflowError(
|
|
105
|
+
"wildcards " + ", ".join(sorted(names)) + " share the value "
|
|
106
|
+
f"{match.group(0)!r}; cannot infer a unique pattern"
|
|
107
|
+
)
|
|
108
|
+
result.append("{" + names[0] + "}")
|
|
109
|
+
i = match.end()
|
|
110
|
+
return "".join(result)
|
transcript/cli.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
"""Execute documents, compare archives, or export recorded content to HTML."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import difflib
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import traceback
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
|
|
11
|
+
from .document import parse
|
|
12
|
+
from .html import extract as extract_html
|
|
13
|
+
from .renderers.label import set_cache
|
|
14
|
+
from .review.load import read_source, review_block
|
|
15
|
+
from .tmd import write
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from ._rule.core import Rule
|
|
19
|
+
|
|
20
|
+
ARCHIVE_SUFFIX = ".tmd.py"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def is_tmd(path: Path):
|
|
24
|
+
"""Return whether *path* names an archive (``.tmd.py``)."""
|
|
25
|
+
return path.name.endswith(ARCHIVE_SUFFIX)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def tmd_path(path: Path):
|
|
29
|
+
"""Return the archive path for a source, report, or archive *path*."""
|
|
30
|
+
if is_tmd(path):
|
|
31
|
+
return path
|
|
32
|
+
return path.with_suffix(ARCHIVE_SUFFIX)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def tmd_stem(path: Path):
|
|
36
|
+
"""The logical stem of an archive: ``demo.tmd.py`` -> ``demo``."""
|
|
37
|
+
if is_tmd(path):
|
|
38
|
+
return path.name[: -len(ARCHIVE_SUFFIX)]
|
|
39
|
+
return path.stem
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def output_path(path: Path):
|
|
43
|
+
"""Return the archive name for an explicit ``-o`` argument.
|
|
44
|
+
|
|
45
|
+
A ``.py`` name is the source form of an archive, so ``-o demo.py`` names
|
|
46
|
+
``demo.tmd.py`` rather than ``demo.py.tmd.py``. Other names receive the
|
|
47
|
+
archive suffix; an ``.html`` name is left alone because it selects a report.
|
|
48
|
+
"""
|
|
49
|
+
if path.suffix == ".html":
|
|
50
|
+
return path
|
|
51
|
+
if is_tmd(path):
|
|
52
|
+
return path
|
|
53
|
+
if path.suffix == ".py":
|
|
54
|
+
return path.with_suffix(ARCHIVE_SUFFIX)
|
|
55
|
+
return path.with_name(path.name + ARCHIVE_SUFFIX)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def html_path(path: Path):
|
|
59
|
+
"""Return the report path for an archive (``demo.tmd.py`` -> ``demo.html``)."""
|
|
60
|
+
return path.with_name(tmd_stem(path) + ".html")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def get_parser():
|
|
64
|
+
parser = argparse.ArgumentParser(prog="transcript")
|
|
65
|
+
parser.add_argument(
|
|
66
|
+
"file",
|
|
67
|
+
type=Path,
|
|
68
|
+
help="Python source (.py), archive (.tmd.py), or report (.html)",
|
|
69
|
+
)
|
|
70
|
+
group_diff = parser.add_mutually_exclusive_group()
|
|
71
|
+
group_diff.add_argument(
|
|
72
|
+
"--diff",
|
|
73
|
+
dest="diff",
|
|
74
|
+
action="store_true",
|
|
75
|
+
help="create missing archives; fail on differences",
|
|
76
|
+
)
|
|
77
|
+
group_diff.add_argument(
|
|
78
|
+
"--overwrite",
|
|
79
|
+
dest="diff",
|
|
80
|
+
action="store_false",
|
|
81
|
+
help="force to write or overwrite .tmd.py file",
|
|
82
|
+
)
|
|
83
|
+
group_html = parser.add_mutually_exclusive_group()
|
|
84
|
+
group_html.add_argument(
|
|
85
|
+
"--html",
|
|
86
|
+
action="store_true",
|
|
87
|
+
help="force HTML export after a successful archive step",
|
|
88
|
+
)
|
|
89
|
+
group_html.add_argument(
|
|
90
|
+
"--no-html",
|
|
91
|
+
action="store_true",
|
|
92
|
+
help="write only the archive, ignoring a declared .html document",
|
|
93
|
+
)
|
|
94
|
+
parser.add_argument(
|
|
95
|
+
"--wildcards",
|
|
96
|
+
nargs="+",
|
|
97
|
+
metavar="KEY=VALUE",
|
|
98
|
+
help="wildcard value for a declared pattern; may be repeated",
|
|
99
|
+
)
|
|
100
|
+
parser.add_argument(
|
|
101
|
+
"--previous",
|
|
102
|
+
type=Path,
|
|
103
|
+
help="reviewed .tmd.py or .html whose annotations are transferred to the"
|
|
104
|
+
" generated archive; defaults to an existing target .tmd.py",
|
|
105
|
+
)
|
|
106
|
+
parser.add_argument(
|
|
107
|
+
"--snakefile",
|
|
108
|
+
type=Path,
|
|
109
|
+
help="overwrite/create the file with the document's rule",
|
|
110
|
+
)
|
|
111
|
+
parser.add_argument(
|
|
112
|
+
"-o",
|
|
113
|
+
"--output",
|
|
114
|
+
type=Path,
|
|
115
|
+
help="output path; .html selects HTML export, .tmd.py selects the archive name;"
|
|
116
|
+
" other names receive the mode's suffix",
|
|
117
|
+
)
|
|
118
|
+
parser.set_defaults(diff=None)
|
|
119
|
+
return parser
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _parse_wildcards(values, parser: argparse.ArgumentParser):
|
|
123
|
+
result: dict[str, str] = {}
|
|
124
|
+
for item in values or ():
|
|
125
|
+
key, separator, value = item.partition("=")
|
|
126
|
+
if not separator or not key:
|
|
127
|
+
parser.error(f"--wildcards expects KEY=VALUE, got {item!r}")
|
|
128
|
+
result[key] = value
|
|
129
|
+
return result
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def html2tmd(html: Path, tmd: Path | None = None, diff: bool | None = None):
|
|
133
|
+
"""Handle an exported ``.html`` input by extracting its embedded archive."""
|
|
134
|
+
try:
|
|
135
|
+
source = extract_html(html.read_text(encoding="utf-8-sig"))
|
|
136
|
+
except Exception:
|
|
137
|
+
traceback.print_exc()
|
|
138
|
+
return 2
|
|
139
|
+
tmd = tmd_path(tmd or html)
|
|
140
|
+
return check_exist(tmd, source, diff, tmd.exists())
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def main(argv: list[str] | None = None):
|
|
144
|
+
parser = get_parser()
|
|
145
|
+
args = parser.parse_args(argv)
|
|
146
|
+
path: Path = args.file.resolve()
|
|
147
|
+
if path.suffix not in (".py", ".html"):
|
|
148
|
+
parser.error("input must end in .py or .html")
|
|
149
|
+
output: Path | None = args.output
|
|
150
|
+
if output is not None:
|
|
151
|
+
output = output_path(output)
|
|
152
|
+
target = None if output is None else output.resolve()
|
|
153
|
+
if path.suffix == ".html":
|
|
154
|
+
if args.previous is not None:
|
|
155
|
+
parser.error("--previous does not apply to a .html input")
|
|
156
|
+
sys.exit(html2tmd(path, target, args.diff))
|
|
157
|
+
output_html = output is not None and output.suffix == ".html"
|
|
158
|
+
# --no-html always wins. An archive-only -o suppresses export unless
|
|
159
|
+
# --html explicitly asks for it; force_html and only_tmd are never both
|
|
160
|
+
# true except when -o names the report but --no-html was given.
|
|
161
|
+
force_html = args.html or output_html
|
|
162
|
+
only_tmd = args.no_html or (
|
|
163
|
+
output is not None and not output_html and not args.html
|
|
164
|
+
)
|
|
165
|
+
if is_tmd(path) and force_html and args.diff is None:
|
|
166
|
+
if args.previous is not None:
|
|
167
|
+
parser.error(
|
|
168
|
+
"--previous needs the archive to be regenerated;"
|
|
169
|
+
" use --overwrite (or --diff) together with --html"
|
|
170
|
+
)
|
|
171
|
+
# The archive already exists; only the HTML needs rendering.
|
|
172
|
+
ret, tmd, is_html, executed = 0, path, True, False
|
|
173
|
+
else:
|
|
174
|
+
wildcards = _parse_wildcards(args.wildcards, parser)
|
|
175
|
+
previous = None if args.previous is None else args.previous.resolve()
|
|
176
|
+
ret = py2tmd(path, output, wildcards, previous)
|
|
177
|
+
if isinstance(ret, tuple):
|
|
178
|
+
tmd, candidate, is_html = ret
|
|
179
|
+
ret = check_exist(tmd, candidate, args.diff, path == tmd, force_html)
|
|
180
|
+
executed = True
|
|
181
|
+
if not ret and tmd is not None:
|
|
182
|
+
if not only_tmd and (force_html or is_html):
|
|
183
|
+
html_target = html_path(tmd if target is None else target)
|
|
184
|
+
if executed:
|
|
185
|
+
ret = fresh_tmd2html(tmd, html_target)
|
|
186
|
+
else:
|
|
187
|
+
ret = tmd2html(tmd, html_target)
|
|
188
|
+
if not ret and args.snakefile:
|
|
189
|
+
ret = write_smk(tmd, args.snakefile, args.file)
|
|
190
|
+
sys.exit(ret)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def write_smk(tmd: Path, smk: Path, document_src: Path):
|
|
194
|
+
"""Write a Snakefile rule for ``document`` into ``target``.
|
|
195
|
+
|
|
196
|
+
The rule is read statically from ``archive``'s canonical block; ``document``
|
|
197
|
+
is the source the rule's ``input.document`` and name are derived from.
|
|
198
|
+
"""
|
|
199
|
+
from ._rule.core import Rule
|
|
200
|
+
|
|
201
|
+
source = tmd.read_text(encoding="utf-8-sig")
|
|
202
|
+
try:
|
|
203
|
+
job = Rule.from_tmd(source, document_src)
|
|
204
|
+
except Exception:
|
|
205
|
+
traceback.print_exc()
|
|
206
|
+
return 2
|
|
207
|
+
directory = smk.parent
|
|
208
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
209
|
+
env = job._conda
|
|
210
|
+
if env:
|
|
211
|
+
conda_path = directory / f"{smk.stem}.conda.yaml"
|
|
212
|
+
conda_path.write_text(env.to_yaml(), encoding="utf-8")
|
|
213
|
+
else:
|
|
214
|
+
conda_path = None
|
|
215
|
+
smk.write_text(job.make_snakemake_rule(conda_path), encoding="utf-8")
|
|
216
|
+
return 0
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def get_document(job: Rule | None):
|
|
220
|
+
"""Resolve the declared document to ``(archive, is_html)``, if any."""
|
|
221
|
+
if job is None:
|
|
222
|
+
return None
|
|
223
|
+
found = job.smk_target_document
|
|
224
|
+
if found is None:
|
|
225
|
+
return None
|
|
226
|
+
_, pattern = found
|
|
227
|
+
resolved = Path(job.resolve(pattern))
|
|
228
|
+
if resolved.suffix == ".html":
|
|
229
|
+
return tmd_path(resolved), True
|
|
230
|
+
return resolved, False
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def check_previous(path: Path):
|
|
234
|
+
"""Raise when an explicit ``--previous`` no longer matches its body hash.
|
|
235
|
+
|
|
236
|
+
A reviewed archive records the hash of its own body in the review marker.
|
|
237
|
+
When the body was edited behind the block's back, its coordinates cannot be
|
|
238
|
+
trusted, so an explicit ``--previous`` refuses to transfer instead of
|
|
239
|
+
silently dropping the annotations. A ``.html`` previous is rebuilt from its
|
|
240
|
+
islands and never carries a stale hash.
|
|
241
|
+
"""
|
|
242
|
+
source = read_source(path)
|
|
243
|
+
if source is not None and source.stale:
|
|
244
|
+
raise ValueError(
|
|
245
|
+
f"{path}: the review block hash does not match its archive body"
|
|
246
|
+
" (edited behind transcript's back?); refusing to transfer annotations"
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def py2tmd(
|
|
251
|
+
path: Path,
|
|
252
|
+
output: Path | None,
|
|
253
|
+
wildcards: dict[str, str] | None = None,
|
|
254
|
+
previous: Path | None = None,
|
|
255
|
+
):
|
|
256
|
+
"""Execute the document, resolve the archive target, and write the archive.
|
|
257
|
+
|
|
258
|
+
Returns ``(status, archive, is_html)`` where *is_html* says whether the
|
|
259
|
+
effective target was an ``.html`` document. The review block is carried
|
|
260
|
+
over explicitly (see :func:`review_block`): ``--previous`` first, else the
|
|
261
|
+
document's own block, else an existing target archive.
|
|
262
|
+
"""
|
|
263
|
+
source = path.read_text(encoding="utf-8-sig")
|
|
264
|
+
if previous is not None:
|
|
265
|
+
try:
|
|
266
|
+
check_previous(previous)
|
|
267
|
+
except Exception as error:
|
|
268
|
+
print(f"transcript: {error}", file=sys.stderr)
|
|
269
|
+
return 2
|
|
270
|
+
try:
|
|
271
|
+
document = parse(source, str(path))
|
|
272
|
+
blocks, outputs, job = document.execute(path, wildcards)
|
|
273
|
+
if output is not None:
|
|
274
|
+
if job is not None:
|
|
275
|
+
job.smk_target_document = str(output)
|
|
276
|
+
target = tmd_path(output.resolve())
|
|
277
|
+
html = output.suffix == ".html"
|
|
278
|
+
else:
|
|
279
|
+
found = get_document(job)
|
|
280
|
+
if found is None:
|
|
281
|
+
target, html = tmd_path(path), False
|
|
282
|
+
else:
|
|
283
|
+
target, html = found
|
|
284
|
+
candidate = document.render_tmd(blocks, outputs, job)
|
|
285
|
+
block = review_block(document, target, previous, candidate)
|
|
286
|
+
if block:
|
|
287
|
+
candidate = candidate.rstrip("\n") + "\n\n" + block + "\n"
|
|
288
|
+
except Exception:
|
|
289
|
+
traceback.print_exc()
|
|
290
|
+
return 2
|
|
291
|
+
return target, candidate, html
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def check_exist(
|
|
295
|
+
target: Path,
|
|
296
|
+
candidate: str,
|
|
297
|
+
diff: bool | None = None,
|
|
298
|
+
default_diff=True,
|
|
299
|
+
create_missing=False,
|
|
300
|
+
):
|
|
301
|
+
if create_missing and not target.exists():
|
|
302
|
+
diff = False # HTML export needs an archive to read.
|
|
303
|
+
elif diff is None:
|
|
304
|
+
diff = default_diff
|
|
305
|
+
if not target.exists():
|
|
306
|
+
previous = ""
|
|
307
|
+
if not diff:
|
|
308
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
309
|
+
target.touch()
|
|
310
|
+
else:
|
|
311
|
+
previous = target.read_text(encoding="utf-8")
|
|
312
|
+
updated = candidate != previous
|
|
313
|
+
if diff:
|
|
314
|
+
sys.stdout.writelines(
|
|
315
|
+
difflib.unified_diff(
|
|
316
|
+
previous.splitlines(keepends=True),
|
|
317
|
+
candidate.splitlines(keepends=True),
|
|
318
|
+
fromfile=str(target),
|
|
319
|
+
tofile=f"{target} (generated)",
|
|
320
|
+
)
|
|
321
|
+
)
|
|
322
|
+
return 1 if updated else 0
|
|
323
|
+
elif updated:
|
|
324
|
+
write(target, candidate)
|
|
325
|
+
return 0
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def tmd2html(tmd: Path, html: Path):
|
|
329
|
+
source = tmd.read_text(encoding="utf-8-sig")
|
|
330
|
+
previous_cache = set_cache({})
|
|
331
|
+
try:
|
|
332
|
+
document = parse(source, str(tmd))
|
|
333
|
+
candidate = document.render_html(title=tmd_stem(tmd))
|
|
334
|
+
except Exception:
|
|
335
|
+
traceback.print_exc()
|
|
336
|
+
return 2
|
|
337
|
+
finally:
|
|
338
|
+
set_cache(previous_cache)
|
|
339
|
+
html.parent.mkdir(parents=True, exist_ok=True)
|
|
340
|
+
write(html, candidate)
|
|
341
|
+
return 0
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def fresh_tmd2html(tmd: Path, html: Path):
|
|
345
|
+
"""Render HTML from an archive in a fresh process.
|
|
346
|
+
|
|
347
|
+
The document already ran in this process; a child keeps its side effects
|
|
348
|
+
(``os.chdir``, ``sys.modules``, ...) away from the HTML renderer.
|
|
349
|
+
"""
|
|
350
|
+
command = [
|
|
351
|
+
sys.executable,
|
|
352
|
+
"-c",
|
|
353
|
+
"from transcript.cli import main; main()",
|
|
354
|
+
str(tmd),
|
|
355
|
+
"-o",
|
|
356
|
+
str(html),
|
|
357
|
+
]
|
|
358
|
+
try:
|
|
359
|
+
ret = subprocess.run(command, check=False).returncode
|
|
360
|
+
except OSError:
|
|
361
|
+
traceback.print_exc()
|
|
362
|
+
return 2
|
|
363
|
+
return 128 - ret if ret < 0 else ret
|
transcript/document.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""An executable Python document and its archive and HTML operations."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import NamedTuple
|
|
6
|
+
|
|
7
|
+
from . import review
|
|
8
|
+
from .execute import execute as _execute
|
|
9
|
+
from .html import render as _render_html
|
|
10
|
+
from .parse import Region, locate
|
|
11
|
+
from .tmd import render as _render_tmd
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse(source: str, filename: str):
|
|
15
|
+
"""Locate module-level report regions, never compute a block here.
|
|
16
|
+
|
|
17
|
+
for with block, only one with item is allowed
|
|
18
|
+
"""
|
|
19
|
+
tree, position, regions = locate(source, filename)
|
|
20
|
+
return AstDocument(
|
|
21
|
+
source, tree, position, regions, review.ReviewBlock.find(tree, position)
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AstDocument(NamedTuple):
|
|
26
|
+
source: str
|
|
27
|
+
tree: ast.Module
|
|
28
|
+
position: Callable[[int, int], int]
|
|
29
|
+
"""(line, column) -> character offset in the source."""
|
|
30
|
+
regions: dict[int, Region]
|
|
31
|
+
review: review.ReviewBlock | None = None
|
|
32
|
+
"""The trailing ``transcript.review`` block, when the archive has one."""
|
|
33
|
+
|
|
34
|
+
def indent_of(self, start: int):
|
|
35
|
+
source = self.source
|
|
36
|
+
return source[source.rfind("\n", 0, start) + 1 : start]
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def source_without_review(self):
|
|
40
|
+
"""The archive text before the trailing review block."""
|
|
41
|
+
if self.review is None:
|
|
42
|
+
return self.source
|
|
43
|
+
return self.source[: self.review.start]
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def blocks(self):
|
|
47
|
+
"""Compute all report blocks from the document's regions."""
|
|
48
|
+
return [
|
|
49
|
+
region.parse_block(self.source, self.position)
|
|
50
|
+
for region in self.regions.values()
|
|
51
|
+
if region.kind == "if" or region.marker
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
execute = _execute
|
|
55
|
+
render_tmd = _render_tmd
|
|
56
|
+
render_html = _render_html
|