Passed
Push — appveyor ( e37cfd...86a896 )
by Konstantinos
01:25
created

appveyor-download.make_auth_headers()   A

Complexity

Conditions 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 15
rs 9.9
c 0
b 0
f 0
cc 3
nop 0
1
#!/usr/bin/env python
2
"""
3
Use the AppVeyor API to download Windows artifacts.
4
5
Taken from: https://bitbucket.org/ned/coveragepy/src/tip/ci/download_appveyor.py
6
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
7
# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
8
"""
9
from __future__ import unicode_literals
10
11
import argparse
12
import os
13
import zipfile
14
15
import requests
16
17
18
def make_auth_headers():
19
    """Make the authentication headers needed to use the Appveyor API."""
20
    path = os.path.expanduser("~/.appveyor.token")
21
    if not os.path.exists(path):
22
        raise RuntimeError(
23
            "Please create a file named `.appveyor.token` in your home directory. "
24
            "You can get the token from https://ci.appveyor.com/api-token"
25
        )
26
    with open(path) as f:
27
        token = f.read().strip()
28
29
    headers = {
30
        'Authorization': 'Bearer {}'.format(token),
31
    }
32
    return headers
33
34
35
def download_latest_artifacts(account_project, build_id):
36
    """Download all the artifacts from the latest build."""
37
    if build_id is None:
38
        url = "https://ci.appveyor.com/api/projects/{}".format(account_project)
39
    else:
40
        url = "https://ci.appveyor.com/api/projects/{}/build/{}".format(account_project, build_id)
41
    build = requests.get(url, headers=make_auth_headers()).json()
42
    jobs = build['build']['jobs']
43
    print(u"Build {0[build][version]}, {1} jobs: {0[build][message]}".format(build, len(jobs)))
44
45
    for job in jobs:
46
        name = job['name']
47
        print(u"  {0}: {1[status]}, {1[artifactsCount]} artifacts".format(name, job))
48
49
        url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts".format(job['jobId'])
50
        response = requests.get(url, headers=make_auth_headers())
51
        artifacts = response.json()
52
53
        for artifact in artifacts:
54
            is_zip = artifact['type'] == "Zip"
55
            filename = artifact['fileName']
56
            print(u"    {0}, {1} bytes".format(filename, artifact['size']))
57
58
            url = "https://ci.appveyor.com/api/buildjobs/{}/artifacts/{}".format(job['jobId'], filename)
59
            ensure_dirs(filename)
60
            response = requests.get(url, headers=headers, stream=True)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable headers does not seem to be defined.
Loading history...
61
            if response.status_code == 200:
62
                with open(filename, 'wb') as f:
63
                    for chunk in response.iter_content(16 * 1024):
64
                        f.write(chunk)
65
            else:
66
                print(u"    Error downloading {}: {}".format(url, response))
67
68
            if is_zip:
69
                unpack_zipfile(filename)
70
                os.remove(filename)
71
72
73
def ensure_dirs(filename):
74
    """Make sure the directories exist for `filename`."""
75
    dirname = os.path.dirname(filename)
76
    if dirname and not os.path.exists(dirname):
77
        os.makedirs(dirname)
78
79
80
def unpack_zipfile(filename):
81
    """Unpack a zipfile, using the names in the zip."""
82
    with open(filename, 'rb') as fzip:
83
        z = zipfile.ZipFile(fzip)
84
        for name in z.namelist():
85
            print(u"      extracting {}".format(name))
86
            ensure_dirs(name)
87
            z.extract(name)
88
89
90
parser = argparse.ArgumentParser(description='Download artifacts from AppVeyor.')
91
parser.add_argument('--id',
92
                    metavar='PROJECT_ID',
93
                    default='alpha/dibou-repo',
94
                    help='Project ID in AppVeyor.')
95
parser.add_argument('build',
96
                    nargs='?',
97
                    metavar='BUILD_ID',
98
                    help='Build ID in AppVeyor. Eg: master-123')
99
100
if __name__ == "__main__":
101
    # import logging
102
    # logging.basicConfig(level="DEBUG")
103
    args = parser.parse_args()
104
    download_latest_artifacts(args.id, args.build)
105