Completed
Push — master ( d6f670...02bc12 )
by John
01:13
created

main()   A

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
c 1
b 1
f 0
dl 0
loc 13
rs 9.4285
1
#!/usr/bin/env python3
2
3
"""Manually download dat files, if Git-LFS isn't working or something."""
4
5
import os
6
import requests
7
from bbarchivist.bbconstants import CAP, CFP
8
9
__author__ = "Thurask"
10
__license__ = "WTFPL v2"
11
__copyright__ = "Copyright 2015-2016 Thurask"
12
13
14
def download(url, output_directory=None):
15
    """
16
    Download file from given URL.
17
18
    :param url: URL to download from.
19
    :type url: str
20
21
    :param output_directory: Download folder. Default is local.
22
    :type output_directory: str
23
    """
24
    if output_directory is None:
25
        output_directory = os.getcwd()
26
    lfname = url.split('/')[-1]
27
    fname = os.path.join(output_directory, lfname)
28
    with open(fname, "wb") as file:
29
        req = requests.get(url, stream=True)
30
        if req.status_code == 200:  # 200 OK
31
            print("DOWNLOADING {0}".format(lfname))
32
            for chunk in req.iter_content(chunk_size=1024):
33
                file.write(chunk)
34
        else:
35
            print("ERROR: HTTP {0} IN {1}".format(req.status_code, lfname))
36
37
38
def prep_file(datafile, filelist):
39
    """
40
    Prepare a file for download if necessary.
41
42
    :param datafile: Datafile instance.
43
    :type datafile: bbarchivist.bbconstants.Datafile
44
45
    :param filelist: List of files that need downloading.
46
    :type filelist: list(str)
47
    """
48
    basename = "https://github.com/thurask/bbarchivist/raw/master/bbarchivist/"
49
    afile = os.path.basename(datafile.location)
50
    try:
51
        if os.path.getsize(datafile.location) != datafile.size:
52
            filelist.append(basename + afile)
53
    except FileNotFoundError:
54
        filelist.append(basename + afile)
55
    return filelist
56
57
58
def main():
59
    """
60
    Download cap and cfp files, in lieu of Git-LFS.
61
    """
62
    files = []
63
    files = prep_file(CAP, files)
64
    files = prep_file(CFP, files)
65
    outdir = os.path.join(os.getcwd(), "bbarchivist")
66
    if files:
67
        for file in files:
68
            download(file, outdir)
69
    else:
70
        print("NOTHING TO DOWNLOAD!")
71
72
73
if __name__ == "__main__":
74
    main()
75