Coverage for downtify/file_naming.py: 100%
19 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""How a name becomes a file or folder name - and, from that, when two names
2are "the same name on disk".
4A leaf module (it imports nothing from Downtify) so that both the
5downloader, which writes the files, and the code that looks an artist up by
6name on a streaming service can use the one rule without importing each
7other.
9Downloads store ``AC/DC`` as ``ACDC``: the characters a file name can't hold
10are dropped. The library then takes an artist's name from the audio tag and,
11for a track without one, from that file name - so the same artist can turn up
12as ``AC/DC`` or as ``ACDC``. Matching a name against a service's search
13results by :func:`file_name_key` treats both as the same, since to the disk
14they are.
15"""
17from __future__ import annotations
19import re
21_INVALID_FS_CHARS = re.compile(r'[\\/:*?"<>|\x00-\x1f]')
22_WHITESPACE = re.compile(r'\s+')
23# "Song (Remastered 2011)", "Song [Live]", "Song - Radio Edit": the part a
24# title match ignores.
25_TITLE_EXTRAS = re.compile(r'\s*(?:[(\[].*?[)\]]|\s-\s.*)$')
28def _without_invalid_chars(text: str) -> str:
29 return _INVALID_FS_CHARS.sub('', text or '').strip().strip('.')
32def sanitize_file_name(text: str) -> str:
33 """*text* as a single file or folder name: the characters a file name
34 can't hold are dropped, and so are surrounding whitespace and dots.
35 ``'unknown'`` when nothing is left."""
37 return _without_invalid_chars(text) or 'unknown'
40def file_name_key(name: str) -> str:
41 """*name* reduced to what the disk keeps of it, for comparing names:
42 ``'AC/DC'`` and ``'ACDC'`` give the same key, as do ``'*NSYNC'`` and
43 ``'NSYNC'`` or ``'M.I.A.'`` and ``'M.I.A'``. Case and runs of spaces
44 are ignored too.
46 Empty when nothing is left of *name* (``'???'``) - unlike
47 :func:`sanitize_file_name` there is no ``'unknown'`` stand-in, so two
48 such names can't be mistaken for each other or for a real one; callers
49 should not match on an empty key.
50 """
52 return _WHITESPACE.sub(' ', _without_invalid_chars(name)).casefold()
55def title_key(title: str) -> str:
56 """A song or album title as a title match compares it: its
57 :func:`file_name_key`, without trailing ``(…)``/``[…]`` parts or a
58 `` - …`` suffix - so ``Dummy (Deluxe Edition)``, ``Roads - Live`` and
59 ``Glory Box [Remastered]`` match ``Dummy``, ``Roads`` and ``Glory Box``.
60 """
62 text = str(title or '').strip()
63 while True:
64 trimmed = _TITLE_EXTRAS.sub('', text).strip()
65 if trimmed == text or not trimmed:
66 break
67 text = trimmed
68 return file_name_key(text)