-
Notifications
You must be signed in to change notification settings - Fork 775
Expand file tree
/
Copy pathGitHub.java
More file actions
1343 lines (1240 loc) · 45.9 KB
/
GitHub.java
File metadata and controls
1343 lines (1240 loc) · 45.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
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
/*
* The MIT License
*
* Copyright (c) 2010, Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.kohsuke.github;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.kohsuke.github.authorization.AuthorizationProvider;
import org.kohsuke.github.authorization.ImmutableAuthorizationProvider;
import org.kohsuke.github.authorization.UserAuthorizationProvider;
import org.kohsuke.github.connector.GitHubConnector;
import org.kohsuke.github.internal.GitHubJackson;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
// TODO: Auto-generated Javadoc
/**
* Root of the GitHub API.
*
* <h2>Thread safety</h2>
* <p>
* This library aims to be safe for use by multiple threads concurrently, although the library itself makes no attempt
* to control/serialize potentially conflicting operations to GitHub, such as updating & deleting a repository at
* the same time.
*
* @author Kohsuke Kawaguchi
*/
public class GitHub {
/**
* The Class DependentAuthorizationProvider.
*/
public static abstract class DependentAuthorizationProvider implements AuthorizationProvider {
private final AuthorizationProvider authorizationProvider;
private GitHub baseGitHub;
private GitHub gitHub;
/**
* An AuthorizationProvider that requires an authenticated GitHub instance to provide its authorization.
*
* @param authorizationProvider
* A authorization provider to be used when refreshing this authorization provider.
*/
@BetaApi
protected DependentAuthorizationProvider(AuthorizationProvider authorizationProvider) {
this.authorizationProvider = authorizationProvider;
}
/**
* Git hub.
*
* @return the git hub
*/
protected synchronized final GitHub gitHub() {
if (gitHub == null) {
gitHub = new GitHub.AuthorizationRefreshGitHubWrapper(this.baseGitHub, authorizationProvider);
}
return gitHub;
}
/**
* Binds this authorization provider to a github instance.
*
* Only needs to be implemented by dynamic credentials providers that use a github instance in order to refresh.
*
* @param github
* The github instance to be used for refreshing dynamic credentials
*/
synchronized void bind(GitHub github) {
if (baseGitHub != null) {
throw new IllegalStateException("Already bound to another GitHub instance.");
}
this.baseGitHub = github;
}
}
private static class AuthorizationRefreshGitHubWrapper extends GitHub {
private final AuthorizationProvider authorizationProvider;
AuthorizationRefreshGitHubWrapper(GitHub github, AuthorizationProvider authorizationProvider) {
super(github.client);
this.authorizationProvider = authorizationProvider;
// no dependent authorization providers nest like this currently, but they might in future
if (authorizationProvider instanceof DependentAuthorizationProvider) {
((DependentAuthorizationProvider) authorizationProvider).bind(this);
}
}
@Nonnull
@Override
Requester createRequest() {
try {
// Override
return super.createRequest().setHeader("Authorization", authorizationProvider.getEncodedAuthorization())
.rateLimit(RateLimitTarget.NONE);
} catch (IOException e) {
throw new GHException("Failed to create requester to refresh credentials", e);
}
}
}
private static class LoginLoadingUserAuthorizationProvider implements UserAuthorizationProvider {
private final AuthorizationProvider authorizationProvider;
private final GitHub gitHub;
private String login;
private boolean loginLoaded = false;
LoginLoadingUserAuthorizationProvider(AuthorizationProvider authorizationProvider, GitHub gitHub) {
this.gitHub = gitHub;
this.authorizationProvider = authorizationProvider;
}
@Override
public String getEncodedAuthorization() throws IOException {
return authorizationProvider.getEncodedAuthorization();
}
@Override
public String getLogin() {
synchronized (this) {
if (!loginLoaded) {
loginLoaded = true;
try {
GHMyself u = gitHub.setMyself();
if (u != null) {
login = u.getLogin();
}
} catch (IOException e) {
}
}
return login;
}
}
}
private static final Logger LOGGER = Logger.getLogger(GitHub.class.getName());
/**
* Obtains the credential from "~/.github" or from the System Environment Properties.
*
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connect() throws IOException {
return GitHubBuilder.fromCredentials().build();
}
/**
* Connect git hub.
*
* @param login
* the login
* @param oauthAccessToken
* the oauth access token
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connect(String login, String oauthAccessToken) throws IOException {
return new GitHubBuilder().withOAuthToken(oauthAccessToken, login).build();
}
/**
* Connects to GitHub anonymously.
* <p>
* All operations that require authentication will fail.
*
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connectAnonymously() throws IOException {
return new GitHubBuilder().build();
}
/**
* Connects to GitHub Enterprise anonymously.
* <p>
* All operations that require authentication will fail.
*
* @param apiUrl
* the api url
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connectToEnterpriseAnonymously(String apiUrl) throws IOException {
return new GitHubBuilder().withEndpoint(apiUrl).build();
}
/**
* Version that connects to GitHub Enterprise.
*
* @param apiUrl
* The URL of GitHub (or GitHub Enterprise) API endpoint, such as "https://api.github.com" or
* "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has <code>/api/v3</code> in the URL. For
* historical reasons, this parameter still accepts the bare domain name, but that's considered
* deprecated.
* @param login
* the login
* @param oauthAccessToken
* the oauth access token
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connectToEnterpriseWithOAuth(String apiUrl, String login, String oauthAccessToken)
throws IOException {
return new GitHubBuilder().withEndpoint(apiUrl).withOAuthToken(oauthAccessToken, login).build();
}
/**
* Connect using o auth git hub.
*
* @param oauthAccessToken
* the oauth access token
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connectUsingOAuth(String oauthAccessToken) throws IOException {
return new GitHubBuilder().withOAuthToken(oauthAccessToken).build();
}
/**
* Connect using o auth git hub.
*
* @param githubServer
* the github server
* @param oauthAccessToken
* the oauth access token
* @return the git hub
* @throws IOException
* the io exception
*/
public static GitHub connectUsingOAuth(String githubServer, String oauthAccessToken) throws IOException {
return new GitHubBuilder().withEndpoint(githubServer).withOAuthToken(oauthAccessToken).build();
}
/**
* Gets an {@link ObjectReader} that can be used to convert JSON into library data objects.
*
* If you must manually create library data objects from JSON, the {@link ObjectReader} returned by this method is
* the only supported way of doing so.
*
* WARNING: Objects generated from this method have limited functionality. They will not throw when being crated
* from valid JSON matching the expected object, but they are not guaranteed to be usable beyond that. Use with
* extreme caution.
*
* @return an {@link ObjectReader} instance that can be further configured.
*/
@Nonnull
public static ObjectReader getMappingObjectReader() {
return GitHubClient.getMappingObjectReader(GitHub.offline());
}
/**
* Gets an {@link ObjectWriter} that can be used to convert data objects in this library to JSON.
*
* If you must convert data object in this library to JSON, the {@link ObjectWriter} returned by this method is the
* only supported way of doing so. This {@link ObjectWriter} can be used to convert any library data object to JSON
* without throwing an exception.
*
* WARNING: While the JSON generated is generally expected to be stable, it is not part of the API of this library
* and may change without warning. Use with extreme caution.
*
* @return an {@link ObjectWriter} instance that can be further configured.
*/
@Nonnull
public static ObjectWriter getMappingObjectWriter() {
return GitHubClient.getMappingObjectWriter();
}
/**
* An offline-only {@link GitHub} useful for parsing event notification from an unknown source.
* <p>
* All operations that require a connection will fail.
*
* @return An offline-only {@link GitHub}.
*/
public static GitHub offline() {
try {
return new GitHubBuilder().withEndpoint("https://api.github.invalid")
.withConnector(GitHubConnector.OFFLINE)
.build();
} catch (IOException e) {
throw new IllegalStateException("The offline implementation constructor should not connect", e);
}
}
@Nonnull
private final GitHubClient client;
@CheckForNull
private GHMyself myself;
private final ConcurrentMap<String, GHOrganization> orgs;
@Nonnull
private final GitHubSanityCachedValue<GHMeta> sanityCachedMeta = new GitHubSanityCachedValue<>();
private final ConcurrentMap<String, GHUser> users;
private GitHub(GitHubClient client) {
users = new ConcurrentHashMap<>();
orgs = new ConcurrentHashMap<>();
this.client = client;
}
/**
* Creates a client API root object.
*
* <p>
* Several different combinations of the login/oauthAccessToken/password parameters are allowed to represent
* different ways of authentication.
*
* <dl>
* <dt>Log in anonymously
* <dd>Leave all three parameters null and you will be making HTTP requests without any authentication.
*
* <dt>Log in with password
* <dd>Specify the login and password, then leave oauthAccessToken null. This will use the HTTP BASIC auth with the
* GitHub API.
*
* <dt>Log in with OAuth token
* <dd>Specify oauthAccessToken, and optionally specify the login. Leave password null. This will send OAuth token
* to the GitHub API. If the login parameter is null, The constructor makes an API call to figure out the user name
* that owns the token.
*
* <dt>Log in with JWT token
* <dd>Specify jwtToken. Leave password null. This will send JWT token to the GitHub API via the Authorization HTTP
* header. Please note that only operations in which permissions have been previously configured and accepted during
* the GitHub App will be executed successfully.
* </dl>
*
* @param apiUrl
* The URL of GitHub (or GitHub enterprise) API endpoint, such as "https://api.github.com" or
* "http://ghe.acme.com/api/v3". Note that GitHub Enterprise has <code>/api/v3</code> in the URL. For
* historical reasons, this parameter still accepts the bare domain name, but that's considered
* deprecated.
* @param connector
* a connector
* @param rateLimitHandler
* rateLimitHandler
* @param abuseLimitHandler
* abuseLimitHandler
* @param rateLimitChecker
* rateLimitChecker
* @param authorizationProvider
* a authorization provider
* @param jackson
* the Jackson implementation to use for JSON serialization
* @throws IOException
* Signals that an I/O exception has occurred.
*/
@SuppressFBWarnings(value = { "CT_CONSTRUCTOR_THROW" }, justification = "internal constructor")
GitHub(String apiUrl,
GitHubConnector connector,
GitHubRateLimitHandler rateLimitHandler,
GitHubAbuseLimitHandler abuseLimitHandler,
GitHubRateLimitChecker rateLimitChecker,
AuthorizationProvider authorizationProvider,
GitHubJackson jackson) throws IOException {
if (authorizationProvider instanceof DependentAuthorizationProvider) {
((DependentAuthorizationProvider) authorizationProvider).bind(this);
} else if (authorizationProvider instanceof ImmutableAuthorizationProvider
&& authorizationProvider instanceof UserAuthorizationProvider) {
UserAuthorizationProvider provider = (UserAuthorizationProvider) authorizationProvider;
if (provider.getLogin() == null && provider.getEncodedAuthorization() != null
&& provider.getEncodedAuthorization().startsWith("token")) {
authorizationProvider = new LoginLoadingUserAuthorizationProvider(provider, this);
}
}
users = new ConcurrentHashMap<>();
orgs = new ConcurrentHashMap<>();
this.client = new GitHubClient(apiUrl,
connector,
rateLimitHandler,
abuseLimitHandler,
rateLimitChecker,
authorizationProvider,
jackson);
// Ensure we have the login if it is available
// This preserves previously existing behavior. Consider removing in future.
if (authorizationProvider instanceof LoginLoadingUserAuthorizationProvider) {
((LoginLoadingUserAuthorizationProvider) authorizationProvider).getLogin();
}
}
/**
* Tests the connection.
*
* <p>
* Verify that the API URL and credentials are valid to access this GitHub.
*
* <p>
* This method returns normally if the endpoint is reachable and verified to be GitHub API URL. Otherwise this
* method throws {@link IOException} to indicate the problem.
*
* @throws IOException
* the io exception
*/
public void checkApiUrlValidity() throws IOException {
client.checkApiUrlValidity();
}
/**
* Check auth gh authorization.
*
* @param clientId
* the client id
* @param accessToken
* the access token
* @return the gh authorization
* @throws IOException
* the io exception
* @see <a href="https://developer.github.com/v3/oauth_authorizations/#check-an-authorization">Check an
* authorization</a>
*/
public GHAuthorization checkAuth(@Nonnull String clientId, @Nonnull String accessToken) throws IOException {
return createRequest().withUrlPath("/applications/" + clientId + "/tokens/" + accessToken)
.fetch(GHAuthorization.class);
}
/**
* Creates a GitHub App from a manifest.
*
* @param code
* temporary code returned during the manifest flow
* @return the app
* @throws IOException
* the IO exception
* @see <a href=
* "https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#create-a-github-app-from-a-manifest">Get an
* app</a>
*/
public GHAppFromManifest createAppFromManifest(@Nonnull String code) throws IOException {
return createRequest().method("POST")
.withUrlPath("/app-manifests/" + code + "/conversions")
.fetch(GHAppFromManifest.class);
}
/**
* Create gist gh gist builder.
*
* @return the gh gist builder
*/
public GHGistBuilder createGist() {
return new GHGistBuilder(this);
}
/**
* Create or get auth gh authorization.
*
* @param clientId
* the client id
* @param clientSecret
* the client secret
* @param scopes
* the scopes
* @param note
* the note
* @param noteUrl
* the note url
* @return the gh authorization
* @throws IOException
* the io exception
* @see <a href=
* "https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app">docs</a>
*/
public GHAuthorization createOrGetAuth(String clientId,
String clientSecret,
List<String> scopes,
String note,
String noteUrl) throws IOException {
Requester requester = createRequest().with("client_secret", clientSecret)
.with("scopes", scopes)
.with("note", note)
.with("note_url", noteUrl);
return requester.method("PUT").withUrlPath("/authorizations/clients/" + clientId).fetch(GHAuthorization.class);
}
/**
* Starts a builder that creates a new repository.
*
* <p>
* You use the returned builder to set various properties, then call {@link GHCreateRepositoryBuilder#create()} to
* finally create a repository.
*
* @param name
* the name
* @return the gh create repository builder
*/
public GHCreateRepositoryBuilder createRepository(String name) {
return new GHCreateRepositoryBuilder(name, this, "/user/repos");
}
/**
* Creates a new authorization.
* <p>
* The token created can be then used for {@link GitHub#connectUsingOAuth(String)} in the future.
*
* @param scope
* the scope
* @param note
* the note
* @param noteUrl
* the note url
* @return the gh authorization
* @throws IOException
* the io exception
* @see <a href="http://developer.github.com/v3/oauth/#create-a-new-authorization">Documentation</a>
*/
public GHAuthorization createToken(Collection<String> scope, String note, String noteUrl) throws IOException {
Requester requester = createRequest().with("scopes", scope).with("note", note).with("note_url", noteUrl);
return requester.method("POST").withUrlPath("/authorizations").fetch(GHAuthorization.class);
}
/**
* Creates a new authorization using an OTP.
* <p>
* Start by running createToken, if exception is thrown, prompt for OTP from user
* <p>
* Once OTP is received, call this token request
* <p>
* The token created can be then used for {@link GitHub#connectUsingOAuth(String)} in the future.
*
* @param scope
* the scope
* @param note
* the note
* @param noteUrl
* the note url
* @param OTP
* the otp
* @return the gh authorization
* @throws IOException
* the io exception
* @see <a href="http://developer.github.com/v3/oauth/#create-a-new-authorization">Documentation</a>
*/
public GHAuthorization createToken(Collection<String> scope, String note, String noteUrl, Supplier<String> OTP)
throws IOException {
try {
return createToken(scope, note, noteUrl);
} catch (GHOTPRequiredException ex) {
String OTPstring = OTP.get();
Requester requester = createRequest().with("scopes", scope).with("note", note).with("note_url", noteUrl);
// Add the OTP from the user
requester.setHeader("x-github-otp", OTPstring);
return requester.method("POST").withUrlPath("/authorizations").fetch(GHAuthorization.class);
}
}
/**
* Delete auth.
*
* @param id
* the id
* @throws IOException
* the io exception
* @see <a href="https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization">Delete an
* authorization</a>
*/
public void deleteAuth(long id) throws IOException {
createRequest().method("DELETE").withUrlPath("/authorizations/" + id).send();
}
/**
* Gets api url.
*
* @return the api url
*/
public String getApiUrl() {
return client.getApiUrl();
}
/**
* Returns the GitHub App associated with the authentication credentials used.
* <p>
* You must use a JWT to access this endpoint.
*
* @return the app
* @throws IOException
* the io exception
* @see <a href="https://developer.github.com/v3/apps/#get-the-authenticated-github-app">Get the authenticated
* GitHub App</a>
*/
public GHApp getApp() throws IOException {
return createRequest().withUrlPath("/app").fetch(GHApp.class);
}
/**
* Returns the GitHub App identified by the given slug
*
* @param slug
* the slug of the application
* @return the app
* @throws IOException
* the IO exception
* @see <a href="https://docs.github.com/en/rest/apps/apps?apiVersion=2022-11-28#get-an-app">Get an app</a>
*/
public GHApp getApp(@Nonnull String slug) throws IOException {
return createRequest().withUrlPath("/apps/" + slug).fetch(GHApp.class);
}
/**
* Public events visible to you. Equivalent of what's displayed on https://github.com/
*
* @return the events
* @throws IOException
* the io exception
*/
public List<GHEventInfo> getEvents() throws IOException {
return createRequest().withUrlPath("/events").toIterable(GHEventInfo[].class, null).toList();
}
/**
* Gets a single gist by ID.
*
* @param id
* the id
* @return the gist
* @throws IOException
* the io exception
*/
public GHGist getGist(String id) throws IOException {
return createRequest().withUrlPath("/gists/" + id).fetch(GHGist.class);
}
/**
* Returns the GitHub App Installation associated with the authentication credentials used.
* <p>
* You must use an installation token to access this endpoint; otherwise consider {@link #getApp()} and its various
* ways of retrieving installations.
*
* @return the app
* @see <a href="https://docs.github.com/en/rest/apps/installations">GitHub App installations</a>
*/
public GHAuthenticatedAppInstallation getInstallation() {
return new GHAuthenticatedAppInstallation(this);
}
/**
* Returns the full details for a license.
*
* @param key
* The license key provided from the API
* @return The license details
* @throws IOException
* the io exception
* @see GHLicense#getKey() GHLicense#getKey()
*/
public GHLicense getLicense(String key) throws IOException {
return createRequest().withUrlPath("/licenses/" + key).fetch(GHLicense.class);
}
/**
* Provides a list of GitHub's IP addresses.
*
* @return an instance of {@link GHMeta}
* @throws IOException
* if the credentials supplied are invalid or if you're trying to access it as a GitHub App via the JWT
* authentication
* @see <a href="https://developer.github.com/v3/meta/#meta">Get Meta</a>
*/
public GHMeta getMeta() throws IOException {
return this.sanityCachedMeta.get(() -> createRequest().withUrlPath("/meta").fetch(GHMeta.class));
}
/**
* Gets complete list of open invitations for current user.
*
* @return the my invitations
* @throws IOException
* the io exception
*/
public List<GHInvitation> getMyInvitations() throws IOException {
return createRequest().withUrlPath("/user/repository_invitations")
.toIterable(GHInvitation[].class, null)
.toList();
}
/**
* Returns only active subscriptions.
* <p>
* You must use a user-to-server OAuth access token, created for a user who has authorized your GitHub App, to
* access this endpoint
* <p>
* OAuth Apps must authenticate using an OAuth token.
*
* @return the paged iterable of GHMarketplaceUserPurchase
* @see <a href="https://developer.github.com/v3/apps/marketplace/#get-a-users-marketplace-purchases">Get a
* user's Marketplace purchases</a>
*/
public PagedIterable<GHMarketplaceUserPurchase> getMyMarketplacePurchases() {
return createRequest().withUrlPath("/user/marketplace_purchases")
.toIterable(GHMarketplaceUserPurchase[].class, null);
}
/**
* This method returns shallowly populated organizations.
* <p>
* To retrieve full organization details, you need to call {@link #getOrganization(String)} TODO: make this
* automatic.
*
* @return the my organizations
* @throws IOException
* the io exception
*/
public Map<String, GHOrganization> getMyOrganizations() throws IOException {
GHOrganization[] orgs = createRequest().withUrlPath("/user/orgs")
.toIterable(GHOrganization[].class, null)
.toArray();
Map<String, GHOrganization> r = new HashMap<>();
for (GHOrganization o : orgs) {
// don't put 'o' into orgs because they are shallow
r.put(o.getLogin(), o);
}
return r;
}
/**
* Gets complete map of organizations/teams that current user belongs to.
* <p>
* Leverages the new GitHub API /user/teams made available recently to get in a single call the complete set of
* organizations, teams and permissions in a single call.
*
* @return the my teams
* @throws IOException
* the io exception
*/
public Map<String, Set<GHTeam>> getMyTeams() throws IOException {
Map<String, Set<GHTeam>> allMyTeams = new HashMap<>();
for (GHTeam team : createRequest().withUrlPath("/user/teams")
.toIterable(GHTeam[].class, item -> item.wrapUp(this))
.toArray()) {
String orgLogin = team.getOrganization().getLogin();
Set<GHTeam> teamsPerOrg = allMyTeams.get(orgLogin);
if (teamsPerOrg == null) {
teamsPerOrg = new HashSet<>();
}
teamsPerOrg.add(team);
allMyTeams.put(orgLogin, teamsPerOrg);
}
return allMyTeams;
}
/**
* Gets the {@link GHUser} that represents yourself.
*
* @return the myself
* @throws IOException
* the io exception
*/
@SuppressFBWarnings(value = { "EI_EXPOSE_REP" }, justification = "Expected")
public GHMyself getMyself() throws IOException {
client.requireCredential();
return setMyself();
}
/**
* Gets {@link GHOrganization} specified by name.
*
* @param name
* the name
* @return the organization
* @throws IOException
* the io exception
*/
public GHOrganization getOrganization(String name) throws IOException {
GHOrganization o = orgs.get(name);
if (o == null) {
o = createRequest().withUrlPath("/orgs/" + name).fetch(GHOrganization.class);
orgs.put(name, o);
}
return o;
}
/**
* Gets project.
*
* @param id
* the id
* @return the project
* @throws IOException
* the io exception
*/
public GHProject getProject(long id) throws IOException {
return createRequest().withUrlPath("/projects/" + id).fetch(GHProject.class);
}
/**
* Gets project card.
*
* @param id
* the id
* @return the project card
* @throws IOException
* the io exception
*/
public GHProjectCard getProjectCard(long id) throws IOException {
return createRequest().withUrlPath("/projects/columns/cards/" + id).fetch(GHProjectCard.class).lateBind(this);
}
/**
* Gets project column.
*
* @param id
* the id
* @return the project column
* @throws IOException
* the io exception
*/
public GHProjectColumn getProjectColumn(long id) throws IOException {
return createRequest().withUrlPath("/projects/columns/" + id).fetch(GHProjectColumn.class).lateBind(this);
}
/**
* Gets the current full rate limit information from the server.
*
* For some versions of GitHub Enterprise, the {@code /rate_limit} endpoint returns a {@code 404 Not Found}. In that
* case, the most recent {@link GHRateLimit} information will be returned, including rate limit information returned
* in the response header for this request in if was present.
*
* For most use cases it would be better to implement a {@link RateLimitChecker} and add it via
* {@link GitHubBuilder#withRateLimitChecker(RateLimitChecker)}.
*
* @return the rate limit
* @throws IOException
* the io exception
*/
@Nonnull
public GHRateLimit getRateLimit() throws IOException {
return client.getRateLimit();
}
/**
* Gets the repository object from 'owner/repo' string that GitHub calls as "repository name".
*
* @param name
* the name
* @return the repository
* @throws IOException
* the io exception
* @see GHRepository#getName() GHRepository#getName()
*/
public GHRepository getRepository(String name) throws IOException {
String[] tokens = name.split("/");
if (tokens.length != 2) {
throw new IllegalArgumentException("Repository name must be in format owner/repo");
}
return GHRepository.read(this, tokens[0], tokens[1]);
}
/**
* Gets the repository object from its ID.
*
* @param id
* the id
* @return the repository by id
* @throws IOException
* the io exception
*/
public GHRepository getRepositoryById(long id) throws IOException {
return createRequest().withUrlPath("/repositories/" + id).fetch(GHRepository.class);
}
/**
* Obtains the object that represents the named user.
*
* @param login
* the login
* @return the user
* @throws IOException
* the io exception
*/
public GHUser getUser(String login) throws IOException {
GHUser u = users.get(login);
if (u == null) {
u = createRequest().withUrlPath("/users/" + login).fetch(GHUser.class);
users.put(u.getLogin(), u);
}
return u;
}
/**
* List public events for a user
* <a href="https://docs.github.com/en/rest/activity/events?apiVersion=2022-11-28#list-public-events-for-a-user">see
* API documentation</a>
*
* @param login
* the login (user) to look public events for
* @return the events
* @throws IOException
* the io exception
*/
public List<GHEventInfo> getUserPublicEvents(String login) throws IOException {
return createRequest().withUrlPath("/users/" + login + "/events/public")
.toIterable(GHEventInfo[].class, null)
.toList();
}
/**
* Alias for {@link #getUserPublicOrganizations(String)}.
*
* @param user
* the user
* @return the user public organizations
* @throws IOException
* the io exception
*/
public Map<String, GHOrganization> getUserPublicOrganizations(GHUser user) throws IOException {
return getUserPublicOrganizations(user.getLogin());
}
/**
* This method returns a shallowly populated organizations.
* <p>
* To retrieve full organization details, you need to call {@link #getOrganization(String)}
*
* @param login
* the user to retrieve public Organization membership information for
* @return the public Organization memberships for the user
* @throws IOException
* the io exception
*/
public Map<String, GHOrganization> getUserPublicOrganizations(String login) throws IOException {
GHOrganization[] orgs = createRequest().withUrlPath("/users/" + login + "/orgs")
.toIterable(GHOrganization[].class, null)
.toArray();
Map<String, GHOrganization> r = new HashMap<>();
for (GHOrganization o : orgs) {
// don't put 'o' into orgs cache because they are shallow records
r.put(o.getLogin(), o);
}
return r;
}
/**
* Is this an anonymous connection.
*
* @return {@code true} if operations that require authentication will fail.
*/
public boolean isAnonymous() {
return client.isAnonymous();
}
/**
* Ensures that the credential is valid.
*
* @return the boolean
*/
public boolean isCredentialValid() {
return client.isCredentialValid();
}
/**
* Is this an always offline "connection".
*
* @return {@code true} if this is an always offline "connection".
*/
public boolean isOffline() {
return client.isOffline();