summaryrefslogtreecommitdiff
path: root/hacking/shippable/run.py
blob: 310a7f53f008c2039d5b87ad13183e6e65563046 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK

# (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
"""CLI tool for starting new Shippable CI runs."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

# noinspection PyCompatibility
import argparse
import json
import os

import requests

try:
    import argcomplete
except ImportError:
    argcomplete = None


def main():
    """Main program body."""
    args = parse_args()
    start_run(args)


def parse_args():
    """Parse and return args."""
    api_key = get_api_key()

    parser = argparse.ArgumentParser(description='Start a new Shippable run.')

    parser.add_argument('project',
                        metavar='account/project',
                        help='Shippable account/project')

    target = parser.add_mutually_exclusive_group()

    target.add_argument('--branch',
                        help='branch name')

    target.add_argument('--run',
                        metavar='ID',
                        help='Shippable run ID')

    parser.add_argument('--key',
                        metavar='KEY',
                        default=api_key,
                        required=not api_key,
                        help='Shippable API key')

    parser.add_argument('--env',
                        nargs=2,
                        metavar=('KEY', 'VALUE'),
                        action='append',
                        help='environment variable to pass')

    if argcomplete:
        argcomplete.autocomplete(parser)

    args = parser.parse_args()

    return args


def start_run(args):
    """Start a new Shippable run."""
    headers = dict(
        Authorization='apiToken %s' % args.key,
    )

    # get project ID

    data = dict(
        projectFullNames=args.project,
    )

    url = 'https://api.shippable.com/projects'
    response = requests.get(url, data, headers=headers)

    if response.status_code != 200:
        raise Exception(response.content)

    result = response.json()

    if len(result) != 1:
        raise Exception(
            'Received %d items instead of 1 looking for %s in:\n%s' % (
                len(result),
                args.project,
                json.dumps(result, indent=4, sort_keys=True)))

    project_id = response.json()[0]['id']

    # new build

    data = dict(
        globalEnv=dict((kp[0], kp[1]) for kp in args.env or [])
    )

    if args.branch:
        data['branchName'] = args.branch
    elif args.run:
        data['runId'] = args.run

    url = 'https://api.shippable.com/projects/%s/newBuild' % project_id
    response = requests.post(url, json=data, headers=headers)

    if response.status_code != 200:
        raise Exception("HTTP %s: %s\n%s" % (response.status_code, response.reason, response.content))

    print(json.dumps(response.json(), indent=4, sort_keys=True))


def get_api_key():
    """
    rtype: str
    """
    key = os.environ.get('SHIPPABLE_KEY', None)

    if key:
        return key

    path = os.path.join(os.environ['HOME'], '.shippable.key')

    try:
        with open(path, 'r') as key_fd:
            return key_fd.read().strip()
    except IOError:
        return None


if __name__ == '__main__':
    main()