Passed
Push — development/test ( 7ab62a...6c4337 )
by Daniel
01:22
created

BasicNeeds.fn_validate_one_value()   A

Complexity

Conditions 4

Size

Total Lines 22
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 22
nop 4
dl 0
loc 22
rs 9.352
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
    lcl = None
18
19
    def __init__(self, default_language='en_US'):
20
        current_script = os.path.basename(__file__).replace('.py', '')
21
        lang_folder = os.path.join(os.path.dirname(__file__), current_script + '_Locale')
22
        self.lcl = gettext.translation(current_script, lang_folder, languages=[default_language])
23
24
    def fn_check_inputs(self, input_parameters):
25
        if input_parameters.output_log_file is not None:
26
            # checking log folder first as there's all further messages will be stored
27
            self.fn_validate_single_value(os.path.dirname(input_parameters.output_log_file),
28
                                          'folder', self.lcl.gettext('log file'))
29
30
    def fn_final_message(self, local_logger, log_file_name, performance_in_seconds):
31
        total_time_string = str(timedelta(seconds=performance_in_seconds))
32
        if log_file_name == 'None':
33
            self.fn_timestamped_print(self.lcl.gettext( \
34
                'Application finished, whole script took {total_time_string}') \
35
                                      .replace('{total_time_string}', total_time_string))
36
        else:
37
            local_logger.info(self.lcl.gettext('Total execution time was {total_time_string}') \
38
                              .replace('{total_time_string}', total_time_string))
39
            self.fn_timestamped_print(self.lcl.gettext( \
40
                'Application finished, for complete logged details please check {log_file_name}')
41
                                      .replace('{log_file_name}', log_file_name))
42
43
    @staticmethod
44
    def fn_multi_line_string_to_single_line(input_string):
45
        string_to_return = input_string.replace('\n', ' ').replace('\r', ' ')
46
        return re.sub(r'\s{2,100}', ' ', string_to_return).replace(' , ', ', ').strip()
47
48
    @staticmethod
49
    def fn_numbers_with_leading_zero(input_number_as_string, digits):
50
        final_number = input_number_as_string
51
        if len(input_number_as_string) < digits:
52
            final_number = '0' * (digits - len(input_number_as_string)) + input_number_as_string
53
        return final_number
54
55
    def fn_optional_print(self, boolean_variable, string_to_print):
56
        if boolean_variable:
57
            self.fn_timestamped_print(string_to_print)
58
59
    @staticmethod
60
    def fn_timestamped_print(string_to_print):
61
        print(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f %Z") + ' - ' + string_to_print)
62
63
    def fn_validate_one_value(self, value_to_validate, validation_type, name_meaning):
64
        is_invalid = False
65
        message = ''
66
        if validation_type == 'file':
67
            is_invalid = (not os.path.isfile(value_to_validate))
68
            message = self.lcl.gettext( \
69
                'Given file "{value_to_validate}" does not exist') \
70
                .replace('{value_to_validate}', value_to_validate)
71
        elif validation_type == 'folder':
72
            is_invalid = (not os.path.isdir(value_to_validate))
73
            message = self.lcl.gettext( \
74
                'Given folder "{value_to_validate}" does not exist') \
75
                .replace('{value_to_validate}', value_to_validate)
76
        elif validation_type == 'url':
77
            url_reg_expression = 'https?://(?:www)?(?:[\\w-]{2,255}(?:\\.\\w{2,66}){1,2})'
78
            is_invalid = (not re.match(url_reg_expression, value_to_validate))
79
            message = self.lcl.gettext( \
80
                'Given url "{value_to_validate}" is not valid') \
81
                .replace('{value_to_validate}', value_to_validate)
82
        return {
83
            'is_invalid': is_invalid,
84
            'message': message,
85
        }
86
87
    def fn_validate_single_value(self, value_to_validate, validation_type, name_meaning):
88
        validation_details = self.fn_validate_one_value(value_to_validate, validation_type,
89
                                                        name_meaning)
90
        if validation_details['is_invalid']:
91
            self.fn_timestamped_print(validation_details['message'])
92
            exit(1)
93