Metadata-Version: 2.4
Name: vcti-path-tree
Version: 2.0.0
Summary: VCollab Path Tree - directory tree scanning and serialization using Pydantic models
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-path-tree
Project-URL: Changelog, https://github.com/vcollab/vcti-python-path-tree/blob/main/CHANGELOG.md
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0.2
Requires-Dist: vcti-enum>=1.0.3
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# Path Tree

VCollab Path Tree - directory tree scanning and serialization using Pydantic models.

## Overview

`vcti-path-tree` scans a directory into a tree of Pydantic models, so a
directory structure can be returned from an API, stored as JSON, or printed
as a CLI-style tree without ad-hoc processing at every call site. A scan
produces a `PathTree`: a list of `Directory`, `File` and `Symlink` nodes,
where each `Directory` holds its `children`. Links inside the scanned
directory are reported but never followed, so a scan reads nothing outside
it. Scans can store paths relative to a base directory, use forward slashes
on every OS, limit depth, filter entries with a callback, and record
modification times. Once scanned, a tree can be walked, summarized, rendered as
text, and rebuilt from its serialized form.

---

## Installation

```bash
pip install vcti-path-tree
```

### In `requirements.txt`

```
vcti-path-tree>=2.0.0
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-path-tree>=2.0.0",
]
```

---

## Quick Start

The examples below scan `project_dir`, a directory laid out like this:

```
project/
├── src/
│   ├── main.py
│   └── utils.py
└── README.md
```

### Scan and print

```python
from vcti.pathtree import get_cli_tree, get_path_tree

tree = get_path_tree(project_dir)

for line in get_cli_tree(tree):
    print(line)
# project/
# ├── README.md
# └── src/
#     ├── main.py
#     └── utils.py

root = tree[0]
print(root.name)  # project
print(root.type)  # directory
for child in root.children:
    print(f"  {child.name} ({child.type})")
```

### Relative, forward-slash paths

Without `base_path`, every node's path keeps the form you passed in:
absolute for an absolute `path`, relative for a relative one. Pass
`base_path` to store paths relative to it, and `as_posix=True` for forward
slashes on every OS:

```python
tree = get_path_tree(project_dir, base_path=project_dir.parent, as_posix=True)
print(tree[0].path)  # project
print(tree[0].children[1].children[0].path)  # project/src/main.py
```

### Shaping the scan

```python
# Only the children of the scanned directory, without the root node
children = get_path_tree(project_dir, skip_root=True)

# Recurse at most one level of subdirectories below the root
shallow = get_path_tree(project_dir, max_depth=1)

# Leave out hidden entries and anything below them
visible = get_path_tree(project_dir, filter_fn=lambda p: not p.name.startswith("."))

# Record modified_time on every node
with_times = get_path_tree(project_dir, include_metadata=True)
```

### Walk, summarize, serialize

```python
import json

from vcti.pathtree import get_tree_stats, parse_path_tree, walk_tree

tree = get_path_tree(project_dir, base_path=project_dir.parent, as_posix=True)

for dir_path, dirs, files in walk_tree(tree):
    print(dir_path, [f.name for f in files])
# project ['README.md']
# project/src ['main.py', 'utils.py']

stats = get_tree_stats(tree)
print(stats.total_files, stats.total_dirs, stats.max_depth)  # 3 2 1

data = [node.model_dump(mode="json") for node in tree]
text = json.dumps(data, indent=2)
restored = parse_path_tree(json.loads(text))
assert restored == tree
```

---

## Public API

| Name | Kind | Description |
|------|------|-------------|
| `get_path_tree(...)` | Function | Scan a file or directory into a `PathTree` |
| `handle_file(...)` | Function | Build a `File` model for one file |
| `handle_directory(...)` | Function | Build a `Directory` model, recursing into children |
| `handle_symlink(...)` | Function | Build a `Symlink` model for one link, without following it |
| `get_cli_tree(path_tree)` | Function | Render a tree as box-drawing text lines |
| `walk_tree(tree)` | Function | Yield `(dir_path, dirs, files)` tuples, like `os.walk` |
| `get_tree_stats(tree)` | Function | Count files, directories and links, sum sizes, find max depth |
| `parse_path_tree(data)` | Function | Rebuild a `PathTree` from a list of dicts; each node's `type` picks its model |
| `File` | Model | File node: `name`, `path`, `size`, optional `modified_time` |
| `Directory` | Model | Directory node: `name`, `path`, `children`, optional `modified_time` |
| `Symlink` | Model | Link node (symbolic link or Windows junction): `name`, `path`, optional `modified_time`; never followed |
| `PathBase` | Model | Common base of the node models: `name`, `path`, `type` |
| `PathType` | Enum | `FILE` (`"file"`), `DIRECTORY` (`"directory"`) or `SYMLINK` (`"symlink"`) |
| `TreeStats` | Model | `total_files`, `total_dirs`, `total_symlinks`, `total_size`, `max_depth` |
| `PathTree` | Type alias | `list[Directory \| File \| Symlink]` |
| `PathNode` | Type alias | `Directory \| File \| Symlink` discriminated by `type`, for use in your own Pydantic models |
| `FilterFn` | Type alias | `Callable[[Path], bool]`, the `filter_fn` signature |

### `get_path_tree` parameters

| Parameter | Default | Effect |
|---|---|---|
| `base_path` | `None` | Store paths relative to this ancestor; when `None`, paths keep the form `path` was given in |
| `as_posix` | `False` | Use forward slashes in paths |
| `skip_root` | `False` | Return the root's children instead of the root (empty list for a file) |
| `max_depth` | `None` | Levels of subdirectories to recurse into; `0` gives the root alone; a negative value raises `ValueError` |
| `filter_fn` | `None` | Keep entries for which it returns `True`; links are passed to it too; not applied to the root |
| `include_metadata` | `False` | Populate `modified_time` |

`filter_fn` is your own code and runs before the scanner classifies an
entry, so it sees links too. Calls such as `p.is_dir()` or `p.stat()`
read through a link to its target, which may be outside the scanned
directory; decide from `p.name` or `p.suffix`, or use `p.lstat()`, to
keep the filter inside it.

A path that does not exist gives an empty list; any other error reading
it, such as a permission error, is raised. Each directory's children
are sorted by name, ignoring case, in the same order on every OS.

### Links and special files

Entries are classified without reading through them:

| Entry found during the scan | In the tree |
|---|---|
| Regular file | `File` |
| Directory | `Directory`, scanned recursively |
| Symbolic link or Windows junction | `Symlink`, never followed; its target is not recorded |
| FIFO, socket, device file | left out |

The scanned `path` itself is read through if it is a link, so a data
directory deployed as a link can be scanned directly. To drop links from
the tree, filter them out:

```python
no_links = get_path_tree(project_dir, filter_fn=lambda p: not p.is_symlink())
```

In `get_cli_tree()` output, links end in `@`, as `ls -F` marks them.
`walk_tree()` lists neither links nor special files; read
`Directory.children` to see links.

---

## Limitations

- **Errors propagate.** If an entry cannot be read, `OSError` is raised;
  there is no partial-tree or skip-on-error mode.
- **The whole tree is held in memory.** There is no streaming mode.

---

## Dependencies

- [`pydantic`](https://pypi.org/project/pydantic/) — the tree node models
  and their serialization.
- [`vcti-enum`](https://pypi.org/project/vcti-enum/) — the lowercase-valued
  `PathType` enum.

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | Quick Start above |
| Understand the design decisions and trade-offs | [docs/design.md](docs/design.md) |
| Run a complete example | [examples/basic_usage.py](examples/basic_usage.py) |
