Completed
Push — master ( 152b55...0bdad9 )
by John
01:22
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
    """
22
    if len(sys.argv) > 1:
23
        parser = scriptutils.default_parser("bb-autolookup", "Get software releases")
24
        parser.add_argument("os", help="OS version, 10.x.y.zzzz")
25
        parser.add_argument(
26
            "-l", "--loop",
27
            dest="recurse",
28
            help="Loop lookup, CTRL-C to quit",
29
            action="store_true",
30
            default=False)
31
        parser.add_argument(
32
            "-o", "--output",
33
            dest="log",
34
            help="Output to file",
35
            action="store_true",
36
            default=False)
37
        parser.add_argument(
38
            "-a", "--autogen",
39
            dest="autogen",
40
            help="Generate links for availables",
41
            action="store_true",
42
            default=False)
43
        parser.add_argument(
44
            "-q", "--quiet",
45
            dest="quiet",
46
            help="Only print if available",
47
            action="store_true",
48
            default=False)
49
        parser.add_argument(
50
            "-i", "--increment",
51
            dest="increment",
52
            help="Loop increment, default = 3",
53
            default=3,
54
            type=utilities.positive_integer,
55
            metavar="INT")
56
        if not getattr(sys, 'frozen', False):
57
            parser.add_argument(
58
                "-s", "--sql",
59
                dest="sql",
60
                help="Add valid links to database",
61
                action="store_true",
62
                default=False)
63
            parser.add_argument(
64
                "-e", "--email",
65
                dest="email",
66
                help="Email valid links to self",
67
                action="store_true",
68
                default=False)
69
        parser.add_argument(
70
            "-c", "--ceiling",
71
            dest="ceiling",
72
            help="When to stop script, default = 9996",
73
            default=9996,
74
            type=int,
75
            choices=range(1, 9997),
76
            metavar="INT")
77
        args = parser.parse_args(sys.argv[1:])
78
        parser.set_defaults()
79
        if getattr(sys, 'frozen', False):
80
            args.sql = False
81
            args.email = False
82
        autolookup_main(
83
            args.os,
84
            args.recurse,
85
            args.log,
86
            args.autogen,
87
            args.increment,
88
            args.sql,
89
            args.quiet,
90
            args.ceiling,
91
            args.email)
92
    else:
93
        osversion = input("OS VERSION: ")
94
        recurse = utilities.s2b(input("LOOP (Y/N)?: "))
95
        if recurse:
96
            print("Press Ctrl+C to stop loop")
97
        print(" ")
98
        autolookup_main(
99
            osversion,
100
            recurse,
101
            True,
102
            False,
103
            3,
104
            False,
105
            False,
106
            9996,
107
            False)
108
        decorators.enter_to_exit(True)
109
110
111
@decorators.wrap_keyboard_except
112
def autolookup_main(osversion, loop=False, log=False,
113
                    autogen=False, inc=3, sql=False,
114
                    quiet=False, ceiling=9996, mailer=False):
115
    """
116
    Lookup a software release from an OS. Can iterate.
117
118
    :param osversion: OS version, 10.x.y.zzzz.
119
    :type osversion: str
120
121
    :param loop: Whether or not to automatically lookup. Default is false.
122
    :type loop: bool
123
124
    :param log: Whether to log. Default is false.
125
    :type log: bool
126
127
    :param autogen: Whether to create text links. Default is false.
128
    :type autogen: bool
129
130
    :param inc: Lookup inc. Default is 3.
131
    :type inc: int
132
133
    :param sql: Whether to add valid lookups to a database. Default is false.
134
    :type sql: bool
135
136
    :param quiet: Whether to only output if release exists. Default is false.
137
    :type quiet: bool
138
139
    :param ceiling: When to stop loop. Default is 9996 (i.e. 10.x.y.9996).
140
    :type ceiling: int
141
142
    :param mailer: Whether to email new valid links. Default is false.
143
    :type mailer: bool
144
    """
145
    if mailer:
146
        sql = True
147
        smtpc = smtputils.smtp_config_loader()
148
        smtpc = smtputils.smtp_config_generator(smtpc)
149
        smtpc['homepath'] = None
150
        pword = smtpc['password']
151
        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...
152
    else:
153
        pword = None
154
    scriptutils.slim_preamble("AUTOLOOKUP")
155
    record = utilities.prep_logfile() if log else None
156
    while True:
157
        if loop and int(osversion.split(".")[3]) > ceiling:
158
            raise KeyboardInterrupt
159
        print("NOW SCANNING: {0}".format(osversion), end="\r")
160
        results = networkutils.sr_lookup_bootstrap(osversion)
161
        if results is None:
162
            raise KeyboardInterrupt
163
        a1rel, a1av = networkutils.clean_availability(results, 'a1')
164
        a2rel, a2av = networkutils.clean_availability(results, 'a2')
165
        b1rel, b1av = networkutils.clean_availability(results, 'b1')
166
        b2rel, b2av = networkutils.clean_availability(results, 'b2')
167
        prel, pav, avail = scriptutils.prod_avail(results, mailer, osversion, pword)
168
        avpack = (a1av, a2av, b1av, b2av, pav)
169
        swrelease = scriptutils.clean_swrel(set([a1rel, a2rel, b1rel, b2rel, prel]))
170
        if swrelease != "":
171
            out = scriptutils.autolookup_output(osversion, swrelease, avail, avpack, sql)
172
            scriptutils.autolookup_printer(out, avail, log, quiet, record)
173
        if autogen and avail == "Available":
174
            rad = utilities.increment(osversion, 1)
175
            scriptutils.linkgen(osversion, rad, prel)
176
        if not loop:
177
            raise KeyboardInterrupt  # hack, but whatever
178
        else:
179
            if int(osversion.split(".")[3]) > ceiling:
180
                raise KeyboardInterrupt
181
            else:
182
                osversion = utilities.increment(osversion, inc)
183
                swrelease = ""
184
                continue
185
186
187
if __name__ == "__main__":
188
    grab_args()
189