1#!/usr/bin/env python3
2
3#
4# Copyright (C) 2018 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18
19"""A command line utility to post review votes to multiple CLs on Gerrit."""
20
21from __future__ import print_function
22
23import argparse
24import json
25import os
26import sys
27
28try:
29    from urllib.error import HTTPError  # PY3
30except ImportError:
31    from urllib2 import HTTPError  # PY2
32
33from gerrit import (
34    abandon, add_reviewers, create_url_opener_from_args, delete_reviewer,
35    delete_topic, find_gerrit_name, query_change_lists, restore, set_hashtags,
36    set_review, set_topic, submit
37)
38
39
40def _get_labels_from_args(args):
41    """Collect and check labels from args."""
42    if not args.label:
43        return None
44    labels = {}
45    for (name, value) in args.label:
46        try:
47            labels[name] = int(value)
48        except ValueError:
49            print('error: Label {} takes integer, but {} is specified'
50                  .format(name, value), file=sys.stderr)
51    return labels
52
53
54# pylint: disable=redefined-builtin
55def _print_change_lists(change_lists, file=sys.stdout):
56    """Print matching change lists for each projects."""
57    change_lists = sorted(
58        change_lists, key=lambda change: (change['project'], change['_number']))
59
60    prev_project = None
61    print('Change Lists:', file=file)
62    for change in change_lists:
63        project = change['project']
64        if project != prev_project:
65            print(' ', project, file=file)
66            prev_project = project
67
68        change_id = change['change_id']
69        revision_sha1 = change['current_revision']
70        revision = change['revisions'][revision_sha1]
71        subject = revision['commit']['subject']
72        print('   ', change_id, '--', subject, file=file)
73
74
75def _confirm(question):
76    """Confirm before proceeding."""
77    try:
78        if input(question + ' [yn] ').lower() not in {'y', 'yes'}:
79            print('Cancelled', file=sys.stderr)
80            sys.exit(1)
81    except KeyboardInterrupt:
82        print('Cancelled', file=sys.stderr)
83        sys.exit(1)
84
85
86def _parse_args():
87    """Parse command line options."""
88    parser = argparse.ArgumentParser()
89
90    parser.add_argument('query', help='Change list query string')
91    parser.add_argument('-g', '--gerrit', help='Gerrit review URL')
92
93    parser.add_argument('--gitcookies',
94                        default=os.path.expanduser('~/.gitcookies'),
95                        help='Gerrit cookie file')
96    parser.add_argument('--limits', default=1000,
97                        help='Max number of change lists')
98
99    parser.add_argument('-l', '--label', nargs=2, action='append',
100                        help='Labels to be added')
101    parser.add_argument('-m', '--message', help='Review message')
102
103    parser.add_argument('--submit', action='store_true', help='Submit a CL')
104
105    parser.add_argument('--abandon', help='Abandon a CL with a message')
106    parser.add_argument('--restore', action='store_true', help='Restore a CL')
107
108    parser.add_argument('--add-hashtag', action='append', help='Add hashtag')
109    parser.add_argument('--remove-hashtag', action='append',
110                        help='Remove hashtag')
111    parser.add_argument('--delete-hashtag', action='append',
112                        help='Remove hashtag', dest='remove_hashtag')
113
114    parser.add_argument('--set-topic', help='Set topic name')
115    parser.add_argument('--delete-topic', action='store_true',
116                        help='Delete topic name')
117    parser.add_argument('--remove-topic', action='store_true',
118                        help='Delete topic name', dest='delete_topic')
119    parser.add_argument('--add-reviewer', action='append', default=[],
120                        help='Add reviewer')
121    parser.add_argument('--delete-reviewer', action='append', default=[],
122                        help='Delete reviewer')
123
124    return parser.parse_args()
125
126
127def _has_task(args):
128    """Determine whether a task has been specified in the arguments."""
129    if args.label is not None or args.message is not None:
130        return True
131    if args.submit:
132        return True
133    if args.abandon is not None:
134        return True
135    if args.restore:
136        return True
137    if args.add_hashtag or args.remove_hashtag:
138        return True
139    if args.set_topic or args.delete_topic:
140        return True
141    if args.add_reviewer or args.delete_reviewer:
142        return True
143    return False
144
145
146_SEP_SPLIT = '=' * 79
147_SEP = '-' * 79
148
149
150def _print_error(change, res_code, res_body, res_json):
151    """Print the error message"""
152
153    change_id = change['change_id']
154    project = change['project']
155    revision_sha1 = change['current_revision']
156    revision = change['revisions'][revision_sha1]
157    subject = revision['commit']['subject']
158
159    print(_SEP_SPLIT, file=sys.stderr)
160    print('Project:', project, file=sys.stderr)
161    print('Change-Id:', change_id, file=sys.stderr)
162    print('Subject:', subject, file=sys.stderr)
163    print('HTTP status code:', res_code, file=sys.stderr)
164    if res_json:
165        print(_SEP, file=sys.stderr)
166        json.dump(res_json, sys.stderr, indent=4,
167                  separators=(', ', ': '))
168        print(file=sys.stderr)
169    elif res_body:
170        print(_SEP, file=sys.stderr)
171        print(res_body.decode('utf-8'), file=sys.stderr)
172    print(_SEP_SPLIT, file=sys.stderr)
173
174
175def _do_task(change, func, *args, **kwargs):
176    """Process a task and report errors when necessary."""
177
178    res_code, res_body, res_json = func(*args)
179
180    if res_code != kwargs.get('expected_http_code', 200):
181        _print_error(change, res_code, res_body, res_json)
182
183        errors = kwargs.get('errors')
184        if errors is not None:
185            errors['num_errors'] += 1
186
187
188def main():
189    """Set review labels to selected change lists"""
190
191    # Parse and check the command line options
192    args = _parse_args()
193
194    if not args.gerrit:
195        try:
196            args.gerrit = find_gerrit_name()
197        # pylint: disable=bare-except
198        except:
199            print('gerrit instance not found, use [-g GERRIT]')
200            sys.exit(1)
201
202    if not _has_task(args):
203        print('error: Either --label, --message, --submit, --abandon, --restore, '
204              '--add-hashtag, --remove-hashtag, --set-topic, --delete-topic, '
205              '--add-reviewer or --delete-reviewer must be specified',
206              file=sys.stderr)
207        sys.exit(1)
208
209    # Convert label arguments
210    labels = _get_labels_from_args(args)
211
212    # Convert reviewer arguments
213    new_reviewers = [{'reviewer': name} for name in args.add_reviewer]
214
215    # Load authentication credentials
216    url_opener = create_url_opener_from_args(args)
217
218    # Retrieve change lists
219    change_lists = query_change_lists(
220        url_opener, args.gerrit, args.query, args.limits)
221    if not change_lists:
222        print('error: No matching change lists.', file=sys.stderr)
223        sys.exit(1)
224
225    # Print matching lists
226    _print_change_lists(change_lists, file=sys.stdout)
227
228    # Confirm
229    _confirm('Do you want to continue?')
230
231    # Post review votes
232    errors = {'num_errors': 0}
233    for change in change_lists:
234        if args.label or args.message:
235            _do_task(change, set_review, url_opener, args.gerrit, change['id'],
236                     labels, args.message, errors=errors)
237        if args.add_hashtag or args.remove_hashtag:
238            _do_task(change, set_hashtags, url_opener, args.gerrit,
239                     change['id'], args.add_hashtag, args.remove_hashtag,
240                     errors=errors)
241        if args.set_topic:
242            _do_task(change, set_topic, url_opener, args.gerrit, change['id'],
243                     args.set_topic, errors=errors)
244        if args.delete_topic:
245            _do_task(change, delete_topic, url_opener, args.gerrit,
246                     change['id'], expected_http_code=204, errors=errors)
247        if args.submit:
248            _do_task(change, submit, url_opener, args.gerrit, change['id'],
249                     errors=errors)
250        if args.abandon:
251            _do_task(change, abandon, url_opener, args.gerrit, change['id'],
252                     args.abandon, errors=errors)
253        if args.restore:
254            _do_task(change, restore, url_opener, args.gerrit, change['id'],
255                     errors=errors)
256        if args.add_reviewer:
257            _do_task(change, add_reviewers, url_opener, args.gerrit,
258                     change['id'], new_reviewers, errors=errors)
259        for name in args.delete_reviewer:
260            _do_task(change, delete_reviewer, url_opener, args.gerrit,
261                     change['id'], name, expected_http_code=204, errors=errors)
262
263
264    if errors['num_errors']:
265        sys.exit(1)
266
267
268if __name__ == '__main__':
269    main()
270