Word count with the same (size, mtime_ns) stat-fastpath cache as :func:`file_hash`, persisted in the shared stat index. ``detect()`` counts words in every PDF/docx/text file to size the corpus, which re-opens and re-parses every binary on each run — minutes on a large docs corpus ev
(path: Path, root: Path, compute, cache_root: "Path | None" = None)
| 725 | |
| 726 | |
| 727 | def cached_word_count(path: Path, root: Path, compute, cache_root: "Path | None" = None) -> int: |
| 728 | """Word count with the same (size, mtime_ns) stat-fastpath cache as |
| 729 | :func:`file_hash`, persisted in the shared stat index. |
| 730 | |
| 731 | ``detect()`` counts words in every PDF/docx/text file to size the corpus, |
| 732 | which re-opens and re-parses every binary on each run — minutes on a large |
| 733 | docs corpus even when only a handful of files changed (#1656). This caches |
| 734 | the count against the file's stat signature so an unchanged file is counted |
| 735 | once and read from the index thereafter. ``compute(path)`` produces the |
| 736 | count on a miss. A file that can't be stat'd (e.g. a Windows long path the |
| 737 | index normalization can't reach) simply recomputes and isn't cached — |
| 738 | correct, just not accelerated. |
| 739 | """ |
| 740 | global _stat_index_dirty |
| 741 | raw_path = Path(path) |
| 742 | raw_root = Path(root) |
| 743 | src = Path(_os_long_path(raw_path)) |
| 744 | _ensure_stat_index(_normalize_path(raw_root), cache_root=cache_root) |
| 745 | abs_key = _resolved_key(src) |
| 746 | st: "os.stat_result | None" = None |
| 747 | try: |
| 748 | st = src.stat() |
| 749 | entry = _stat_index.get(abs_key) |
| 750 | if entry is not None and _stat_sig_fresh(entry, st) and "word_count" in entry: |
| 751 | return entry["word_count"] |
| 752 | except OSError: |
| 753 | pass |
| 754 | |
| 755 | # Captured BEFORE compute() reads the file, for the same reason file_hash |
| 756 | # stamps before its read (see _stat_sig_fresh). |
| 757 | observed_at_ns = time.time_ns() |
| 758 | wc = compute(raw_path) |
| 759 | |
| 760 | if st is not None: |
| 761 | _stat_entry_for(abs_key, st, observed_at_ns)["word_count"] = wc |
| 762 | _stat_index_dirty = True |
| 763 | |
| 764 | return wc |
| 765 | |
| 766 | |
| 767 | # MD5 of each file's raw bytes, recorded by the one build-time read that |
nothing calls this directly
no test coverage detected