-
Notifications
You must be signed in to change notification settings - Fork 407
/
Copy pathrepo.py
3435 lines (2939 loc) · 116 KB
/
repo.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
"""This module contains Repository objects.
The Repository objects represent various different repository representations
returned by GitHub.
"""
import base64
import json as jsonlib
import uritemplate as urit # type: ignore
from . import branch
from . import comment
from . import commit
from . import comparison
from . import contents
from . import deployment
from . import hook
from . import invitation
from . import issue_import
from . import pages
from . import release
from . import stats
from . import status
from . import tag
from . import topics
from . import traffic
from .. import checks
from .. import decorators
from .. import events
from .. import exceptions
from .. import git
from .. import issues
from .. import licenses
from .. import models
from .. import notifications
from .. import projects
from .. import pulls
from .. import users
from .. import utils
from ..issues import event as ievent
from ..issues import label
from ..issues import milestone
class _Repository(models.GitHubCore):
"""This class serves as the base for all other Repository objects.
Sub-classes should need only to override the ``_update_attributes``
method to ensure that all attributes are present on the object.
"""
PREVIEW_HEADERS = {"Accept": "application/vnd.github.mercy-preview+json"}
STAR_HEADERS = {"Accept": "application/vnd.github.v3.star+json"}
class_name = "_Repository"
def _update_attributes(self, repo):
self.url = self._api = repo["url"]
self.archive_urlt = urit.URITemplate(repo["archive_url"])
self.assignees_urlt = urit.URITemplate(repo["assignees_url"])
self.blobs_urlt = urit.URITemplate(repo["blobs_url"])
self.branches_urlt = urit.URITemplate(repo["branches_url"])
self.collaborators_urlt = urit.URITemplate(repo["collaborators_url"])
self.comments_urlt = urit.URITemplate(repo["comments_url"])
self.commits_urlt = urit.URITemplate(repo["commits_url"])
self.compare_urlt = urit.URITemplate(repo["compare_url"])
self.contents_urlt = urit.URITemplate(repo["contents_url"])
self.contributors_url = repo["contributors_url"]
self.deployments_url = repo["deployments_url"]
self.description = repo["description"]
self.downloads_url = repo["downloads_url"]
self.events_url = repo["events_url"]
self.fork = repo["fork"]
self.forks_url = repo["forks_url"]
self.full_name = repo["full_name"]
self.git_commits_urlt = urit.URITemplate(repo["git_commits_url"])
self.git_refs_urlt = urit.URITemplate(repo["git_refs_url"])
self.git_tags_urlt = urit.URITemplate(repo["git_tags_url"])
self.hooks_url = repo["hooks_url"]
self.html_url = repo["html_url"]
self.id = repo["id"]
self.issue_comment_urlt = urit.URITemplate(repo["issue_comment_url"])
self.issue_events_urlt = urit.URITemplate(repo["issue_events_url"])
self.issues_urlt = urit.URITemplate(repo["issues_url"])
self.keys_urlt = urit.URITemplate(repo["keys_url"])
self.labels_urlt = urit.URITemplate(repo["labels_url"])
self.languages_url = repo["languages_url"]
self.merges_url = repo["merges_url"]
self.milestones_urlt = urit.URITemplate(repo["milestones_url"])
self.name = repo["name"]
self.notifications_urlt = urit.URITemplate(repo["notifications_url"])
self.owner = repo["owner"]
if self.owner:
self.owner = users.ShortUser(self.owner, self)
self.private = repo["private"]
self.pulls_urlt = urit.URITemplate(repo["pulls_url"])
self.releases_urlt = urit.URITemplate(repo["releases_url"])
self.stargazers_url = repo["stargazers_url"]
self.statuses_urlt = urit.URITemplate(repo["statuses_url"])
self.subscribers_url = repo["subscribers_url"]
self.subscription_url = repo["subscription_url"]
self.tags_url = repo["tags_url"]
self.teams_url = repo["teams_url"]
self.trees_urlt = urit.URITemplate(repo["trees_url"])
def _repr(self):
return f"<{self.class_name} [{self}]>"
def __str__(self):
return self.full_name
def _create_pull(self, data):
self._remove_none(data)
json = None
if data:
url = self._build_url("pulls", base_url=self._api)
json = self._json(self._post(url, data=data), 201)
return self._instance_or_null(pulls.ShortPullRequest, json)
@decorators.requires_auth
def add_collaborator(self, username, permission=None):
"""Add ``username`` as a collaborator to a repository.
:param username:
(required), username of the user
:type username:
str or :class:`~github3.users.User`
:param str permission:
(optional), permission to grant the collaborator, valid on
organization repositories only.
Can be 'pull', 'triage', 'push', 'maintain', 'admin' or an
organization-defined custom role name.
:returns:
True if successful, False otherwise
:rtype:
"""
if not username:
return False
url = self._build_url(
"collaborators", str(username), base_url=self._api
)
if permission:
data = {"permission": permission}
resp = self._put(url, data=jsonlib.dumps(data))
else:
resp = self._put(url)
return self._boolean(resp, 201, 404)
def archive(self, format, path="", ref="master"):
"""Get the tarball or zipball archive for this repo at ref.
See: http://developer.github.com/v3/repos/contents/#get-archive-link
:param str format:
(required), accepted values: ('tarball', 'zipball')
:param path:
(optional), path where the file should be saved
to, default is the filename provided in the headers and will be
written in the current directory.
it can take a file-like object as well
:type path:
str, file
:param str ref:
(optional)
:returns:
True if successful, False otherwise
:rtype:
bool
"""
resp = None
if format in ("tarball", "zipball"):
url = self._build_url(format, ref, base_url=self._api)
resp = self._get(url, allow_redirects=True, stream=True)
if resp and self._boolean(resp, 200, 404):
utils.stream_response_to_file(resp, path)
return True
return False
def asset(self, id):
"""Return a single asset.
:param int id:
(required), id of the asset
:returns:
the asset
:rtype:
:class:`~github3.repos.release.Asset`
"""
data = None
if int(id) > 0:
url = self._build_url(
"releases", "assets", str(id), base_url=self._api
)
data = self._json(self._get(url), 200)
return self._instance_or_null(release.Asset, data)
def assignees(self, number=-1, etag=None):
"""Iterate over all assignees to which an issue may be assigned.
:param int number:
(optional), number of assignees to return. Default:
-1 returns all available assignees
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of users
:rtype:
:class:`~github3.users.ShortUser`
"""
url = self._build_url("assignees", base_url=self._api)
return self._iter(int(number), url, users.ShortUser, etag=etag)
def blob(self, sha):
"""Get the blob indicated by ``sha``.
:param str sha:
(required), sha of the blob
:returns:
the git blob
:rtype:
:class:`~github3.git.Blob`
"""
url = self._build_url("git", "blobs", sha, base_url=self._api)
json = self._json(self._get(url), 200)
return self._instance_or_null(git.Blob, json)
def branch(self, name):
"""Get the branch ``name`` of this repository.
:param str name:
(required), branch name
:returns:
the branch
:rtype:
:class:`~github3.repos.branch.Branch`
"""
json = None
if name:
url = self._build_url("branches", name, base_url=self._api)
json = self._json(
self._get(url, headers=branch.Branch.PREVIEW_HEADERS), 200
)
return self._instance_or_null(branch.Branch, json)
def branches(self, number=-1, protected=False, etag=None):
"""Iterate over the branches in this repository.
:param int number:
(optional), number of branches to return. Default: -1 returns all
branches
:param bool protected:
(optional), True lists only protected branches.
Default: False
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of branches
:rtype:
:class:`~github3.repos.branch.Branch`
"""
url = self._build_url("branches", base_url=self._api)
params = {"protected": "1"} if protected else None
return self._iter(
int(number),
url,
branch.ShortBranch,
params,
etag=etag,
headers=branch.Branch.PREVIEW_HEADERS,
)
def check_run(self, id):
"""Return a single check run.
.. versionadded:: 1.3.0
:param int id:
(required), id of the check run
:returns:
the check run
:rtype:
:class:`~github3.checks.CheckRun`
"""
data = None
if int(id) > 0:
url = self._build_url("check-runs", str(id), base_url=self._api)
data = self._json(
self._get(url, headers=checks.CheckRun.CUSTOM_HEADERS), 200
)
return self._instance_or_null(checks.CheckRun, data)
def check_suite(self, id):
"""Return a single check suite.
.. versionadded:: 1.3.0
:param int id:
(required), id of the check suite
:returns:
the check suite
:rtype:
:class:`~github3.checks.CheckSuite`
"""
data = None
if int(id) > 0:
url = self._build_url("check-suites", str(id), base_url=self._api)
data = self._json(
self._get(url, headers=checks.CheckSuite.CUSTOM_HEADERS), 200
)
return self._instance_or_null(checks.CheckSuite, data)
def code_frequency(self, number=-1, etag=None):
"""Iterate over the code frequency per week.
.. versionadded:: 0.7
Returns a weekly aggregate of the number of additions and deletions
pushed to this repository.
.. note::
All statistics methods may return a 202. On those occasions,
you will not receive any objects. You should store your
iterator and check the new ``last_status`` attribute. If it
is a 202 you should wait before re-requesting.
:param int number:
(optional), number of weeks to return. Default: -1
returns all weeks
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of lists ``[seconds_from_epoch, additions, deletions]``
:rtype:
list
"""
url = self._build_url("stats", "code_frequency", base_url=self._api)
return self._iter(int(number), url, list, etag=etag)
def collaborators(self, affiliation="all", number=-1, etag=None):
"""Iterate over the collaborators of this repository.
:param str affiliation:
(optional), affiliation of the collaborator to the repository.
Default: "all" returns contributors with all affiliations
:param int number:
(optional), number of collaborators to return.
Default: -1 returns all comments
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of collaborators
:rtype:
:class:`~github3.users.Collaborator`
"""
url = self._build_url("collaborators", base_url=self._api)
affiliations = {"outside", "direct", "all"}
if affiliation not in affiliations:
raise ValueError(
(
"Invalid affiliation value {!r} parameter passed, must "
"be 'outside', 'direct', or 'all' (defaults to 'all')."
).format(affiliation)
)
params = {"affiliation": affiliation}
return self._iter(
int(number), url, users.Collaborator, params, etag=etag
)
def comments(self, number=-1, etag=None):
"""Iterate over comments on all commits in the repository.
:param int number:
(optional), number of comments to return. Default:
-1 returns all comments
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of comments on commits
:rtype:
:class:`~github3.repos.comment.RepoComment`
"""
url = self._build_url("comments", base_url=self._api)
return self._iter(int(number), url, comment.RepoComment, etag=etag)
def commit(self, sha):
"""Get a single (repo) commit.
See :meth:`git_commit` for the Git Data Commit.
:param str sha:
(required), sha of the commit
:returns:
the commit
:rtype:
:class:`~github3.repos.commit.RepoCommit`
"""
url = self._build_url("commits", sha, base_url=self._api)
json = self._json(self._get(url), 200)
return self._instance_or_null(commit.RepoCommit, json)
def commit_activity(self, number=-1, etag=None):
"""Iterate over last year of commit activity by week.
.. versionadded:: 0.7
See: http://developer.github.com/v3/repos/statistics/
.. note::
All statistics methods may return a 202. On those occasions,
you will not receive any objects. You should store your
iterator and check the new ``last_status`` attribute. If it
is a 202 you should wait before re-requesting.
:param int number:
(optional), number of weeks to return. Default -1
will return all of the weeks.
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of dictionaries
:rtype:
dict
"""
url = self._build_url("stats", "commit_activity", base_url=self._api)
return self._iter(int(number), url, dict, etag=etag)
def commit_comment(self, comment_id):
"""Get a single commit comment.
:param int comment_id:
(required), id of the comment used by GitHub
:returns:
the comment on the commit
:rtype:
:class:`~github3.repos.comment.RepoComment`
"""
url = self._build_url("comments", str(comment_id), base_url=self._api)
json = self._json(self._get(url), 200)
return self._instance_or_null(comment.RepoComment, json)
def commits(
self,
sha=None,
path=None,
author=None,
number=-1,
etag=None,
since=None,
until=None,
per_page=None,
):
"""Iterate over commits in this repository.
:param str sha:
(optional), sha or branch to start listing commits from
:param str path:
(optional), commits containing this path will be listed
:param str author:
(optional), GitHub login, real name, or email to
filter commits by (using commit author)
:param int number:
(optional), number of commits to return. Default:
-1 returns all commits
:param str etag:
(optional), ETag from a previous request to the same endpoint
:param since:
(optional), Only commits after this date will be returned.
This can be a ``datetime`` or an ``ISO8601`` formatted
date string.
:type since:
:class:`~datetime.datetime` or str
:param until:
(optional), Only commits before this date will
be returned. This can be a ``datetime`` or an ``ISO8601`` formatted
date string.
:type until:
:class:`~datetime.datetime` or str
:param int per_page:
(optional), commits listing page size
:returns:
generator of commits
:rtype:
:class:`~github3.repos.commit.RepoCommit`
"""
params = {
"sha": sha,
"path": path,
"author": author,
"since": utils.timestamp_parameter(since),
"until": utils.timestamp_parameter(until),
"per_page": per_page,
}
self._remove_none(params)
url = self._build_url("commits", base_url=self._api)
return self._iter(int(number), url, commit.ShortCommit, params, etag)
def compare_commits(self, base, head):
"""Compare two commits.
:param str base:
(required), base for the comparison
:param str head:
(required), compare this against base
:returns:
the comparison of the commits
:rtype:
:class:`~github3.repos.comparison.Comparison`
"""
url = self._build_url(
"compare", base + "..." + head, base_url=self._api
)
json = self._json(self._get(url), 200)
return self._instance_or_null(comparison.Comparison, json)
def contributor_statistics(self, number=-1, etag=None):
"""Iterate over the contributors list.
.. versionadded:: 0.7
See also: http://developer.github.com/v3/repos/statistics/
.. note::
All statistics methods may return a 202. On those occasions,
you will not receive any objects. You should store your
iterator and check the new ``last_status`` attribute. If it
is a 202 you should wait before re-requesting.
:param int number:
(optional), number of weeks to return. Default -1
will return all of the weeks.
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of contributor statistics for each contributor
:rtype:
:class:`~github3.repos.stats.ContributorStats`
"""
url = self._build_url("stats", "contributors", base_url=self._api)
return self._iter(int(number), url, stats.ContributorStats, etag=etag)
def contributors(self, anon=False, number=-1, etag=None):
"""Iterate over the contributors to this repository.
:param bool anon:
(optional), True lists anonymous contributors as well
:param int number:
(optional), number of contributors to return.
Default: -1 returns all contributors
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
generator of contributor users
:rtype:
:class:`~github3.users.Contributor`
"""
url = self._build_url("contributors", base_url=self._api)
params = {}
if anon:
params = {"anon": "true"}
return self._iter(int(number), url, users.Contributor, params, etag)
def views(self, per="day"):
"""Get the total number of repository views and breakdown per day or
week for the last 14 days.
.. versionadded:: 1.4.0
See also: https://developer.github.com/v3/repos/traffic/
:param str per:
(optional), ('day', 'week'), views reporting period. Default 'day'
will return views per day for the last 14 days.
:returns:
views data
:rtype:
:class:`~github3.repos.traffic.ViewsStats`
:raises:
ValueError if per is not a valid choice
"""
params = {}
if per in ("day", "week"):
params.update(per=per)
else:
raise ValueError("per must be 'day' or 'week'")
url = self._build_url("traffic", "views", base_url=self._api)
json = self._json(self._get(url, params=params), 200)
return self._instance_or_null(traffic.ViewsStats, json)
def clones(self, per="day"):
"""Get the total number of repository clones and breakdown per day or
week for the last 14 days.
.. versionadded:: 1.4.0
See also: https://developer.github.com/v3/repos/traffic/
:param str per:
(optional), ('day', 'week'), clones reporting period. Default 'day'
will return clones per day for the last 14 days.
:returns:
clones data
:rtype:
:class:`~github3.repos.traffic.ClonesStats`
:raises:
ValueError if per is not a valid choice
"""
params = {}
if per in ("day", "week"):
params.update(per=per)
else:
raise ValueError("per must be 'day' or 'week'")
url = self._build_url("traffic", "clones", base_url=self._api)
json = self._json(self._get(url, params=params), 200)
return self._instance_or_null(traffic.ClonesStats, json)
@decorators.requires_app_installation_auth
def create_check_run(
self,
name,
head_sha,
details_url=None,
external_id=None,
started_at=None,
status=None,
conclusion=None,
completed_at=None,
output=None,
actions=None,
):
"""Create a check run object on a commit
.. versionadded:: 1.3.0
:param str name:
(required), The name of the check
:param str head_sha:
(required), The SHA of the commit
:param str details_url:
(optional), The URL of the integrator's site that has the full
details of the check
:param str external_id:
(optional), A reference for the run on the integrator's system
:param str started_at:
(optional), ISO 8601 time format: YYYY-MM-DDTHH:MM:SSZ
:param str status:
(optional), ('queued', 'in_progress', 'completed')
:param str conclusion:
(optional), Required if you provide 'completed_at', or a
'status' of 'completed'. The final conclusion of the check.
('success', 'failure', 'neutral', 'cancelled', 'timed_out',
'action_required')
:param str completed_at:
(optional), Required if you provide 'conclusion'. ISO 8601 time
format: YYYY-MM-DDTHH:MM:SSZ
:param dict output:
(optional), key-value pairs representing the output. Format:
``{'title': 'string', 'summary': 'text, can be markdown', 'text':
'text, can be markdown', 'annotations': [{}], 'images': [{}]}``
:param list actions:
(optional), list of action objects. Format is:
``[{'label': 'text', 'description', 'text', 'identifier', 'text'},
...]``
:returns:
the created check run
:rtype:
:class:`~github3.checks.CheckRun`
"""
json = None
# TODO: Cleanse output dict, actions array
if name and head_sha:
data = {
"name": name,
"head_sha": head_sha,
"details_url": details_url,
"external_id": external_id,
"started_at": started_at,
"status": status,
"conclusion": conclusion,
"completed_at": completed_at,
"output": output,
"actions": actions,
}
self._remove_none(data)
url = self._build_url("check-runs", base_url=self._api)
json = self._json(
self._post(
url, headers=checks.CheckRun.CUSTOM_HEADERS, data=data
),
201,
)
return self._instance_or_null(checks.CheckRun, json)
@decorators.requires_app_installation_auth
def create_check_suite(self, head_sha):
"""Create a check suite object on a commit
.. versionadded:: 1.3.0
:param str head_sha:
The sha of the head commit.
:returns:
the created check suite
:rtype:
:class:`~github3.checks.CheckSuite`
"""
json = None
if head_sha:
data = {"head_sha": head_sha}
self._remove_none(data)
url = self._build_url("check-suites", base_url=self._api)
json = self._json(
self._post(
url, data=data, headers=checks.CheckSuite.CUSTOM_HEADERS
),
201,
)
return self._instance_or_null(checks.CheckSuite, json)
@decorators.requires_auth
def create_blob(self, content, encoding):
"""Create a blob with ``content``.
:param str content:
(required), content of the blob
:param str encoding:
(required), ('base64', 'utf-8')
:returns:
string of the SHA returned
:returns:
str
"""
sha = ""
if encoding in ("base64", "utf-8"):
url = self._build_url("git", "blobs", base_url=self._api)
data = {"content": content, "encoding": encoding}
json = self._json(self._post(url, data=data), 201)
if json:
sha = json.get("sha")
return sha
@decorators.requires_auth
def create_branch_ref(self, name, sha=None):
"""Create a branch git reference.
This is a shortcut for calling
:meth:`github3.repos.repo.Repository.create_ref`.
:param str branch:
(required), the branch to create
:param str sha:
the commit to base the branch from
:returns:
a reference object representing the branch
:rtype:
:class:`~github3.git.Reference`
"""
ref = "refs/heads/%s" % name
return self.create_ref(ref, sha)
@decorators.requires_auth
def create_comment(self, body, sha, path=None, position=None, line=1):
"""Create a comment on a commit.
:param str body:
(required), body of the message
:param str sha:
(required), commit id
:param str path:
(optional), relative path of the file to comment on
:param str position:
(optional), line index in the diff to comment on
:param int line:
(optional), line number of the file to comment on, default: 1
:returns:
the created comment
:rtype:
:class:`~github3.repos.comment.RepoComment`
"""
json = None
if body and sha and (line and int(line) > 0):
data = {
"body": body,
"line": line,
"path": path,
"position": position,
}
self._remove_none(data)
url = self._build_url(
"commits", sha, "comments", base_url=self._api
)
json = self._json(self._post(url, data=data), 201)
return self._instance_or_null(comment.RepoComment, json)
@decorators.requires_auth
def create_commit(
self, message, tree, parents, author=None, committer=None
):
"""Create a commit on this repository.
:param str message:
(required), commit message
:param str tree:
(required), SHA of the tree object this commit points to
:param list parents:
(required), SHAs of the commits that were parents
of this commit. If empty, the commit will be written as the root
commit. Even if there is only one parent, this should be an
array.
:param dict author:
(optional), if omitted, GitHub will
use the authenticated user's credentials and the current
time. Format: {'name': 'Committer Name', 'email':
'[email protected]', 'date': 'YYYY-MM-DDTHH:MM:SS+HH:00'}
:param dict committer:
(optional), if ommitted, GitHub will use the
author parameters. Should be the same format as the author
parameter.
:returns:
the created commit
:rtype:
:class:`~github3.git.Commit`
"""
json = None
if message and tree and isinstance(parents, list):
url = self._build_url("git", "commits", base_url=self._api)
data = {
"message": message,
"tree": tree,
"parents": parents,
"author": author,
"committer": committer,
}
self._remove_none(data)
json = self._json(self._post(url, data=data), 201)
return self._instance_or_null(git.Commit, json)
@decorators.requires_auth
def create_deployment(
self,
ref,
required_contexts=None,
payload="",
auto_merge=False,
description="",
environment=None,
):
"""Create a deployment.
:param str ref:
(required), The ref to deploy. This can be a branch, tag, or sha.
:param list required_contexts:
Optional array of status contexts
verified against commit status checks. To bypass checking
entirely pass an empty array. Default: []
:param str payload:
Optional JSON payload with extra information about
the deployment. Default: ""
:param bool auto_merge:
Optional parameter to merge the default branch
into the requested deployment branch if necessary. Default: False
:param str description:
Optional short description. Default: ""
:param str environment:
Optional name for the target deployment
environment (e.g., production, staging, qa). Default: "production"
:returns:
the created deployment
:rtype:
:class:`~github3.repos.deployment.Deployment`
"""
json = None
if ref:
if required_contexts is None:
required_contexts = []
url = self._build_url("deployments", base_url=self._api)
data = {
"ref": ref,
"required_contexts": required_contexts,
"payload": payload,
"auto_merge": auto_merge,
"description": description,
"environment": environment,
}
self._remove_none(data)
json = self._json(self._post(url, data=data), 201)
return self._instance_or_null(deployment.Deployment, json)
@decorators.requires_auth
def create_file(
self, path, message, content, branch=None, committer=None, author=None
):
"""Create a file in this repository.
See also: http://developer.github.com/v3/repos/contents/#create-a-file
:param str path:
(required), path of the file in the repository
:param str message:
(required), commit message
:param bytes content:
(required), the actual data in the file
:param str branch:
(optional), branch to create the commit on.
Defaults to the default branch of the repository
:param dict committer:
(optional), if no information is given the
authenticated user's information will be used. You must specify
both a name and email.
:param dict author:
(optional), if omitted this will be filled in with
committer information. If passed, you must specify both a name and
email.
:returns:
dictionary of contents and commit for created file
:rtype:
:class:`~github3.repos.contents.Contents`,
:class:`~github3.git.Commit`
"""
if content and not isinstance(content, bytes):
raise ValueError( # (No coverage)
"content must be a bytes object"
) # (No coverage)
json = None
if path and message and content:
url = self._build_url("contents", path, base_url=self._api)
content = base64.b64encode(content).decode("utf-8")
data = {
"message": message,
"content": content,
"branch": branch,
"committer": contents.validate_commmitter(committer),
"author": contents.validate_commmitter(author),
}
self._remove_none(data)
json = self._json(self._put(url, data=jsonlib.dumps(data)), 201)
if json and "content" in json and "commit" in json:
json["content"] = contents.Contents(json["content"], self)
json["commit"] = git.Commit(json["commit"], self)
return json
@decorators.requires_auth
def create_fork(self, organization=None):
"""Create a fork of this repository.
:param str organization:
(required), login for organization to create the fork under
:returns:
the fork of this repository
:rtype:
:class:`~github3.repos.repo.Repository`
"""
url = self._build_url("forks", base_url=self._api)
if organization:
resp = self._post(url, data={"organization": organization})
else:
resp = self._post(url)
json = self._json(resp, 202)
return self._instance_or_null(Repository, json)
@decorators.requires_auth
def create_hook(self, name, config, events=["push"], active=True):
"""Create a hook on this repository.
:param str name:
(required), name of the hook
:param dict config:
(required), key-value pairs which act as settings for this hook
:param list events:
(optional), events the hook is triggered for
:param bool active:
(optional), whether the hook is actually triggered
:returns:
the created hook
:rtype:
:class:`~github3.repos.hook.Hook`
"""
json = None
if name and config and isinstance(config, dict):
url = self._build_url("hooks", base_url=self._api)
data = {
"name": name,
"config": config,
"events": events,
"active": active,
}
json = self._json(self._post(url, data=data), 201)
return hook.Hook(json, self) if json else None
@decorators.requires_auth
def create_issue(
self,