Repository navigation
Expand file tree
/
Copy pathgit-hub
More file actions
executable file
·2047 lines (1874 loc) · 68.1 KB
/
Copy pathgit-hub
File metadata and controls
executable file
·2047 lines (1874 loc) · 68.1 KB
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
# vim: set fileencoding=utf-8 :
# Git command line interface to GitHub.
#
# Written by Leandro Lucarella <leandro.lucarella@sociomantic.com>
#
# Copyright (c) 2013 by Sociomantic Labs GmbH
#
# This program is written as a single file for practical reasons, this way
# users can download just one file and use it, while if it's spread across
# multiple modules, a setup procedure must be provided. This might change in
# the future though, if the program keeps growing.
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
"""\
Git command line interface to GitHub.
This program integrates Git and GitHub as a Git extension command (hub).
It enabling most useful GitHub tasks (like creating and listing pull request or
issues) to be accessed directly through the git command line.
"""
VERSION = "git-hub devel"
import re
import sys
import json
import string
import base64
import urllib
import pprint
import urllib2
import getpass
import os.path
import urlparse
import argparse
import subprocess
# Output levels according to user selected verbosity
DEBUG = 3
INFO = 2
WARN = 1
ERR = 0
# Output functions, all use the str.format() function for formatting
########################################################################
def localeprintf(stream, fmt='', *args, **kwargs):
encoding = sys.getfilesystemencoding()
msg = fmt.decode(encoding, 'replace').format(*args, **kwargs) + '\n'
stream.write(msg.encode(encoding, 'replace'))
def pformat(obj):
return pprint.pformat(obj, indent=4)
def debugf(fmt='', *args, **kwargs):
if verbose < DEBUG:
return
localeprintf(sys.stdout, fmt, *args, **kwargs)
def infof(fmt='', *args, **kwargs):
if verbose < INFO:
return
localeprintf(sys.stdout, fmt, *args, **kwargs)
def warnf(fmt='', *args, **kwargs):
if verbose < WARN:
return
msg = ''
if sys.stderr.isatty():
msg += '\033[33m'
msg += 'Warning: ' + fmt.format(*args, **kwargs)
if sys.stderr.isatty():
msg += '\033[0m'
localeprintf(sys.stderr, '{}', msg)
sys.stderr.flush()
def errf(fmt='', *args, **kwargs):
if verbose < ERR:
return
msg = ''
if sys.stderr.isatty():
msg += '\033[31m'
msg += 'Error: ' + fmt.format(*args, **kwargs)
if sys.stderr.isatty():
msg += '\033[0m'
localeprintf(sys.stderr, '{}', msg)
sys.stderr.flush()
def die(fmt='', *args, **kwargs):
errf(fmt, *args, **kwargs)
sys.exit(1)
# This is very similar to die() but used to exit the program normally having
# full stack unwinding. The message is printed with infof() and the exit status
# is 0 (normal termination). The exception is handled by the regular exception
# handling code after calling main()
def interrupt(fmt='', *args, **kwargs):
raise InterruptException(fmt.format(*args, **kwargs))
class InterruptException (Exception):
def __init__(self, msg):
super(InterruptException, self).__init__(msg)
# Ask the user a question
#
# `question` is the text to display (information with the available options
# will be automatically appended). `options` must be an array of strings, and
# `default` a string inside that list, or None. If default is None, if the user
# press ENTER without giving an actual answer, it will be asked again,
# otherwise this function returns the `default` option.
#
# Returns the item selected by the user (one of the strings in `options`)
# unless stdin is not a tty, in which case no question is asked and this
# function returns None.
def ask(question, default=None, options=["yes", "no"]):
if not sys.stdin.isatty():
return None
if default not in options and default is not None:
raise ValueError("invalid default answer: '%s'" % default)
valid_answers = dict()
opts_strings = list()
for opt in options:
if opt is None:
raise ValueError("options can't be None")
valid_answers[opt.lower()] = opt
valid_answers[opt[0].lower()] = opt
opt_str = opt.capitalize()
if default == opt:
# default in bold
opt_str = '\033[1m' + opt.upper() + '\033[21m'
opts_strings.append(opt_str)
# options in dark
question += ' \033[2m[' + '/'.join(opts_strings) + '] '
while True:
# question in yellow
sys.stderr.write('\033[33m' + question + '\033[0m')
choice = raw_input().lower().strip()
if default is not None and choice == '':
return default
elif choice in valid_answers:
return valid_answers[choice]
else:
errf("Invalid answer, valid options: {}",
', '.join(options))
# Git manipulation functions and constants
########################################################################
GIT_CONFIG_PREFIX = 'hub.'
# This error is thrown when a git command fails (if git prints something in
# stderr, this is considered an error even if the return code is 0). The
# `output` argument is really the stderr output only, the `output` name is
# preserved because that's how is it called in the parent class.
class GitError (subprocess.CalledProcessError):
def __init__(self, returncode, cmd, output):
super(GitError, self).__init__(returncode, cmd, output)
def __str__(self):
return '%s failed (return code: %s)\n%s' % (' '.join(self.cmd),
self.returncode, self.output)
# Convert a variable arguments tuple to an argument list
#
# If args as only one element, the element is expected to be a string and the
# new argument list is populated by splitting the string using spaces as
# separator. If it has multiple arguments, is just converted to a list.
def args_to_list(args):
if len(args) == 1:
return args[0].split()
return list(args)
# Run a git command returning its output (throws GitError on error)
#
# `args` should be strings. If only one string is found in the list, is split
# by spaces and the resulting list is used as `args`. kwargs are extra
# arguments you might want to pass to subprocess.Popen().
#
# Returns the text printed to stdout by the git command without the EOL.
def git(*args, **kwargs):
args = args_to_list(args)
args.insert(0, 'git')
kwargs['stdout'] = subprocess.PIPE
kwargs['stderr'] = subprocess.PIPE
debugf('git command: {} {}', args, kwargs)
proc = subprocess.Popen(args, **kwargs)
(stdout, stderr) = proc.communicate()
if proc.returncode != 0:
raise GitError(proc.returncode, args, stderr.rstrip('\n'))
return stdout.rstrip('\n')
# Check if the git version is at least min_version
# Returns a tuple with the current version and True/False depending on how the
# check went (True if it passed, False otherwise)
def git_check_version(min_version):
cur_ver_str = git('--version').split()[2]
cur_ver = cur_ver_str.split('.')
min_ver = min_version.split('.')
for i in range(len(min_ver)):
if cur_ver[i] < min_ver[i]:
return (cur_ver_str, False)
if cur_ver[i] > min_ver[i]:
return (cur_ver_str, True)
return (cur_ver_str, True)
# Same as git() but inserts --quiet at quiet_index if verbose is less than DEBUG
def git_quiet(quiet_index, *args, **kwargs):
args = args_to_list(args)
if verbose < DEBUG:
args.insert(quiet_index, '--quiet')
return git(*args, **kwargs)
# Specialized version of git_quiet() for `push`ing that accepts an extra
# keyword argument named 'force'. If present, '--force' is passed to git push.
def git_push(*args, **kwargs):
cmd = ['push']
if 'force' in kwargs:
cmd.append('--force')
del kwargs['force']
cmd += args_to_list(args)
git_quiet(1, *cmd, **kwargs)
# Dummy class to indicate a value is required by git_config
class NO_DEFAULT:
pass
# Specialized version of git() to get/set git config variables.
#
# `name` is the name of the git variable to get/set. `default` is the value
# that should be returned if variable is not defined (None will return None in
# that case, use NO_DEFAULT to make this function exit with an error if the
# variable is undefined). `prefix` is a text to prefix to the variable `name`.
# If `value` is present, then the variable is set instead. `opts` is an
# optional list of extra arguments to pass to git config.
#
# Returns the variable value (or the default if not present) if `value` is
# None, otherwise it just sets the variable.
def git_config(name, default=None, prefix=GIT_CONFIG_PREFIX, value=None, opts=()):
name = prefix + name
cmd = ['config'] + list(opts) + [name]
try:
if value is not None:
cmd.append(value)
return git(*cmd)
except subprocess.CalledProcessError as e:
if e.returncode == 1:
if default is not NO_DEFAULT:
return default
die("Can't find '{}' config key in git config. "
"Read the man page for details.",
name)
raise e
# Returns the .git directory location
def git_dir():
return git('rev-parse', '--git-dir')
# Invokes the editor defined by git var GIT_EDITOR.
#
# The editor is invoked to edit the file .git/HUB_EDITMSG, the default content
# of that file will be the `msg` (if any) followed by the `help_msg`, used to
# hint the user about the file format.
#
# The contents of .git/HUB_EDITMSG are returned by the function (after the
# editor is closed). The text is not filtered at all at this stage (so if the
# user left the `help_msg`, it will be part of the returned string too.
def editor(help_msg, msg=None):
prog = git('var', 'GIT_EDITOR')
fname = os.path.join(git_dir(), 'HUB_EDITMSG')
with file(fname, 'w') as f:
f.write(msg or '')
f.write(help_msg)
status = subprocess.call([prog, fname])
if status != 0:
die("Editor returned {}, aborting...", status)
with file(fname) as f:
msg = f.read()
return msg
# git-hub specific configuration container
#
# These variables are described in the manual page.
class Config:
def __init__(self):
self.username = git_config('username', getpass.getuser())
self.oauthtoken = git_config('oauthtoken')
self.upstream = git_config('upstream')
if self.upstream and '/' not in self.upstream:
die("Invalid hub.upstream configuration, '/' not found")
self.forkrepo = git_config('forkrepo')
if not self.forkrepo and self.upstream:
upstream = self.upstream.split('/')
self.forkrepo = self.username + '/' + upstream[1]
self.forkremote = git_config('forkremote', 'origin')
self.pullbase = git_config('pullbase', 'master')
self.urltype = git_config('urltype', 'ssh_url')
self.baseurl = self.sanitize_url('baseurl',
git_config('baseurl', 'https://api.github.com'))
self.forcerebase = git_config('forcerebase', "true",
opts=['--bool']) == "true"
self.triangular = git_config('triangular', "false",
opts=['--bool']) == "true"
def sanitize_url(self, name, url):
u = urlparse.urlsplit(url)
name = GIT_CONFIG_PREFIX + name
# interpret www.github.com/api/v4 as www.github.com, /api/v4
if not u.hostname or not u.scheme:
die("Please provide a full URL for '{}' (e.g. "
"https://api.github.com), got {}",
name, url)
if u.username or u.password:
warnf("Username and password in '{}' ({}) will be "
"ignored, use the 'setup' command "
"for authentication", name, url)
netloc = u.hostname
if u.port:
netloc += ':' + u.port
return urlparse.urlunsplit((u.scheme, netloc,
u.path.rstrip('/'), u.query, u.fragment))
def check(self, name):
if getattr(self, name) is None:
die("Can't find '{}{}' config key in git config. "
"Read the man page for details.",
GIT_CONFIG_PREFIX, name)
# Manages GitHub request handling authentication and content headers.
#
# The real interesting methods are created after the class declaration, for
# each type of request: head(), get(), post(), patch(), put() and delete().
#
# All these methods take an URL (relative to the config.baseurl) and optionally
# an arbitrarily number of positional or keyword arguments (but not both at the
# same time). The extra arguments, if present, are serialized as json and sent
# as the request body.
# All these methods return None if the response is empty, or the deserialized
# json data received in the body of the response.
#
# Example:
#
# r = req.post('/repos/sociomantic/test/labels/', name=name, color=color)
#
# The basic auth has priority over oauthtoken for authentication. If you want
# to use OAuth just leave `basic_auth` and set `oauthtoken`. To fill the
# `basic_auth` member, the `set_basic_auth()` convenient method is provided).
#
# See http://developer.github.com/ for more details on the GitHub API
class RequestManager:
basic_auth = None
oauthtoken = None
links_re = re.compile(r'<([^>]+)>;.*rel=[\'"]?([^"]+)[\'"]?', re.M)
def __init__(self, base_url, oauthtoken=None,
username=None, password=None):
self.base_url = base_url
if oauthtoken is not None:
self.oauthtoken = oauthtoken
elif username is not None:
self.set_basic_auth(username, password)
# Configure the class to use basic authentication instead of OAuth
def set_basic_auth(self, username, password):
self.basic_auth = "Basic " + base64.urlsafe_b64encode("%s:%s" %
(username, password))
# Open an URL in an authenticated manner using the specified HTTP
# method. It also add other convenience headers, like Content-Type,
# Accept (both to json) and Content-Length).
def auth_urlopen(self, url, method, body):
req = urllib2.Request(url, body)
if self.basic_auth:
req.add_header("Authorization", self.basic_auth)
elif self.oauthtoken:
req.add_header("Authorization", "bearer " +
self.oauthtoken)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/vnd.github.v3+json")
req.add_header("Content-Length", str(len(body) if body else 0))
req.get_method = lambda: method.upper()
debugf('{}', req.get_full_url())
# Hide sensitive information from DEBUG output
if verbose >= DEBUG:
for h in req.header_items():
if h[0].lower() == 'authorization':
debugf('{}: {}', h[0], '<hidden>')
else:
debugf('{}: {}', *h)
debugf('{}', req.get_data())
return urllib2.urlopen(req)
# Serialize args OR kwargs (they are mutually exclusive) as json.
def dump(self, *args, **kwargs):
if args and kwargs:
raise ValueError('args and kwargs are mutually '
'exclusive')
if args:
return json.dumps(args)
if kwargs:
return json.dumps(kwargs)
return None
# Get the next URL from the Link: header, if any
def get_next_url(self, response):
links = list()
for l in response.headers.get("Link", "").split(','):
links.extend(self.links_re.findall(l))
links = dict((rel, url) for url, rel in links)
return links.get("next", None)
# This is the real method used to do the work of the head(), get() and
# other high-level methods. `url` should be a relative URL for the
# GitHub API, `method` is the HTTP method to be used (must be in
# uppercase), and args/kwargs are data to be sent to the client. Only
# one can be specified at a time and they are serialized as json (args
# as a json list and kwargs as a json dictionary/object).
def json_req(self, url, method, *args, **kwargs):
url = self.base_url + url
if method.upper() in ('POST', 'PATCH', 'PUT'):
body = self.dump(*args, **kwargs)
else:
body = None
url += '?' + urllib.urlencode(kwargs)
data = None
prev_data = None
while url:
debugf("Request: {} {}\n{}", method, url, body)
res = self.auth_urlopen(url, method, body)
data = res.read()
debugf("Response:\n{}", data)
if data:
data = json.loads(data)
if isinstance(data, list):
if prev_data is None:
prev_data = list()
prev_data.extend(data)
data = None
url = self.get_next_url(res)
assert not (prev_data and data)
if prev_data is not None:
data = prev_data
debugf("Parsed data:\n{}", pformat(data))
return data
# Create RequestManager.head(), get(), ... methods
# We need the make_method() function to make Python bind the method variable
# (from the loop) early (in the loop) instead of when is called. Otherwise all
# methods get bind with the last value of method ('delete') in this case, which
# is not only what we want, is also very dangerous.
def make_method(method):
return lambda self, url, *args, **kwargs: \
self.json_req(url, method, *args, **kwargs)
for method in ('OPTIONS', 'HEAD', 'GET', 'POST', 'PATCH', 'PUT', 'DELETE'):
setattr(RequestManager, method.lower(), make_method(method))
# Message cleaning and parsing functions
# (used to clean the text returned by editor())
########################################################################
def check_empty_message(msg):
if not msg.strip():
die("Message is empty, aborting...")
return msg
message_markdown_help = '''\
# Remember GitHub will parse comments and descriptions as GitHub
# Flavored Markdown.
# For details see: http://github.github.com/github-flavored-markdown/
#
# Lines starting with '# ' (note the space after the hash!) will be
# ignored, and an empty message aborts the command. The space after the
# hash is required by comments to avoid accidentally commenting out a
# line starting with a reference to an issue (#4 for example). If you
# want to include Markdown headers in your message, use the Setext-style
# headers, which consist on underlining titles with '=' for first-level
# or '-' for second-level headers.
'''
# For now it only removes comment lines
def clean_message(msg):
lines = msg.splitlines()
# Remove comment lines
lines = [l for l in lines if not l.strip().startswith('#')]
return '\n'.join(lines)
# For messages expecting a title, split the first line as the title and the
# rest as the message body (but expects the title and message to be separated
# by an empty line).
#
# Returns the tuple (title, body) where body might be an empty string.
def split_titled_message(msg):
lines = check_empty_message(clean_message(msg)).splitlines()
title = lines[0]
body = ''
if len(lines) > 1:
if lines[1].strip():
die("Wrong message format, leave an "
"empty line between the title "
"and the body")
body = '\n'.join(lines[2:])
return (title, body)
# Command-line commands helper classes
########################################################################
# Base class for commands that just group other subcommands
#
# The subcommands are inspected automatically from the derived class by
# matching the names to the `subcommand_suffix`. For each sub-command, the
# method will be called to add options to the command-line
# parser..
#
# Each sub-command is expected to have a certain structure (some methods and/or
# attributes):
#
# `run(parser, args)`
# Required method that actually does the command work.
# `parser` is the command-line parser instance, and `args` are the parsed
# arguments (only the ones specific to that sub-command).
#
# `setup_parser(parser)`
# Will be called to setup the command-line parser. This is where new
# subcommands or specific options can be added to the parser. If it returns
# True, then parse_known_args() will be used instead, so you can collect
# unknown arguments (stored in args.unknown_args).
#
# `cmd_name`
# Command name, if not present the name of the class (with the
# `subcommand_suffix` removed and all in lowercase) is used as the name.
#
# `cmd_title`
# A string shown in the help message when listing the group of subcommands
# (not required but strongly recommended) for the current class.
#
# `cmd_help`
# A string describing what this command is for (shown in the help text when
# listing subcommands). If not present, the class __doc__ will be used.
#
# `cmd_usage`
# A usage string to be passed to the parser. If it's not defined, is
# genreated from the options as usual. %(prog)s can be used to name the
# current program (and subcommand).
#
# `cmd_required_config`
# An optional list of configuration variables that this command needs to work
# (if any of the configuration variables in this list is not defined, the
# program exists with an error).
#
# All methods are expected to be `classmethod`s really.
class CmdGroup (object):
subcommand_suffix = 'Cmd'
@classmethod
def setup_parser(cls, parser):
partial = False
suffix = cls.subcommand_suffix
subcommands = [getattr(cls, a) for a in dir(cls)
if a.endswith(suffix)]
if not subcommands:
return
title = None
if hasattr(cls, 'cmd_title'):
title = cls.cmd_title
subparsers = parser.add_subparsers(title=title)
for cmd in subcommands:
name = cmd.__name__.lower()[:-len(suffix)]
if hasattr(cmd, 'cmd_name'):
name = cmd.cmd_name
help = cmd.__doc__
if hasattr(cmd, 'cmd_help'):
help = cmd.cmd_help
kwargs = dict(help=help)
if hasattr(cmd, 'cmd_usage'):
kwargs['usage'] = cmd.cmd_usage
p = subparsers.add_parser(name, **kwargs)
partial = cmd.setup_parser(p) or partial
if not hasattr(cmd, 'run'):
continue
if hasattr(cmd, 'cmd_required_config'):
def make_closure(cmd):
def check_config_and_run(parser, args):
for c in cmd.cmd_required_config:
config.check(c)
cmd.run(parser, args)
return check_config_and_run
p.set_defaults(run=make_closure(cmd))
else:
p.set_defaults(run=cmd.run)
return partial
# `git hub setup` command implementation
class SetupCmd (object):
cmd_help = 'perform an initial setup to connect to GitHub'
@classmethod
def setup_parser(cls, parser):
parser.add_argument('-u', '--username',
help="GitHub's username (login name). If an e-mail is "
"provided instead, a username matching that e-mail "
"will be searched and used instead, if found (for "
"this to work the e-mail must be part of the public "
"profile)")
parser.add_argument('-p', '--password',
help="GitHub's password (will not be stored)")
parser.add_argument('-b', '--baseurl', metavar='URL',
help="GitHub's base URL to use to access the API "
"(Enterprise servers usually use https://host/api/v3)")
group = parser.add_mutually_exclusive_group()
group.add_argument('--global',
dest='opts', action='store_const', const=['--global'],
help="store settings in the global configuration "
"(see git config --global for details)")
group.add_argument('--system',
dest='opts', action='store_const', const=['--system'],
help="store settings in the system configuration "
"(see git config --system for details)")
parser.set_defaults(opts=[])
@classmethod
def run(cls, parser, args):
is_global = ('--system' in args.opts or
'--global' in args.opts)
try:
if not is_global:
git('rev-parse --git-dir')
except GitError as error:
errf(error.output)
die("Maybe you want to use --global or --system?")
username = args.username
password = args.password
if (username is None or password is None) and \
not sys.stdin.isatty():
die("Can't perform an interactive setup outside a tty")
if username is None:
username = config.username or getpass.getuser()
reply = raw_input('GitHub username [%s]: ' % username)
if reply:
username = reply
if password is None:
password = getpass.getpass(
'GitHub password (will not be stored): ')
if '@' in username:
infof("E-mail used to authenticate, trying to "
"retrieve the GitHub username...")
username = cls.find_username(username)
infof("Found: {}", username)
req.set_basic_auth(username, password)
note = 'git-hub'
if not is_global and config.forkrepo:
proj = config.forkrepo.split('/', 1)[1]
note += ' (%s)' % proj
while True:
infof("Looking for GitHub authorization token...")
auths = dict([(a['note'], a)
for a in req.get('/authorizations')])
if note not in auths:
break
errf("The OAuth token with name '{}' already exists.",
note)
infof("If you want to create a new one, enter a "
"name for it. Otherwise you can go to "
"https://github.com/settings/tokens to "
"regenerate or delete the token '{}'", note)
note = raw_input("Enter a new token name (an empty "
"name cancels the setup): ")
if not note:
sys.exit(0)
infof("Creating auth token '{}'", note)
auth = req.post('/authorizations', note=note,
scopes=['user', 'repo'])
set_config = lambda k, v: git_config(k, value=v, opts=args.opts)
set_config('username', username)
set_config('oauthtoken', auth['token'])
if args.baseurl is not None:
set_config('baseurl', args.baseurl)
@classmethod
def find_username(cls, name):
users = req.get('/search/users', q=name)['items']
users = [u['login'] for u in users]
if not users:
die("No users found when searching for '{}'", name)
if len(users) > 1:
die("More than one username found ({}), please try "
"again using your username instead",
', '.join(users))
return users[0].encode('UTF8')
# `git hub clone` command implementation
class CloneCmd (object):
cmd_required_config = ['username', 'urltype', 'oauthtoken']
cmd_help = 'clone a GitHub repository (and fork as needed)'
cmd_usage = '%(prog)s [OPTIONS] [GIT CLONE OPTIONS] REPO [DEST]'
@classmethod
def setup_parser(cls, parser):
parser.add_argument('repository', metavar='REPO',
help="name of the repository to fork; in "
"<owner>/<project> format is the upstream repository, "
"if only <project> is specified, the <owner> part is "
"taken from hub.username")
parser.add_argument('dest', metavar='DEST', nargs='?',
help="destination directory where to put the new "
"cloned repository")
parser.add_argument('-r', '--remote', metavar='NAME',
help="use NAME as the upstream remote repository name "
"instead of the default 'upstream' (for a conventional "
"clone) or 'fork' (for a --triangular clone)")
parser.add_argument('-t', '--triangular', action="store_true",
help="use Git 'triangular workflow' setup, so you can "
"push by default to your fork but pull by default "
"from 'upstream'")
return True # we need to get unknown arguments
@classmethod
def run(cls, parser, args):
upstream = urlparse.urlsplit(args.repository).path
if upstream.endswith('.git'): upstream = upstream[:-4]
if '/' in upstream:
(owner, proj) = upstream.split('/')[-2:]
for repo in req.get('/user/repos'):
if repo['name'] == proj and repo['fork']:
break
else: # Fork not found
infof('Forking {} to {}/{}', upstream,
config.username, proj)
repo = req.post('/repos/' + upstream + '/forks')
repo = req.get('/repos/' + repo['full_name'])
else: # no '/' in upstream
repo = req.get('/repos/%s/%s' % (config.username,
upstream))
if not repo['fork']:
warnf('Repository {} is not a fork, just '
'cloning, upstream will not be set',
repo['full_name'])
upstream = None
else:
upstream = repo['parent']['full_name']
dest = args.dest or repo['name']
triangular = cls.check_triangular(config.triangular or
args.triangular)
if triangular and not upstream:
parser.error("Can't use triangular workflow without "
"an upstream repo")
url = repo['parent'][config.urltype] if triangular \
else repo[config.urltype]
infof('Cloning {} to {}', url, dest)
git_quiet(1, 'clone', *(args.unknown_args + [url, dest]))
if not upstream:
# Not a forked repository, nothing else to do
return
# Complete the repository setup
os.chdir(dest)
remote = args.remote or ('fork' if triangular else 'upstream')
remote_url = repo['parent'][config.urltype]
if triangular:
remote_url = repo[config.urltype]
git_config('remote.pushdefault', prefix='', value=remote)
git_config('forkremote', value=remote)
git_config('upstream', value=upstream)
git('remote', 'add', remote, remote_url)
infof('Fetching from {} ({})', remote, remote_url)
git_quiet(1, 'fetch', remote)
@classmethod
def check_triangular(cls, triangular):
if not triangular:
return False
min_ver = '1.8.3'
(cur_ver, ver_ok) = git_check_version(min_ver)
if not ver_ok:
warnf("Current git version ({}) is too old to support "
"--triangular, at least {} is needed. Ignoring "
"the --triangular option...", cur_ver, min_ver)
return False
min_ver = '1.8.4'
(cur_ver, ver_ok) = git_check_version(min_ver)
pd = git_config('push.default', prefix='', default=None)
if not ver_ok and pd == 'simple':
warnf("Current git version ({}) has an issue when "
"using the option push.default=simple and "
"using the --triangular workflow. Please "
"use Git {} or newer, or change push.default "
"to 'current' for example. Ignoring the "
"--triangular option...", cur_ver, min_ver)
return False
return True
# Utility class that group common functionality used by the multiple `git hub
# issue` (and `git hub pull`) subcommands.
class IssueUtil (object):
cmd_required_config = ['upstream', 'oauthtoken']
# Since this class is reused by the CmdPull subcommands, we use several
# variables to customize the out and help message to adjust to both
# issues and pull requests.
name = 'issue'
gh_path = 'issues'
id_var = 'ISSUE'
help_msg = '''
# Please enter the title and description below.
#
# The first line is interpreted as the title. An optional description
# can follow after and empty line.
#
# Example:
#
# Some title
#
# Some description that can span several
# lines.
#
''' + message_markdown_help
comment_help_msg = '''
# Please enter your comment below.
#
''' + message_markdown_help
@classmethod
def print_issue_summary(cls, issue):
infof(u'[{number}] {title} ({user[login]})\n{}{html_url}',
u' ' * (len(str(issue['number'])) + 3),
**issue)
@classmethod
def print_issue_header(cls, issue):
issue['labels'] = ' '.join(['['+l['name']+']'
for l in issue.get('labels', [])])
if issue['labels']:
issue['labels'] += '\n'
infof(u"""
#{number}: {title}
================================================================================
{name} is {state}, was reported by {user[login]} and has {comments} comment(s).
{labels}<{html_url}>
{body}
""",
**issue)
if issue['comments'] > 0:
infof(u'Comments:')
@classmethod
def print_issue_comment(cls, comment):
body = comment['body']
body = '\n'.join([' '+l for l in body.splitlines()])
infof(u'On {created_at}, {user[login]} commented:\n'
'{0}\n\n <{html_url}>\n', body, **comment)
@classmethod
def merge_issue_comments(cls, comments, review_comments):
for c in comments:
c['sort_key'] = c['created_at']
prev_commit_pos = None
prev_created = None
for c in review_comments:
curr_commit_pos = c['commit_id'], c['position']
if prev_commit_pos is None:
prev_commit_pos = curr_commit_pos
prev_created = c['created_at']
if prev_commit_pos == curr_commit_pos:
c['sort_key'] = '%s %s %s' % (prev_created,
prev_commit_pos[0], prev_commit_pos[1])
else:
prev_commit_pos = None
prev_created = None
comments = comments + review_comments
comments.sort(key=lambda c: c['sort_key'])
return comments
@classmethod
def print_issue(cls, issue, comments, review_comments=()):
review_comments = list(review_comments)
issue = dict(issue)
issue['name'] = cls.name.capitalize()
issue['comments'] += len(comments) + len(review_comments)
cls.print_issue_header(issue)
prev_commit_pos = None
for c in cls.merge_issue_comments(comments, review_comments):
if 'diff_hunk' in c:
curr_commit_pos = c['commit_id'], ['position']
if prev_commit_pos is None:
infof(u'{}\n', u'-' * 80)
infof(u'diff --git a/{path} b/{path}\n'
u'index {original_commit_id}..{commit_id}\n'
u'--- a/{path}\n'
u'+++ b/{path}\n'
u'{diff_hunk}\n',
**c)
prev_commit_pos = curr_commit_pos
if prev_commit_pos == curr_commit_pos:
cls.print_issue_comment(c)
else:
infof(u'{}\n', u'-' * 80)
cls.print_issue_comment(c)
@classmethod
def print_comment(cls, comment):
body = comment['body'].decode('UTF8')
infof(u'[{id}] {}{} ({user[login]})', body[:60],
u'…' if len(body) > 60 else u'',
u' ' * (len(str(comment['id'])) + 3),
**comment)
@classmethod
def url(cls, number=None):
s = '/repos/%s/%s' % (config.upstream, cls.gh_path)
if number:
s += '/' + number
return s
@classmethod
def editor(cls, msg=None):
return editor(cls.help_msg, msg)
@classmethod
def comment_editor(cls, msg=None):
return editor(cls.comment_help_msg, msg)
@classmethod
def clean_and_post_comment(cls, issue_num, body):
# URL fixed to issues, pull requests comments are made through
# issues
url = '/repos/%s/issues/%s/comments' % (config.upstream,
issue_num)
body = check_empty_message(clean_message(body))
comment = req.post(url, body=body)
cls.print_comment(comment)
# `git hub issue` command implementation
class IssueCmd (CmdGroup):
cmd_title = 'subcommands to manage issues'
cmd_help = 'manage issues'
class ListCmd (IssueUtil):
cmd_help = "show a list of open issues"
@classmethod
def setup_parser(cls, parser):
parser.add_argument('-c', '--closed',
action='store_true', default=False,
help="show only closed pull requests")
parser.add_argument('-C', '--created-by-me',
action='store_true',
help=("show only %ss created by me" %
cls.name))
parser.add_argument('-A', '--assigned-to-me',
action='store_true',
help=("show only %ss assigned to me" %
cls.name))
@classmethod
def run(cls, parser, args):
def filter(issue, name):
a = issue[name]
if a and a['login'] == config.username: