Passed
Push — development/test ( 6383cd...222d55 )
by Daniel
02:57
created

FileOperations.fn_get_file_simple_statistics()   A

Complexity

Conditions 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
"""
2
facilitates File Operations
3
"""
4
# package to handle date and times
5
from datetime import datetime
6
# package to add support for multi-language (i18n)
7
import gettext
8
# package to use for checksum calculations (in this file)
9
import hashlib
10
# package to handle json files
11
import json
12
# package to facilitate operating system operations
13
import os
14
# package to facilitate os path manipulations
15
import pathlib
16
# package regular expressions
17
import re
18
19
20
class FileOperations:
21
    timestamp_format = '%Y-%m-%d %H:%M:%S.%f %Z'
22
    lcl = None
23
24
    def __init__(self, default_language='en_US'):
25
        current_script = os.path.basename(__file__).replace('.py', '')
26
        lang_folder = os.path.join(os.path.dirname(__file__), current_script + '_Locale')
27
        self.lcl = gettext.translation(current_script, lang_folder, languages=[default_language])
28
29
    def build_file_list(self, local_logger, timmer, given_input_file):
30
        if re.search(r'(\*|\?)*', given_input_file):
31
            local_logger.debug(self.lcl.gettext('File matching pattern identified'))
32
            parent_directory = os.path.dirname(given_input_file)
33
            # loading from a specific folder all files matching a given pattern into a file list
34
            relevant_files_list = self.fn_build_relevant_file_list(local_logger, timmer,
35
                                                                   parent_directory,
36
                                                                   given_input_file)
37
        else:
38
            local_logger.debug(self.lcl.gettext('Specific file name provided'))
39
            relevant_files_list = [given_input_file]
40
        return relevant_files_list
41
42
    def fn_build_file_list(self, local_logger, working_path, matching_pattern):
43
        resulted_file_list = []
44
        file_counter = 0
45
        for current_file in working_path.iterdir():
46
            if current_file.is_file() and current_file.match(matching_pattern):
47
                resulted_file_list.append(file_counter)
48
                resulted_file_list[file_counter] = str(current_file.absolute())
49
                local_logger.info(self.lcl.gettext('{file_name} identified') \
50
                                  .replace('{file_name}', str(current_file.absolute())))
51
                file_counter = file_counter + 1
52
        return resulted_file_list
53
54
    def fn_build_relevant_file_list(self, local_logger, timmer, in_folder, matching_pattern):
55
        timmer.start()
56
        local_logger.info(self.lcl.gettext('Listing all files within {in_folder} folder '
57
                                           + 'looking for {matching_pattern} as matching pattern') \
58
                          .replace('{in_folder}', in_folder) \
59
                          .replace('{matching_pattern}', matching_pattern))
60
        list_files = []
61
        if os.path.isdir(in_folder):
62
            working_path = pathlib.Path(in_folder)
63
            list_files = self.fn_build_file_list(local_logger, working_path, matching_pattern)
64
            file_counter = len(list_files)
65
            local_logger.info(self.lcl.ngettext( \
66
                '{files_counted} file from {in_folder} folder identified',
67
                '{files_counted} files from {in_folder} folder identified', file_counter) \
68
                              .replace('{files_counted}', str(file_counter)) \
69
                              .replace('{in_folder}', in_folder))
70
        else:
71
            local_logger.error(self.lcl.gettext('Folder {folder_name} does not exist') \
72
                               .replace('{folder_name}', in_folder))
73
        timmer.stop()
74
        return list_files
75
76
    def fn_get_file_content(self, in_file_handler, in_file_type):
77
        if in_file_type == 'json':
78
            try:
79
                json_interpreted_details = json.load(in_file_handler)
80
                print(datetime.utcnow().strftime(self.timestamp_format) +
81
                      self.lcl.gettext('JSON structure interpreted'))
82
                return json_interpreted_details
83
            except Exception as e:
84
                print(datetime.utcnow().strftime(self.timestamp_format) +
85
                      self.lcl.gettext('Error encountered when trying to interpret JSON'))
86
                print(e)
87
        elif in_file_type == 'raw':
88
            raw_interpreted_file = in_file_handler.read()
89
            print(datetime.utcnow().strftime(self.timestamp_format) +
90
                  self.lcl.gettext('Entire file content read'))
91
            return raw_interpreted_file
92
        else:
93
            print(datetime.utcnow().strftime(self.timestamp_format) +
94
                  self.lcl.gettext('Unknown file type provided, '
95
                                   + 'expected either "json" or "raw" but got {in_file_type}') \
96
                  .replace('{in_file_type}', in_file_type))
97
98
    def fn_get_file_simple_statistics(self, file_to_evaluate):
99
        f_dts = {
100
            'created': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)),
101
            'modified': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)),
102
        }
103
        return {
104
            'date when created': datetime.strftime(f_dts['created'], self.timestamp_format),
105
            'date when last modified': datetime.strftime(f_dts['modified'], self.timestamp_format),
106
            'size [bytes]': os.path.getsize(file_to_evaluate),
107
        }
108
109
    def fn_get_file_statistics(self, file_to_evaluate):
110
        file_statistics = self.fn_get_file_simple_statistics(file_to_evaluate)
111
        try:
112
            file_handler = open(file=file_to_evaluate, mode='r', encoding='mbcs')
113
        except UnicodeDecodeError:
114
            file_handler = open(file=file_to_evaluate, mode='r', encoding='utf-8')
115
        file_content = file_handler.read().encode()
116
        file_handler.close()
117
        file_statistics['MD5 Checksum'] = hashlib.md5(file_content).hexdigest()
118
        file_statistics['SHA1 Checksum'] = hashlib.sha1(file_content).hexdigest()
119
        file_statistics['SHA224 Checksum'] = hashlib.sha224(file_content).hexdigest()
120
        file_statistics['SHA256 Checksum'] = hashlib.sha256(file_content).hexdigest()
121
        file_statistics['SHA384 Checksum'] = hashlib.sha384(file_content).hexdigest()
122
        file_statistics['SHA512 Checksum'] = hashlib.sha512(file_content).hexdigest()
123
        return file_statistics
124
125
    def fn_move_files(self, local_logger, timmer, file_names, destination_folder):
126
        timmer.start()
127
        resulted_files = []
128
        for current_file in file_names:
129
            source_folder = os.path.dirname(current_file)
130
            new_file_name = current_file.replace(source_folder, destination_folder)
131
            if os.path.isfile(new_file_name):
132
                local_logger.warning(self.lcl.gettext('File {file_name} will be overwritten') \
133
                                     .replace('{file_name}', current_file))
134
                os.replace(current_file, new_file_name)
135
                local_logger.info(self.lcl.gettext( \
136
                    'File {file_name} has just been been overwritten as {new_file_name}') \
137
                                     .replace('{file_name}', current_file) \
138
                                     .replace('{new_file_name}', current_file))
139
            else:
140
                local_logger.info(self.lcl.gettext( \
141
                    'File {file_name} will be renamed as {new_file_name}') \
142
                                     .replace('{file_name}', current_file) \
143
                                     .replace('{new_file_name}', current_file))
144
                os.rename(current_file, new_file_name)
145
                local_logger.info(self.lcl.gettext( \
146
                    'File {file_name} has just been renamed as {new_file_name}') \
147
                                     .replace('{file_name}', current_file) \
148
                                     .replace('{new_file_name}', current_file))
149
            resulted_files.append(str(new_file_name))
150
        timmer.stop()
151
        return resulted_files
152
153
    def fn_open_file_and_get_content(self, input_file, content_type='json'):
154
        if os.path.isfile(input_file):
155
            with open(input_file, 'r') as file_handler:
156
                print(datetime.utcnow().strftime(self.timestamp_format) +
157
                      self.lcl.gettext('File {file_name} has just been opened') \
158
                      .replace('{file_name}', str(input_file)))
159
                return self.fn_get_file_content(file_handler, content_type)
160
        else:
161
            print(datetime.utcnow().strftime(self.timestamp_format) +
162
                  self.lcl.gettext('File {file_name} does not exist') \
163
                  .replace('{file_name}', str(input_file)))
164
165
    def fn_store_file_statistics(self, local_logger, timmer, file_name, file_meaning):
166
        timmer.start()
167
        list_file_names = [file_name]
168
        if type(file_name) == list:
169
            list_file_names = file_name
170
        for current_file_name in list_file_names:
171
            file_statistics = str(self.fn_get_file_statistics(current_file_name)) \
172
                .replace('date when created', self.lcl.gettext('date when created')) \
173
                .replace('date when last modified', self.lcl.gettext('date when last modified')) \
174
                .replace('size [bytes]', self.lcl.gettext('size [bytes]')) \
175
                .replace('Checksum', self.lcl.gettext('Checksum'))
176
            local_logger.info(self.lcl.gettext( \
177
                'File "{file_name}" has the following characteristics: {file_statistics}') \
178
                              .replace('{file_meaning}', file_meaning) \
179
                              .replace('{file_name}', current_file_name) \
180
                              .replace('{file_statistics}', file_statistics))
181
        timmer.stop()
182