Source code for s365b.modules.paths
"""Folder paths: folder names joined with ``/``.
A ``/`` inside a folder name ("Projects/2026") is stored as U+2215 DIVISION
SLASH, which looks the same, so a path splits back into the
folders it was made of. Restore turns it back into ``/``.
"""
from __future__ import annotations
import re
[docs]
SLASH = "\N{DIVISION SLASH}"
[docs]
def join(prefix: str, name: str) -> str:
"""Return the path of a folder named ``name`` inside ``prefix``.
Args:
prefix: The parent's path; empty for a top-level folder.
name: The folder's own name.
Returns:
The path.
"""
own = name.replace("/", SLASH)
return f"{prefix}/{own}" if prefix else own
[docs]
def names(path: str) -> tuple[str, ...]:
"""Return the folder names along a path, as Exchange names them.
Args:
path: A path made by :func:`join`.
Returns:
The names, outermost first; empty parts are skipped.
"""
return tuple(p.replace(SLASH, "/") for p in path.split("/") if p)
# Characters Windows does not allow in file names, and control characters.
_UNSAFE = re.compile(r'[<>:"/\\|?*\x00-\x1f\x7f]')
[docs]
def file_path(folder: str, name: str, extension: str, taken: set[str]) -> str:
"""A unique path for an item in an archive: its folders, then its name.
Names are cut to 80 characters and stripped of what file systems
refuse; a name used before gets " (2)", " (3)"… Folder names with a
"/" keep it as the lookalike they are stored with.
Args:
folder: The item's folder path.
name: The item's name, e.g. a message subject or a file name.
extension: File extension, without the dot; empty to keep the
extension the name has (a file's own).
taken: Paths used so far (case-insensitively); updated.
Returns:
The path, with ``/`` between folders.
"""
def clean(part: str) -> str:
return _UNSAFE.sub("_", part).strip(" .")[:80].strip(" .") or "_"
if not extension and "." in name.strip("."):
name, extension = name.rsplit(".", 1)
dot = f".{clean(extension)[:16]}" if extension else ""
base = "/".join([*(clean(p) for p in folder.split("/") if p), clean(name)])
path, n = f"{base}{dot}", 1
while path.casefold() in taken:
n += 1
path = f"{base} ({n}){dot}"
taken.add(path.casefold())
return path