pferd/PFERD/transform.py

42 lines
1.0 KiB
Python
Raw Normal View History

2020-04-22 20:25:09 +02:00
"""
Transforms let the user define functions to decide where the downloaded files
should be placed locally. They let the user do more advanced things like moving
only files whose names match a regex, or renaming files from one numbering
scheme to another.
"""
from dataclasses import dataclass
2020-04-23 19:38:41 +02:00
from pathlib import PurePath
2020-04-22 20:25:09 +02:00
from typing import Callable, List, Optional, TypeVar
2020-04-23 19:38:41 +02:00
Transform = Callable[[PurePath], Optional[PurePath]]
2020-04-22 20:25:09 +02:00
@dataclass
class Transformable:
"""
An object that can be transformed by a Transform.
"""
2020-04-23 19:38:41 +02:00
path: PurePath
2020-04-22 20:25:09 +02:00
TF = TypeVar("TF", bound=Transformable)
def apply_transform(
2020-04-23 19:38:41 +02:00
transform: Transform,
2020-04-22 20:25:09 +02:00
transformables: List[TF],
) -> List[TF]:
"""
Apply a Transform to multiple Transformables, discarding those that were
not transformed by the Transform.
"""
result: List[TF] = []
for transformable in transformables:
if new_path := transform(transformable.path):
transformable.path = new_path
result.append(transformable)
return result