doc-cli-test 0.2.3__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.
cli_test/parser.py ADDED
@@ -0,0 +1,395 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from dataclasses import dataclass, field
5
+ from pathlib import Path
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+
9
+ MARKERS = (
10
+ "cli-test-cmd",
11
+ "cli-test-cfg",
12
+ "cli-test-out",
13
+ "cli-test-err",
14
+ "cli-test-ret",
15
+ "cli-test-end",
16
+ )
17
+
18
+ # file suffixes supporting comment-anchored transcript blocks (see README)
19
+ TRANSCRIPT_SUFFIXES = (".md", ".adoc", ".asciidoc")
20
+ _TRANSCRIPT_ANCHOR = "cli-test"
21
+ _TRANSCRIPT_CMP = str(Path(__file__).with_name("_sphinx_compare.py"))
22
+ _MD_FENCE_RE = re.compile(r"^(`{3,}|~{3,})")
23
+ _ADOC_LISTING = "----"
24
+
25
+
26
+ @dataclass
27
+ class Example:
28
+ cmd: str = ""
29
+ stdout: str = ""
30
+ stderr: str = ""
31
+ code: str = ""
32
+ config: Dict[str, object] = field(default_factory=dict)
33
+ path: Optional[Path] = None
34
+ index: int = 0
35
+ block_prefix: str = ""
36
+ content_indent: str = ""
37
+ cmd_start_line: int = 0
38
+ stdout_start_line: int = 0
39
+ stderr_start_line: int = 0
40
+ code_start_line: int = 0
41
+ cmd_lines: List[str] = field(default_factory=list)
42
+ stdout_lines: List[str] = field(default_factory=list)
43
+ stderr_lines: List[str] = field(default_factory=list)
44
+ code_lines: List[str] = field(default_factory=list)
45
+
46
+
47
+ def _match_marker(line: str) -> Optional[Tuple[str, str]]:
48
+ for marker in MARKERS:
49
+ pos = line.find(marker)
50
+ if pos < 0:
51
+ continue
52
+ suffix = line[pos + len(marker) :]
53
+ if suffix.strip() == "":
54
+ return line[:pos], marker
55
+ return None
56
+
57
+
58
+ def _strip_block_prefix(line: str, block_prefix: str) -> str:
59
+ if block_prefix and line.startswith(block_prefix):
60
+ return line[len(block_prefix) :]
61
+ return line
62
+
63
+
64
+ def _leading_ws(line: str) -> str:
65
+ return line[: len(line) - len(line.lstrip())]
66
+
67
+
68
+ def _compute_content_indent(lines: List[str], block_prefix: str) -> str:
69
+ for line in lines:
70
+ if not line.strip():
71
+ continue
72
+ without_block = _strip_block_prefix(line, block_prefix)
73
+ return without_block[: len(without_block) - len(without_block.lstrip())]
74
+ return ""
75
+
76
+
77
+ def _normalize_block(lines: List[str], block_prefix: str, content_indent: str) -> str:
78
+ out: List[str] = []
79
+ for line in lines:
80
+ if not line.strip():
81
+ out.append("")
82
+ continue
83
+ without_block = _strip_block_prefix(line, block_prefix)
84
+ if content_indent and without_block.startswith(content_indent):
85
+ without_block = without_block[len(content_indent) :]
86
+ out.append(without_block)
87
+ return "\n".join(out)
88
+
89
+
90
+ def _parse_cfg_block(lines: List[str]) -> Dict[str, object]:
91
+ cfg: Dict[str, object] = {}
92
+ for raw in lines:
93
+ text = raw.strip()
94
+ if not text:
95
+ continue
96
+ if "=" not in text:
97
+ raise ValueError(f"Invalid config line: {raw!r}")
98
+ key, value = text.split("=", 1)
99
+ key = key.strip()
100
+ value = value.strip()
101
+ if not key:
102
+ raise ValueError(f"Invalid config key in: {raw!r}")
103
+ cfg[key] = value
104
+ return cfg
105
+
106
+
107
+ def _anchor_content(line: str, suffix: str) -> Optional[str]:
108
+ """Return the inner text of a comment line usable as a transcript anchor."""
109
+ stripped = line.strip()
110
+ if suffix == ".md":
111
+ if stripped.startswith("<!--") and stripped.endswith("-->"):
112
+ return stripped[4:-3].strip()
113
+ return None
114
+ if stripped.startswith("//"):
115
+ return stripped[2:].strip()
116
+ return None
117
+
118
+
119
+ def _anchor_options(text: str, path: Path, line_number: int) -> Dict[str, object]:
120
+ tokens = text.split()
121
+ options: Dict[str, object] = {}
122
+ for token in tokens[1:]:
123
+ key, separator, value = token.partition("=")
124
+ if not separator or not key:
125
+ raise ValueError(f"{path}:{line_number}: invalid cli-test anchor option: {token!r}")
126
+ options[key] = value
127
+ return options
128
+
129
+
130
+ def _find_transcript_block(
131
+ lines: List[str], start: int, suffix: str, path: Path, anchor_line: int
132
+ ) -> Optional[List[Tuple[int, str]]]:
133
+ """Find the code/listing block following an anchor, with 1-based line numbers."""
134
+ i = start
135
+ if suffix == ".md":
136
+ while i < len(lines) and not lines[i].strip():
137
+ i += 1
138
+ if i >= len(lines):
139
+ return None
140
+ match = _MD_FENCE_RE.match(lines[i])
141
+ if match is None:
142
+ return None
143
+ fence_char = match.group(1)[0]
144
+ close_re = re.compile(r"^" + re.escape(fence_char) + r"{3,}\s*$")
145
+ content = []
146
+ j = i + 1
147
+ while j < len(lines) and close_re.match(lines[j]) is None:
148
+ content.append((j + 1, lines[j]))
149
+ j += 1
150
+ if j >= len(lines):
151
+ raise ValueError(f"{path}:{anchor_line}: unterminated code block")
152
+ return content
153
+
154
+ while i < len(lines):
155
+ stripped = lines[i].strip()
156
+ if not stripped or (stripped.startswith("[") and stripped.endswith("]")):
157
+ i += 1
158
+ continue
159
+ break
160
+ if i >= len(lines) or lines[i].strip() != _ADOC_LISTING:
161
+ return None
162
+ content = []
163
+ j = i + 1
164
+ while j < len(lines) and lines[j].strip() != _ADOC_LISTING:
165
+ content.append((j + 1, lines[j]))
166
+ j += 1
167
+ if j >= len(lines):
168
+ raise ValueError(f"{path}:{anchor_line}: unterminated listing block")
169
+ return content
170
+
171
+
172
+ def _parse_transcript_option_int(
173
+ options: Dict[str, object], key: str, path: Path
174
+ ) -> Optional[int]:
175
+ if key not in options:
176
+ return None
177
+ try:
178
+ return int(str(options[key]))
179
+ except ValueError:
180
+ raise ValueError(
181
+ f"{path}: invalid {key} option: {options[key]!r} (expected an integer)"
182
+ )
183
+
184
+
185
+ def _parse_transcript_content(
186
+ content: List[Tuple[int, str]], path: Path, options: Dict[str, object], anchor_line: int
187
+ ) -> List[Example]:
188
+ if "ret" in options:
189
+ try:
190
+ int(str(options["ret"]))
191
+ except ValueError:
192
+ raise ValueError(f"{path}: invalid ret option: {options['ret']!r} (expected an integer)")
193
+ # out=N / err=N: expected stdout (resp. stderr) starts N lines below the
194
+ # anchor (the fence line counts) and runs to the end of the block, so
195
+ # output starting with `$ ` is not mistaken for a new command.
196
+ out_offset = _parse_transcript_option_int(options, "out", path)
197
+ err_offset = _parse_transcript_option_int(options, "err", path)
198
+ out_start = anchor_line + out_offset if out_offset is not None else None
199
+ err_start = anchor_line + err_offset if err_offset is not None else None
200
+ if out_start is not None and err_start is not None and err_start <= out_start:
201
+ raise ValueError(f"{path}: err={err_offset} must come after out={out_offset}")
202
+ if out_start is not None and (not content or out_start > content[-1][0]):
203
+ raise ValueError(f"{path}: out={out_offset} points outside the transcript block")
204
+ if err_start is not None and (not content or err_start > content[-1][0]):
205
+ raise ValueError(f"{path}: err={err_offset} points outside the transcript block")
206
+ config = {
207
+ key: value
208
+ for key, value in options.items()
209
+ if key not in ("ret", "out", "err")
210
+ }
211
+ # transcript blocks cannot express a trailing newline, so compare with
212
+ # trailing newlines ignored unless the user supplies a custom cmp
213
+ config.setdefault("cmp", _TRANSCRIPT_CMP)
214
+
215
+ examples: List[Example] = []
216
+ current: Optional[Example] = None
217
+ indent = ""
218
+
219
+ def finalize() -> None:
220
+ assert current is not None
221
+ if current.stdout_lines:
222
+ current.stdout_start_line = current.stdout_lines[0][0]
223
+ current.stdout = "\n".join(text for _, text in current.stdout_lines)
224
+ if current.stderr_lines:
225
+ current.stderr_start_line = current.stderr_lines[0][0]
226
+ current.stderr = "\n".join(text for _, text in current.stderr_lines)
227
+ current.code = str(options.get("ret", ""))
228
+ current.config = dict(config)
229
+ examples.append(current)
230
+
231
+ def capture(stream: str, line_number: int, line: str) -> None:
232
+ if current is None:
233
+ raise ValueError(
234
+ f"{path}:{line_number}: expected output does not follow any command"
235
+ )
236
+ if indent and line.startswith(indent):
237
+ line = line[len(indent):]
238
+ target = current.stdout_lines if stream == "stdout" else current.stderr_lines
239
+ target.append((line_number, line))
240
+
241
+ for line_number, line in content:
242
+ if out_start is not None and line_number >= out_start:
243
+ if err_start is not None and line_number >= err_start:
244
+ capture("stderr", line_number, line)
245
+ else:
246
+ capture("stdout", line_number, line)
247
+ continue
248
+ if err_start is not None and line_number >= err_start:
249
+ capture("stderr", line_number, line)
250
+ continue
251
+ stripped = line.lstrip()
252
+ if stripped.startswith("$ "):
253
+ if current is not None:
254
+ finalize()
255
+ current = None
256
+ cmd = stripped[2:].strip()
257
+ if not cmd:
258
+ raise ValueError(f"{path}:{line_number}: empty command in transcript block")
259
+ current = Example(path=path, cmd=cmd, cmd_start_line=line_number)
260
+ indent = line[: len(line) - len(stripped)]
261
+ elif current is not None:
262
+ if indent and line.startswith(indent):
263
+ line = line[len(indent):]
264
+ current.stdout_lines.append((line_number, line))
265
+ if current is not None:
266
+ finalize()
267
+ return examples
268
+
269
+
270
+ def _parse_transcript_anchors(path: Path, lines: List[str], start_index: int) -> List[Example]:
271
+ suffix = path.suffix.lower()
272
+ examples: List[Example] = []
273
+ for index, line in enumerate(lines):
274
+ content = _anchor_content(line, suffix)
275
+ if content is None:
276
+ continue
277
+ tokens = content.split()
278
+ if not tokens or tokens[0] != _TRANSCRIPT_ANCHOR:
279
+ continue
280
+ options = _anchor_options(content, path, index + 1)
281
+ block = _find_transcript_block(lines, index + 1, suffix, path, index + 1)
282
+ if block is None:
283
+ raise ValueError(f"{path}:{index + 1}: cli-test anchor is not followed by a code or listing block")
284
+ for example in _parse_transcript_content(block, path, options, index + 1):
285
+ example.index = start_index + len(examples) + 1
286
+ examples.append(example)
287
+ return examples
288
+
289
+
290
+ def parse_file(path: Path | str) -> List[Example]:
291
+ file_path = Path(path)
292
+ text = file_path.read_text(encoding="utf-8")
293
+ lines = text.splitlines()
294
+
295
+ examples: List[Example] = []
296
+ current: Optional[Example] = None
297
+ current_section: Optional[str] = None
298
+ sections: Dict[str, List[str]] = {}
299
+ block_prefix = ""
300
+ content_indent = ""
301
+
302
+ for line_number, line in enumerate(lines, start=1):
303
+ match = _match_marker(line)
304
+ if match is not None:
305
+ prefix, marker = match
306
+ if marker == "cli-test-cmd":
307
+ current = Example(path=file_path, index=len(examples) + 1)
308
+ current_section = "cmd"
309
+ sections = {"cmd": []}
310
+ block_prefix = prefix
311
+ content_indent = ""
312
+ current.block_prefix = prefix
313
+ current.content_indent = ""
314
+ current.cmd_start_line = line_number + 1
315
+ current.stdout_start_line = 0
316
+ current.stderr_start_line = 0
317
+ current.cmd_lines = []
318
+ current.stdout_lines = []
319
+ current.stderr_lines = []
320
+ continue
321
+
322
+ if current is None:
323
+ continue
324
+
325
+ if marker == "cli-test-cfg":
326
+ current_section = "cfg"
327
+ sections.setdefault("cfg", [])
328
+ continue
329
+
330
+ if marker == "cli-test-out":
331
+ current_section = "stdout"
332
+ current.stdout_start_line = line_number + 1
333
+ sections.setdefault("stdout", [])
334
+ continue
335
+
336
+ if marker == "cli-test-err":
337
+ current_section = "stderr"
338
+ current.stderr_start_line = line_number + 1
339
+ sections.setdefault("stderr", [])
340
+ continue
341
+
342
+ if marker == "cli-test-ret":
343
+ current_section = "code"
344
+ current.code_start_line = line_number + 1
345
+ sections.setdefault("code", [])
346
+ continue
347
+
348
+ if marker == "cli-test-end":
349
+ if current is not None:
350
+ content_indent = _compute_content_indent(sections.get("cmd", []), block_prefix)
351
+ current.block_prefix = block_prefix
352
+ current.content_indent = content_indent
353
+ current.cmd_lines = sections.get("cmd", [])
354
+ current.stdout_lines = sections.get("stdout", [])
355
+ current.stderr_lines = sections.get("stderr", [])
356
+ current.code_lines = sections.get("code", [])
357
+ current.cmd = _normalize_block(sections.get("cmd", []), block_prefix, content_indent)
358
+ current.config = _parse_cfg_block(
359
+ _normalize_block(sections.get("cfg", []), block_prefix, content_indent).splitlines()
360
+ )
361
+ current.stdout = _normalize_block(sections.get("stdout", []), block_prefix, content_indent)
362
+ current.stderr = _normalize_block(sections.get("stderr", []), block_prefix, content_indent)
363
+ current.code = _normalize_block(sections.get("code", []), block_prefix, content_indent)
364
+ examples.append(current)
365
+ current = None
366
+ current_section = None
367
+ sections = {}
368
+ block_prefix = ""
369
+ content_indent = ""
370
+ continue
371
+
372
+ if current is not None and current_section is not None:
373
+ sections.setdefault(current_section, []).append(line)
374
+
375
+ if current is not None:
376
+ content_indent = _compute_content_indent(sections.get("cmd", []), block_prefix)
377
+ current.block_prefix = block_prefix
378
+ current.content_indent = content_indent
379
+ current.cmd_lines = sections.get("cmd", [])
380
+ current.stdout_lines = sections.get("stdout", [])
381
+ current.stderr_lines = sections.get("stderr", [])
382
+ current.code_lines = sections.get("code", [])
383
+ current.cmd = _normalize_block(sections.get("cmd", []), block_prefix, content_indent)
384
+ current.config = _parse_cfg_block(
385
+ _normalize_block(sections.get("cfg", []), block_prefix, content_indent).splitlines()
386
+ )
387
+ current.stdout = _normalize_block(sections.get("stdout", []), block_prefix, content_indent)
388
+ current.stderr = _normalize_block(sections.get("stderr", []), block_prefix, content_indent)
389
+ current.code = _normalize_block(sections.get("code", []), block_prefix, content_indent)
390
+ examples.append(current)
391
+
392
+ if file_path.suffix.lower() in TRANSCRIPT_SUFFIXES:
393
+ examples.extend(_parse_transcript_anchors(file_path, lines, start_index=len(examples)))
394
+
395
+ return examples
cli_test/runner.py ADDED
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import shlex
4
+ import subprocess
5
+ from typing import Any, Dict
6
+
7
+
8
+ def _byte_location(data: bytes, offset: int) -> Dict[str, int]:
9
+ if offset < 0:
10
+ offset = 0
11
+ line = 1
12
+ column = 1
13
+ for index in range(offset):
14
+ if index >= len(data):
15
+ break
16
+ if data[index] == 10:
17
+ line += 1
18
+ column = 1
19
+ else:
20
+ column += 1
21
+ return {"line": line, "column": column}
22
+
23
+
24
+ def _first_mismatch_index(expected: bytes, actual: bytes) -> int:
25
+ limit = min(len(expected), len(actual))
26
+ for i in range(limit):
27
+ if expected[i] != actual[i]:
28
+ return i
29
+ if len(expected) != len(actual):
30
+ return limit
31
+ return -1
32
+
33
+
34
+ def run_example(command: str, cwd: str | None = None, timeout: int = 30, env: Dict[str, str] | None = None) -> Dict[str, Any]:
35
+ argv = shlex.split(command)
36
+ completed = subprocess.run(
37
+ argv,
38
+ cwd=cwd,
39
+ env=env,
40
+ capture_output=True,
41
+ timeout=timeout,
42
+ text=True,
43
+ )
44
+
45
+ stdout = completed.stdout.encode("utf-8") if isinstance(completed.stdout, str) else b""
46
+ stderr = completed.stderr.encode("utf-8") if isinstance(completed.stderr, str) else b""
47
+ mismatch = _first_mismatch_index(stdout, stdout)
48
+ location = _byte_location(stdout, mismatch if mismatch >= 0 else 0)
49
+
50
+ return {
51
+ "ok": True,
52
+ "stdout": completed.stdout,
53
+ "stderr": completed.stderr,
54
+ "returncode": completed.returncode,
55
+ "location": location,
56
+ "mismatch_index": mismatch,
57
+ }