2016-12-20 13:22:44 +00:00
|
|
|
from os.path import basename, dirname
|
|
|
|
from os.path import join as joinpath
|
2018-09-02 13:52:52 +00:00
|
|
|
from re import sub
|
|
|
|
|
|
|
|
from unidecode import unidecode
|
2016-12-08 17:15:56 +00:00
|
|
|
|
2017-05-28 17:55:21 +00:00
|
|
|
|
2018-09-02 13:52:52 +00:00
|
|
|
class Normalisename:
|
|
|
|
def __init__(self, operation, separator, whitelist):
|
|
|
|
self._operation, self.operation = None, operation
|
|
|
|
self._separator = separator
|
|
|
|
self._whitelist = set(whitelist)
|
|
|
|
|
2017-08-23 20:34:02 +00:00
|
|
|
@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
|
|
|
|
|
2017-08-23 16:48:49 +00:00
|
|
|
@property
|
|
|
|
def separator(self):
|
|
|
|
return self._separator
|
|
|
|
|
|
|
|
@property
|
|
|
|
def whitelist(self):
|
|
|
|
return self._whitelist
|
|
|
|
|
2017-08-23 21:27:50 +00:00
|
|
|
def __call__(self, files):
|
2017-08-23 16:48:49 +00:00
|
|
|
for path in files:
|
2017-08-23 20:34:02 +00:00
|
|
|
if not self.check_normal(path):
|
2018-09-02 13:52:52 +00:00
|
|
|
directory = dirname(path)
|
|
|
|
filename = basename(path)
|
|
|
|
normalpath = joinpath(directory, self.normalname(filename))
|
|
|
|
self.operation(path, normalpath) # pylint: disable=not-callable
|
2017-08-23 20:34:02 +00:00
|
|
|
|
2018-09-02 13:52:52 +00:00
|
|
|
def check_normal(self, filename):
|
|
|
|
filename = basename(filename)
|
|
|
|
return filename == self.normalname(filename)
|
2017-08-23 16:48:49 +00:00
|
|
|
|
|
|
|
def normalname(self, filename):
|
2018-09-02 13:52:52 +00:00
|
|
|
return unidecode(
|
|
|
|
''.join(
|
|
|
|
ch for ch in sub(r'\s+', self.separator, filename)
|
|
|
|
if ch.isalnum()
|
|
|
|
or ch in self.whitelist
|
|
|
|
)
|
|
|
|
)
|