run_report.py ダウンロード/コピー

run_report.py をダウンロード

run_report.py
run_report.py
  1#!/usr/bin/env python3
  2"""
  3概要:
  4    コマンドを実行し、ポータブルな実行レポートをHTMLまたはMarkdown形式で作成します。
  5詳細説明:
  6    対象となる作業ディレクトリ内のファイルを監視し、コマンド実行前後での変更を検出してレポート化します。
  7"""
  8from __future__ import annotations
  9
 10import argparse
 11from datetime import datetime
 12import fnmatch
 13import hashlib
 14import html
 15import importlib.metadata
 16import json
 17import locale
 18import os
 19from pathlib import Path
 20import platform
 21import re
 22import shlex
 23import shutil
 24import signal
 25import subprocess
 26import sys
 27import threading
 28import time
 29from urllib.parse import quote
 30
 31
 32DEFAULT_IGNORE = ".git,__pycache__,venv,.venv,.mypy_cache,.pytest_cache,*.pyc,*.pyo,*.tmp,*.bak,*.swp"
 33DEFAULT_LOG_EXTS = ".log,.out,.txt"
 34DEFAULT_ERROR_RE = r"\b(error|exception|traceback|failed|failure|not found|permission denied|overflow|underflow)\b"
 35DEFAULT_WARNING_RE = r"\b(warning|warn|deprecated|convergence|ill-conditioned)\b"
 36IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".bmp"}
 37
 38
 39def now_iso() -> str:
 40    """
 41    概要:
 42        現在時刻をISO 8601形式の文字列で取得します。
 43    戻り値:
 44        :returns: 秒精度かつタイムゾーン付きのISO 8601形式の文字列
 45        :rtype: str
 46    """
 47    return datetime.now().astimezone().isoformat(timespec="seconds")
 48
 49
 50def parse_csv(text: str) -> list[str]:
 51    """
 52    概要:
 53        カンマ区切りの文字列をパースし、空白を取り除いた要素のリストを返します。
 54    引数:
 55        :param text: カンマ区切りの入力文字列
 56        :type text: str
 57    戻り値:
 58        :returns: パースされた文字列のリスト
 59        :rtype: list[str]
 60    """
 61    return [part.strip() for part in text.split(",") if part.strip()]
 62
 63
 64def ignored(rel: str, patterns: list[str]) -> bool:
 65    """
 66    概要:
 67        指定された相対パスが無視パターンに一致するかどうかを判定します。
 68    引数:
 69        :param rel: 判定対象の相対パス
 70        :type rel: str
 71        :param patterns: fnmatchで利用する除外パターンのリスト
 72        :type patterns: list[str]
 73    戻り値:
 74        :returns: パターンに一致する場合はTrue、そうでない場合はFalse
 75        :rtype: bool
 76    """
 77    parts = rel.split("/")
 78    return any(fnmatch.fnmatch(rel, p) or any(fnmatch.fnmatch(part, p) for part in parts)
 79               for p in patterns)
 80
 81
 82def snapshot(root: Path, excluded: Path | None, patterns: list[str], hash_mode: str,
 83             hash_names: set[str] | None = None):
 84    """
 85    概要:
 86        ディレクトリ内のファイルのスナップショットを取得し、メタデータとハッシュの辞書およびエラーリストを返します。
 87    詳細説明:
 88        相対パスをキーとして、ファイルサイズ、更新日時、ハッシュ値を格納した辞書と、読み込みエラーのリストを返します。
 89    引数:
 90        :param root: スナップショットの対象となるルートディレクトリ
 91        :type root: pathlib.Path
 92        :param excluded: 除外するディレクトリのパス、またはNone
 93        :type excluded: pathlib.Path | None
 94        :param patterns: 無視するパターンのリスト
 95        :type patterns: list[str]
 96        :param hash_mode: ハッシュ計算のモード、all、changed、noneのいずれか
 97        :type hash_mode: str
 98        :param hash_names: ハッシュを計算する対象のファイル名のセット、またはNone
 99        :type hash_names: set[str] | None
100    戻り値:
101        :returns: メタデータ辞書とエラー文字列のリストのタプル
102        :rtype: tuple
103    """
104    records: dict[str, tuple[int, int, str | None]] = {}
105    errors: list[str] = []
106    for base, dirs, names in os.walk(root, followlinks=False):
107        base_path = Path(base)
108        dirs[:] = sorted(d for d in dirs if not (base_path / d).is_symlink()
109                         and (base_path / d).resolve() != excluded
110                         and not ignored((base_path / d).relative_to(root).as_posix(), patterns))
111        for name in sorted(names):
112            path = base_path / name
113            if path.is_symlink():
114                continue
115            rel = path.relative_to(root).as_posix()
116            if ignored(rel, patterns):
117                continue
118            try:
119                st = path.stat()
120                if not path.is_file():
121                    continue
122                digest = None
123                if hash_mode == "all" or (hash_names is not None and rel in hash_names):
124                    digest = sha256(path)
125                records[rel] = (st.st_size, st.st_mtime_ns, digest)
126            except OSError as exc:
127                errors.append(f"{rel}: {exc}")
128    return records, errors
129
130
131def sha256(path: Path) -> str:
132    """
133    概要:
134        指定されたファイルのSHA256ハッシュ値を計算して返します。
135    引数:
136        :param path: ハッシュ値を計算するファイルのパス
137        :type path: pathlib.Path
138    戻り値:
139        :returns: SHA256ハッシュ値の16進数文字列
140        :rtype: str
141    """
142    digest = hashlib.sha256()
143    with path.open("rb") as stream:
144        for block in iter(lambda: stream.read(1024 * 1024), b""):
145            digest.update(block)
146    return digest.hexdigest()
147
148
149def compare(before, after, root: Path, hash_mode: str):
150    """
151    概要:
152        コマンド実行前後のスナップショットを比較し、作成、変更、削除されたファイルのリストを返します。
153    引数:
154        :param before: 実行前のスナップショット辞書
155        :param after: 実行後のスナップショット辞書
156        :param root: 作業ディレクトリのルートパス
157        :param hash_mode: ハッシュによる比較モード
158    戻り値:
159        :returns: 作成されたファイル、変更されたファイル、削除されたファイルの各リストのタプル
160        :rtype: tuple
161    """
162    created = sorted(after.keys() - before.keys())
163    deleted = sorted(before.keys() - after.keys())
164    modified = []
165    for name in sorted(before.keys() & after.keys()):
166        old, new = before[name], after[name]
167        changed_stat = old[:2] != new[:2]
168        different = changed_stat
169        if hash_mode == "all":
170            # Hashes were recorded in both snapshots.
171            different = different or old[2] != new[2]
172        elif hash_mode == "changed" and changed_stat and old[2] is not None and new[2] is not None:
173            # Optimized mode hashes metadata candidates only and can miss a
174            # content change that preserves both size and modification time.
175            different = old[2] != new[2]
176        if different:
177            modified.append(name)
178    return created, modified, deleted
179
180
181def command_environment() -> dict:
182    """
183    概要:
184        実行環境のOS、CPU、メモリ、GPU、Pythonライブラリなどの情報を収集します。
185    詳細説明:
186        サードパーティの依存関係なしに、ホストやランタイムの有用な詳細情報を収集します。
187    戻り値:
188        :returns: 環境情報を格納した辞書
189        :rtype: dict
190    """
191    missing = "取得不可"
192    env = {
193        "取得時刻": now_iso(), "OS": platform.platform(),
194        "アーキテクチャ": platform.machine(), "Python": sys.version.replace("\n", " "),
195        "Python実行ファイル": sys.executable, "CPU": platform.processor() or missing,
196        "CPU論理コア数": os.cpu_count(), "物理メモリ合計": missing,
197        "利用可能メモリ(取得時点)": missing,
198    }
199    if platform.system() == "Linux":
200        try:
201            cpu = Path("/proc/cpuinfo").read_text(errors="replace")
202            names = re.findall(r"^model name\s*:\s*(.*)$", cpu, re.M)
203            if names:
204                env["CPU"] = "; ".join(dict.fromkeys(names))
205            cores = set()
206            for block in cpu.split("\n\n"):
207                fields = dict(line.split(":", 1) for line in block.splitlines() if ":" in line)
208                fields = {k.strip(): v.strip() for k, v in fields.items()}
209                if "physical id" in fields and "core id" in fields:
210                    cores.add((fields["physical id"], fields["core id"]))
211            if cores:
212                env["CPU物理コア数"] = len(cores)
213            mem = Path("/proc/meminfo").read_text()
214            for key, label in (("MemTotal", "物理メモリ合計"), ("MemAvailable", "利用可能メモリ(取得時点)")):
215                match = re.search(r"^" + key + r":\s*(\d+)\s+kB", mem, re.M)
216                if match:
217                    env[label] = f"{int(match[1]) / 1024**2:.2f} GiB"
218        except OSError:
219            pass
220    elif platform.system() == "Windows":
221        ps = ("[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; "
222              "$c=@(Get-CimInstance Win32_Processor); $o=Get-CimInstance Win32_OperatingSystem; "
223              "[pscustomobject]@{cpu=($c.Name -join '; '); cores=($c|Measure-Object NumberOfCores -Sum).Sum; "
224              "total=[double]$o.TotalVisibleMemorySize*1024; available=[double]$o.FreePhysicalMemory*1024}|ConvertTo-Json -Compress")
225        try:
226            raw = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", ps],
227                                 capture_output=True, timeout=10, text=True, encoding="utf-8", errors="replace").stdout
228            data = json.loads(raw.lstrip("\ufeff"))
229            env["CPU"] = data.get("cpu", env["CPU"])
230            env["CPU物理コア数"] = data.get("cores", missing)
231            for key, label in (("total", "物理メモリ合計"), ("available", "利用可能メモリ(取得時点)")):
232                env[label] = f"{float(data[key]) / 1024**3:.2f} GiB"
233        except (OSError, subprocess.TimeoutExpired, ValueError, KeyError, TypeError):
234            pass
235    if hasattr(os, "sched_getaffinity"):
236        try:
237            env["CPU affinityで利用可能な論理コア数"] = len(os.sched_getaffinity(0))
238        except OSError:
239            pass
240    env["GPU情報の範囲"] = "NVIDIAはnvidia-smiから取得。他社GPUは対象外。"
241    smi = shutil.which("nvidia-smi")
242    if not smi and os.name == "nt":
243        candidate = Path(os.environ.get("ProgramW6432", r"C:\Program Files")) / "NVIDIA Corporation" / "NVSMI" / "nvidia-smi.exe"
244        if candidate.is_file():
245            smi = str(candidate)
246    env["NVIDIA GPU"] = missing
247    env["NVIDIAドライバー"] = missing
248    env["CUDA(ドライバー対応上限・nvidia-smi)"] = missing
249    if smi:
250        try:
251            raw = subprocess.run([smi, "-q", "-x"], capture_output=True, timeout=10,
252                                 text=True, encoding="utf-8", errors="replace").stdout
253            import xml.etree.ElementTree as ET
254            root = ET.fromstring(raw) if raw else None
255            if root is not None:
256                env["NVIDIAドライバー"] = root.findtext("driver_version") or missing
257                env["CUDA(ドライバー対応上限・nvidia-smi)"] = root.findtext("cuda_version") or missing
258                env["NVIDIA GPU"] = [{"GPU": g.findtext("product_name") or missing,
259                                     "PCI bus ID": g.findtext("pci/pci_bus_id") or missing,
260                                     "VRAM合計": g.findtext("fb_memory_usage/total") or missing,
261                                     "VRAM使用量(取得時点)": g.findtext("fb_memory_usage/used") or missing,
262                                     "VRAM空き(取得時点)": g.findtext("fb_memory_usage/free") or missing}
263                                    for g in root.findall("gpu")] or missing
264        except (OSError, subprocess.TimeoutExpired, Exception):
265            pass
266        if env["CUDA(ドライバー対応上限・nvidia-smi)"] == missing:
267            try:
268                raw = subprocess.run([smi], capture_output=True, timeout=10, text=True,
269                                     encoding="utf-8", errors="replace").stdout
270                match = re.search(r"CUDA Version:\s*([\d.]+)", raw)
271                if match:
272                    env["CUDA(ドライバー対応上限・nvidia-smi)"] = match[1]
273            except (OSError, subprocess.TimeoutExpired):
274                pass
275    nvcc = shutil.which("nvcc")
276    if not nvcc and os.environ.get("CUDA_PATH"):
277        candidate = Path(os.environ["CUDA_PATH"]) / "bin" / ("nvcc.exe" if os.name == "nt" else "nvcc")
278        if candidate.is_file():
279            nvcc = str(candidate)
280    try:
281        env["CUDA Toolkit(nvcc)"] = subprocess.run([nvcc, "--version"], capture_output=True, timeout=10,
282                                                   text=True, encoding="utf-8", errors="replace").stdout.strip() if nvcc else "未検出"
283    except (OSError, subprocess.TimeoutExpired):
284        env["CUDA Toolkit(nvcc)"] = "未検出"
285    for name in ("numpy", "scipy", "matplotlib", "numba", "cupy", "cupy-cuda11x", "cupy-cuda12x", "cupy-cuda13x"):
286        try:
287            env["Pythonパッケージ " + name] = importlib.metadata.version(name)
288        except importlib.metadata.PackageNotFoundError:
289            pass
290    for name in ("CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
291        if name in os.environ:
292            env["環境変数 " + name] = os.environ[name]
293    env["注記"] = "レポート生成側の環境を記録しています。対象コマンドが別Python・コンテナー・リモート環境の場合は一致しないことがあります。"
294    return env
295
296
297def pump(pipe, path: Path, display: bool, display_lock: threading.Lock, source_encoding: str):
298    """
299    概要:
300        パイプからデータを読み込み、CRLFをLFに正規化してファイルに書き込みます。
301    詳細説明:
302        元のバイト列を保持しつつ、チャンクの境界を含めて改行コードを正規化します。必要に応じて標準出力に表示します。
303    引数:
304        :param pipe: 読み込み元のパイプストリーム
305        :param path: 書き込み先ファイルのパス
306        :type path: pathlib.Path
307        :param display: 標準出力へ表示するかどうかのフラグ
308        :type display: bool
309        :param display_lock: 標準出力への排他制御用ロックオブジェクト
310        :type display_lock: threading.Lock
311        :param source_encoding: 出力時のフォールバック用文字エンコーディング
312        :type source_encoding: str
313    """
314    pending_cr = False
315    with path.open("wb") as log:
316        while True:
317            block = pipe.read(65536)
318            data = (b"\r" if pending_cr else b"") + block
319            pending_cr = False
320            if data.endswith(b"\r"):
321                data = data[:-1]
322                pending_cr = True
323            normalized = data.replace(b"\r\n", b"\n")
324            if not block and pending_cr:
325                normalized += b"\r"
326                pending_cr = False
327            log.write(normalized)
328            if display and normalized:
329                with display_lock:
330                    try:
331                        sys.stdout.buffer.write(normalized)
332                        sys.stdout.buffer.flush()
333                    except (AttributeError, OSError):
334                        sys.stdout.write(normalized.decode(source_encoding, errors="replace"))
335                        sys.stdout.flush()
336            if not block:
337                break
338
339
340def terminate_process(proc: subprocess.Popen, shell: bool):
341    """
342    概要:
343        実行中のプロセスを安全に終了、または強制終了させます。
344    引数:
345        :param proc: 対象のプロセスオブジェクト
346        :type proc: subprocess.Popen
347        :param shell: シェル経由で実行されたかどうかのフラグ
348        :type shell: bool
349    """
350    if proc.poll() is not None:
351        return
352    try:
353        if os.name != "nt":
354            os.killpg(proc.pid, signal.SIGTERM)
355        else:
356            try:
357                subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"],
358                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
359                               timeout=5, check=False)
360            except (OSError, subprocess.TimeoutExpired):
361                proc.terminate()
362        proc.wait(timeout=3)
363    except (OSError, subprocess.TimeoutExpired):
364        try:
365            if os.name != "nt":
366                os.killpg(proc.pid, signal.SIGKILL)
367            else:
368                proc.kill()
369        except OSError:
370            pass
371
372
373def execute(command: list[str], cwd: Path, shell: bool, timeout: float, display: bool,
374            stdout_path: Path, stderr_path: Path, source_encoding: str):
375    """
376    概要:
377        指定されたコマンドを実行し、実行時間や終了コードなどの結果を返します。
378    引数:
379        :param command: 実行するコマンドとその引数のリスト
380        :type command: list[str]
381        :param cwd: 作業ディレクトリ
382        :type cwd: pathlib.Path
383        :param shell: シェル経由で実行するかどうかのフラグ
384        :type shell: bool
385        :param timeout: タイムアウト秒数
386        :type timeout: float
387        :param display: 標準出力を表示するかどうかのフラグ
388        :type display: bool
389        :param stdout_path: 標準出力を保存するファイルのパス
390        :type stdout_path: pathlib.Path
391        :param stderr_path: 標準エラー出力を保存するファイルのパス
392        :type stderr_path: pathlib.Path
393        :param source_encoding: ログ出力の文字エンコーディング
394        :type source_encoding: str
395    戻り値:
396        :returns: 実行結果の詳細を格納した辞書
397        :rtype: dict
398    """
399    started = now_iso()
400    t0 = time.perf_counter()
401    failure = ""
402    timed_out = False
403    returncode = None
404    popen_command = command
405    if shell:
406        popen_command = subprocess.list2cmdline(command) if os.name == "nt" else shlex.join(command)
407    try:
408        kwargs = {"start_new_session": os.name != "nt"}
409        if os.name == "nt":
410            kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
411        proc = subprocess.Popen(popen_command, cwd=cwd, shell=shell, stdout=subprocess.PIPE,
412                                stderr=subprocess.PIPE, **kwargs)
413        lock = threading.Lock()
414        out_thread = threading.Thread(target=pump, args=(proc.stdout, stdout_path, display, lock, source_encoding), daemon=True)
415        err_thread = threading.Thread(target=pump, args=(proc.stderr, stderr_path, display, lock, source_encoding), daemon=True)
416        out_thread.start(); err_thread.start()
417        try:
418            proc.wait(timeout=None if timeout <= 0 else timeout)
419            returncode = proc.returncode
420        except subprocess.TimeoutExpired:
421            timed_out = True
422            failure = f"タイムアウト({timeout:g} 秒)に達したため、プロセスを終了しました。"
423            terminate_process(proc, shell)
424            returncode = 124
425        except KeyboardInterrupt:
426            failure = "ユーザー操作で中断されました。"
427            terminate_process(proc, shell)
428            returncode = 130
429        out_thread.join(); err_thread.join()
430    except OSError as exc:
431        failure = f"コマンドを起動できませんでした: {exc}"
432        returncode = 127
433        stdout_path.touch(exist_ok=True); stderr_path.touch(exist_ok=True)
434    return {"started": started, "finished": now_iso(), "elapsed": time.perf_counter() - t0,
435            "returncode": returncode, "timed_out": timed_out, "failure": failure}
436
437
438def scan_text(relpath: str, text: str, error_re, warning_re, ignore_re, max_hits: int):
439    """
440    概要:
441        テキストの各行を走査し、エラーおよび警告の正規表現に一致する箇所を抽出します。
442    引数:
443        :param relpath: スキャン対象のファイルパス
444        :type relpath: str
445        :param text: スキャン対象のテキストデータ
446        :type text: str
447        :param error_re: エラーを検出するための正規表現オブジェクト
448        :param warning_re: 警告を検出するための正規表現オブジェクト
449        :param ignore_re: 無視する行を判定するための正規表現オブジェクト、またはNone
450        :param max_hits: 記録する最大の検出数
451        :type max_hits: int
452    戻り値:
453        :returns: 検出結果の辞書のリスト
454        :rtype: list
455    """
456    hits = []
457    for number, line in enumerate(text.splitlines(), 1):
458        if ignore_re and ignore_re.search(line):
459            continue
460        kind = "ERROR" if error_re.search(line) else "WARNING" if warning_re.search(line) else None
461        if kind:
462            hits.append({"file": relpath, "line": number, "kind": kind, "text": line.rstrip()})
463            if len(hits) >= max_hits:
464                break
465    return hits
466
467
468def scan_logs(root: Path, changed: list[str], out: Path, args):
469    """
470    概要:
471        変更されたファイルおよびログファイルを走査し、警告やエラーのメッセージを抽出します。
472    引数:
473        :param root: 検索対象のルートディレクトリ
474        :type root: pathlib.Path
475        :param changed: 変更されたファイル名のリスト
476        :type changed: list[str]
477        :param out: レポート出力ディレクトリ
478        :type out: pathlib.Path
479        :param args: コマンドライン引数を格納したオブジェクト
480    戻り値:
481        :returns: エラーおよび警告の検出結果のリスト
482        :rtype: list
483    """
484    error_re = re.compile(args.error_regex, re.IGNORECASE)
485    warning_re = re.compile(args.warning_regex, re.IGNORECASE)
486    ignore_re = re.compile(args.ignore_log_regex, re.IGNORECASE) if args.ignore_log_regex else None
487    exts = {x.lower() if x.startswith(".") else "." + x.lower() for x in parse_csv(args.log_exts)}
488    hits = []
489    candidates = [(root / n, n) for n in changed if (root / n).suffix.lower() in exts]
490    candidates.extend([(out / "stdout.log", "stdout.log"), (out / "stderr.log", "stderr.log")])
491    for path, label in candidates:
492        try:
493            with path.open("rb") as stream:
494                data = stream.read(args.max_read_bytes + 1)
495            truncated = len(data) > args.max_read_bytes
496            text = data[:args.max_read_bytes].decode(args.encoding, errors="replace")
497            file_hits = scan_text(label, text, error_re, warning_re, ignore_re, args.max_hits_per_file)
498            if truncated and file_hits:
499                file_hits[-1]["text"] += " [読み込み上限に達しました]"
500            hits.extend(file_hits)
501        except OSError:
502            continue
503    return hits
504
505
506def copy_artifacts(root: Path, out: Path, names: list[str]):
507    """
508    概要:
509        コマンド実行によって生成または変更されたファイルを成果物ディレクトリにコピーします。
510    引数:
511        :param root: コピー元となるルートディレクトリ
512        :type root: pathlib.Path
513        :param out: レポート出力ディレクトリ
514        :type out: pathlib.Path
515        :param names: コピー対象のファイル名のリスト
516        :type names: list[str]
517    戻り値:
518        :returns: コピーされたファイルのパス辞書とエラーメッセージのリストのタプル
519        :rtype: tuple
520    """
521    errors = []
522    copied = {}
523    for name in names:
524        source = root / name
525        destination = out / "artifacts" / name
526        try:
527            destination.parent.mkdir(parents=True, exist_ok=True)
528            shutil.copy2(source, destination)
529            copied[name] = Path("artifacts") / name
530        except OSError as exc:
531            errors.append(f"{name}: {exc}")
532    return copied, errors
533
534
535def human_size(value: int) -> str:
536    """
537    概要:
538        バイト単位のファイルサイズを人間が読みやすい形式に変換します。
539    引数:
540        :param value: バイト単位のファイルサイズ
541        :type value: int
542    戻り値:
543        :returns: 単位付きのファイルサイズの文字列
544        :rtype: str
545    """
546    units = ("B", "KiB", "MiB", "GiB", "TiB")
547    size = float(value)
548    for unit in units:
549        if size < 1024 or unit == units[-1]:
550            return f"{int(size)} {unit}" if unit == "B" else f"{size:.2f} {unit}"
551        size /= 1024
552    return f"{value} B"
553
554
555def make_rows(names, before, after, copied):
556    """
557    概要:
558        レポート表示用のファイル比較行データを生成します。
559    引数:
560        :param names: 対象のファイル名のリスト
561        :param before: 実行前のメタデータ辞書
562        :param after: 実行後のメタデータ辞書
563        :param copied: コピーされた成果物のパス辞書
564    戻り値:
565        :returns: 各ファイルの比較結果を含む辞書のリスト
566        :rtype: list
567    """
568    rows = []
569    for name in names:
570        old, new = before.get(name), after.get(name)
571        rows.append({"name": name, "old_size": old[0] if old else None,
572                     "new_size": new[0] if new else None,
573                     "artifact": copied.get(name)})
574    return rows
575
576
577def make_html(data: dict, out: Path, encoding: str, max_chars: int) -> str:
578    """
579    概要:
580        実行結果のレポートをHTML形式で作成します。
581    引数:
582        :param data: レポートに記載する実行結果データ
583        :type data: dict
584        :param out: 出力ディレクトリのパス
585        :type out: pathlib.Path
586        :param encoding: ログファイルの文字エンコーディング
587        :type encoding: str
588        :param max_chars: レポートに含めるログの最大文字数
589        :type max_chars: int
590    戻り値:
591        :returns: 生成されたHTML文字列
592        :rtype: str
593    """
594    e = html.escape
595    def table(rows):
596        if not rows:
597            return "<p>なし</p>"
598        body = []
599        for row in rows:
600            name = e(row["name"])
601            if row["artifact"]:
602                href = quote(row["artifact"].as_posix(), safe="/")
603                name = f'<a href="{e(href, quote=True)}">{name}</a>'
604            old = "—" if row["old_size"] is None else str(row["old_size"])
605            new = "—" if row["new_size"] is None else str(row["new_size"])
606            body.append(f"<tr><td>{name}</td><td>{old}</td><td>{new}</td></tr>")
607        return "<table><tr><th>ファイル</th><th>実行前 bytes</th><th>実行後 bytes</th></tr>" + "".join(body) + "</table>"
608    stdout = (out / "stdout.log").read_bytes().decode(encoding, errors="replace")
609    stderr = (out / "stderr.log").read_bytes().decode(encoding, errors="replace")
610    env_rows = "".join(f"<tr><th>{e(str(k))}</th><td><pre>{e(json.dumps(v, ensure_ascii=False, indent=2) if isinstance(v, (dict,list)) else str(v))}</pre></td></tr>" for k,v in data["environment"].items())
611    hits = "<p>該当なし</p>" if not data["hits"] else "<table><tr><th>種類</th><th>ファイル</th><th>行</th><th>内容</th></tr>" + "".join(f"<tr><td>{e(h['kind'])}</td><td>{e(h['file'])}</td><td>{h['line']}</td><td>{e(h['text'])}</td></tr>" for h in data["hits"][:data["max_log_hits"]]) + "</table>"
612    images = []
613    for name in data["created"] + data["modified"]:
614        artifact = data["copied"].get(name)
615        if artifact and Path(name).suffix.lower() in IMAGE_EXTS:
616            href = quote(artifact.as_posix(), safe="/")
617            images.append(f'<details><summary>{e(name)}</summary><a href="{e(href, quote=True)}"><img loading="lazy" src="{e(href, quote=True)}" alt="{e(name, quote=True)}"></a></details>')
618    def log_block(text):
619        clipped = text[:max_chars]
620        if len(text) > max_chars:
621            clipped += "\n\n... レポート表示を省略しました。完全なログは同梱ファイルを参照してください ..."
622        return f"<pre>{e(clipped)}</pre>"
623    cmd = subprocess.list2cmdline(data["command"]) if os.name == "nt" else shlex.join(data["command"])
624    return f'''<!doctype html><html lang="ja"><head><meta charset="utf-8"><title>コマンド実行レポート</title>
625<style>body{{font-family:system-ui,sans-serif;max-width:1100px;margin:32px auto;padding:0 16px;line-height:1.6}}pre{{white-space:pre-wrap;overflow-wrap:anywhere;background:#f3f5f7;padding:16px}}details{{border:1px solid #ccd3dc;border-radius:6px;padding:12px;margin:12px 0}}summary{{cursor:pointer;font-weight:bold}}table{{border-collapse:collapse;width:100%;margin-top:12px}}th,td{{border:1px solid #ddd;padding:6px;text-align:left;overflow-wrap:anywhere}}img{{max-width:100%;height:auto}}</style></head><body>
626<h1>コマンド実行レポート</h1><p>作業ディレクトリ: {e(data['cwd'])}<br>開始: {e(data['started'])}<br>終了: {e(data['finished'])}<br>実行時間: {data['elapsed']:.6f} 秒<br>終了コード: {data['returncode']}<br>タイムアウト: {data['timed_out']}<br>差分ハッシュ方式: {e(data['hash_mode'])}</p>
627<pre>{e(cmd)}</pre>{('<p>'+e(data['failure'])+'</p>') if data['failure'] else ''}
628<details open><summary>実行環境</summary><p><a href="environment.json">environment.json</a></p><table>{env_rows}</table></details>
629<details><summary>標準出力</summary><p><a href="stdout.log">stdout.log</a></p>{log_block(stdout)}</details><details><summary>標準エラー</summary><p><a href="stderr.log">stderr.log</a></p>{log_block(stderr)}</details>
630<details open><summary>新規作成 ({len(data['created'])})</summary>{table(data['rows_created'])}</details><details open><summary>更新 ({len(data['modified'])})</summary>{table(data['rows_modified'])}</details><details open><summary>削除 ({len(data['deleted'])})</summary>{table(data['rows_deleted'])}</details>
631<details><summary>警告・エラー検出 ({len(data['hits'])})</summary>{hits}</details><details><summary>新規・更新画像 ({len(images)})</summary>{''.join(images) or '<p>なし</p>'}</details>
632<details><summary>比較時・コピー時のエラー ({len(data['errors'])})</summary><pre>{e(chr(10).join(data['errors']))}</pre></details>
633<p>比較は作業ディレクトリ以下の通常ファイルを対象とし、除外パターンと出力フォルダーを除きます。実行中に作成・削除されたファイルは検出できません。新規・更新ファイルは artifacts/ 以下にコピーされています。</p></body></html>'''
634
635
636def md_escape(text: str) -> str:
637    """
638    概要:
639        Markdownテーブル内で使用するために特殊文字をエスケープします。
640    引数:
641        :param text: エスケープ対象の文字列
642        :type text: str
643    戻り値:
644        :returns: エスケープ処理された文字列
645        :rtype: str
646    """
647    return text.replace("|", r"\|").replace("\n", " ")
648
649
650def make_markdown(data: dict, out: Path, encoding: str, max_chars: int) -> str:
651    """
652    概要:
653        実行結果のレポートをMarkdown形式で作成します。
654    引数:
655        :param data: レポートに記載する実行結果データ
656        :type data: dict
657        :param out: 出力ディレクトリのパス
658        :type out: pathlib.Path
659        :param encoding: ログファイルの文字エンコーディング
660        :type encoding: str
661        :param max_chars: レポートに含めるログの最大文字数
662        :type max_chars: int
663    戻り値:
664        :returns: 生成されたMarkdown文字列
665        :rtype: str
666    """
667    lines = ["# コマンド実行レポート", "", "| 項目 | 値 |", "|---|---|",
668             f"| 作業ディレクトリ | {md_escape(data['cwd'])} |", f"| 開始 | {data['started']} |",
669             f"| 終了 | {data['finished']} |", f"| 実行時間 | {data['elapsed']:.6f} 秒 |",
670             f"| 終了コード | {data['returncode']} |", f"| タイムアウト | {data['timed_out']} |", f"| 差分ハッシュ方式 | {data['hash_mode']} |", "", "## コマンド", "",
671             "```text", subprocess.list2cmdline(data["command"]) if os.name == "nt" else shlex.join(data["command"]), "```", ""]
672    if data["failure"]:
673        lines += [f"実行状態: {md_escape(data['failure'])}", ""]
674    for title, names, rows in (("新規作成", data["created"], data["rows_created"]), ("更新", data["modified"], data["rows_modified"]), ("削除", data["deleted"], data["rows_deleted"])):
675        lines += [f"## {title} ({len(names)})", "", "| ファイル | 実行前 bytes | 実行後 bytes |", "|---|---:|---:|"]
676        if not rows:
677            lines += ["| なし | | |"]
678        for row in rows:
679            label = md_escape(row["name"])
680            if row["artifact"]:
681                label = f"[{label}](<{row['artifact'].as_posix()}>)"
682            lines.append(f"| {label} | {row['old_size'] if row['old_size'] is not None else '—'} | {row['new_size'] if row['new_size'] is not None else '—'} |")
683        lines.append("")
684    lines += ["## 警告・エラー検出", ""]
685    if not data["hits"]:
686        lines += ["該当なし。", ""]
687    else:
688        lines += ["| 種類 | ファイル | 行 | 内容 |", "|---|---|---:|---|"]
689        for hit in data["hits"][:data["max_log_hits"]]:
690            lines.append(f"| {hit['kind']} | {md_escape(hit['file'])} | {hit['line']} | {md_escape(hit['text'])} |")
691        lines.append("")
692    for label, filename in (("標準出力", "stdout.log"), ("標準エラー", "stderr.log")):
693        text = (out / filename).read_bytes().decode(encoding, errors="replace")
694        clipped = text[:max_chars]
695        if len(text) > max_chars:
696            clipped += "\n\n... レポート表示を省略しました。完全なログは同梱ファイルを参照してください ..."
697        fence = "````" if "```" in clipped else "```"
698        lines += [f"## {label}", "", f"ログファイル: [{filename}](<{filename}>)", "", fence + "text", clipped.rstrip() or "(出力なし)", fence, ""]
699    lines += ["## 実行環境", "", "詳細は [environment.json](<environment.json>) を参照してください。", "", "```json", json.dumps(data["environment"], ensure_ascii=False, indent=2), "```", ""]
700    images = [n for n in data["created"] + data["modified"] if n in data["copied"] and Path(n).suffix.lower() in IMAGE_EXTS]
701    lines += ["## 新規・更新画像", ""]
702    lines.extend(f"![{md_escape(n)}](<{data['copied'][n].as_posix()}>)" for n in images)
703    if not images:
704        lines.append("該当なし。")
705    lines.append("")
706    if data["errors"]:
707        lines += ["## 比較・コピー時のエラー", "", "```text", *data["errors"], "```", ""]
708    return "\n".join(lines)
709
710
711def build_parser():
712    """
713    概要:
714        コマンドライン引数のパーサーを構築します。
715    戻り値:
716        :returns: コマンドライン引数を解析するためのパーサーオブジェクト
717        :rtype: argparse.ArgumentParser
718    """
719    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter,
720        epilog="例: python run_report.py --cwd ./case --timeout 3600 --ignore .git,.venv,__pycache__ --cmd python simulate.py --temperature 300")
721    p.add_argument("--cwd", type=Path, default=Path.cwd(), help="実行・比較する作業ディレクトリ")
722    p.add_argument("--output-dir", type=Path, help="専用レポートフォルダー。既定はcwd/run_report_日時")
723    p.add_argument("--timeout", type=float, default=0, help="タイムアウト秒。0以下は無制限")
724    p.add_argument("--shell", action="store_true", help="シェル経由で実行(パイプやリダイレクト向け)")
725    p.add_argument("--display-output", choices=("combined", "none"), default="combined", help="実行中の画面表示")
726    p.add_argument("--format", choices=("html", "md", "both"), default="html", help="生成するレポート形式")
727    p.add_argument("--ignore", default=DEFAULT_IGNORE, help="比較から除外するfnmatchパターン(カンマ区切り)")
728    p.add_argument("--hash", choices=("none", "changed", "all"), default="all", dest="hash_mode",
729                   help="none=サイズ/日時で判定、changed=候補のみハッシュ、all=全ファイルSHA256で判定")
730    p.add_argument("--log-exts", default=DEFAULT_LOG_EXTS, help="走査するログ拡張子")
731    p.add_argument("--error-regex", default=DEFAULT_ERROR_RE, help="ERRORとして検出する正規表現")
732    p.add_argument("--warning-regex", default=DEFAULT_WARNING_RE, help="WARNINGとして検出する正規表現")
733    p.add_argument("--ignore-log-regex", default="", help="ログ走査時に除外する正規表現")
734    p.add_argument("--encoding", default=locale.getpreferredencoding(False), help="対象コマンドおよびログの文字コード")
735    p.add_argument("--max-read-bytes", type=int, default=2_000_000, help="走査時に各ログから読む最大バイト数")
736    p.add_argument("--max-output-chars", type=int, default=30_000, help="レポート内のstdout/stderr表示上限")
737    p.add_argument("--max-log-hits", type=int, default=300, help="レポートに表示する警告・エラー数")
738    p.add_argument("--max-hits-per-file", type=int, default=100, help="各ファイルから記録する警告・エラー数")
739    p.add_argument("--cmd", nargs=argparse.REMAINDER, required=True, help="実行コマンドと引数。最後に指定")
740    return p
741
742
743def main() -> int:
744    """
745    概要:
746        スクリプトのエントリポイントです。引数をパースし、コマンドを実行してレポートを生成します。
747    戻り値:
748        :returns: プロセスの終了コード
749        :rtype: int
750    """
751    args = build_parser().parse_args()
752    command = args.cmd
753    if command and command[0] == "--":
754        command = command[1:]
755    if not command:
756        print("ERROR: --cmd の後にコマンドを指定してください", file=sys.stderr)
757        return 2
758    try:
759        "".encode(args.encoding)
760    except LookupError:
761        print(f"ERROR: 不明な文字コードです: {args.encoding}", file=sys.stderr)
762        return 2
763    if args.max_read_bytes < 0 or args.max_output_chars < 0 or args.max_log_hits < 0 or args.max_hits_per_file < 1:
764        print("ERROR: 上限値が不正です", file=sys.stderr)
765        return 2
766    try:
767        re.compile(args.error_regex); re.compile(args.warning_regex)
768        if args.ignore_log_regex:
769            re.compile(args.ignore_log_regex)
770    except re.error as exc:
771        print(f"ERROR: 正規表現が不正です: {exc}", file=sys.stderr)
772        return 2
773    cwd = args.cwd.resolve()
774    if not cwd.is_dir():
775        print(f"ERROR: 作業ディレクトリがありません: {cwd}", file=sys.stderr)
776        return 2
777    out = (args.output_dir if args.output_dir else Path("run_report_" + datetime.now().strftime("%Y%m%d_%H%M%S_%f")))
778    out = (cwd / out).resolve() if not out.is_absolute() else out.resolve()
779    try:
780        out.mkdir(parents=True, exist_ok=False)
781    except OSError as exc:
782        print(f"ERROR: 新しい出力フォルダーを作成できません: {exc}", file=sys.stderr)
783        return 2
784    excluded = out if out.is_relative_to(cwd) else None
785    patterns = parse_csv(args.ignore)
786    environment = command_environment()
787    (out / "environment.json").write_text(json.dumps(environment, ensure_ascii=False, indent=2), encoding="utf-8")
788    # "changed" keeps before-run hashes, then hashes only files whose size or
789    # mtime changed after the command. "all" hashes every file on both passes.
790    before, errors_before = snapshot(cwd, excluded, patterns,
791                                     "all" if args.hash_mode in ("all", "changed") else "none")
792    stdout_path, stderr_path = out / "stdout.log", out / "stderr.log"
793    display = args.display_output == "combined"
794    print(f"[run_report] cwd: {cwd}\n[run_report] command: {command}", flush=True)
795    result = execute(command, cwd, args.shell, args.timeout, display, stdout_path, stderr_path, args.encoding)
796    after, errors_after = snapshot(cwd, excluded, patterns, "all" if args.hash_mode == "all" else "none")
797    if args.hash_mode == "changed":
798        candidates = {name for name in before.keys() & after.keys() if before[name][:2] != after[name][:2]}
799        for name in candidates:
800            try:
801                size, mtime, _ = after[name]
802                after[name] = (size, mtime, sha256(cwd / name))
803            except OSError:
804                pass
805    created, modified, deleted = compare(before, after, cwd, args.hash_mode)
806    changed = created + modified
807    copied, copy_errors = copy_artifacts(cwd, out, changed)
808    hits = scan_logs(cwd, changed, out, args)
809    data = {**result, "cwd": str(cwd), "command": command, "environment": environment, "hash_mode": args.hash_mode,
810            "created": created, "modified": modified, "deleted": deleted, "copied": copied,
811            "hits": hits, "max_log_hits": args.max_log_hits,
812            "rows_created": make_rows(created, before, after, copied),
813            "rows_modified": make_rows(modified, before, after, copied),
814            "rows_deleted": make_rows(deleted, before, after, copied),
815            "errors": ["実行前: " + x for x in errors_before] + ["実行後: " + x for x in errors_after] + copy_errors}
816    if args.format in ("html", "both"):
817        (out / "report.html").write_text(make_html(data, out, args.encoding, args.max_output_chars), encoding="utf-8")
818    if args.format in ("md", "both"):
819        (out / "report.md").write_text(make_markdown(data, out, args.encoding, args.max_output_chars), encoding="utf-8", newline="\n")
820    print(f"\n[run_report] New={len(created)}, Modified={len(modified)}, Deleted={len(deleted)}")
821    print(f"[run_report] Report folder: {out}")
822    if args.format in ("html", "both"):
823        print(f"[run_report] HTML: {out / 'report.html'}")
824    if args.format in ("md", "both"):
825        print(f"[run_report] Markdown: {out / 'report.md'}")
826    return int(result["returncode"] if result["returncode"] is not None else 1)
827
828
829if __name__ == "__main__":
830    sys.exit(main())