normalisename/normalisename.py

52 lines
1.4 KiB
Python
Executable File

from os.path import basename, dirname
from os.path import join as joinpath
from re import sub
from unidecode import unidecode
class Normalisename:
def __init__(self, operation, separator, whitelist):
self._operation, self.operation = None, operation
self._separator = separator
self._whitelist = set(whitelist)
@property
def operation(self):
return self._operation
@operation.setter
def operation(self, value):
if not callable(value):
raise ValueError('Operation must be callable!')
self._operation = value
@property
def separator(self):
return self._separator
@property
def whitelist(self):
return self._whitelist
def __call__(self, files):
for path in files:
if not self.check_normal(path):
directory = dirname(path)
filename = basename(path)
normalpath = joinpath(directory, self.normalname(filename))
self.operation(path, normalpath) # pylint: disable=not-callable
def check_normal(self, filename):
filename = basename(filename)
return filename == self.normalname(filename)
def normalname(self, filename):
return unidecode(
''.join(
ch for ch in sub(r'\s+', self.separator, filename)
if ch.isalnum()
or ch in self.whitelist
)
)