• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_common_parse_args, add_reviewers, create_url_opener_from_args,
35    delete, delete_reviewer, delete_topic, find_gerrit_name, normalize_gerrit_name,
36    query_change_lists, restore, set_hashtags, 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    add_common_parse_args(parser)
90
91    parser.add_argument('-l', '--label', nargs=2, action='append',
92                        help='Labels to be added')
93    parser.add_argument('-m', '--message', help='Review message')
94
95    parser.add_argument('--submit', action='store_true', help='Submit a CL')
96
97    parser.add_argument('--abandon', help='Abandon a CL with a message')
98    parser.add_argument('--restore', action='store_true', help='Restore a CL')
99    parser.add_argument('--delete', action='store_true', help='Delete a CL')
100
101    parser.add_argument('--add-hashtag', action='append', help='Add hashtag')
102    parser.add_argument('--remove-hashtag', action='append',
103                        help='Remove hashtag')
104    parser.add_argument('--delete-hashtag', action='append',
105                        help='Remove hashtag', dest='remove_hashtag')
106
107    parser.add_argument('--set-topic', help='Set topic name')
108    parser.add_argument('--delete-topic', action='store_true',
109                        help='Delete topic name')
110    parser.add_argument('--remove-topic', action='store_true',
111                        help='Delete topic name', dest='delete_topic')
112    parser.add_argument('--add-reviewer', action='append', default=[],
113                        help='Add reviewer')
114    parser.add_argument('--delete-reviewer', action='append', default=[],
115                        help='Delete reviewer')
116
117    return parser.parse_args()
118
119
120def _has_task(args):
121    """Determine whether a task has been specified in the arguments."""
122    if args.label is not None or args.message is not None:
123        return True
124    if args.submit:
125        return True
126    if args.abandon is not None:
127        return True
128    if args.restore:
129        return True
130    if args.delete:
131        return True
132    if args.add_hashtag or args.remove_hashtag:
133        return True
134    if args.set_topic or args.delete_topic:
135        return True
136    if args.add_reviewer or args.delete_reviewer:
137        return True
138    return False
139
140
141_SEP_SPLIT = '=' * 79
142_SEP = '-' * 79
143
144
145def _print_error(change, res_code, res_body, res_json):
146    """Print the error message"""
147
148    change_id = change['change_id']
149    project = change['project']
150    revision_sha1 = change['current_revision']
151    revision = change['revisions'][revision_sha1]
152    subject = revision['commit']['subject']
153
154    print(_SEP_SPLIT, file=sys.stderr)
155    print('Project:', project, file=sys.stderr)
156    print('Change-Id:', change_id, file=sys.stderr)
157    print('Subject:', subject, file=sys.stderr)
158    print('HTTP status code:', res_code, file=sys.stderr)
159    if res_json:
160        print(_SEP, file=sys.stderr)
161        json.dump(res_json, sys.stderr, indent=4,
162                  separators=(', ', ': '))
163        print(file=sys.stderr)
164    elif res_body:
165        print(_SEP, file=sys.stderr)
166        print(res_body.decode('utf-8'), file=sys.stderr)
167    print(_SEP_SPLIT, file=sys.stderr)
168
169
170def _do_task(change, func, *args, **kwargs):
171    """Process a task and report errors when necessary."""
172
173    res_code, res_body, res_json = func(*args)
174
175    if res_code != kwargs.get('expected_http_code', 200):
176        _print_error(change, res_code, res_body, res_json)
177
178        errors = kwargs.get('errors')
179        if errors is not None:
180            errors['num_errors'] += 1
181
182
183def main():
184    """Set review labels to selected change lists"""
185
186    # Parse and check the command line options
187    args = _parse_args()
188
189    if args.gerrit:
190        args.gerrit = normalize_gerrit_name(args.gerrit)
191    else:
192        try:
193            args.gerrit = find_gerrit_name()
194        # pylint: disable=bare-except
195        except:
196            print('gerrit instance not found, use [-g GERRIT]')
197            sys.exit(1)
198
199    if not _has_task(args):
200        print('error: Either --label, --message, --submit, --abandon, --restore, '
201              '--add-hashtag, --remove-hashtag, --set-topic, --delete-topic, '
202              '--add-reviewer, --delete-reviewer or --delete must be specified',
203              file=sys.stderr)
204        sys.exit(1)
205
206    # Convert label arguments
207    labels = _get_labels_from_args(args)
208
209    # Convert reviewer arguments
210    new_reviewers = [{'reviewer': name} for name in args.add_reviewer]
211
212    # Load authentication credentials
213    url_opener = create_url_opener_from_args(args)
214
215    # Retrieve change lists
216    change_lists = query_change_lists(
217        url_opener, args.gerrit, args.query, args.start, args.limits)
218    if not change_lists:
219        print('error: No matching change lists.', file=sys.stderr)
220        sys.exit(1)
221
222    # Print matching lists
223    _print_change_lists(change_lists, file=sys.stdout)
224
225    # Confirm
226    _confirm('Do you want to continue?')
227
228    # Post review votes
229    errors = {'num_errors': 0}
230    for change in change_lists:
231        if args.label or args.message:
232            _do_task(change, set_review, url_opener, args.gerrit, change['id'],
233                     labels, args.message, errors=errors)
234        if args.add_hashtag or args.remove_hashtag:
235            _do_task(change, set_hashtags, url_opener, args.gerrit,
236                     change['id'], args.add_hashtag, args.remove_hashtag,
237                     errors=errors)
238        if args.set_topic:
239            _do_task(change, set_topic, url_opener, args.gerrit, change['id'],
240                     args.set_topic, errors=errors)
241        if args.delete_topic:
242            _do_task(change, delete_topic, url_opener, args.gerrit,
243                     change['id'], expected_http_code=204, errors=errors)
244        if args.submit:
245            _do_task(change, submit, url_opener, args.gerrit, change['id'],
246                     errors=errors)
247        if args.abandon:
248            _do_task(change, abandon, url_opener, args.gerrit, change['id'],
249                     args.abandon, errors=errors)
250        if args.restore:
251            _do_task(change, restore, url_opener, args.gerrit, change['id'],
252                     errors=errors)
253        if args.delete:
254            _do_task(change, delete, 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