This repository has been archived by the owner on Aug 1, 2019. It is now read-only.
/
cmd.py
executable file
·1658 lines (1345 loc) · 56 KB
/
cmd.py
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import print_function
COPYRIGHT = """\
Copyright (C) 2011-2012 OpenStack LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
See the License for the specific language governing permissions and
limitations under the License."""
import argparse
import datetime
import getpass
import json
import os
import re
import shlex
import subprocess
import sys
import textwrap
import pkg_resources
import requests
if sys.version < '3':
import ConfigParser
import urllib
import urlparse
urlencode = urllib.urlencode
urljoin = urlparse.urljoin
urlparse = urlparse.urlparse
do_input = raw_input
else:
import configparser as ConfigParser
import urllib.parse
import urllib.request
urlencode = urllib.parse.urlencode
urljoin = urllib.parse.urljoin
urlparse = urllib.parse.urlparse
do_input = input
VERBOSE = False
UPDATE = False
LOCAL_MODE = 'GITREVIEW_LOCAL_MODE' in os.environ
CONFIGDIR = os.path.expanduser("~/.config/git-review")
GLOBAL_CONFIG = "/etc/git-review/git-review.conf"
USER_CONFIG = os.path.join(CONFIGDIR, "git-review.conf")
DEFAULTS = dict(scheme='ssh', hostname=False, port=None, project=False,
branch='master', remote="gerrit", rebase="1",
track="0", usepushurl="0")
_branch_name = None
_has_color = None
_use_color = None
_orig_head = None
_rewrites = None
_rewrites_push = None
def print_safe_encoding(str):
if sys.stdout.encoding is None:
print(str)
else:
print(str.encode(sys.stdout.encoding, 'replace'))
class colors(object):
yellow = '\033[33m'
green = '\033[92m'
reset = '\033[0m'
blue = '\033[36m'
class GitReviewException(Exception):
EXIT_CODE = 127
class CommandFailed(GitReviewException):
def __init__(self, *args):
Exception.__init__(self, *args)
(self.rc, self.output, self.argv, self.envp) = args
self.quickmsg = dict([
("argv", " ".join(self.argv)),
("rc", self.rc),
("output", self.output)])
def __str__(self):
return self.__doc__ + """
The following command failed with exit code %(rc)d
"%(argv)s"
-----------------------
%(output)s
-----------------------""" % self.quickmsg
class ChangeSetException(GitReviewException):
def __init__(self, e):
GitReviewException.__init__(self)
self.e = str(e)
def __str__(self):
return self.__doc__ % self.e
def printwrap(unwrapped):
print('\n'.join(textwrap.wrap(unwrapped)))
def warn(warning):
printwrap("WARNING: %s")
def parse_review_number(review):
parts = review.split(',')
if len(parts) < 2:
parts.append(None)
return parts
def build_review_number(review, patchset):
if patchset is not None:
return '%s,%s' % (review, patchset)
return review
def run_command_status(*argv, **kwargs):
if VERBOSE:
print(datetime.datetime.now(), "Running:", " ".join(argv))
if len(argv) == 1:
# for python2 compatibility with shlex
if sys.version_info < (3,) and isinstance(argv[0], unicode):
argv = shlex.split(argv[0].encode('utf-8'))
else:
argv = shlex.split(str(argv[0]))
stdin = kwargs.pop('stdin', None)
newenv = os.environ.copy()
newenv['LANG'] = 'C'
newenv['LANGUAGE'] = 'C'
newenv.update(kwargs)
p = subprocess.Popen(argv,
stdin=subprocess.PIPE if stdin else None,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=newenv)
(out, nothing) = p.communicate(stdin)
out = out.decode('utf-8', 'replace')
return (p.returncode, out.strip())
def run_command(*argv, **kwargs):
(rc, output) = run_command_status(*argv, **kwargs)
return output
def run_command_exc(klazz, *argv, **env):
"""Run command *argv, on failure raise klazz
klazz should be derived from CommandFailed
"""
(rc, output) = run_command_status(*argv, **env)
if rc != 0:
raise klazz(rc, output, argv, env)
return output
def git_credentials(url):
"""Return credentials using git credential or None."""
cmd = 'git', 'credential', 'fill'
stdin = 'url=%s' % url
rc, out = run_command_status(*cmd, stdin=stdin)
if rc:
return None
data = dict(l.split('=', 1) for l in out.splitlines())
return data['username'], data['password']
def http_code_2_return_code(code):
"""Tranform http status code to system return code."""
return (code - 301) % 255 + 1
def run_http_exc(klazz, url, **env):
"""Run http GET request url, on failure raise klazz
klazz should be derived from CommandFailed
"""
if url.startswith("https://") and "verify" not in env:
if "GIT_SSL_NO_VERIFY" in os.environ:
env["verify"] = False
else:
verify = git_config_get_value("http", "sslVerify", as_bool=True)
env["verify"] = verify != 'false'
try:
res = requests.get(url, **env)
if res.status_code == 401:
creds = git_credentials(url)
if creds:
env['auth'] = creds
res = requests.get(url, **env)
except klazz:
raise
except Exception as err:
raise klazz(255, str(err), ('GET', url), env)
if not 200 <= res.status_code < 300:
raise klazz(http_code_2_return_code(res.status_code),
res.text, ('GET', url), env)
return res
def get_version():
requirement = pkg_resources.Requirement.parse('git-review')
provider = pkg_resources.get_provider(requirement)
return provider.version
def git_directories():
"""Determine (absolute git work directory path, .git subdirectory path)."""
cmd = ("git", "rev-parse", "--show-toplevel", "--git-dir")
out = run_command_exc(GitDirectoriesException, *cmd)
try:
return out.splitlines()
except ValueError:
raise GitDirectoriesException(0, out, cmd, {})
class GitDirectoriesException(CommandFailed):
"Cannot determine where .git directory is."
EXIT_CODE = 70
class CustomScriptException(CommandFailed):
"""Custom script execution failed."""
EXIT_CODE = 71
def run_custom_script(action):
"""Get status and output of .git/hooks/$action-review or/and
~/.config/hooks/$action-review if existing.
"""
returns = []
script_file = "%s-review" % (action)
(top_dir, git_dir) = git_directories()
paths = [os.path.join(CONFIGDIR, "hooks", script_file),
os.path.join(git_dir, "hooks", script_file)]
for fpath in paths:
if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
status, output = run_command_status(fpath)
returns.append((status, output, fpath))
for (status, output, path) in returns:
if status is not None and status != 0:
raise CustomScriptException(status, output, [path], {})
elif output and VERBOSE:
print("script %s output is:" % (path))
print_safe_encoding(output)
def git_config_get_value(section, option, default=None, as_bool=False):
"""Get config value for section/option."""
cmd = ["git", "config", "--get", "%s.%s" % (section, option)]
if as_bool:
cmd.insert(2, "--bool")
if LOCAL_MODE:
__, git_dir = git_directories()
cmd[2:2] = ['-f', os.path.join(git_dir, 'config')]
try:
return run_command_exc(GitConfigException, *cmd).strip()
except GitConfigException as exc:
if exc.rc == 1:
return default
raise
class Config(object):
"""Expose as dictionary configuration options."""
def __init__(self, config_file=None):
self.config = DEFAULTS.copy()
filenames = [] if LOCAL_MODE else [GLOBAL_CONFIG, USER_CONFIG]
if config_file:
filenames.append(config_file)
for filename in filenames:
if os.path.exists(filename):
if filename != config_file:
msg = ("Using global/system git-review config files (%s) "
"is deprecated and will be removed in a future "
"release")
warn(msg % filename)
self.config.update(load_config_file(filename))
def __getitem__(self, key):
value = git_config_get_value('gitreview', key)
if value is None:
value = self.config[key]
return value
class GitConfigException(CommandFailed):
"""Git config value retrieval failed."""
EXIT_CODE = 128
class CannotInstallHook(CommandFailed):
"Problems encountered installing commit-msg hook"
EXIT_CODE = 2
def set_hooks_commit_msg(remote, target_file):
"""Install the commit message hook if needed."""
# Create the hooks directory if it's not there already
hooks_dir = os.path.dirname(target_file)
if not os.path.isdir(hooks_dir):
os.mkdir(hooks_dir)
if not os.path.exists(target_file) or UPDATE:
remote_url = get_remote_url(remote)
if (remote_url.startswith('http://') or
remote_url.startswith('https://')):
hook_url = urljoin(remote_url, '/tools/hooks/commit-msg')
if VERBOSE:
print("Fetching commit hook from: %s" % hook_url)
res = run_http_exc(CannotInstallHook, hook_url, stream=True)
with open(target_file, 'wb') as f:
for x in res.iter_content(1024):
f.write(x)
else:
(hostname, username, port, project_name) = \
parse_gerrit_ssh_params_from_git_url(remote_url)
if username is None:
userhost = hostname
else:
userhost = "%s@%s" % (username, hostname)
# OS independent target file
scp_target_file = target_file.replace(os.sep, "/")
cmd = ["scp", userhost + ":hooks/commit-msg", scp_target_file]
if port is not None:
cmd.insert(1, "-P%s" % port)
if VERBOSE:
hook_url = 'scp://%s%s/hooks/commit-msg' \
% (userhost, (":%s" % port) if port else "")
print("Fetching commit hook from: %s" % hook_url)
run_command_exc(CannotInstallHook, *cmd)
if not os.access(target_file, os.X_OK):
os.chmod(target_file, os.path.stat.S_IREAD | os.path.stat.S_IEXEC)
def test_remote_url(remote_url):
"""Tests that a possible gerrit remote url works."""
status, description = run_command_status("git", "push", "--dry-run",
remote_url, "--all")
if status != 128:
if VERBOSE:
print("%s worked. Description: %s" % (remote_url, description))
return True
else:
if VERBOSE:
print("%s did not work. Description: %s" % (
remote_url, description))
return False
def make_remote_url(scheme, username, hostname, port, project):
"""Builds a gerrit remote URL."""
if port is None and scheme == 'ssh':
port = 29418
hostport = '%s:%s' % (hostname, port) if port else hostname
if username is None:
return "%s://%s/%s" % (scheme, hostport, project)
else:
return "%s://%s@%s/%s" % (scheme, username, hostport, project)
def add_remote(scheme, hostname, port, project, remote, usepushurl):
"""Adds a gerrit remote."""
asked_for_username = False
username = git_config_get_value("gitreview", "username")
if not username:
username = getpass.getuser()
remote_url = make_remote_url(scheme, username, hostname, port, project)
if VERBOSE:
print("No remote set, testing %s" % remote_url)
if not test_remote_url(remote_url):
print("Could not connect to gerrit.")
username = do_input("Enter your gerrit username: ")
remote_url = make_remote_url(scheme, username, hostname, port, project)
print("Trying again with %s" % remote_url)
if not test_remote_url(remote_url):
raise GerritConnectionException(
"Could not connect to gerrit at %s" % remote_url
)
asked_for_username = True
if usepushurl:
cmd = "git remote set-url --push %s %s" % (remote, remote_url)
print("Adding a git push url to '%s' that maps to:" % remote)
else:
cmd = "git remote add -f %s %s" % (remote, remote_url)
print("Creating a git remote called '%s' that maps to:" % remote)
print("\t%s" % remote_url)
(status, remote_output) = run_command_status(cmd)
if status != 0:
raise CommandFailed(status, remote_output, cmd, {})
if asked_for_username:
print()
printwrap("This repository is now set up for use with git-review. "
"You can set the default username for future repositories "
"with:")
print(' git config --global --add gitreview.username "%s"' % username)
print()
def populate_rewrites():
"""Populate the global _rewrites and _rewrites_push maps based on the
output of "git-config".
"""
cmd = ['git', 'config', '--list']
out = run_command_exc(CommandFailed, *cmd).strip()
global _rewrites, _rewrites_push
_rewrites = {}
_rewrites_push = {}
for entry in out.splitlines():
key, _, value = entry.partition('=')
key = key.lower()
if key.startswith('url.') and key.endswith('.insteadof'):
rewrite = key[len('url.'):-len('.insteadof')]
if rewrite:
_rewrites[value] = rewrite
elif key.startswith('url.') and key.endswith('.pushinsteadof'):
rewrite = key[len('url.'):-len('.pushinsteadof')]
if rewrite:
_rewrites_push[value] = rewrite
def alias_url(url, rewrite_push):
"""Expand a remote URL. Use the global map _rewrites to replace the
longest match with its equivalent. If rewrite_push is True, try
_rewrites_push before _rewrites.
"""
if _rewrites is None:
populate_rewrites()
if rewrite_push:
maps = [_rewrites_push, _rewrites]
else:
maps = [_rewrites]
for rewrites in maps:
# If Git finds a pushInsteadOf alias, it uses that even if
# there is a longer insteadOf alias.
longest = None
for alias in rewrites:
if (url.startswith(alias)
and (longest is None or len(longest) < len(alias))):
longest = alias
if longest:
return url.replace(longest, rewrites[longest])
return url
def get_remote_url(remote):
"""Retrieve the remote URL. Read the configuration to expand the URL of a
remote repository taking into account any "url.<base>.insteadOf" or
"url.<base>.pushInsteadOf" config setting.
TODO: Replace current code with something like "git ls-remote
--get-url" after Git grows a version of it that returns the push
URL rather than the fetch URL.
"""
push_url = git_config_get_value('remote.%s' % remote, 'pushurl')
if push_url is not None:
# Git rewrites pushurl using insteadOf but not pushInsteadOf.
push_url = alias_url(push_url, False)
else:
url = git_config_get_value('remote.%s' % remote, 'url')
# Git rewrites url using pushInsteadOf or insteadOf.
push_url = alias_url(url, True)
if VERBOSE:
print("Found origin Push URL:", push_url)
return push_url
def parse_gerrit_ssh_params_from_git_url(git_url):
"""Parse a given Git "URL" into Gerrit parameters. Git "URLs" are either
real URLs or SCP-style addresses.
"""
# The exact code for this in Git itself is a bit obtuse, so just do
# something sensible and pythonic here instead of copying the exact
# minutiae from Git.
# Handle real(ish) URLs
if "://" in git_url:
parsed_url = urlparse(git_url)
path = parsed_url.path
hostname = parsed_url.netloc
username = None
port = parsed_url.port
# Workaround bug in urlparse on OSX
if parsed_url.scheme == "ssh" and parsed_url.path[:2] == "//":
hostname = parsed_url.path[2:].split("/")[0]
if "@" in hostname:
(username, hostname) = hostname.split("@")
if ":" in hostname:
(hostname, port) = hostname.split(":")
if port is not None:
port = str(port)
# Handle SCP-style addresses
else:
username = None
port = None
(hostname, path) = git_url.split(":", 1)
if "@" in hostname:
(username, hostname) = hostname.split("@", 1)
# Strip leading slash and trailing .git from the path to form the project
# name.
project_name = re.sub(r"^/|(\.git$)", "", path)
return (hostname, username, port, project_name)
def query_reviews(remote_url, change=None, current_patch_set=True,
exception=CommandFailed, parse_exc=Exception):
if remote_url.startswith('http://') or remote_url.startswith('https://'):
query = query_reviews_over_http
else:
query = query_reviews_over_ssh
return query(remote_url,
change=change,
current_patch_set=current_patch_set,
exception=exception,
parse_exc=parse_exc)
def query_reviews_over_http(remote_url, change=None, current_patch_set=True,
exception=CommandFailed, parse_exc=Exception):
url = urljoin(remote_url, '/changes/')
if change:
if current_patch_set:
url += '?q=%s&o=CURRENT_REVISION' % change
else:
url += '?q=%s&o=ALL_REVISIONS' % change
else:
project_name = re.sub(r"^/|(\.git$)", "", urlparse(remote_url).path)
params = urlencode({'q': 'project:%s status:open' % project_name})
url += '?' + params
if VERBOSE:
print("Query gerrit %s" % url)
request = run_http_exc(exception, url)
if VERBOSE:
print(request.text)
reviews = json.loads(request.text[4:])
# Reformat output to match ssh output
try:
for review in reviews:
review["number"] = str(review.pop("_number"))
if "revisions" not in review:
continue
patchsets = {}
for key, revision in review["revisions"].items():
fetch_value = list(revision["fetch"].values())[0]
patchset = {"number": str(revision["_number"]),
"ref": fetch_value["ref"]}
patchsets[key] = patchset
review["patchSets"] = patchsets.values()
review["currentPatchSet"] = patchsets[review["current_revision"]]
except Exception as err:
raise parse_exc(err)
return reviews
def query_reviews_over_ssh(remote_url, change=None, current_patch_set=True,
exception=CommandFailed, parse_exc=Exception):
(hostname, username, port, project_name) = \
parse_gerrit_ssh_params_from_git_url(remote_url)
if change:
if current_patch_set:
query = "--current-patch-set change:%s" % change
else:
query = "--patch-sets change:%s" % change
else:
query = "project:%s status:open" % project_name
port_data = "p%s" % port if port is not None else ""
if username is None:
userhost = hostname
else:
userhost = "%s@%s" % (username, hostname)
if VERBOSE:
print("Query gerrit %s %s" % (remote_url, query))
output = run_command_exc(
exception,
"ssh", "-x" + port_data, userhost,
"gerrit", "query",
"--format=JSON %s" % query)
if VERBOSE:
print_safe_encoding(output)
changes = []
try:
for line in output.split("\n"):
if line[0] == "{":
try:
data = json.loads(line)
if "type" not in data:
changes.append(data)
except Exception:
if VERBOSE:
print_safe_encoding(output)
except Exception as err:
raise parse_exc(err)
return changes
def set_color_output(color="auto"):
global _use_color
if check_color_support():
if color == "auto":
check_use_color_output()
else:
_use_color = color == "always"
def check_use_color_output():
global _use_color
if _use_color is None:
if check_color_support():
# we can support color, now check if we should use it
stdout = "true" if sys.stdout.isatty() else "false"
test_command = "git config --get-colorbool color.review " + stdout
color = run_command(test_command)
_use_color = color == "true"
else:
_use_color = False
return _use_color
def check_color_support():
global _has_color
if _has_color is None:
test_command = "git log --color=never --oneline HEAD^1..HEAD"
(status, output) = run_command_status(test_command)
if status == 0:
_has_color = True
else:
_has_color = False
return _has_color
def load_config_file(config_file):
"""Load configuration options from a file."""
configParser = ConfigParser.ConfigParser()
configParser.read(config_file)
options = {
'scheme': 'scheme',
'hostname': 'host',
'port': 'port',
'project': 'project',
'branch': 'defaultbranch',
'remote': 'defaultremote',
'rebase': 'defaultrebase',
'track': 'track',
'usepushurl': 'usepushurl',
}
config = {}
for config_key, option_name in options.items():
if configParser.has_option('gerrit', option_name):
config[config_key] = configParser.get('gerrit', option_name)
return config
def update_remote(remote):
cmd = "git remote update %s" % remote
(status, output) = run_command_status(cmd)
if VERBOSE:
print_safe_encoding(output)
if status != 0:
print("Problem running '%s'" % cmd)
if not VERBOSE:
print_safe_encoding(output)
return False
return True
def parse_tracking(ref=None):
"""Return tracked (remote, branch) of current HEAD or other named
branch if tracking remote.
"""
if ref is None:
ref = run_command_exc(
SymbolicRefFailed,
"git", "symbolic-ref", "-q", "HEAD")
tracked = run_command_exc(
ForEachRefFailed,
"git", "for-each-ref", "--format=%(upstream)", ref)
# Only on explicitly tracked remote branch do we diverge from default
if tracked and tracked.startswith('refs/remotes/'):
return tracked[13:].partition('/')[::2]
return None, None
def resolve_tracking(remote, branch):
"""Resolve tracked upstream remote/branch if current branch is tracked."""
tracked_remote, tracked_branch = parse_tracking()
# tracked_branch will be empty when tracking a local branch
if tracked_branch:
if VERBOSE:
print('Following tracked %s/%s rather than default %s/%s' % (
tracked_remote, tracked_branch,
remote, branch))
return tracked_remote, tracked_branch
return remote, branch
def check_remote(branch, remote, scheme, hostname, port, project,
usepushurl=False):
"""Check that a Gerrit Git remote repo exists, if not, set one."""
if usepushurl:
push_url = git_config_get_value('remote.%s' % remote, 'pushurl', None)
if push_url:
return
else:
has_color = check_color_support()
if has_color:
color_never = "--color=never"
else:
color_never = ""
if remote in run_command("git remote").split("\n"):
remotes = run_command("git branch -a %s" % color_never).split("\n")
for current_remote in remotes:
remote_string = "remotes/%s/%s" % (remote, branch)
if (current_remote.strip() == remote_string and not UPDATE):
return
# We have the remote, but aren't set up to fetch. Fix it
if VERBOSE:
print("Setting up gerrit branch tracking for better rebasing")
update_remote(remote)
return
if hostname is False or project is False:
# This means there was no .gitreview file
printwrap("No '.gitreview' file found in this repository. We don't "
"know where your gerrit is.")
if usepushurl:
printwrap("Please set the push-url on your origin remote to the "
"location of your gerrit server and try again")
else:
printwrap("Please manually create a remote "
"named \"%s\" and try again." % remote)
sys.exit(1)
# Gerrit remote not present, try to add it
try:
add_remote(scheme, hostname, port, project, remote, usepushurl)
except Exception:
if usepushurl:
printwrap("We don't know where your gerrit is. Please manually"
" add a push-url to the '%s' remote and try again."
% remote)
else:
printwrap("We don't know where your gerrit is. Please manually"
" create a remote named '%s' and try again." % remote)
raise
def rebase_changes(branch, remote, interactive=True):
global _orig_head
remote_branch = "remotes/%s/%s" % (remote, branch)
if not update_remote(remote):
return False
# since the value of ORIG_HEAD may not be set by rebase as expected
# for use in undo_rebase, make sure to save it explicitly
cmd = "git rev-parse HEAD"
(status, output) = run_command_status(cmd)
if status != 0:
print("Errors running %s" % cmd)
if interactive:
print_safe_encoding(output)
return False
_orig_head = output
cmd = "git show-ref --quiet --verify refs/%s" % remote_branch
(status, output) = run_command_status(cmd)
if status != 0:
printwrap("The branch '%s' does not exist on the given remote '%s'. "
"If these changes are intended to start a new branch, "
"re-run with the '-R' option enabled." % (branch, remote))
sys.exit(1)
if interactive:
cmd = "git rebase -p -i %s" % remote_branch
else:
cmd = "git rebase -p %s" % remote_branch
(status, output) = run_command_status(cmd, GIT_EDITOR='true')
if status != 0:
print("Errors running %s" % cmd)
if interactive:
print_safe_encoding(output)
print("It is likely that your change has a merge conflict. "
"You may resolve it in the working tree now as "
"described above and then run 'git review' again, or "
"if you do not want to resolve it yet (note that the "
"change can not merge until the conflict is resolved) "
"you may run 'git rebase --abort' then 'git review -R' "
"to upload the change without rebasing.")
return False
return True
def undo_rebase():
global _orig_head
if not _orig_head:
return True
cmd = "git reset --hard %s" % _orig_head
(status, output) = run_command_status(cmd)
if status != 0:
print("Errors running %s" % cmd)
print_safe_encoding(output)
return False
return True
def get_branch_name(target_branch):
global _branch_name
if _branch_name is not None:
return _branch_name
cmd = "git rev-parse --symbolic-full-name --abbrev-ref HEAD"
_branch_name = run_command(cmd)
if _branch_name == "HEAD":
# detached head or no branch found
_branch_name = target_branch
return _branch_name
def assert_one_change(remote, branch, yes, have_hook):
if check_use_color_output():
use_color = "--color=always"
else:
use_color = "--color=never"
cmd = ("git log %s --decorate --oneline HEAD --not --remotes=%s" % (
use_color, remote))
(status, output) = run_command_status(cmd)
if status != 0:
print("Had trouble running %s" % cmd)
print_safe_encoding(output)
sys.exit(1)
filtered = filter(None, output.split("\n"))
output_lines = sum(1 for s in filtered)
if output_lines == 1 and not have_hook:
printwrap("Your change was committed before the commit hook was "
"installed. Amending the commit to add a gerrit change id.")
run_command("git commit --amend", GIT_EDITOR='true')
elif output_lines == 0:
printwrap("No changes between HEAD and %s/%s. Submitting for review "
"would be pointless." % (remote, branch))
sys.exit(1)
elif output_lines > 1:
if not yes:
printwrap("You are about to submit multiple commits. This is "
"expected if you are submitting a commit that is "
"dependent on one or more in-review commits, or if you "
"are submitting multiple self-contained but dependent "
"changes. Otherwise you should consider squashing your "
"changes into one commit before submitting (for "
"indivisible changes) or submitting from separate "
"branches (for independent changes).")
print("\nThe outstanding commits are:\n\n%s\n\n"
"Do you really want to submit the above commits?" % output)
yes_no = do_input("Type 'yes' to confirm, other to cancel: ")
if yes_no.lower().strip() != "yes":
print("Aborting.")
sys.exit(1)
def use_topic(why, topic):
"""Inform the user about why a particular topic has been selected."""
if VERBOSE:
print(why % ('"%s"' % topic,))
return topic
def get_topic(target_branch):
branch_name = get_branch_name(target_branch)
branch_parts = branch_name.split("/")
if len(branch_parts) >= 3 and branch_parts[0] == "review":
return use_topic("Using change number %s "
"for the topic of the change submitted",
"/".join(branch_parts[2:]))
preferred_log_format = "%B"
log_output = run_command("git log --pretty='" + preferred_log_format +
"' HEAD^1..HEAD")
if log_output == preferred_log_format:
# The %B format specifier is supported starting at Git v1.7.2. If it's
# not supported, we'll just get back '%B', so we try something else.
# The downside of %s is that it removes newlines in the subject.
log_output = run_command("git log --pretty='%s%n%b' HEAD^1..HEAD")
bug_re = r'''(?x) # verbose regexp
\b([Bb]ug|[Ll][Pp]) # bug or lp
[ \t\f\v]* # don't want to match newline
[:]? # separator if needed
[ \t\f\v]* # don't want to match newline
[#]? # if needed
[ \t\f\v]* # don't want to match newline
(\d+) # bug number'''
match = re.search(bug_re, log_output)
if match is not None:
return use_topic("Using bug number %s "
"for the topic of the change submitted",
"bug/%s" % match.group(2))
bp_re = r'''(?x) # verbose regexp
\b([Bb]lue[Pp]rint|[Bb][Pp]) # a blueprint or bp
[ \t\f\v]* # don't want to match newline
[#:]? # separator if needed
[ \t\f\v]* # don't want to match newline
([0-9a-zA-Z-_]+) # any identifier or number'''
match = re.search(bp_re, log_output)
if match is not None:
return use_topic("Using blueprint number %s "
"for the topic of the change submitted",
"bp/%s" % match.group(2))
return use_topic("Using local branch name %s "
"for the topic of the change submitted",
branch_name)
class CannotQueryOpenChangesets(CommandFailed):
"Cannot fetch review information from gerrit"
EXIT_CODE = 32
class CannotParseOpenChangesets(ChangeSetException):
"Cannot parse JSON review information from gerrit"
EXIT_CODE = 33
class Review(dict):
_default_fields = ('branch', 'topic', 'subject')
def __init__(self, data):
if 'number' not in data:
raise TypeError("<Review> requires 'number' key in data")
super(Review, self).__init__(data)