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 not in (None, 'None'): |
84
|
|
|
# checking log folder first as there's all further messages will be stored |
85
|
|
|
self.fn_timestamped_print(self.locale.gettext( |
86
|
|
|
'Checking if provided folder for the log file is valid')) |
87
|
|
|
self.fn_validate_single_value( |
88
|
|
|
os.path.dirname(input_parameters.output_log_file), 'folder') |
89
|
|
|
|
90
|
|
|
@staticmethod |
91
|
|
|
def fn_decide_by_omission_or_specific_true(in_dictionary, key_decision_factor): |
92
|
|
|
""" |
93
|
|
|
Evaluates if a property is specified in a Dict structure |
94
|
|
|
|
95
|
|
|
@param in_dictionary: input Dict structure |
96
|
|
|
@param key_decision_factor: key used to search value in Dict structure |
97
|
|
|
@return: True|False |
98
|
|
|
""" |
99
|
|
|
final_decision = False |
100
|
|
|
if key_decision_factor in in_dictionary: |
101
|
|
|
final_decision = True |
102
|
|
|
elif in_dictionary[key_decision_factor]: |
103
|
|
|
final_decision = True |
104
|
|
|
return final_decision |
105
|
|
|
|
106
|
|
|
@staticmethod |
107
|
|
|
def fn_evaluate_dict_values(in_dict): |
108
|
|
|
true_counted = 0 |
109
|
|
|
for crt_value in in_dict: |
110
|
|
|
if in_dict[crt_value]: |
111
|
|
|
true_counted += 1 |
112
|
|
|
all_true = False |
113
|
|
|
if true_counted == len(in_dict): |
114
|
|
|
all_true = True |
115
|
|
|
return all_true |
116
|
|
|
|
117
|
|
|
@staticmethod |
118
|
|
|
def fn_evaluate_list_values(in_list): |
119
|
|
|
true_counted = 0 |
120
|
|
|
for crt_value in in_list: |
121
|
|
|
if crt_value: |
122
|
|
|
true_counted += 1 |
123
|
|
|
all_true = False |
124
|
|
|
if true_counted == len(in_list): |
125
|
|
|
all_true = True |
126
|
|
|
return all_true |
127
|
|
|
|
128
|
|
|
def fn_final_message(self, local_logger, log_file_name, performance_in_seconds): |
129
|
|
|
total_time_string = str(timedelta(seconds=performance_in_seconds)) |
130
|
|
|
if log_file_name == 'None': |
131
|
|
|
self.fn_timestamped_print(self.locale.gettext( |
132
|
|
|
'Application finished, whole script took {total_time_string}') |
133
|
|
|
.replace('{total_time_string}', total_time_string)) |
134
|
|
|
else: |
135
|
|
|
local_logger.info(self.locale.gettext('Total execution time was {total_time_string}') |
136
|
|
|
.replace('{total_time_string}', total_time_string)) |
137
|
|
|
self.fn_timestamped_print(self.locale.gettext( |
138
|
|
|
'Application finished, for complete logged details please check {log_file_name}') |
139
|
|
|
.replace('{log_file_name}', log_file_name)) |
140
|
|
|
|
141
|
|
|
@staticmethod |
142
|
|
|
def fn_multi_line_string_to_single(input_string): |
143
|
|
|
string_to_return = input_string.replace('\n', ' ').replace('\r', ' ') |
144
|
|
|
return re.sub(r'\s{2,100}', ' ', string_to_return).replace(' , ', ', ').strip() |
145
|
|
|
|
146
|
|
|
@staticmethod |
147
|
|
|
def fn_numbers_with_leading_zero(input_number_as_string, digits): |
148
|
|
|
final_number = input_number_as_string |
149
|
|
|
if len(input_number_as_string) < digits: |
150
|
|
|
final_number = '0' * (digits - len(input_number_as_string)) + input_number_as_string |
151
|
|
|
return final_number |
152
|
|
|
|
153
|
|
|
def fn_optional_print(self, boolean_variable, string_to_print): |
154
|
|
|
if boolean_variable: |
155
|
|
|
self.fn_timestamped_print(string_to_print) |
156
|
|
|
|
157
|
|
|
@staticmethod |
158
|
|
|
def fn_timestamped_print(string_to_print): |
159
|
|
|
print(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f %Z") + '- ' + string_to_print) |
160
|
|
|
|
161
|
|
|
def fn_validate_one_value(self, value_to_validate, validation_type): |
162
|
|
|
is_invalid = False |
163
|
|
|
message = '' |
164
|
|
|
if validation_type == 'file': |
165
|
|
|
is_invalid = (not os.path.isfile(value_to_validate)) |
166
|
|
|
message = self.locale.gettext('Given file "{value_to_validate}" does not exist') |
167
|
|
|
elif validation_type == 'folder': |
168
|
|
|
is_invalid = (not os.path.isdir(value_to_validate)) |
169
|
|
|
message = self.locale.gettext('Given folder "{value_to_validate}" does not exist') |
170
|
|
|
elif validation_type == 'url': |
171
|
|
|
url_reg_expression = 'https?://(?:www)?(?:[\\w-]{2,255}(?:\\.\\w{2,66}){1,2})' |
172
|
|
|
is_invalid = (not re.match(url_reg_expression, value_to_validate)) |
173
|
|
|
message = self.locale.gettext('Given url "{value_to_validate}" is not valid') |
174
|
|
|
return { |
175
|
|
|
'is_invalid': is_invalid, |
176
|
|
|
'message': message.replace('{value_to_validate}', value_to_validate), |
177
|
|
|
} |
178
|
|
|
|
179
|
|
|
def fn_validate_single_value(self, value_to_validate, validation_type): |
180
|
|
|
validation_details = self.fn_validate_one_value(value_to_validate, validation_type) |
181
|
|
|
if validation_details['is_invalid']: |
182
|
|
|
self.fn_timestamped_print(validation_details['message']) |
183
|
|
|
exit(1) |
184
|
|
|
|