Passed
Branch master (074b4c)
by Daniel
01:12
created

BasicNeeds.fn_timestamped_print()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
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 add support for multi-language (i18n)
9
import gettext
10
# package to handle files/folders and related metadata/operations
11
import os
12
# package regular expressions
13
import re
14
15
16
class BasicNeeds:
17
    locale = None
18
19
    def __init__(self, in_language='en_US'):
20
        file_parts = os.path.normpath(os.path.abspath(__file__)).replace('\\', os.path.altsep)\
21
            .split(os.path.altsep)
22
        locale_domain = file_parts[(len(file_parts)-1)].replace('.py', '')
23
        locale_folder = os.path.normpath(os.path.join(
24
            os.path.join(os.path.altsep.join(file_parts[:-2]), 'project_locale'), locale_domain))
25
        self.locale = gettext.translation(locale_domain, localedir=locale_folder,
26
                                          languages=[in_language], fallback=True)
27
28
    def fn_add_value_to_dictionary(self, in_list, adding_value, adding_type, reference_column):
29
        add_type = adding_type.lower()
30
        total_columns = len(in_list.copy())
31
        reference_indexes = {
32
            'add': {'after': 0, 'before': 0},
33
            'cycle_down_to': {'after': 0, 'before': 0}
34
        }
35
        if reference_column is not None:
36
            reference_indexes = {
37
                'add': {
38
                    'after': in_list.copy().index(reference_column) + 1,
39
                    'before': in_list.copy().index(reference_column),
40
                },
41
                'cycle_down_to': {
42
                    'after': in_list.copy().index(reference_column),
43
                    'before': in_list.copy().index(reference_column),
44
                }
45
            }
46
        positions = {
47
            'after': {
48
                'cycle_down_to': reference_indexes.get('cycle_down_to').get('after'),
49
                'add': reference_indexes.get('add').get('after'),
50
            },
51
            'before': {
52
                'cycle_down_to': reference_indexes.get('cycle_down_to').get('before'),
53
                'add': reference_indexes.get('add').get('before'),
54
            },
55
            'first': {
56
                'cycle_down_to': 0,
57
                'add': 0,
58
            },
59
            'last': {
60
                'cycle_down_to': total_columns,
61
                'add': total_columns,
62
            }
63
        }
64
        return self.add_value_to_dictionary_by_position({
65
            'adding_value': adding_value,
66
            'list': in_list.copy(),
67
            'position_to_add': positions.get(add_type).get('add'),
68
            'position_to_cycle_down_to': positions.get(add_type).get('cycle_down_to'),
69
            'total_columns': total_columns,
70
        })
71
72
    @staticmethod
73
    def add_value_to_dictionary_by_position(adding_dictionary):
74
        list_with_values = adding_dictionary['list']
75
        list_with_values.append(adding_dictionary['total_columns'])
76
        for counter in range(adding_dictionary['total_columns'],
77
                             adding_dictionary['position_to_cycle_down_to'], -1):
78
            list_with_values[counter] = list_with_values[(counter - 1)]
79
        list_with_values[adding_dictionary['position_to_add']] = adding_dictionary['adding_value']
80
        return list_with_values
81
82
    def fn_check_inputs(self, input_parameters):
83
        if input_parameters.output_log_file is not None:
84
            # checking log folder first as there's all further messages will be stored
85
            self.fn_validate_single_value(
86
                    os.path.dirname(input_parameters.output_log_file), 'folder')
87
88
    @staticmethod
89
    def fn_decide_by_omission_or_specific_true(in_dictionary, key_decision_factor):
90
        """
91
        Evaluates if a property is specified in a Dict structure
92
93
        @param in_dictionary: input Dict structure
94
        @param key_decision_factor: key used to search value in Dict structure
95
        @return: True|False
96
        """
97
        final_decision = False
98
        if key_decision_factor in in_dictionary:
99
            final_decision = True
100
        elif in_dictionary[key_decision_factor]:
101
            final_decision = True
102
        return final_decision
103
104
    @staticmethod
105
    def fn_evaluate_dict_values(in_dict):
106
        true_counted = 0
107
        for crt_value in in_dict:
108
            if in_dict[crt_value]:
109
                true_counted += 1
110
        all_true = False
111
        if true_counted == len(in_dict):
112
            all_true = True
113
        return all_true
114
115
    @staticmethod
116
    def fn_evaluate_list_values(in_list):
117
        true_counted = 0
118
        for crt_value in in_list:
119
            if crt_value:
120
                true_counted += 1
121
        all_true = False
122
        if true_counted == len(in_list):
123
            all_true = True
124
        return all_true
125
126
    def fn_final_message(self, local_logger, log_file_name, performance_in_seconds):
127
        total_time_string = str(timedelta(seconds=performance_in_seconds))
128
        if log_file_name == 'None':
129
            self.fn_timestamped_print(self.locale.gettext(
130
                'Application finished, whole script took {total_time_string}')
131
                                      .replace('{total_time_string}', total_time_string))
132
        else:
133
            local_logger.info(self.locale.gettext('Total execution time was {total_time_string}')
134
                              .replace('{total_time_string}', total_time_string))
135
            self.fn_timestamped_print(self.locale.gettext(
136
                'Application finished, for complete logged details please check {log_file_name}')
137
                                      .replace('{log_file_name}', log_file_name))
138
139
    @staticmethod
140
    def fn_multi_line_string_to_single(input_string):
141
        string_to_return = input_string.replace('\n', ' ').replace('\r', ' ')
142
        return re.sub(r'\s{2,100}', ' ', string_to_return).replace(' , ', ', ').strip()
143
144
    @staticmethod
145
    def fn_numbers_with_leading_zero(input_number_as_string, digits):
146
        final_number = input_number_as_string
147
        if len(input_number_as_string) < digits:
148
            final_number = '0' * (digits - len(input_number_as_string)) + input_number_as_string
149
        return final_number
150
151
    def fn_optional_print(self, boolean_variable, string_to_print):
152
        if boolean_variable:
153
            self.fn_timestamped_print(string_to_print)
154
155
    @staticmethod
156
    def fn_timestamped_print(string_to_print):
157
        print(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f %Z") + '- ' + string_to_print)
158
159
    def fn_validate_one_value(self, value_to_validate, validation_type):
160
        is_invalid = False
161
        message = ''
162
        if validation_type == 'file':
163
            is_invalid = (not os.path.isfile(value_to_validate))
164
            message = self.locale.gettext('Given file "{value_to_validate}" does not exist')
165
        elif validation_type == 'folder':
166
            is_invalid = (not os.path.isdir(value_to_validate))
167
            message = self.locale.gettext('Given folder "{value_to_validate}" does not exist')
168
        elif validation_type == 'url':
169
            url_reg_expression = 'https?://(?:www)?(?:[\\w-]{2,255}(?:\\.\\w{2,66}){1,2})'
170
            is_invalid = (not re.match(url_reg_expression, value_to_validate))
171
            message = self.locale.gettext('Given url "{value_to_validate}" is not valid')
172
        return {
173
            'is_invalid': is_invalid,
174
            'message': message.replace('{value_to_validate}', value_to_validate),
175
        }
176
177
    def fn_validate_single_value(self, value_to_validate, validation_type):
178
        validation_details = self.fn_validate_one_value(value_to_validate, validation_type)
179
        if validation_details['is_invalid']:
180
            self.fn_timestamped_print(validation_details['message'])
181
            exit(1)
182