Repository navigation
Expand file tree
/
Copy pathgit-hub
More file actions
executable file
·898 lines (824 loc) · 31.9 KB
/
Copy pathgit-hub
File metadata and controls
executable file
·898 lines (824 loc) · 31.9 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
10BC8
div>
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
#!/usr/bin/env python
#
# Github integration for git.
# Usage: See README
#
# Copyright (C) 2012-2013 Dennis Kaarsemaker <dennis@kaarsemaker.net>
#
# 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/>.
import datetime
import getpass
import github3
import glob
import docopt
import os
import re
import requests
import socket
import sys
import webbrowser
from whelk import Shell
shell = Shell(encoding='utf-8')
if sys.version_info[0] > 2:
# On python 3, shell decodes into utf-8 as above
try_decode = lambda x: x
else:
# Try decoding as utf-8 only
try_decode = lambda x: x.decode('utf-8')
## ANSI color library from github.com/seveas/hacks
class Attr(object):
def __init__(self, **attr):
self.attr = attr
self.rev_attr = dict([(v,k) for k,v in attr.items()])
for k, v in attr.items():
setattr(self, k, v)
def name(self, val):
return self.rev_attr[val]
def xterm(self, val):
return '%d;5;%d' % (self._xterm, val)
fgcolor = Attr(black=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, _xterm=38, default=39, none=None)
bgcolor = Attr(black=40, red=41, green=42, yellow=43, blue=44, magenta=45, cyan=46, white=47, _xterm=48, default=49, none=None)
attr = Attr(normal=0, bright=1, faint=2, underline=4, negative=7, conceal=8, crossed=9, none=None)
esc = '\033'
mode = lambda *args: "%s[%sm" % (esc, ';'.join([str(x) for x in args if x is not None]))
reset = mode(attr.normal)
wrap = lambda text, *args: "%s%s%s" % (mode(*args), text, reset)
erase_line = esc + '[K'
erase_display = esc + '[2J'
save_cursor = esc + '[s'
restore_cursor = esc + '[u'
## End ansi color library
def main():
usage = """github integration for git
A full manual can be found on http://seveas.github.com/git-hub
Usage:
git-hub add-hook <name> [<setting>...]
git-hub add-public-keys [<key>...]
git-hub add-remote [--ssh|--http] <user>
git-hub browse [--parent]
git-hub calendar [<user>]
git-hub clone [--ssh|--http] <repo>
git-hub create [-d <description>]
git-hub edit-hook <name> [<setting>...]
git-hub fork [--ssh|--http] [<repo>]
git-hub forks
git-hub gist [--desc <description>] <file>...
git-hub gists [<user>]
git-hub hooks
git-hub ignore [<language>...]
git-hub issue [--parent] <issue>...
git-hub issues [--parent] [<filter>...]
git-hub log [<what>]
git-hub mirror [--goblet] [<repo>]
git-hub network [<level>]
git-hub public-keys <user>
git-hub pull-request [--issue=<issue>] [<branch1:branch2>]
git-hub remove-hook <name>
git-hub repos [<user>]
git-hub set-origin
git-hub whoami
git-hub whois <user>...
Options:
-h --help Show this help message and exit
--desc=<description> Description for the new gist/repo
--parent Show issues for the parent repo
--issue=<issue> Turn this issue into a pull request
--ssh Use SSH for cloning 3rd party repos
--http Use https for cloning 3rd party repos
--goblet When mirroring, set up goblet configuration
"""
opts = docopt.docopt(usage)
for command in commands:
if opts[command]:
try:
commands[command](opts)
except KeyboardInterrupt:
sys.exit(1)
break
def err(msg):
sys.stderr.write(msg + "\n")
sys.exit(1)
def check(result):
if result.returncode != 0:
print(result.stderr.rstrip())
sys.exit(result.returncode)
return result
commands = {}
def command(fnc):
commands[fnc.__name__.replace('_','-')] = fnc
return fnc
def github():
config_file = os.path.join(os.path.expanduser('~'), '.githubconfig')
old_umask = os.umask(63) # 0o077
user = shell.git('config', '--file', config_file, 'github.user').stdout.strip()
if not user:
user = raw_input("Github user: ").strip()
shell.git('config', '--file', config_file, 'github.user', user)
token = shell.git('config', '--file', config_file, 'github.token').stdout.strip()
if not token:
password = getpass.getpass("GitHub password: ")
auth = github3.authorize(user, password, ['user', 'repo', 'gist'],
"Github Git integration on %s" % socket.gethostname(), "http://seveas.github.com/git-hub")
token = auth.token
shell.git('config', '--file', config_file, 'github.token', token)
shell.git('config', '--file', config_file, 'github.auth_id', str(auth.id))
if not user or not token:
err("No user or token specified")
gh = github3.login(username=user, token=token)
try:
gh.user()
except github3.GitHubError:
# Token obsolete
shell.git('config', '--file', config_file, '--unset', 'github.token')
gh = github()
os.umask(old_umask)
return gh
def get_repo():
# Find the repo on github by searching for remotes hosted on github in the
# following order
# - A remote owned by the current user
# - A remote named 'origin'
# - A remote named 'upstream'
# - The first defined remote
gh = github()
me = gh.user().login
mine = origin = upstream = repo = None
remotes = shell.git('config', '--get-regexp', 'remote\..*\.url', 'github.com').stdout.strip().splitlines()
for remote in reversed(remotes):
m = re.match('^remote\.([^.]*)\.url.*github.com[/:]([^/]*)/([^/]*?)(?:\.git)?$', remote)
remote, user, repo = m.groups()
repo = gh.repository(user, repo)
if not repo:
print "Repository %s/%s no longer exists on github" % m.grou
10BC8
ps()[1:]
continue
repo.remote = remote
if remote == 'origin':
origin = repo
elif remote == 'upstream':
upstream = repo
if user == me:
mine = repo
return mine or origin or upstream or repo
@command
def create(opts):
"""Create a repository on github to push to"""
root = check(shell.git('rev-parse', '--show-toplevel')).stdout.strip()
name = os.path.basename(root)
gh = github()
if name in [x.name for x in gh.iter_repos()]:
err("Repository already exists")
gh.create_repo(name=name, description=opts['<description>'] or "")
set_origin(opts)
@command
def set_origin(opts):
"""Set the remote 'origin' to github.\n If this is a fork, set the remote 'upstream' to the parent"""
gh = github()
me = gh.user()
repo = get_repo()
# Is this mine? No? Do I have a clone?
if repo.owner.login != me.login:
my_repo = gh.repository(me, repo.name)
if my_repo:
repo = my_repo
shell.git('config', 'remote.origin.url', repo.ssh_url)
shell.git('config', '--replace-all', 'remote.origin.fetch', '+refs/heads/*:refs/remotes/origin/*')
if repo.fork:
parent = repo.parent
shell.git('config', 'remote.upstream.url', parent.git_url)
shell.git('config', 'remote.upstream.fetch', '+refs/heads/*:refs/remotes/upstream/*')
else:
# If issues are enabled, fetch pull requests
try:
list(repo.iter_issues(number=1))
except github3.GitHubError:
pass
else:
shell.git('config', '--add', 'remote.origin.fetch', '+refs/pull/*/head:refs/pull/*/head')
@command
def repos(opts):
"""[user] List all repos of a user, by default yours"""
gh = github()
user = (opts['<user>'] or [gh.user().login])[0]
repos = list(gh.iter_user_repos(user))
maxlen = max([len(x.name) for x in repos])
fmt = "%%-%ds %%s" % maxlen
for repo in repos:
print(wrap(fmt % (repo.name, repo.description), attr.faint if repo.fork else attr.normal))
@command
def clone(opts):
"""Clone a repositories by name"""
gh = github()
if '/' in opts['<repo>']:
user, repo = opts['<repo>'].rsplit('/',2)[-2:]
else:
user, repo = gh.user().login, opts['<repo>']
if repo.endswith('.git'):
repo = repo[:-4]
repo_ = gh.repository(user, repo)
if not repo_:
err("Repository %s/%s does not exist" % (user, repo))
repo = repo_
url = repo.ssh_url
if gh.user().login != user:
url = repo.git_url
if opts['--ssh']:
url = repo.ssh_url
elif opts['--http']:
url = repo.clone_url
rc = shell.git('clone', url, redirect=False).returncode
if rc:
sys.exit(rc)
if repo.fork:
os.chdir(repo.name)
set_origin(opts)
shell.git('fetch', 'upstream', redirect=False)
@command
def mirror(opts):
gh = github()
if opts['<repo>']:
if '/' in opts['<repo>']:
user, repo = opts['<repo>'].rsplit('/',2)[-2:]
else:
user, repo = gh.user().login, opts['<repo>']
if repo.endswith('.git'):
repo = repo[:-4]
git_dir = repo + '.git'
if repo == '*':
for repo in gh.iter_user_repos(user):
opts['<repo>'] = '%s/%s' % (user, repo)
mirror(opts)
return
repo_ = gh.repository(user, repo)
if not repo_:
err("Repository %s/%s does not exist" % (user, repo))
else:
git_dir = '.'
repo_ = get_repo()
if not repo_:
err("Repository %s/%s does not exist" % (user, repo))
repo = repo_
if not os.path.exists(git_dir):
url = repo.git_url
if opts['--ssh']:
url = repo.ssh_url
elif opts['--http']:
url = repo.clone_url
rc = shell.git('clone', '--mirror', url, redirect=False).returncode
if rc:
sys.exit(rc)
else:
# Update the current, mirrored repo
if shell.git('--git-dir', git_dir, 'config', 'core.bare').stdout.strip() != 'true' or \
shell.git('--git-dir', git_dir, 'config', 'remote.origin.mirror').stdout.strip() != 'true':
err("This is not a mirrored repository")
rc = shell.git('--git-dir', git_dir, 'fetch', '-q', 'origin', redirect=False).returncode
if rc:
sys.exit(rc)
shell.git('--git-dir', git_dir, 'remote', 'prune', 'origin', redirect=False).returncode
if rc:
sys.exit(rc)
with open(os.path.join(git_dir, 'description'), 'w') as fd:
fd.write(repo.description.encode('utf-8'))
if opts['--goblet']:
if repo.fork:
owner = gh.user(repo.parent.owner.login)
else:
owner = gh.user(repo.owner.login)
shell.git('--git-dir', git_dir, 'config', 'goblet.owner', owner.name.encode('utf-8') or owner.login)
shell.git('--git-dir', git_dir, 'config', 'goblet.cloneurlgit', repo.git_url)
shell.git('--git-dir', git_dir, 'config', 'goblet.cloneurlhttp', repo.clone_url)
goblet_dir = os.path.join(git_dir, 'goblet')
if not os.path.exists(goblet_dir):
os.mkdir(goblet_dir, 0o777)
os.chmod(goblet_dir, 0o777)
@command
def fork(opts):
gh = github()
"""Fork a repo and clone it"""
if not opts['<repo>']:
repo = get_repo()
user, repo = repo.owner.login, repo.name
do_clone = False
else:
if '/' not in opts['<repo>']:
err("Usage: git hub fork url\n git hub fork user/repo")
user, repo = opts['<repo>'].rsplit('/',2)[-2:]
do_clone = True
if repo.endswith('.git'):
repo = repo[:-4]
if repo in [x.name for x in gh.iter_repos()]:
err("Repository already exists")
repo_ = gh.repository(user, repo)
if not repo_:
err("Repository %s/%s does not exist" % (user, repo))
my_clone = repo_.create_fork()
opts['<repo>'] = my_clone.name
if do_clone:
clone(opts)
else:
set_origin(opts)
@command
def forks(opts):
"""List all forks of this repository"""
repo = get_repo()
if repo.fork:
repo = repo.parent
print("[%s] %s" % (wrap(repo.owner.login, attr.bright), repo.html_url))
for fork in repo.iter_forks():
print("[%s] %s" % (fork.owner.login, fork.html_url))
@command
def issues(opts):
"""List issues"""
repo = get_repo()
if repo.fork and opts['--parent']:
repo = repo.parent
filters = dict([x.split('=', 1) for x in opts['<filter>']])
try:
for issue in repo.iter_issues(**filters):
url = issue.pull_request and issue.pull_request['html_url'] or issue.html_url
print("[%d] %s %s" % (issue.number, issue.title, url))
except github3.GitHubError:
_, err, _ = sys.exc_info()
if err.code == 410:
print(err.message)
else:
raise
@command
def issue(opts):
"""Issue details"""
repo = get_repo()
if repo.fork and opts['--parent']:
repo = repo.parent
for issue in opts['<issue>']:
issue = repo.issue(issue)
print(wrap(issue.title, attr.bright, attr.underline))
print(issue.body)
print(issue.pull_request and issue.pull_request['html_url'] or issue.html_url)
@command
def add_remote(opts):
"""Add user's fork as a remote by that name"""
repo = get_repo()
if repo.fork:
repo = repo.parent
forks = repo.iter_forks()
for fork in forks:
if fork.owner.login in opts['<user>']:
url = fork.git_url
if opts['--ssh']:
url = fork.ssh_url
elif opts['--http']:
url = fork.clone_url
check(shell.git('remote', 'add', fork.owner.login, url))
check(shell.git('fetch', fork.owner.login, stdout=False, stderr=False))
@command
def whois(opts):
"""Display github user info"""
gh = github()
for user_ in opts['<user>']:
user = gh.user(user_)
if not user:
print("No such user: %s" % user_)
continue
print(wrap(user.name or user.login, attr.bright, attr.underline))
print('Profile %s' % user.html_url)
if user.email:
print('Email %s' % user.email)
if user.blog:
print('Blog %s' % user.blog)
if user.location:
print('Location %s' % user.location)
if user.company:
print('Company %s' % user.company)
print('Repos %d public, %d private' % (user.public_repos, user.total_private_repos))
print('Gists %d public, %d private' % (user.public_gists, user.total_private_gists))
if user.login == gh.user().login:
keys = gh.iter_keys()
else:
keys = user.iter_keys()
for pkey in keys:
algo, key = pkey.key.split()
algo = algo[4:].upper()
if pkey.title:
print("%s key%s...%s (%s)" % (algo, ' ' * (6 - len(algo)), key[-10:], pkey.title))
else:
print("%s key%s...%s" % (algo, ' ' * (6 - len(algo)), key[-10:]))
@command
def whoami(opts):
"""Display github user info"""
gh = github()
opts['<user>'] = [gh.user().login]
whois(opts)
@command
def gist(opts):
"""Create a new gist from files"""
files = {}
description = opts['<description>'] or ''
for f in opts['<file>']:
if f == '-':
files['stdout'] = {'content': sys.stdin.read()}
else:
if not os.path.exists(f):
err("No such file: %s" % f)
with open(f) as fd:
files[os.path.basename(f)] = {'content': fd.read()}
gist = github().create_gist(description=description, files=files)
print("Gist created at %s" % gist.html_url)
@command
def gists(opts):
gh = github()
user = (opts['<user>'] or [gh.user().login])[0]
for gist in gh.iter_gists(user):
print("%s - %s" % (gist.html_url, gist.description))
@command
def add_public_keys(opts):
"""Adds keys to your public keys"""
if not opts['<key>']:
opts['<key>'] = glob.glob(os.path.join(os.path.expanduser('~'), '.ssh', 'id_*.pub'))
gh = github()
existing = [x.key for x in gh.iter_keys()]
for arg in opts['<key>']:
with open(arg) as fd:
algo, key, title = fd.read().strip().split(None, 2)
key = "%s %s" % (algo, key)
if key in existing:
continue
print("Adding %s" % arg)
gh.create_key(title=title, key=key)
@command
def public_keys(opts):
"""Lists all keys for a user"""
gh = github()
if gh.user().login == opts['<user>'][0]:
keys = gh.iter_keys()
else:
keys = gh.user(opts['<user>'][0]).iter_keys()
for key in keys:
print("%s %s" % (key.key, key.title or ''))
@command
def pull_request(opts):
"""Opens a pull request to merge your branch1 to upstream branch2"""
repo = get_repo()
if not repo.fork:
err("This is not a forked repository")
parent = repo.parent
# Which branch?
src = opts['<branch1:branch2>'] or ''
dst = None
if ':' in src:
src, dst = src.split(':', 1)
if not src:
src = check(shell.git('rev-parse', '--abbrev-ref', 'HEAD')).stdout.strip()
if not dst:
dst = 'master'
# Try to get the local commit
commit = check(shell.git('show-ref', 'refs/heads/%s' % src)).stdout.split()[0]
# Do they exist on github?
srcb = repo.branch(src)
if not srcb:
if raw_input("Branch %s does not exist in your github repo, shall I push? [Y/n] " % src).lower() in ['y', 'Y', '']:
shell.git('push', repo.remote, src)
else:
err("Aborting")
elif srcb and srcb.commit.sha != commit:
# Have we diverged? Then there are commits that are reachable from the github branch but not local
diverged = shell.git('rev-list', srcb.commit.sha, '^' + commit)
if diverged.stderr or diverged.stdout:
if raw_input("Branch %s has diverged from github, shall I push and overwrite? [y/N] " % src) in ['y', 'Y']:
shell.git('push', '--force', repo.remote, src)
else:
err("Aborting")
else:
if raw_input("Branch %s not up to date on github, but can be fast forwarded, shall I push? [Y/n] " % src) in ['y', 'Y', '']:
shell.git('push', repo.remote, src)
else:
err("Aborting")
dstb = parent.branch(dst)
if not dstb:
err("Branch %s does not exist in %s/%s" % (dst, parent.owner.login, parent.name))
# Do we have the dst locally?
for remote in check(shell.git('remote')).stdout.strip().split("\n"):
if check(shell.git('config', 'remote.%s.url' % remote)).stdout.strip() in [parent.git_url, parent.ssh_url, parent.clone_url]:
break
else:
err("You don't have %s/%s configured as a remote repository" % (parent.owner.login, parent.name))
# How many commits?
commits = try_decode(check(shell.git('log', '--pretty=%H', '%s/%s..%s' % (remote, dst, src))).stdout).strip().split()
commits.reverse()
# 1: title/body from commit
if not commits:
err("Your branch has no commits yet")
# Are we turning an issue into a commit?
if opts['<issue>']:
pull = parent.create_pull_from_issue(base=dst, head='%s:%s' % (repo.owner.login, src), issue=int(opts['<issue>']))
print("Pull request %d created %s" % (pull.number, pull.html_url))
return
if len(commits) == 1:
title, body = check(shell.git('log', '--pretty=%s\n%b', '%s^..%s' % (commits[0], commits[0]))).stdout.split('\n', 1)
title = title.strip()
body = body.strip()
# More: title from branchname (titlecased, s/-/ /g), body comments from shortlog
else:
title = src
if '/' in title:
title = title[title.rfind('/') + 1:]
title = title.title().replace('-', ' ')
body = ""
body += """
# Requesting a pull from %s/%s into %s/%s
#
# Please enter a message to accompany your pull request. Lines starting
# with '#' will be ignored, and an empty message aborts the request.
#""" % (repo.owner.login, src, parent.owner.login, dst)
body += "\n# " + try_decode(check(shell.git('shortlog', '%s/%s..%s' % (remote, dst, src))).stdout).strip().replace('\n', '\n# ')
body += "\n#\n# " + try_decode(check(shell.git('diff', '--stat', '%s^..%s' % (commits[0], commits[-1]))).stdout).strip().replace('\n', '\n#')
temp_file = os.path.join(check(shell.git('rev-parse', '--git-dir')).stdout.strip(), 'PULL_REQUEST_EDITMSG')
with open(temp_file, 'w') as fd:
fd.write("%s\n\n%s" % (title,body))
getattr(shell, check(shell.git('var', 'GIT_EDITOR')).stdout.strip())(temp_file, redirect=False)
with open(temp_file) as fd:
title, body = (try_decode(fd.read()) +'\n').split('\n', 1)
title = title.strip()
body = body.strip()
body = re.sub('^#.*', '', body, flags=re.MULTILINE).strip()
if not body:
err("No pull request message specified")
pull = parent.create_pull(base=dst, head='%s:%s' % (repo.owner.login, src), title=title, body=body)
print("Pull request %d created %s" % (pull.number, pull.html_url))
@command
def network(opts):
"""Create a graphviz graph of followers and forks"""
from collections import defaultdict
class P:
def __init__(self, user):
self.user = user
self.done = False
self.rel_to = defaultdict(list)
def __repr__(self):
return dict.__repr__(self.rel_to)
level = 1
if opts['<level>']:
try:
level = int(opts['<level>'])
except ValueError:
err("Integer argument required")
gh = github()
me = gh.user()
people = {me.login: P(me)}
for i in range(level):
for login, person in list(people.items()):
if person.done:
continue
sys.stderr.write("Looking at user %s" % login)
# Followers
for other in person.user.iter_followers():
if other.login not in people:
people[other.login] = P(other)
people[other.login].rel_to[login].append('follows')
for other in person.user.iter_following():
if other.login not in people:
people[other.login] = P(other)
person.rel_to[other.login].append('follows')
# Forks
for repo in gh.iter_repos(login, type='owner'):
sys.stderr.write("Looking at repo %s" % repo.name)
if repo.fork:
# Sigh. GH doesn't return parent info in iter_repos
repo = gh.repository(repo.owner.login, repo.name)
if repo.owner.login not in people:
people[repo.owner.login] = P(repo.owner)
person.rel_to[repo.parent.owner.login].append('forked %s' % repo.parent.name)
else:
for fork in repo.iter_forks():
if fork.owner.login == login:
continue
if fork.owner.login not in people:
people[fork.owner.login] = P(fork.owner)
people[fork.owner.login].rel_to[login].append('forked %s' % repo.name)
person.done = True
# Now we create a graph
graph = ["digraph network {"]
for person in people:
graph.append(' "%s"' % person)
for login, person in people.items():
for other, types in person.rel_to.items():
graph.append(' "%s" -> "%s" [label="%s"]' % (login, other, "\\n".join(types)))
graph.append("}")
print("\n".join(graph))
@command
def hooks(opts):
repo = get_repo()
for hook in repo.iter_hooks():
print(wrap("%s (%s)" % (hook.name, ', '.join(hook.events)), attr.bright))
for key, val in sorted(hook.config.items()):
if val in (None, ''):
continue
print(" %s: %s" % (key, val))
@command
def remove_hook(opts):
repo = get_repo()
for hook in repo.iter_hooks():
if hook.name == opts['<name>']:
hook.delete()
@command
def add_hook(opts):
repo = get_repo()
for hook in repo.iter_hooks():
if hook.name == opts['<name>']:
raise ValueError("Hook %s already exists" % opts['<name>'])
settings = dict([x.split('=', 1) for x in opts['<setting>']])
for key in settings:
if settings[key].isdigit():
settings[key] = int(settings[key])
events = settings.pop('events', 'push').split(',')
repo.create_hook(opts['<name>'], settings, events)
@command
def edit_hook(opts):
repo = get_repo()
for hook in repo.iter_hooks():
if hook.name == opts['<name>']:
break
else:
raise ValueError("Hook %s does not exist" % opts['<name>'])
settings = dict([x.split('=', 1) for x in opts['<setting>']])
for key in settings:
if settings[key].isdigit():
settings[key] = int(settings[key])
events = settings.pop('events', ','.join(hook.events)).split(',')
config = hook.config
config.update(settings)
hook.edit(opts['<name>'], config, events)
@command
def ignore(opts):
lang = opts['<language>']
gh = github()
if not lang:
langs = sorted(gh.gitignore_templates(), key = lambda x: x.lower())
print("Languages for which a gitignore template is available:\n * " + "\n * ".join(langs))
else:
for l in lang:
print("# Ignore patterns for " + l)
print(gh.gitignore_template(l).strip())
@command
def browse(opts):
"""Open the GitHub page for this repo in a browser"""
repo = get_repo()
if repo.fork and opts['--parent']:
repo = repo.parent
webbrowser.open_new(repo.html_url)
@command
def log(opts):
"""Display github log for yourself or other users"""
gh = github()
logtype = 'user'
if not opts['<what>']:
what = gh.user()
else:
if '/' in opts['<what>']:
logtype = 'repo'
user, repo = opts['<what>'].split('/', 1)
what = gh.repository(user, repo)
if not what:
err("Repository %s/%s does not exist" % (user, repo))
else:
what = gh.user(opts['<what>'])
if not what:
err("User %s does not exist" % opts['<what>'])
events = [x for x in what.iter_events(number=30)]
now = datetime.datetime.now()
for event in reversed(events):
ts = event.created_at
if ts.year == now.year:
if (ts.month, ts.day) == (now.month, now.day):
ts = wrap(ts.strftime("%H:%M"), attr.faint)
else:
ts = wrap(ts.strftime("%m/%d %H:%M"), attr.faint)
else:
ts = wrap(ts.strftime("%Y/%m/%d %H:%M"), attr.faint)
repo = '/'.join(event.repo)
repo_ = ' (%s)' % repo
if logtype == 'repo':
repo_ = ''
ts += ' %s' % event.actor.login
if event.type == 'CommitCommentEvent':
print("%s commented on commit %s%s" % (ts, event.payload['comment'].commit_id, repo_))
elif event.type == 'CreateEvent':
print("%s created %s %s%s" % (ts, event.payload['ref_type'], event.payload['ref'], repo_))
elif event.type == 'DeleteEvent':
print("%s deleted %s %s%s" % (ts, event.payload['ref_type'], event.payload['ref'], repo_))
elif event.type == 'FollowEvent':
print("%s started following %s" % (ts, event.payload['target'].login))
elif event.type == 'ForkEvent':
print("%s forked %s to %s/%s" % (ts, repo, event.payload['forkee'].owner.login, event.payload['forkee'].name))
elif event.type == 'ForkApplyEvent':
print("%s applied %s to %s%s" % (ts, event.payload['after'][:7], event.payload['head'], repo_))
elif event.type == 'GistEvent':
print("%s %sd gist #%s" % (ts, event.payload['action'], event.payload['gist'].html_url))
elif event.type == 'GollumEvent':
pages = len(event.payload['pages'])
print("%s updated %d wikipage%s%s" % (ts, pages, {1:''}.get(pages, 's'), repo_))
elif event.type == 'IssueCommentEvent':
print("%s commented on issue #%s%s" % (ts, event.payload['issue'].number, repo_))
elif event.type == 'IssuesEvent':
print("%s %s issue #%s%s" % (ts, event.payload['action'], event.payload['issue'].number, repo_))
elif event.type == 'MemberEvent':
print("%s %s %s to %s" % (ts, event.payload['action'], event.payload['member'].login, repo))
elif event.type == 'PublicEvent':
print("%s made %s open source" % repo)
elif event.type == 'PullRequestEvent':
print("%s %s pull_request #%s%s" % (ts, event.payload['action'], event.payload['pull_request'].number, repo_))
elif event.type == 'PushEvent':
# Old push events have shas and not commits
if 'commits' in event.payload:
commits = len(event.payload['commits'])
else:
commits = len(event.payload['shas'])
print("%s pushed %d commits to %s%s" % (ts, commits, event.payload['ref'][11:], repo_))
elif event.type == 'WatchEvent':
print("%s %s watching %s" % (ts, event.payload['action'], repo))
else:
from pprint import pprint
print(wrap("Cannot display %s. Please file a bug at github.com/seveas/git-hub\nincluding the following output:" % event.type, attr.bright))
pprint(event.payload)
@command
def calendar(opts):
"""Show a timeline of a user's activity"""
gh = github()
user = (opts['<user>'] or [gh.user().login])[0]
months = []
rows = [[],[],[],[],[],[],[]]
commits = []
data = requests.get('https://github.com/users/%s/contributions_calendar_data' % user).json()
y, m, d = [int(x) for x in data[0][0].split('/')]
wd = (datetime.date(y,m,d).weekday()+1) % 7
for i in range(wd):
rows[i].append((None,None))
if wd:
months.append(m)
for (date, count) in data:
count = int(count)
y, m, d = [int(x) for x in date.split('/')]
wd = (datetime.date(y,m,d).weekday()+1) % 7
rows[wd].append((d, count))
if not wd:
months.append(m)
if count:
commits.append(count)
# Print months
sys.stdout.write(" ")
last = -1
skip = months[2] != months[0]
monthtext = ('', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
for month in months:
if month != last:
sys.stdout.write(monthtext[month] + ' ')
skip = True
last = month
elif not skip:
sys.stdout.write(' ')
else:
skip = False
print("")
# Print commits
days = 'SMTWTFS'
commits.sort()
p5 = commits[int(round(len(commits) * 0.95))]
p15 = commits[int(round(len(commits) * 0.85))]
p35 = commits[int(round(len(commits) * 0.65))]
blob1 = b'\xe2\x96\xa0'.decode('utf-8')
blob2 = b'\xe2\x97\xbc'.decode('utf-8')
for rnum, row in enumerate(rows):
if rnum % 2:
sys.stdout.write(days[rnum] + " ")
else:
sys.stdout.write(" ")
for (day, count) in row:
if count is None:
color = attr.conceal
elif count > p5:
color = fgcolor.xterm(22)
elif count > p15:
color = fgcolor.xterm(28)
elif count > p35:
color = fgcolor.xterm(64)
elif count:
color = fgcolor.xterm(65)
else:
color = fgcolor.xterm(237)
if day == 1:
sys.stdout.write(wrap(blob2, attr.underline, color).encode('utf-8'))
else:
sys.stdout.write(wrap(blob1, color).encode('utf-8'))
sys.stdout.write(' ')
print("")
main()