Passed
Push — master ( 361725...fcee18 )
by Daniel
02:49
created

tableau_hyper_management.CommandLineArgumentsHandling.CommandLineArgumentsHandling.fn_load_configuration()   A

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 3
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 3
dl 3
loc 3
rs 10
c 0
b 0
f 0
cc 2
nop 1
1
"""
2
CommandLineArgumentsHandling - a command line arguments handling library
3
4
This library allows handling pre-configured arguments to be received from command line and use them
5
to call the main package functions
6
7
Potential changes to implement:
8
    argparse = Alternative command line option and argument parsing library.
9
    https://www.programcreek.com/python/example/748/argparse.ArgumentParser
10
"""
11
12
# standard Python packages
13
import getopt
14
import sys
15
16
# additional Python packages available from PyPi
17
import pandas as pd
18
19
# Custom classes specific to this package
20
from .TableauHyperApiExtraLogic import ClassBN
21
from .TableauHyperApiExtraLogic import TableauHyperApiExtraLogic as ClassTHAEL
22
23
24 View Code Duplication
class CommandLineArgumentsHandling:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
25
26
    @staticmethod
27
    def fn_assess_option(current_option, str_meaning, given_default_value):
28
        if ClassBN.cfg_dtls['options'][current_option]['default_value'] == given_default_value:
29
            str_feedback_parts = {
30
                'prefix': 'Fatal Error',
31
                'verdict': 'Expected -' + current_option + '|--'
32
                           + ClassBN.cfg_dtls['options'][current_option]['option_long']
33
                           + ' <'
34
                           + ClassBN.cfg_dtls['options'][current_option]['option_sample_value']
35
                           + '> but nothing of that sort has been seen...',
36
                'suffix': ':-('
37
            }
38
            ln = len(str_feedback_parts['verdict']) - len(str_feedback_parts['prefix'])
39
            ClassBN.fn_timestamped_print(ClassBN, str_feedback_parts['prefix'] + '_'*ln)
40
            print(str_feedback_parts['verdict'] + ' ' + str_feedback_parts['suffix'])
41
            sys.exit(2)
42
        ClassBN.fn_timestamped_print(ClassBN, str_meaning + ' is "' + given_default_value + '"')
43
44
    @staticmethod
45
    def fn_build_combined_options():
46
        str_combined_opts = ''
47
        for option_index, crt_opt in enumerate(ClassBN.cfg_dtls['options']):
48
            if crt_opt is not None:
49
                str_option_crt = '-' + crt_opt + '|--'\
50
                                 + ClassBN.cfg_dtls['options'][crt_opt]['option_long']
51
                if 'option_sample_value' in ClassBN.cfg_dtls['options'][crt_opt]:
52
                    str_option_crt += ' <'\
53
                                      + ClassBN.cfg_dtls['options'][crt_opt]['option_sample_value']\
54
                                      + '>'
55
                if ClassBN.cfg_dtls['options'][crt_opt]['option_type'] == 'optional':
56
                    str_combined_opts += ' [' + str_option_crt\
57
                                         + '|if omitted, default value will be considered: '\
58
                                         + str(ClassBN.cfg_dtls['options'][crt_opt]['default_value'])\
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (102/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
59
                                         + ']'
60
                else:
61
                    str_combined_opts += ' ' + str_option_crt
62
        return str_combined_opts
63
64
    @staticmethod
65
    def fn_build_long_options():
66
        str_opts = []
67
        for option_index, crt_lng_opt in enumerate(ClassBN.cfg_dtls['options']):
68
            if crt_lng_opt is not None:
69
                str_opts.append(option_index)
70
                str_opts[option_index] = ClassBN.cfg_dtls['options'][crt_lng_opt]['option_long']\
71
                                         + '='
72
        return str_opts
73
74
    @staticmethod
75
    def fn_build_short_options():
76
        str_short_options = 'h'
77
        for crt_short_opt in ClassBN.cfg_dtls['options']:
78
            if crt_short_opt is not None:
79
                if ClassBN.cfg_dtls['options'][crt_short_opt]['option_type'] == 'mandatory':
80
                    str_short_options += crt_short_opt + ':'
81
                else:
82
                    str_short_options += crt_short_opt
83
        return str_short_options
84
85
    def fn_command_line_argument_digest(self, help_feedback):
86
        try:
87
            opts, args = getopt.getopt(sys.argv[1:],
88
                                       self.fn_build_short_options(),
89
                                       self.fn_build_long_options())
90
            return opts
91
        except getopt.GetoptError:
92
            print(help_feedback)
93
            sys.exit(2)
94
95
    def fn_command_line_argument_interpretation(self):
96
        print('#' * 120)
97
        input_file = ''
98
        csv_field_separator = ','
99
        output_file = ''
100
        verbose = False
101
        help_feedback = __file__ + self.fn_build_combined_options()
102
        opts = self.fn_command_line_argument_digest(self, help_feedback)
103
        for opt, arg in opts:
104
            if opt in ("-h", "--help"):
105
                print(help_feedback)
106
                sys.exit()
107
            elif opt in ("-i", "--input-file"):
108
                input_file = arg
109
            elif opt in ("-s", "--csv-field-separator"):
110
                csv_field_separator = arg
111
            elif opt in ("-o", "--output-file"):
112
                output_file = arg
113
            elif opt in ("-v", "--verbose"):
114
                verbose = True
115
            else:
116
                assert False, "Unhandled Option: " + arg
117
        self.fn_assess_option('i', 'Input file', input_file)
118
        ClassBN.fn_timestamped_print(ClassBN, 'CSV field separator is "'
119
                                     + csv_field_separator + '"')
120
        self.fn_assess_option('o', 'Output file', output_file)
121
        print('#' * 120)
122
        csv_content_df = pd.read_csv(filepath_or_buffer=input_file,
123
                                     delimiter=csv_field_separator,
124
                                     cache_dates=True,
125
                                     index_col=None,
126
                                     memory_map=True,
127
                                     encoding='utf-8')
128
        ClassTHAEL.fn_run_hyper_creation(ClassTHAEL,
129
                                         csv_content_df,
130
                                         ClassBN.cfg_dtls['data_types'],
131
                                         output_file, verbose)
132