Completed
Push — master ( 974cdd...c16db8 )
by John
01:26
created

autolookup_main()   F

Complexity

Conditions 12

Size

Total Lines 74

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
c 1
b 0
f 0
dl 0
loc 74
rs 2.2446

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like autolookup_main() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#!/usr/bin/env python3
2
"""Get software release for one/many OS versions."""
3
4
import sys  # load arguments
5
from bbarchivist import networkutils  # lookup
6
from bbarchivist import utilities  # incrementer
7
from bbarchivist import smtputils  # email
8
from bbarchivist import scriptutils  # default parser
9
from bbarchivist import decorators  # Ctrl+C wrapper
10
11
__author__ = "Thurask"
12
__license__ = "WTFPL v2"
13
__copyright__ = "Copyright 2015-2016 Thurask"
14
15
16
def grab_args():
17
    """
18
    Parse arguments from argparse/questionnaire.
19
20
    Invoke :func:`autolookup.autolookup_main` with those arguments."""
21
    if len(sys.argv) > 1:
22
        parser = scriptutils.default_parser("bb-autolookup", "Get software releases")
23
        parser.add_argument("os", help="OS version, 10.x.y.zzzz")
24
        parser.add_argument(
25
            "-l", "--loop",
26
            dest="recurse",
27
            help="Loop lookup, CTRL-C to quit",
28
            action="store_true",
29
            default=False)
30
        parser.add_argument(
31
            "-o", "--output",
32
            dest="log",
33
            help="Output to file",
34
            action="store_true",
35
            default=False)
36
        parser.add_argument(
37
            "-a", "--autogen",
38
            dest="autogen",
39
            help="Generate links for availables",
40
            action="store_true",
41
            default=False)
42
        parser.add_argument(
43
            "-q", "--quiet",
44
            dest="quiet",
45
            help="Only print if available",
46
            action="store_true",
47
            default=False)
48
        parser.add_argument(
49
            "-i", "--increment",
50
            dest="increment",
51
            help="Loop increment, default = 3",
52
            default=3,
53
            type=utilities.positive_integer,
54
            metavar="INT")
55
        if not getattr(sys, 'frozen', False):
56
            parser.add_argument(
57
                "-s", "--sql",
58
                dest="sql",
59
                help="Add valid links to database",
60
                action="store_true",
61
                default=False)
62
            parser.add_argument(
63
                "-e", "--email",
64
                dest="email",
65
                help="Email valid links to self",
66
                action="store_true",
67
                default=False)
68
        parser.add_argument(
69
            "-c", "--ceiling",
70
            dest="ceiling",
71
            help="When to stop script, default = 9996",
72
            default=9996,
73
            type=int,
74
            choices=range(1, 9997),
75
            metavar="INT")
76
        args = parser.parse_args(sys.argv[1:])
77
        parser.set_defaults()
78
        if getattr(sys, 'frozen', False):
79
            args.sql = False
80
            args.email = False
81
        autolookup_main(
82
            args.os,
83
            args.recurse,
84
            args.log,
85
            args.autogen,
86
            args.increment,
87
            args.sql,
88
            args.quiet,
89
            args.ceiling,
90
            args.email)
91
    else:
92
        osversion = input("OS VERSION: ")
93
        recurse = utilities.s2b(input("LOOP (Y/N)?: "))
94
        if recurse:
95
            print("Press Ctrl+C to stop loop")
96
        print(" ")
97
        autolookup_main(
98
            osversion,
99
            recurse,
100
            True,
101
            False,
102
            3,
103
            False,
104
            False,
105
            9996,
106
            False)
107
        decorators.enter_to_exit(True)
108
109
110
@decorators.wrap_keyboard_except
111
def autolookup_main(osversion, loop=False, log=False,
112
                    autogen=False, inc=3, sql=False,
113
                    quiet=False, ceiling=9996, mailer=False):
114
    """
115
    Lookup a software release from an OS. Can iterate.
116
117
    :param osversion: OS version, 10.x.y.zzzz.
118
    :type osversion: str
119
120
    :param loop: Whether or not to automatically lookup. Default is false.
121
    :type loop: bool
122
123
    :param log: Whether to log. Default is false.
124
    :type log: bool
125
126
    :param autogen: Whether to create text links. Default is false.
127
    :type autogen: bool
128
129
    :param inc: Lookup inc. Default is 3.
130
    :type inc: int
131
132
    :param sql: Whether to add valid lookups to a database. Default is false.
133
    :type sql: bool
134
135
    :param quiet: Whether to only output if release exists. Default is false.
136
    :type quiet: bool
137
138
    :param ceiling: When to stop loop. Default is 9996 (i.e. 10.x.y.9996).
139
    :type ceiling: int
140
141
    :param mailer: Whether to email new valid links. Default is false.
142
    :type mailer: bool
143
    """
144
    if mailer:
145
        sql = True
146
        smtpc = smtputils.smtp_config_loader()
147
        smtpc = smtputils.smtp_config_generator(smtpc)
148
        smtpc['homepath'] = None
149
        pword = smtpc['password']
150
        smtputils.smtp_config_writer(**smtpc)
1 ignored issue
show
Coding Style introduced by
Usage of * or ** arguments should usually be done with care.

Generally, there is nothing wrong with usage of * or ** arguments. For readability of the code base, we suggest to not over-use these language constructs though.

For more information, we can recommend this blog post from Ned Batchelder including its comments which also touches this aspect.

Loading history...
151
    else:
152
        pword = None
153
    scriptutils.slim_preamble("AUTOLOOKUP")
154
    record = utilities.prep_logfile() if log else None
155
    while True:
156
        if loop and int(osversion.split(".")[3]) > ceiling:
157
            raise KeyboardInterrupt
158
        print("NOW SCANNING: {0}".format(osversion), end="\r")
159
        results = networkutils.sr_lookup_bootstrap(osversion)
160
        if results is None:
161
            raise KeyboardInterrupt
162
        a1rel, a1av = networkutils.clean_availability(results, 'a1')
163
        a2rel, a2av = networkutils.clean_availability(results, 'a2')
164
        b1rel, b1av = networkutils.clean_availability(results, 'b1')
165
        b2rel, b2av = networkutils.clean_availability(results, 'b2')
166
        prel, pav, avail = scriptutils.prod_avail(results, mailer, osversion, pword)
167
        avpack = (a1av, a2av, b1av, b2av, pav)
168
        swrelease = scriptutils.clean_swrel(set([a1rel, a2rel, b1rel, b2rel, prel]))
169
        if swrelease != "":
170
            out = scriptutils.autolookup_output(osversion, swrelease, avail, avpack, sql)
171
            scriptutils.autolookup_printer(out, avail, log, quiet, record)
172
        if autogen and avail == "Available":
173
            rad = utilities.increment(osversion, 1)
174
            scriptutils.linkgen(osversion, rad, prel)
175
        if not loop:
176
            raise KeyboardInterrupt  # hack, but whatever
177
        else:
178
            if int(osversion.split(".")[3]) > ceiling:
179
                raise KeyboardInterrupt
180
            else:
181
                osversion = utilities.increment(osversion, inc)
182
                swrelease = ""
183
                continue
184
185
186
if __name__ == "__main__":
187
    grab_args()
188