1# -*- coding: utf-8 -*-
2# This file is part of beets.
3# Copyright 2016, Adrian Sampson.
4#
5# Permission is hereby granted, free of charge, to any person obtaining
6# a copy of this software and associated documentation files (the
7# "Software"), to deal in the Software without restriction, including
8# without limitation the rights to use, copy, modify, merge, publish,
9# distribute, sublicense, and/or sell copies of the Software, and to
10# permit persons to whom the Software is furnished to do so, subject to
11# the following conditions:
12#
13# The above copyright notice and this permission notice shall be
14# included in all copies or substantial portions of the Software.
15
16"""A simple utility for constructing filesystem-like trees from beets
17libraries.
18"""
19from __future__ import division, absolute_import, print_function
20
21from collections import namedtuple
22from beets import util
23
24Node = namedtuple('Node', ['files', 'dirs'])
25
26
27def _insert(node, path, itemid):
28    """Insert an item into a virtual filesystem node."""
29    if len(path) == 1:
30        # Last component. Insert file.
31        node.files[path[0]] = itemid
32    else:
33        # In a directory.
34        dirname = path[0]
35        rest = path[1:]
36        if dirname not in node.dirs:
37            node.dirs[dirname] = Node({}, {})
38        _insert(node.dirs[dirname], rest, itemid)
39
40
41def libtree(lib):
42    """Generates a filesystem-like directory tree for the files
43    contained in `lib`. Filesystem nodes are (files, dirs) named
44    tuples in which both components are dictionaries. The first
45    maps filenames to Item ids. The second maps directory names to
46    child node tuples.
47    """
48    root = Node({}, {})
49    for item in lib.items():
50        dest = item.destination(fragment=True)
51        parts = util.components(dest)
52        _insert(root, parts, item.id)
53    return root
54