BasicNeeds.fn_check_inputs()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
"""
2
BasicNeeds - useful functions library
3
4
This library has functions useful to keep main logic short and simple
5
"""
6
# package to handle date and times
7
from datetime import datetime, timedelta
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 handle files/folders and related metadata/operations
13
import os
14
# package regular expressions
15
import re
16
17
18
class BasicNeeds:
19
    cfg_dtls = {}
20
21
    def fn_check_inputs(self, input_parameters):
22
        if input_parameters.output_log_file is not None:
23
            # checking log folder first as there's all further messages will be stored
24
            self.fn_validate_single_value(os.path.dirname(input_parameters.output_log_file),
25
                                          'folder', 'log file')
26
27
    def fn_final_message(self, local_logger, log_file_name, performance_in_seconds):
28
        total_time_string = str(timedelta(seconds=performance_in_seconds))
29
        if log_file_name == 'None':
30
            self.fn_timestamped_print('Application finished, whole script took '
31
                                      + total_time_string)
32
        else:
33
            local_logger.info(f'Total execution time was ' + total_time_string)
34
            self.fn_timestamped_print('Application finished, '
35
                                      + 'for complete logged details please check '
36
                                      + log_file_name)
37
38
    def fn_get_file_content(self, in_file_handler, in_content_type):
39
        if in_content_type == 'json':
40
            try:
41
                json_interpreted_details = json.load(in_file_handler)
42
                self.fn_timestamped_print('I have interpreted JSON structure from given file')
43
                return json_interpreted_details
44
            except Exception as e:
45
                self.fn_timestamped_print('Error encountered when trying to interpret JSON')
46
                print(e)
47
        elif in_content_type == 'raw':
48
            raw_interpreted_file = in_file_handler.read()
49
            self.fn_timestamped_print('I have read file entire content')
50
            return raw_interpreted_file
51
        else:
52
            self.fn_timestamped_print('Unknown content type provided, '
53
                                      + 'expected either "json" or "raw" but got '
54
                                      + in_content_type)
55
56
    @staticmethod
57
    def fn_get_file_statistics(file_to_evaluate):
58
        try:
59
            file_content = open(file=file_to_evaluate, mode='r', encoding='utf-8').read().encode()
60
        except UnicodeDecodeError:
61
            file_content = open(file=file_to_evaluate, mode='r', encoding='mbcs').read().encode()
62
        file_sha512 = hashlib.sha512(file_content).hexdigest()
63
        file_content = None
64
        f_dts = {
65
            'created': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)),
66
            'modified': datetime.fromtimestamp(os.path.getctime(file_to_evaluate)),
67
        }
68
        return {
69
            'date when created': datetime.strftime(f_dts['created'], '%Y-%m-%d %H:%M:%S.%f'),
70
            'date when last modified': datetime.strftime(f_dts['modified'], '%Y-%m-%d %H:%M:%S.%f'),
71
            'size [bytes]': os.path.getsize(file_to_evaluate),
72
            'SHA512-Checksum': file_sha512,
73
        }
74
75
    def fn_load_configuration(self):
76
        relevant_file = os.path.join(os.path.dirname(__file__), 'config.json')
77
        self.cfg_dtls = self.fn_open_file_and_get_content(relevant_file)
78
79
    @staticmethod
80
    def fn_multi_line_string_to_single_line(input_string):
81
        string_to_return = input_string.replace('\n', ' ').replace('\r', ' ')
82
        return re.sub(r'\s{2,100}', ' ', string_to_return).replace(' , ', ', ').strip()
83
84
    @staticmethod
85
    def fn_numbers_with_leading_zero(input_number_as_string, digits):
86
        final_number = input_number_as_string
87
        if len(input_number_as_string) < digits:
88
            final_number = '0' * (digits - len(input_number_as_string)) + input_number_as_string
89
        return final_number
90
91
    def fn_open_file_and_get_content(self, input_file, content_type='json'):
92
        if os.path.isfile(input_file):
93
            with open(input_file, 'r') as file_handler:
94
                self.fn_timestamped_print('I have opened file: ' + input_file)
95
                return self.fn_get_file_content(file_handler, content_type)
96
        else:
97
            self.fn_timestamped_print('Given file ' + input_file
98
                                      + ' does not exist, please check your inputs!')
99
100
    def fn_optional_print(self, boolean_variable, string_to_print):
101
        if boolean_variable:
102
            self.fn_timestamped_print(string_to_print)
103
104
    def fn_store_file_statistics(self, local_logger, timmer, file_name, file_meaning):
105
        timmer.start()
106
        file_name_variable_type = str(type(file_name))
107
        list_file_names = [file_name]
108
        if file_name_variable_type == "<class 'list'>":
109
            list_file_names = file_name
110
        for current_file_name in list_file_names:
111
            local_logger.info(file_meaning + ' file "' + current_file_name
112
                              + '" has the following characteristics: '
113
                              + str(self.fn_get_file_statistics(current_file_name)))
114
        timmer.stop()
115
116
    @staticmethod
117
    def fn_timestamped_print(string_to_print):
118
        print(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f %Z") + ' - ' + string_to_print)
119
120
    @staticmethod
121
    def fn_validate_one_value(value_to_validate, validation_type, name_meaning):
122
        is_fatal_error = False
123
        message = ''
124
        if validation_type == 'file':
125
            is_fatal_error = (not os.path.isfile(value_to_validate))
126
            message = 'Given ' + name_meaning + ' "' + value_to_validate \
127
                      + '" does not exist, please check your inputs!'
128
        elif validation_type == 'folder':
129
            is_fatal_error = (not os.path.isdir(value_to_validate))
130
            message = 'Given ' + name_meaning + ' "' + value_to_validate \
131
                      + '" does not exist, please check your inputs!'
132
        elif validation_type == 'url':
133
            url_reg_expression = 'https?://(?:www)?(?:[\\w-]{2,255}(?:\\.\\w{2,66}){1,2})'
134
            is_fatal_error = (not re.match(url_reg_expression, value_to_validate))
135
            message = 'Given ' + name_meaning + ' "' + value_to_validate \
136
                      + '" does not seem a valid one, please check your inputs!'
137
        return {
138
            'is_fatal_error': is_fatal_error,
139
            'message': message,
140
        }
141
142
    def fn_validate_single_value(self, value_to_validate, validation_type, name_meaning):
143
        validation_details = self.fn_validate_one_value(value_to_validate, validation_type,
144
                                                        name_meaning)
145
        if validation_details['is_fatal_error']:
146
            self.fn_timestamped_print(validation_details['message'])
147
            exit(1)
148