(
path: Path,
*,
max_depth: int,
dirs_only: bool,
show_size: bool,
sort_by_size: bool,
include_hidden: bool,
follow_symlinks: bool,
ignore: List[str],
only: List[str],
)
| 449 | JsonNode = Union[str, Dict[str, "JsonNode"], Dict[str, Union[str, int]]] |
| 450 | |
| 451 | def build_json( |
| 452 | path: Path, |
| 453 | *, |
| 454 | max_depth: int, |
| 455 | dirs_only: bool, |
| 456 | show_size: bool, |
| 457 | sort_by_size: bool, |
| 458 | include_hidden: bool, |
| 459 | follow_symlinks: bool, |
| 460 | ignore: List[str], |
| 461 | only: List[str], |
| 462 | ) -> Dict[str, JsonNode]: |
| 463 | def file_value(p: Path) -> JsonNode: |
| 464 | if show_size: |
| 465 | st = safe_lstat(p) |
| 466 | return {"type": "file", "size": int(st.st_size) if st else 0} |
| 467 | return "file" |
| 468 | |
| 469 | def _walk(cur: Path, depth: int) -> Dict[str, JsonNode]: |
| 470 | if max_depth != -1 and depth > max_depth: |
| 471 | return {} |
| 472 | need_sizes = show_size or sort_by_size |
| 473 | ents = scan_entries( |
| 474 | cur, |
| 475 | dirs_only=dirs_only, |
| 476 | include_hidden=include_hidden, |
| 477 | need_sizes=need_sizes, |
| 478 | sort_by_size=sort_by_size, |
| 479 | follow_symlinks=follow_symlinks, |
| 480 | ignore=ignore, |
| 481 | only=only, |
| 482 | ) |
| 483 | out: Dict[str, JsonNode] = {} |
| 484 | for e in ents: |
| 485 | if e.is_dir: |
| 486 | child = _walk(e.path, depth + 1) |
| 487 | out[e.name] = {"type": "dir", "size": e.total_size, "children": child} if show_size else child |
| 488 | else: |
| 489 | out[e.name] = file_value(e.path) |
| 490 | return out |
| 491 | |
| 492 | root_name = str(path) |
| 493 | if path.is_dir(): |
| 494 | tree = _walk(path, 1) |
| 495 | if show_size: |
| 496 | root_size = get_total_size( |
| 497 | path, |
| 498 | follow_symlinks=follow_symlinks, |
| 499 | ignore=ignore, |
| 500 | only=only, |
| 501 | include_hidden=include_hidden, |
| 502 | stats=None, |
| 503 | ) |
| 504 | return {root_name: {"type": "dir", "size": root_size, "children": tree}} |
| 505 | return {root_name: tree} |
| 506 | |
| 507 | return {root_name: file_value(path)} |
| 508 |
no test coverage detected