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, 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
107    parser.add_argument('--add-hashtag', action='append', help='Add hashtag')
108    parser.add_argument('--remove-hashtag', action='append',
109                        help='Remove hashtag')
110    parser.add_argument('--delete-hashtag', action='append',
111                        help='Remove hashtag', dest='remove_hashtag')
112
113    parser.add_argument('--set-topic', help='Set topic name')
114    parser.add_argument('--delete-topic', action='store_true',
115                        help='Delete topic name')
116    parser.add_argument('--remove-topic', action='store_true',
117                        help='Delete topic name', dest='delete_topic')
118    parser.add_argument('--add-reviewer', action='append', default=[],
119                        help='Add reviewer')
120    parser.add_argument('--delete-reviewer', action='append', default=[],
121                        help='Delete reviewer')
122
123    return parser.parse_args()
124
125
126def _has_task(args):
127    """Determine whether a task has been specified in the arguments."""
128    if args.label is not None or args.message is not None:
129        return True
130    if args.submit:
131        return True
132    if args.abandon is not None:
133        return True
134    if args.add_hashtag or args.remove_hashtag:
135        return True
136    if args.set_topic or args.delete_topic:
137        return True
138    if args.add_reviewer or args.delete_reviewer:
139        return True
140    return False
141
142
143_SEP_SPLIT = '=' * 79
144_SEP = '-' * 79
145
146
147def _print_error(change, res_code, res_body, res_json):
148    """Print the error message"""
149
150    change_id = change['change_id']
151    project = change['project']
152    revision_sha1 = change['current_revision']
153    revision = change['revisions'][revision_sha1]
154    subject = revision['commit']['subject']
155
156    print(_SEP_SPLIT, file=sys.stderr)
157    print('Project:', project, file=sys.stderr)
158    print('Change-Id:', change_id, file=sys.stderr)
159    print('Subject:', subject, file=sys.stderr)
160    print('HTTP status code:', res_code, file=sys.stderr)
161    if res_json:
162        print(_SEP, file=sys.stderr)
163        json.dump(res_json, sys.stderr, indent=4,
164                  separators=(', ', ': '))
165        print(file=sys.stderr)
166    elif res_body:
167        print(_SEP, file=sys.stderr)
168        print(res_body.decode('utf-8'), file=sys.stderr)
169    print(_SEP_SPLIT, file=sys.stderr)
170
171
172def _do_task(change, func, *args, **kwargs):
173    """Process a task and report errors when necessary."""
174
175    res_code, res_body, res_json = func(*args)
176
177    if res_code != kwargs.get('expected_http_code', 200):
178        _print_error(change, res_code, res_body, res_json)
179
180        errors = kwargs.get('errors')
181        if errors is not None:
182            errors['num_errors'] += 1
183
184
185def main():
186    """Set review labels to selected change lists"""
187
188    # Parse and check the command line options
189    args = _parse_args()
190
191    if not args.gerrit:
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, '
201              '--add-hashtag, --remove-hashtag, --set-topic, --delete-topic, '
202              '--add-reviewer or --delete-reviewer 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.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.add_reviewer:
251            _do_task(change, add_reviewers, url_opener, args.gerrit,
252                     change['id'], new_reviewers, errors=errors)
253        for name in args.delete_reviewer:
254            _do_task(change, delete_reviewer, url_opener, args.gerrit,
255                     change['id'], name, expected_http_code=204, errors=errors)
256
257
258    if errors['num_errors']:
259        sys.exit(1)
260
261
262if __name__ == '__main__':
263    main()
264