| 1 |
"""A simple utility for constructing filesystem-like trees from beets |
| 2 |
libraries. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
from typing import TYPE_CHECKING, NamedTuple |
| 8 |
|
| 9 |
from beets import util |
| 10 |
|
| 11 |
if TYPE_CHECKING: |
| 12 |
from collections.abc import Sequence |
| 13 |
|
| 14 |
from beets.library import Library |
| 15 |
|
| 16 |
|
| 17 |
class Node(NamedTuple): |
| 18 |
files: dict[str, int] |
| 19 |
# Maps filenames to Item ids. |
| 20 |
|
| 21 |
dirs: dict[str, Node] |
| 22 |
# Maps directory names to child nodes. |
| 23 |
|
| 24 |
|
| 25 |
def _insert(node: Node, path: Sequence[str], itemid: int) -> None: |
| 26 |
"""Insert an item into a virtual filesystem node.""" |
| 27 |
if len(path) == 1: |
| 28 |
# Last component. Insert file. |
| 29 |
node.files[path[0]] = itemid |
| 30 |
else: |
| 31 |
# In a directory. |
| 32 |
dirname = path[0] |
| 33 |
rest = path[1:] |
| 34 |
if dirname not in node.dirs: |
| 35 |
node.dirs[dirname] = Node({}, {}) |
| 36 |
_insert(node.dirs[dirname], rest, itemid) |
| 37 |
|
| 38 |
|
| 39 |
def libtree(lib: Library) -> Node: |
| 40 |
"""Generates a filesystem-like directory tree for the files |
| 41 |
contained in `lib`. Filesystem nodes are (files, dirs) named |
| 42 |
tuples in which both components are dictionaries. The first |
| 43 |
maps filenames to Item ids. The second maps directory names to |
| 44 |
child node tuples. |
| 45 |
""" |
| 46 |
root = Node({}, {}) |
| 47 |
for item in lib.items(): |
| 48 |
if item.id is None: |
| 49 |
continue |
| 50 |
dest = item.destination(relative_to_libdir=True) |
| 51 |
parts = util.components(util.as_string(dest)) |
| 52 |
_insert(root, parts, item.id) |
| 53 |
return root |