Completed
Push — master ( 152b55...0bdad9 )
by John
01:22
created

lazyloader_main()   F

Complexity

Conditions 10

Size

Total Lines 109

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
cc 10
c 2
b 0
f 2
dl 0
loc 109
rs 3.1304

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 lazyloader_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
"""Create one autoloader for personal use."""
3
4
import argparse  # parse arguments
5
import sys  # load arguments
6
import os  # path work
7
import subprocess  # autoloader running
8
from bbarchivist import scriptutils  # script stuff
9
from bbarchivist import decorators  # timer
10
from bbarchivist import utilities  # input validation
11
from bbarchivist import barutils  # file operations
12
from bbarchivist import bbconstants  # constants/versions
13
from bbarchivist import networkutils  # download/lookup
14
from bbarchivist import loadergen  # cap wrapper
15
16
__author__ = "Thurask"
17
__license__ = "WTFPL v2"
18
__copyright__ = "Copyright 2015-2016 Thurask"
19
20
21
@decorators.timer
22
def grab_args():
23
    """
24
    Parse arguments from argparse/questionnaire.
25
26
    Invoke :func:`lazyloader.lazyloader_main` with arguments.
27
    """
28
    if len(sys.argv) > 1:
29
        parser = scriptutils.default_parser("bb-lazyloader", "Create one autoloader",
30
                                            ("folder", "osr"))
31
        devgroup = parser.add_argument_group(
32
            "devices",
33
            "Device to load (one required)")
34
        compgroup = devgroup.add_mutually_exclusive_group()
35
        compgroup.add_argument(
36
            "--stl100-1",
37
            dest="device",
38
            help="STL100-1",
39
            action="store_const",
40
            const=0)
41
        compgroup.add_argument(
42
            "--stl100-x",
43
            dest="device",
44
            help="STL100-2/3, P'9982",
45
            action="store_const",
46
            const=1)
47
        compgroup.add_argument(
48
            "--stl100-4",
49
            dest="device",
50
            help="STL100-4",
51
            action="store_const",
52
            const=2)
53
        compgroup.add_argument(
54
            "--q10",
55
            dest="device",
56
            help="Q10, Q5, P'9983",
57
            action="store_const",
58
            const=3)
59
        compgroup.add_argument(
60
            "--z30",
61
            dest="device",
62
            help="Z30, Classic, Leap",
63
            action="store_const",
64
            const=4)
65
        compgroup.add_argument(
66
            "--z3",
67
            dest="device",
68
            help="Z3",
69
            action="store_const",
70
            const=5)
71
        compgroup.add_argument(
72
            "--passport",
73
            dest="device",
74
            help="Passport",
75
            action="store_const",
76
            const=6)
77
        parser.add_argument(
78
            "--run-loader",
79
            dest="autoloader",
80
            help="Run autoloader after creation",
81
            action="store_true",
82
            default=False)
83
        parser.add_argument(
84
            "-n",
85
            "--no-download",
86
            dest="download",
87
            help="Don't download files",
88
            action="store_false",
89
            default=True)
90
        parser.add_argument(
91
            "-r",
92
            "--radiosw",
93
            dest="altsw",
94
            metavar="SW",
95
            help="Radio software version; use without software to guess",
96
            nargs="?",
97
            const="checkme",
98
            default=None)
99
        parser.add_argument(
100
            "-c",
101
            "--core",
102
            dest="core",
103
            help="Make core/radio loader",
104
            default=False,
105
            action="store_true")
106
        parser.set_defaults(device=None)
107
        args = parser.parse_args(sys.argv[1:])
108
        if args.folder is None:
109
            args.folder = os.getcwd()
110
        if not utilities.is_windows():
111
            args.autoloader = False
112
        else:
113
            if args.os is None:
114
                raise argparse.ArgumentError(argument=None,
115
                                             message="No OS specified!")
116
            if args.device is None:
117
                raise argparse.ArgumentError(argument=None,
118
                                             message="No device specified!")
119
            else:
120
                lazyloader_main(args.device,
121
                                args.os,
122
                                args.radio,
123
                                args.swrelease,
124
                                args.folder,
125
                                args.autoloader,
126
                                args.download,
127
                                args.altsw,
128
                                args.core)
129
    else:
130
        questionnaire()
131
132
133
def questionnaire():
134
    """
135
    Questions to ask if no arguments given.
136
    """
137
    localdir = os.getcwd()
138
    while True:
139
        osversion = input("OS VERSION (REQUIRED): ")
140
        if osversion:
141
            break
142
    radioversion = input("RADIO VERSION (PRESS ENTER TO GUESS): ")
143
    softwareversion = input("OS SOFTWARE RELEASE (PRESS ENTER TO GUESS): ")
144
    if not softwareversion:
145
        softwareversion = None
146
    if not radioversion:
147
        radioversion = None
148
        altcheck = False
149
        altsw = None
150
    else:
151
        altcheck = utilities.s2b(input("USING ALTERNATE RADIO (Y/N)?: "))
152
        if altcheck:
153
            altsw = input("RADIO SOFTWARE RELEASE (PRESS ENTER TO GUESS): ")
154
            if not altsw:
155
                altsw = "checkme"
156
    print("DEVICES:")
157
    devlist = ["0=STL100-1",
158
               "1=STL100-2/3/P9982",
159
               "2=STL100-4",
160
               "3=Q10/Q5/P9983",
161
               "4=Z30/CLASSIC/LEAP",
162
               "5=Z3",
163
               "6=PASSPORT"]
164
    utilities.lprint(devlist)
165
    while True:
166
        device = int(input("SELECTED DEVICE: "))
167
        if not 0 <= device <= len(devlist) - 1:
168
            continue
169
        else:
170
            break
171
    if utilities.is_windows():
172
        autoloader = utilities.s2b(
173
            input("RUN AUTOLOADER - WILL WIPE YOUR DEVICE! (Y/N)?: "))
174
    else:
175
        autoloader = False
176
    print(" ")
177
    lazyloader_main(
178
        device,
179
        osversion,
180
        radioversion,
181
        softwareversion,
182
        localdir,
183
        autoloader,
184
        True,
185
        altsw,
186
        False)
187
188
189
def lazyloader_main(device, osversion, radioversion=None,
190
                    softwareversion=None, localdir=None, autoloader=False,
191
                    download=True, altsw=None, core=False):
192
    """
193
    Wrap the tools necessary to make one autoloader.
194
195
    :param device: Device family to create loader for.
196
    :type device: int
197
198
    :param osversion: OS version, 10.x.y.zzzz.
199
    :type osversion: str
200
201
    :param radioversion: Radio version, 10.x.y.zzzz.
202
    :type radioversion: str
203
204
    :param softwareversion: Software version, 10.x.y.zzzz.
205
    :type softwareversion: str
206
207
    :param localdir: Working path. Default is local dir.
208
    :type localdir: str
209
210
    :param autoloader: Whether to run loader. Default is false. Windows-only.
211
    :type autoloader: bool
212
213
    :param download: Whether to download files. Default is true.
214
    :type download: bool
215
216
    :param altsw: Radio software release, if not the same as OS.
217
    :type altsw: str
218
219
    :param core: Whether to create a core/radio loader. Default is false.
220
    :type core: bool
221
    """
222
    radioversion = scriptutils.return_radio_version(osversion, radioversion)
223
    softwareversion, swc = scriptutils.return_sw_checked(softwareversion, osversion)
224
    if altsw == "checkme":
225
        altsw, altchecked = scriptutils.return_radio_sw_checked(altsw, radioversion)
226
    scriptutils.standard_preamble("lazyloader", osversion, softwareversion, radioversion, altsw)
227
    print("DEVICE: {0}".format(bbconstants.DEVICES[device]))
228
229
    # Make dirs
230
    bd_o, bd_r, ld_o, ld_r, zd_o, zd_r = barutils.make_dirs(localdir, osversion, radioversion)
231
    osurl = radiourl = None
232
233
    # Create download URLs
234
    if download:
235
        baseurl = networkutils.create_base_url(softwareversion)
236
        if altsw:
237
            alturl = networkutils.create_base_url(altsw)
238
        osurl, radiourl = utilities.generate_lazy_urls(baseurl, osversion, radioversion, device)
239
        if altsw:
240
            radiourl = radiourl.replace(baseurl, alturl)
241
        if core:
242
            osurl = osurl.replace(".desktop", "")
243
244
        # Check availability of software releases
245
        scriptutils.check_sw(baseurl, softwareversion, swc)
246
        if altsw:
247
            scriptutils.check_radio_sw(alturl, altsw, altchecked)
248
249
        # Check availability of OS, radio
250
        scriptutils.check_os_single(osurl, osversion, device)
251
        radiourl, radioversion = scriptutils.check_radio_single(radiourl, radioversion)
252
    dllist = [osurl, radiourl]
253
254
    # Download files
255
    if download:
256
        print("DOWNLOADING...")
257
        networkutils.download_bootstrap(dllist, outdir=localdir, workers=2)
258
259
    # Test bar files
260
    scriptutils.test_bar_files(localdir, dllist)
261
262
    # Extract bar files
263
    print("EXTRACTING...")
264
    barutils.extract_bars(localdir)
265
266
    # Test signed files
267
    scriptutils.test_signed_files(localdir)
268
269
    # Move bar files
270
    print("MOVING BAR FILES...")
271
    barutils.move_bars(localdir, bd_o, bd_r)
272
273
    # Generate loader
274
    altradio = radioversion if altsw else None
275
    loadergen.generate_lazy_loader(osversion, device, localdir, altradio, core)
276
277
    # Test loader
278
    suffix = loadergen.format_suffix(bool(altradio), altradio, core)
279
    loadername = loadergen.generate_filename(device, osversion, suffix)
280
    scriptutils.test_single_loader(loadername)
281
282
    # Remove signed files
283
    print("REMOVING SIGNED FILES...")
284
    barutils.remove_signed_files(localdir)
285
286
    # Move loaders
287
    print("MOVING LOADERS...")
288
    barutils.move_loaders(localdir, ld_o, ld_r, zd_o, zd_r)
289
    loadername = os.path.join(ld_o, loadername)
290
291
    # Delete empty folders
292
    print("REMOVING EMPTY FOLDERS...")
293
    barutils.remove_empty_folders(localdir)
294
295
    if autoloader:
296
        subprocess.call(loadername)
297
    print("\nFINISHED!!!")
298
299
300
if __name__ == "__main__":
301
    grab_args()
302
    decorators.enter_to_exit(True)
303