Completed
Push — master ( e08c5d...6dc174 )
by John
03:10
created

wsz_local_good()   A

Complexity

Conditions 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3.6875

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
c 1
b 0
f 0
dl 0
loc 10
ccs 1
cts 4
cp 0.25
crap 3.6875
rs 9.4285
1
#!/usr/bin/env python3
2 5
"""This module is used for miscellaneous utilities."""
3
4 5
import os  # path work
5 5
import argparse  # argument parser for filters
6 5
import platform  # platform info
7 5
import glob  # cap grabbing
8 5
import hashlib  # base url creation
9 5
import threading  # get thread for spinner
10 5
import time  # spinner delay
11 5
import sys  # streams, version info
12 5
import itertools  # spinners gonna spin
13 5
import subprocess  # loader verification
14 5
from bbarchivist import bbconstants  # cap location, version, filename bits
15 5
from bbarchivist import compat  # backwards compat
16 5
from bbarchivist import dummy  # useless stdout
17 5
from bbarchivist import exceptions  # exceptions
18 5
from bbarchivist import iniconfig  # config parsing
19
20 5
__author__ = "Thurask"
21 5
__license__ = "WTFPL v2"
22 5
__copyright__ = "2015-2017 Thurask"
23
24
25 5
def grab_datafile(datafile):
26
    """
27
    Figure out where a datafile is.
28
29
    :param datafile: Datafile to check.
30
    :type datafile: bbconstants.Datafile
31
    """
32 5
    try:
33 5
        afile = glob.glob(os.path.join(os.getcwd(), datafile.filename))[0]
34 5
    except IndexError:
35 5
        afile = datafile.location if datafile.name == "cfp" else grab_capini(datafile)
36 5
    return os.path.abspath(afile)
37
38
39 5
def grab_capini(datafile):
40
    """
41
    Get cap location from .ini file, and write if it's new.
42
43
    :param datafile: Datafile to check.
44
    :type datafile: bbconstants.Datafile
45
    """
46
    try:
47
        apath = cappath_config_loader()
48
        afile = glob.glob(apath)[0]
49
    except IndexError:
50
        cappath_config_writer(datafile.location)
51
        return bbconstants.CAP.location  # no ini cap
52
    else:
53
        cappath_config_writer(os.path.abspath(afile))
54
        return os.path.abspath(afile)  # ini cap:
55
56
57 5
def grab_cap():
58
    """
59
    Figure out where cap is, local, specified or system-supplied.
60
    """
61 5
    return grab_datafile(bbconstants.CAP)
62
63
64 5
def grab_cfp():
65
    """
66
    Figure out where cfp is, local or system-supplied.
67
    """
68 5
    return grab_datafile(bbconstants.CFP)
69
70
71 5
def new_enough(minver):
72
    """
73
    Check if we're at or above a minimum Python version.
74
75
    :param minver: Minimum Python version (3.minver).
76
    :type minver: int
77
    """
78 5
    return False if minver > sys.version_info[1] else True
79
80
81 5
def dirhandler(directory, defaultdir):
82
    """
83
    If directory is None, turn it into defaultdir.
84
85
    :param directory: Target directory.
86
    :type directory: str
87
88
    :param defaultdir: Default directory.
89
    :type defaultdir: str
90
    """
91 5
    directory = defaultdir if directory is None else directory
92 5
    return directory
93
94
95 5
def fsizer(file_size):
96
    """
97
    Raw byte file size to human-readable string.
98
99
    :param file_size: Number to parse.
100
    :type file_size: float
101
    """
102 5
    fsize = prep_filesize(file_size)
103 5
    for sfix in ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']:
104 5
        if fsize < 1024.0:
105 5
            size = "{0:3.2f}{1}".format(fsize, sfix)
106 5
            break
107
        else:
108 5
            fsize /= 1024.0
109
    else:
110 5
        size = "{0:3.2f}{1}".format(fsize, 'YB')
111 5
    return size
112
113
114 5
def prep_filesize(file_size):
115
    """
116
    Convert file size to float.
117
118
    :param file_size: Number to parse.
119
    :type file_size: float
120
    """
121 5
    if file_size is None:
122 5
        file_size = 0.0
123 5
    fsize = float(file_size)
124 5
    return fsize
125
126
127 5
def signed_file_args(files):
128
    """
129
    Check if there are between 1 and 6 files supplied to argparse.
130
131
    :param files: List of signed files, between 1 and 6 strings.
132
    :type files: list(str)
133
    """
134 5
    filelist = [file for file in files if file]
135 5
    if not 1 <= len(filelist) <= 6:
136 5
        raise argparse.ArgumentError(argument=None, message="Requires 1-6 signed files")
137 5
    return files
138
139
140 5
def file_exists(file):
141
    """
142
    Check if file exists, raise argparse error if it doesn't.
143
144
    :param file: Path to a file, including extension.
145
    :type file: str
146
    """
147 5
    if not os.path.exists(file):
148 5
        raise argparse.ArgumentError(argument=None, message="{0} not found.".format(file))
149 5
    return file
150
151
152 5
def positive_integer(input_int):
153
    """
154
    Check if number > 0, raise argparse error if it isn't.
155
156
    :param input_int: Integer to check.
157
    :type input_int: str
158
    """
159 5
    if int(input_int) <= 0:
160 5
        info = "{0} is not >=0.".format(str(input_int))
161 5
        raise argparse.ArgumentError(argument=None, message=info)
162 5
    return int(input_int)
163
164
165 5
def valid_method(method):
166
    """
167
    Check if compression method is valid, raise argparse error if it isn't.
168
169
    :param method: Compression method to check.
170
    :type method: str
171
    """
172 5
    methodlist = bbconstants.METHODS
173 5
    if not new_enough(3):
174 5
        methodlist = [x for x in bbconstants.METHODS if x != "txz"]
175 5
    if method not in methodlist:
176 5
        info = "Invalid method {0}.".format(method)
177 5
        raise argparse.ArgumentError(argument=None, message=info)
178 5
    return method
179
180
181 5
def valid_carrier(mcc_mnc):
182
    """
183
    Check if MCC/MNC is valid (1-3 chars), raise argparse error if it isn't.
184
185
    :param mcc_mnc: MCC/MNC to check.
186
    :type mcc_mnc: str
187
    """
188 5
    if not str(mcc_mnc).isdecimal():
189 5
        infod = "Non-integer {0}.".format(str(mcc_mnc))
190 5
        raise argparse.ArgumentError(argument=None, message=infod)
191 5
    if len(str(mcc_mnc)) > 3 or len(str(mcc_mnc)) == 0:
192 5
        infol = "{0} is invalid.".format(str(mcc_mnc))
193 5
        raise argparse.ArgumentError(argument=None, message=infol)
194
    else:
195 5
        return mcc_mnc
196
197
198 5
def escreens_pin(pin):
199
    """
200
    Check if given PIN is valid, raise argparse error if it isn't.
201
202
    :param pin: PIN to check.
203
    :type pin: str
204
    """
205 5
    if len(pin) == 8:
206 5
        try:
207 5
            int(pin, 16)  # hexadecimal-ness
208 5
        except ValueError:
209 5
            raise argparse.ArgumentError(argument=None, message="Invalid PIN.")
210
        else:
211 5
            return pin.lower()
212
    else:
213 5
        raise argparse.ArgumentError(argument=None, message="Invalid PIN.")
214
215
216 5
def escreens_duration(duration):
217
    """
218
    Check if Engineering Screens duration is valid.
219
220
    :param duration: Duration to check.
221
    :type duration: int
222
    """
223 5
    if int(duration) in (1, 3, 6, 15, 30):
224 5
        return int(duration)
225
    else:
226 5
        raise argparse.ArgumentError(argument=None, message="Invalid duration.")
227
228
229 5
def droidlookup_hashtype(method):
230
    """
231
    Check if Android autoloader lookup hash type is valid.
232
233
    :param method: None for regular OS links, "sha256/512" for SHA256 or 512 hash.
234
    :type method: str
235
    """
236 5
    if method.lower() in ("sha512", "sha256"):
237 5
        return method.lower()
238
    else:
239 5
        raise argparse.ArgumentError(argument=None, message="Invalid type.")
240
241
242 5
def droidlookup_devicetype(device):
243
    """
244
    Check if Android autoloader device type is valid.
245
246
    :param device: Android autoloader types to check.
247
    :type device: str
248
    """
249 5
    devices = ("Priv", "DTEK50", "DTEK60", "KEYone", "Aurora")
250 5
    if device is None:
251 5
        return None
252
    else:
253 5
        for dev in devices:
254 5
            if dev.lower() == device.lower():
255 5
                return dev
256 5
        raise argparse.ArgumentError(argument=None, message="Invalid device.")
257
258
259 5
def s2b(input_check):
260
    """
261
    Return Boolean interpretation of string input.
262
263
    :param input_check: String to check if it means True or False.
264
    :type input_check: str
265
    """
266 5
    return str(input_check).lower() in ("yes", "true", "t", "1", "y")
267
268
269 5
def is_amd64():
270
    """
271
    Check if script is running on an AMD64 system (Python can be 32/64, this is for subprocess)
272
    """
273 5
    return platform.machine().endswith("64")
274
275
276 5
def is_windows():
277
    """
278
    Check if script is running on Windows.
279
    """
280 5
    return platform.system() == "Windows"
281
282
283 5
def talkaprint(msg, talkative=False):
284
    """
285
    Print only if asked to.
286
287
    :param msg: Message to print.
288
    :type msg: str
289
290
    :param talkative: Whether to output to screen. False by default.
291
    :type talkative: bool
292
    """
293 5
    if talkative:
294 5
        print(msg)
295
296
297 5
def get_seven_zip(talkative=False):
298
    """
299
    Return name of 7-Zip executable.
300
    On POSIX, it MUST be 7za.
301
    On Windows, it can be installed or supplied with the script.
302
    :func:`win_seven_zip` is used to determine if it's installed.
303
304
    :param talkative: Whether to output to screen. False by default.
305
    :type talkative: bool
306
    """
307 5
    return win_seven_zip(talkative) if is_windows() else "7za"
308
309
310 5
def win_seven_zip(talkative=False):
311
    """
312
    For Windows, check where 7-Zip is ("where", pretty much).
313
    Consult registry first for any installed instances of 7-Zip.
314
315
    :param talkative: Whether to output to screen. False by default.
316
    :type talkative: bool
317
    """
318
    talkaprint("CHECKING INSTALLED FILES...", talkative)
319
    try:
320
        path = wsz_registry(talkative)
321
    except OSError as exc:
322
        if talkative:
323
            exceptions.handle_exception(exc, xit=None)
324
        talkaprint("TRYING LOCAL FILES...", talkative)
325
        return win_seven_zip_local(talkative)
326
    else:
327
        talkaprint("7ZIP USING INSTALLED FILES", talkative)
328
        return '"{0}"'.format(os.path.join(path[0], "7z.exe"))
329
330
331 5
def wsz_registry(talkative=False):
0 ignored issues
show
Unused Code introduced by
The argument talkative seems to be unused.
Loading history...
332
    """
333
    Check Windows registry for 7-Zip executable location.
334
335
    :param talkative: Whether to output to screen. False by default.
336
    :type talkative: bool
337
    """
338
    import winreg  # windows registry
339
    hk7z = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\7-Zip")
340
    path = winreg.QueryValueEx(hk7z, "Path")
341
    return path
342
343
344 5
def win_seven_zip_local(talkative=False):
345
    """
346
    If 7-Zip isn't in the registry, fall back onto supplied executables.
347
    If *those* aren't there, return "error".
348
349
    :param talkative: Whether to output to screen. False by default.
350
    :type talkative: bool
351
    """
352
    filecount = wsz_filecount()
353
    if filecount == 2:
354
        szexe = wsz_local_good(talkative)
355
    else:
356
        szexe = wsz_local_bad(talkative)
357
    return szexe
358
359
360 5
def wsz_filecount():
361
    """
362
    Get count of 7-Zip executables in local folder.
363
    """
364
    filecount = len([x for x in os.listdir(os.getcwd()) if x in ["7za.exe", "7z.exe"]])
365
    return filecount
366
367
368 5
def wsz_local_good(talkative=False):
369
    """
370
    Get 7-Zip exe name if everything is good.
371
372
    :param talkative: Whether to output to screen. False by default.
373
    :type talkative: bool
374
    """
375
    talkaprint("7ZIP USING LOCAL FILES", talkative)
376
    szexe = "7za.64.exe" if is_amd64() else "7za.exe"
377
    return szexe
378
379
380 5
def wsz_local_bad(talkative=False):
381
    """
382
    Handle 7-Zip exe name in case of issues.
383
384
    :param talkative: Whether to output to screen. False by default.
385
    :type talkative: bool
386
    """
387
    talkaprint("NO LOCAL FILES", talkative)
388
    szexe = "error"
389
    return szexe
390
391
392 5
def get_core_count():
393
    """
394
    Find out how many CPU cores this system has.
395
    """
396 5
    try:
397 5
        cores = str(compat.enum_cpus())  # 3.4 and up
398
    except NotImplementedError:
399
        cores = "1"  # 3.2-3.3
400
    else:
401 5
        if compat.enum_cpus() is None:
402
            cores = "1"
403 5
    return cores
404
405
406 5
def prep_seven_zip_path(path, talkative=False):
407
    """
408
    Print p7zip path on POSIX, or notify if not there.
409
410
    :param path: Path to use.
411
    :type path: str
412
413
    :param talkative: Whether to output to screen. False by default.
414
    :type talkative: bool
415
    """
416 5
    if path is None:
417 5
        talkaprint("NO 7ZIP\nPLEASE INSTALL p7zip", talkative)
418 5
        return False
419
    else:
420 5
        talkaprint("7ZIP FOUND AT {0}".format(path), talkative)
421 5
        return True
422
423
424 5
def prep_seven_zip_posix(talkative=False):
425
    """
426
    Check for p7zip on POSIX.
427
428
    :param talkative: Whether to output to screen. False by default.
429
    :type talkative: bool
430
    """
431 5
    try:
432 5
        path = compat.where_which("7za")
433 5
    except ImportError:
434 5
        talkaprint("PLEASE INSTALL SHUTILWHICH WITH PIP", talkative)
435 5
        return False
436
    else:
437 5
        return prep_seven_zip_path(path, talkative)
438
439
440 5
def prep_seven_zip(talkative=False):
441
    """
442
    Check for presence of 7-Zip.
443
    On POSIX, check for p7zip.
444
    On Windows, check for 7-Zip.
445
446
    :param talkative: Whether to output to screen. False by default.
447
    :type talkative: bool
448
    """
449 5
    if is_windows():
450
        return get_seven_zip(talkative) != "error"
451
    else:
452 5
        return prep_seven_zip_posix(talkative)
453
454
455 5
def increment(version, inc=3):
456
    """
457
    Increment version by given number. For repeated lookups.
458
459
    :param version: w.x.y.ZZZZ, becomes w.x.y.(ZZZZ + increment).
460
    :type version: str
461
462
    :param inc: What to increment by. Default is 3.
463
    :type inc: str
464
    """
465 5
    splitos = version.split(".")
466 5
    splitos[3] = int(splitos[3])
467 5
    if splitos[3] > 9996:  # prevent overflow
468 5
        splitos[3] = 0
469 5
    splitos[3] += int(inc)
470 5
    splitos[3] = str(splitos[3])
471 5
    return ".".join(splitos)
472
473
474 5
def stripper(name):
475
    """
476
    Strip fluff from bar filename.
477
478
    :param name: Bar filename, must contain '-nto+armle-v7+signed.bar'.
479
    :type name: str
480
    """
481 5
    return name.replace("-nto+armle-v7+signed.bar", "")
482
483
484 5
def create_base_url(softwareversion):
485
    """
486
    Make the root URL for production server files.
487
488
    :param softwareversion: Software version to hash.
489
    :type softwareversion: str
490
    """
491
    # Hash software version
492 5
    swhash = hashlib.sha1(softwareversion.encode('utf-8'))
493 5
    hashedsoftwareversion = swhash.hexdigest()
494
    # Root of all urls
495 5
    baseurl = "http://cdn.fs.sl.blackberry.com/fs/qnx/production/{0}".format(hashedsoftwareversion)
496 5
    return baseurl
497
498
499 5
def format_app_name(appname):
500
    """
501
    Convert long reverse DNS name to short name.
502
503
    :param appname: Application name (ex. sys.pim.calendar -> "calendar")
504
    :type appname: str
505
    """
506 5
    final = appname.split(".")[-1]
507 5
    return final
508
509
510 5
def create_bar_url(softwareversion, appname, appversion, clean=False):
511
    """
512
    Make the URL for any production server file.
513
514
    :param softwareversion: Software version to hash.
515
    :type softwareversion: str
516
517
    :param appname: Application name, preferably like on server.
518
    :type appname: str
519
520
    :param appversion: Application version.
521
    :type appversion: str
522
523
    :param clean: Whether or not to clean up app name. Default is False.
524
    :type clean: bool
525
    """
526 5
    baseurl = create_base_url(softwareversion)
527 5
    if clean:
528 5
        appname = format_app_name(appname)
529 5
    return "{0}/{1}-{2}-nto+armle-v7+signed.bar".format(baseurl, appname, appversion)
530
531
532 5
def generate_urls(softwareversion, osversion, radioversion, core=False):
533
    """
534
    Generate a list of OS URLs and a list of radio URLs based on input.
535
536
    :param softwareversion: Software version to hash.
537
    :type softwareversion: str
538
539
    :param osversion: OS version.
540
    :type osversion: str
541
542
    :param radioversion: Radio version.
543
    :type radioversion: str
544
545
    :param core: Whether or not to return core URLs as well.
546
    :type core: bool
547
    """
548 5
    osurls = [
549
        create_bar_url(softwareversion, "winchester.factory_sfi.desktop", osversion),
550
        create_bar_url(softwareversion, "qc8960.factory_sfi.desktop", osversion),
551
        create_bar_url(softwareversion, "qc8960.factory_sfi.desktop", osversion),
552
        create_bar_url(softwareversion, "qc8974.factory_sfi.desktop", osversion)
553
    ]
554 5
    radiourls = [
555
        create_bar_url(softwareversion, "m5730", radioversion),
556
        create_bar_url(softwareversion, "qc8960", radioversion),
557
        create_bar_url(softwareversion, "qc8960.omadm", radioversion),
558
        create_bar_url(softwareversion, "qc8960.wtr", radioversion),
559
        create_bar_url(softwareversion, "qc8960.wtr5", radioversion),
560
        create_bar_url(softwareversion, "qc8930.wtr5", radioversion),
561
        create_bar_url(softwareversion, "qc8974.wtr2", radioversion)
562
    ]
563 5
    coreurls = []
564 5
    osurls, radiourls = filter_urls(osurls, radiourls, osversion)
565 5
    if core:
566 5
        coreurls = [x.replace(".desktop", "") for x in osurls]
567 5
    return osurls, radiourls, coreurls
568
569
570 5
def newer_103(splitos, third):
571
    """
572
    Return True if given split OS version is 10.3.X or newer.
573
574
    :param splitos: OS version, split on the dots: [10, 3, 3, 2205]
575
    :type: list(int)
576
577
    :param third: The X in 10.3.X.
578
    :type third: int
579
    """
580 5
    newer = True if ((splitos[1] >= 4) or (splitos[1] == 3 and splitos[2] >= third)) else False
581 5
    return newer
582
583
584 5
def filter_urls(osurls, radiourls, osversion):
585
    """
586
    Filter lists of OS and radio URLs.
587
588
    :param osurls: List of OS URLs.
589
    :type osurls: list(str)
590
591
    :param radiourls: List of radio URLs.
592
    :type radiourls: list(str)
593
594
    :param osversion: OS version.
595
    :type osversion: str
596
    """
597 5
    splitos = [int(i) for i in osversion.split(".")]
598 5
    osurls[2] = filter_1031(osurls[2], splitos, 5)  # Z3 10.3.1+
599 5
    osurls[3] = filter_1031(osurls[3], splitos, 6)  # Passport 10.3.1+
600 5
    osurls[0], radiourls[0] = pop_stl1(osurls[0], radiourls[0], splitos)  # STL100-1 10.3.3+
601 5
    return osurls, radiourls
602
603
604 5
def filter_1031(osurl, splitos, device):
605
    """
606
    Modify URLs to reflect changes in 10.3.1.
607
608
    :param osurl: OS URL to modify.
609
    :type osurl: str
610
611
    :param splitos: OS version, split and cast to int: [10, 3, 2, 2876]
612
    :type splitos: list(int)
613
614
    :param device: Device to use.
615
    :type device: int
616
    """
617 5
    if newer_103(splitos, 1):
618 5
        filterdict = {5: ("qc8960.factory_sfi", "qc8960.factory_sfi_hybrid_qc8x30"), 6: ("qc8974.factory_sfi", "qc8960.factory_sfi_hybrid_qc8974")}
619 5
        osurl = filter_osversion(osurl, device, filterdict)
620 5
    return osurl
621
622
623 5
def pop_stl1(osurl, radiourl, splitos):
624
    """
625
    Replace STL100-1 links in 10.3.3+.
626
627
    :param osurl: OS URL to modify.
628
    :type osurl: str
629
630
    :param radiourl: Radio URL to modify.
631
    :type radiourl: str
632
633
    :param splitos: OS version, split and cast to int: [10, 3, 3, 2205]
634
    :type splitos: list(int)
635
    """
636 5
    if newer_103(splitos, 3):
637 5
        osurl = osurl.replace("winchester", "qc8960")  # duplicates get filtered out later
638 5
        radiourl = radiourl.replace("m5730", "qc8960")
639 5
    return osurl, radiourl
640
641
642 5
def filter_osversion(osurl, device, filterdict):
643
    """
644
    Modify URLs based on device index and dictionary of changes.
645
646
    :param osurl: OS URL to modify.
647
    :type osurl: str
648
649
    :param device: Device to use.
650
    :type device: int
651
652
    :param filterdict: Dictionary of changes: {device : (before, after)}
653
    :type filterdict: dict(int:(str, str))
654
    """
655 5
    if device in filterdict.keys():
656 5
        osurl = osurl.replace(filterdict[device][0], filterdict[device][1])
657 5
    return osurl
658
659
660 5
def generate_lazy_urls(softwareversion, osversion, radioversion, device):
661
    """
662
    Generate a pair of OS/radio URLs based on input.
663
664
    :param softwareversion: Software version to hash.
665
    :type softwareversion: str
666
667
    :param osversion: OS version.
668
    :type osversion: str
669
670
    :param radioversion: Radio version.
671
    :type radioversion: str
672
673
    :param device: Device to use.
674
    :type device: int
675
    """
676 5
    splitos = [int(i) for i in osversion.split(".")]
677 5
    rads = ["m5730", "qc8960", "qc8960.omadm", "qc8960.wtr",
678
            "qc8960.wtr5", "qc8930.wtr4", "qc8974.wtr2"]
679 5
    oses = ["winchester.factory", "qc8960.factory", "qc8960.verizon",
680
            "qc8974.factory"]
681 5
    maps = {0:0, 1:1, 2:2, 3:1, 4:1, 5:1, 6:3}
682 5
    osurl = create_bar_url(softwareversion, "{0}_sfi.desktop".format(oses[maps[device]]), osversion)
683 5
    radiourl = create_bar_url(softwareversion, rads[device], radioversion)
684 5
    osurl = filter_1031(osurl, splitos, device)
685 5
    return osurl, radiourl
686
687
688 5
def bulk_urls(softwareversion, osversion, radioversion, core=False, altsw=None):
689
    """
690
    Generate all URLs, plus extra Verizon URLs.
691
692
    :param softwareversion: Software version to hash.
693
    :type softwareversion: str
694
695
    :param osversion: OS version.
696
    :type osversion: str
697
698
    :param radioversion: Radio version.
699
    :type radioversion: str
700
701
    :param device: Device to use.
702
    :type device: int
703
704
    :param core: Whether or not to return core URLs as well.
705
    :type core: bool
706
707
    :param altsw: Radio software release, if not the same as OS.
708
    :type altsw: str
709
    """
710 5
    baseurl = create_base_url(softwareversion)
711 5
    osurls, radurls, coreurls = generate_urls(softwareversion, osversion, radioversion, core)
712 5
    vzwos, vzwrad = generate_lazy_urls(softwareversion, osversion, radioversion, 2)
713 5
    osurls.append(vzwos)
714 5
    radurls.append(vzwrad)
715 5
    vzwcore = vzwos.replace("sfi.desktop", "sfi")
716 5
    if core:
717 5
        coreurls.append(vzwcore)
718 5
    osurls = list(set(osurls))  # pop duplicates
719 5
    radurls = list(set(radurls))
720 5
    if core:
721 5
        coreurls = list(set(coreurls))
722 5
    if altsw is not None:
723 5
        altbase = create_base_url(altsw)
724 5
        radiourls2 = []
725 5
        for rad in radurls:
726 5
            radiourls2.append(rad.replace(baseurl, altbase))
727 5
        radurls = radiourls2
728 5
        del radiourls2
729 5
    return osurls, coreurls, radurls
730
731
732 5
def line_begin():
733
    """
734
    Go to beginning of line, to overwrite whatever's there.
735
    """
736 5
    sys.stdout.write("\r")
737 5
    sys.stdout.flush()
738
739
740 5
def spinner_clear():
741
    """
742
    Get rid of any spinner residue left in stdout.
743
    """
744 5
    sys.stdout.write("\b \b")
745 5
    sys.stdout.flush()
746
747
748 5
class Spinner(object):
749
    """
750
    A basic spinner using itertools. No need for progress.
751
    """
752
753 5
    def __init__(self):
754 5
        self.wheel = itertools.cycle(['-', '/', '|', '\\'])
755 5
        self.file = dummy.UselessStdout()
756
757 5
    def after(self):
758
        """
759
        Iterate over itertools.cycle, write to file.
760
        """
761 5
        try:
762 5
            self.file.write(next(self.wheel))
763 5
            self.file.flush()
764 5
            self.file.write("\b\r")
765 5
            self.file.flush()
766
        except (KeyboardInterrupt, SystemExit):
767
            self.stop()
768
769 5
    def stop(self):
770
        """
771
        Kill output.
772
        """
773 5
        self.file = dummy.UselessStdout()
774
775
776 5
class SpinManager(object):
777
    """
778
    Wraps around the itertools spinner, runs it in another thread.
779
    """
780
781 5
    def __init__(self):
782 5
        spinner = Spinner()
783 5
        self.spinner = spinner
784 5
        self.thread = threading.Thread(target=self.loop, args=())
785 5
        self.thread.daemon = True
786 5
        self.scanning = False
787 5
        self.spinner.file = dummy.UselessStdout()
788
789 5
    def start(self):
790
        """
791
        Begin the spinner.
792
        """
793 5
        self.spinner.file = sys.stderr
794 5
        self.scanning = True
795 5
        self.thread.start()
796
797 5
    def loop(self):
798
        """
799
        Spin if scanning, clean up if not.
800
        """
801 5
        while self.scanning:
802 5
            time.sleep(0.5)
803 5
            try:
804 5
                line_begin()
805 5
                self.spinner.after()
806
            except (KeyboardInterrupt, SystemExit):
807
                self.scanning = False
808
                self.stop()
809
810 5
    def stop(self):
811
        """
812
        Stop the spinner.
813
        """
814 5
        self.spinner.stop()
815 5
        self.scanning = False
816 5
        spinner_clear()
817 5
        line_begin()
818 5
        if not is_windows():
819 5
            print("\n")
820
821
822 5
def return_and_delete(target):
823
    """
824
    Read text file, then delete it. Return contents.
825
826
    :param target: Text file to read.
827
    :type target: str
828
    """
829 5
    with open(target, "r") as thefile:
830 5
        content = thefile.read()
831 5
    os.remove(target)
832 5
    return content
833
834
835 5
def verify_loader_integrity(loaderfile):
836
    """
837
    Test for created loader integrity. Windows-only.
838
839
    :param loaderfile: Path to loader.
840
    :type loaderfile: str
841
    """
842 5
    if not is_windows():
843 5
        pass
844
    else:
845 5
        excode = None
846 5
        try:
847 5
            with open(os.devnull, 'rb') as dnull:
848 5
                cmd = "{0} fileinfo".format(loaderfile)
849 5
                excode = subprocess.call(cmd, stdout=dnull, stderr=subprocess.STDOUT)
850 5
        except OSError:
851 5
            excode = -1
852 5
        return excode == 0  # 0 if OK, non-zero if something broke
853
854
855 5
def bulkfilter_printer(afile):
856
    """
857
    Print filename and verify a loader file.
858
859
    :param afile: Path to file.
860
    :type afile: str
861
    """
862 5
    print("TESTING: {0}".format(os.path.basename(afile)))
863 5
    if not verify_loader_integrity(afile):
864 5
        return os.path.basename(afile)
865
866
867 5
def bulkfilter(files):
868
    """
869
    Verify all loader files in a given list.
870
871
    :param files: List of files.
872
    :type files: list(str)
873
    """
874 5
    brokens = [bulkfilter_printer(file) for file in files if prepends(os.path.basename(file), bbconstants.PREFIXES, ".exe")]
875 5
    return brokens
876
877
878 5
def verify_bulk_loaders(ldir):
879
    """
880
    Run :func:`verify_loader_integrity` for all files in a dir.
881
882
    :param ldir: Directory to use.
883
    :type ldir: str
884
    """
885 5
    if not is_windows():
886 5
        pass
887
    else:
888 5
        files = verify_bulk_loaders_filefilter(ldir)
889 5
        brokens = verify_bulk_loaders_brokens(files)
890 5
        return brokens
891
892
893 5
def verify_bulk_loaders_filefilter(ldir):
894
    """
895
    Prepare file names for :func:`verify_bulk_loaders`.
896
897
    :param ldir: Directory to use.
898
    :type ldir: str
899
    """
900 5
    files = [os.path.join(ldir, file) for file in os.listdir(ldir) if not os.path.isdir(file)]
901 5
    return files
902
903
904 5
def verify_bulk_loaders_brokens(files):
905
    """
906
    Prepare filtered file list for :func:`verify_bulk_loaders`.
907
908
    :param files: List of files.
909
    :type files: list(str)
910
    """
911 5
    brokens = [file for file in bulkfilter(files) if file]
912 5
    return brokens
913
914
915 5
def list_workers(input_data, workerlimit):
916
    """
917
    Count number of threads, either length of iterable or provided limit.
918
919
    :param input_data: Input data, some iterable.
920
    :type input_data: list
921
922
    :param workerlimit: Maximum number of workers.
923
    :type workerlimit: int
924
    """
925 5
    runners = len(input_data) if len(input_data) < workerlimit else workerlimit
926 5
    return runners
927
928
929 5
def cpu_workers(input_data):
930
    """
931
    Count number of CPU workers, smaller of number of threads and length of data.
932
933
    :param input_data: Input data, some iterable.
934
    :type input_data: list
935
    """
936 5
    return list_workers(input_data, compat.enum_cpus())
937
938
939 5
def prep_logfile():
940
    """
941
    Prepare log file, labeling it with current date. Select folder based on frozen status.
942
    """
943 5
    logfile = "{0}.txt".format(time.strftime("%Y_%m_%d_%H%M%S"))
944 5
    root = os.getcwd() if getattr(sys, 'frozen', False) else os.path.expanduser("~")
945 5
    basefolder = os.path.join(root, "lookuplogs")
946 5
    os.makedirs(basefolder, exist_ok=True)
947 5
    record = os.path.join(basefolder, logfile)
948 5
    open(record, "w").close()
949 5
    return record
950
951
952 5
def prepends(file, pre, suf):
953
    """
954
    Check if filename starts with/ends with stuff.
955
956
    :param file: File to check.
957
    :type file: str
958
959
    :param pre: Prefix(es) to check.
960
    :type pre: str or list or tuple
961
962
    :param suf: Suffix(es) to check.
963
    :type suf: str or list or tuple
964
    """
965 5
    return file.startswith(pre) and file.endswith(suf)
966
967
968 5
def lprint(iterable):
969
    """
970
    A oneliner for 'for item in x: print item'.
971
972
    :param iterable: Iterable to print.
973
    :type iterable: list/tuple
974
    """
975 5
    for item in iterable:
976 5
        print(item)
977
978
979 5
def cappath_config_loader(homepath=None):
980
    """
981
    Read a ConfigParser file to get cap preferences.
982
983
    :param homepath: Folder containing ini file. Default is user directory.
984
    :type homepath: str
985
    """
986 5
    capini = iniconfig.generic_loader('cappath', homepath)
987 5
    cappath = capini.get('path', fallback=bbconstants.CAP.location)
988 5
    return cappath
989
990
991 5
def cappath_config_writer(cappath=None, homepath=None):
992
    """
993
    Write a ConfigParser file to store cap preferences.
994
995
    :param cappath: Method to use.
996
    :type cappath: str
997
998
    :param homepath: Folder containing ini file. Default is user directory.
999
    :type homepath: str
1000
    """
1001 5
    cappath = grab_cap() if cappath is None else cappath
1002 5
    results = {"path": cappath}
1003 5
    iniconfig.generic_writer("cappath", results, homepath)
1004
1005
1006 5
def def_args(dirs):
1007
    """
1008
    Return prepared argument list for most instances of :func:`cond_check:.
1009
1010
    :param dirs: List of directories.
1011
    :type dirs: list(str)
1012
    """
1013 5
    return [dirs[4], dirs[5], dirs[2], dirs[3]]
1014
1015
1016 5
def cond_do(dofunc, goargs, restargs=None, condition=True):
1017
    """
1018
    Do a function, check a condition, then do same function but swap first argument.
1019
1020
    :param dofunc: Function to do.
1021
    :type dofunc: function
1022
1023
    :param goargs: List of variable arguments.
1024
    :type goargs: list(str)
1025
1026
    :param restargs: Rest of arguments, which are constant.
1027
    :type restargs: list(str)
1028
1029
    :param condition: Condition to check in order to use secondarg.
1030
    :type condition: bool
1031
    """
1032 5
    restargs = [] if restargs is None else restargs
1033 5
    dofunc(goargs[0], *restargs)
1034 5
    if condition:
1035 5
        dofunc(goargs[1], *restargs)
1036
1037
1038 5
def cond_check(dofunc, goargs, restargs=None, condition=True, checkif=True, checkifnot=True):
1039
    """
1040
    Do :func:`cond_do` based on a condition, then do it again based on a second condition.
1041
1042
    :param dofunc: Function to do.
1043
    :type dofunc: function
1044
1045
    :param goargs: List of variable arguments.
1046
    :type goargs: list(str)
1047
1048
    :param restargs: Rest of arguments, which are constant.
1049
    :type restargs: list(str)
1050
1051
    :param condition: Condition to check in order to use secondarg.
1052
    :type condition: bool
1053
1054
    :param checkif: Do :func:`cond_do` if this is True.
1055
    :type checkif: bool
1056
1057
    :param checkifnot: Do :func:`cond_do` if this is False.
1058
    :type checkifnot: bool
1059
    """
1060 5
    if checkif:
1061 5
        cond_do(dofunc, goargs[0:2], restargs, condition)
1062 5
    if not checkifnot:
1063
        cond_do(dofunc, goargs[2:4], restargs, condition)
1064