Test Failed
Push — master ( 16370d...2bdc04 )
by Steffen
02:30
created

saucenao.files.filehandler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 29
dl 0
loc 57
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A FileHandler.get_files() 0 15 5
A FileHandler.unicode_translate() 0 12 2
A FileHandler.move_to_category() 0 15 2
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
import html
4
import os
5
import re
6
from shutil import move
7
from typing import Generator
8
9
from saucenao.files.filter import Filter
10
11
12
class FileHandler:
13
    @staticmethod
14
    def get_files(directory, file_filter=None) -> Generator[str, None, None]:
15
        """Get all files from given directory
16
17
        :type directory: str
18
        :type file_filter: Filter
19
        :return:
20
        """
21
        if file_filter:
22
            for f in file_filter.apply(directory=directory):
23
                yield f
24
        else:
25
            for f in os.listdir(directory):
26
                if os.path.isfile(os.path.join(directory, f)):
27
                    yield f
28
29
    @staticmethod
30
    def unicode_translate(text, chars="", replacement="") -> str:
31
        """Replacement for the string.maketrans function
32
33
        :type text: str
34
        :type chars: str
35
        :type replacement: str
36
        :return:
37
        """
38
        for char in chars:
39
            text = text.replace(char, replacement[chars.index(char)])
40
        return text
41
42
    @staticmethod
43
    def move_to_category(filename, category, base_directory=os.getcwd()):
44
        """Move file to the sub_category folder
45
46
        :type base_directory: str
47
        :type filename: str
48
        :type category: str
49
        :return:
50
        """
51
        folder = re.sub(r'["/?*:<>|]', r'', html.unescape(category))
52
        folder = os.path.join(base_directory, folder)
53
        folder = os.path.abspath(FileHandler.unicode_translate(folder, "\n\t\r", "   "))
54
        if not os.path.exists(folder):
55
            os.makedirs(folder)
56
        move(os.path.join(base_directory, filename), os.path.join(folder, filename))
57