Compare commits

..

23 Commits

Author SHA1 Message Date
Kohsuke Kawaguchi
9d75913005 [maven-release-plugin] prepare release github-api-1.35 2013-01-06 16:47:24 -08:00
Kohsuke Kawaguchi
887ca772e0 switching to Markdown 2013-01-06 16:45:17 -08:00
Kohsuke Kawaguchi
45286598aa adding OAuth support in ~/.github 2013-01-06 16:43:43 -08:00
Kohsuke Kawaguchi
2e074b5bc4 follow up fix to the pull request #28 2013-01-06 16:25:02 -08:00
Johno Crawford
560e3c257a Refactored test. 2013-01-06 16:25:02 -08:00
Johno Crawford
6e0202fa0b Added membership checks. 2013-01-06 16:25:01 -08:00
Kohsuke Kawaguchi
ef241b1a07 Merge pull request #27 from johnou/deprecated-password
Password is no longer required for api usage and fix for broken base64 encoding.
2013-01-06 16:14:15 -08:00
Johno Crawford
f80cb541d5 Fix base64 encoding. 2013-01-06 21:11:19 +01:00
Johno Crawford
1fe61f72e2 Password is no longer required for api usage. 2013-01-06 13:08:41 +01:00
Jerome Lacoste
bf1b0edfd2 Merge pull request #26 from johnou/remove-webclient
Removed web client and proprietary api usage.
2013-01-06 00:34:15 -08:00
johnou
f0ab946b88 Removed proprietary api usage. 2013-01-06 04:27:18 +01:00
Johno Crawford
975ef1a43d Removed last traces of web client. 2013-01-06 04:06:55 +01:00
Kohsuke Kawaguchi
7064865157 [maven-release-plugin] prepare for next development iteration 2013-01-05 17:18:17 -08:00
Kohsuke Kawaguchi
3dd738b0db [maven-release-plugin] prepare release github-api-1.34 2013-01-05 17:18:11 -08:00
Kohsuke Kawaguchi
6480dde247 oops test failures 2013-01-05 17:15:46 -08:00
Kohsuke Kawaguchi
555dab7403 Merge branch 'pull-22' 2013-01-05 17:11:58 -08:00
Kohsuke Kawaguchi
13158a28e1 turns out we never exposed the ability to specify the custom URL.
So no backward compatibility provision is needed.
Also in this change, I stopped exposin the password. See the code comment for more details
2013-01-05 17:10:24 -08:00
Kohsuke Kawaguchi
cbaca87bbc massaging this a bit to accept the full URL 2013-01-05 16:08:42 -08:00
Kohsuke Kawaguchi
5166202f67 follow-up fix and documenting the expected value 2013-01-05 15:59:02 -08:00
johnou
35d45ca47d JENKINS-13726: Github plugin should work with Guthub enterprise by allowing for overriding the github URL. 2013-01-06 00:47:44 +01:00
Honza Brázdil
b66ede98c7 Retrieve repository directly. 2012-10-20 23:24:56 +02:00
Kohsuke Kawaguchi
1ba8f2ccbf Update pom.xml
Added <repository> definition
2012-10-17 07:45:15 -07:00
Kohsuke Kawaguchi
82133c117a [maven-release-plugin] prepare for next development iteration 2012-09-13 16:31:58 -07:00
11 changed files with 216 additions and 140 deletions

1
.gitignore vendored
View File

@@ -1,4 +1,5 @@
target target
.idea/
*.iml *.iml
*.ipr *.ipr
*.iws *.iws

29
pom.xml
View File

@@ -3,11 +3,11 @@
<parent> <parent>
<groupId>org.kohsuke</groupId> <groupId>org.kohsuke</groupId>
<artifactId>pom</artifactId> <artifactId>pom</artifactId>
<version>3</version> <version>4</version>
</parent> </parent>
<artifactId>github-api</artifactId> <artifactId>github-api</artifactId>
<version>1.33</version> <version>1.35</version>
<name>GitHub API for Java</name> <name>GitHub API for Java</name>
<url>http://github-api.kohsuke.org/</url> <url>http://github-api.kohsuke.org/</url>
<description>GitHub API for Java</description> <description>GitHub API for Java</description>
@@ -44,16 +44,14 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.jvnet.hudson</groupId> <groupId>commons-lang</groupId>
<artifactId>htmlunit</artifactId> <artifactId>commons-lang</artifactId>
<version>2.6-hudson-2</version> <version>2.6</version>
<exclusions> </dependency>
<exclusion> <dependency>
<!-- hides JDK DOM classes in Eclipse --> <groupId>commons-codec</groupId>
<groupId>xml-apis</groupId> <artifactId>commons-codec</artifactId>
<artifactId>xml-apis</artifactId> <version>1.7</version>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@@ -85,6 +83,13 @@
</dependency> </dependency>
</dependencies> </dependencies>
<repositories>
<repository>
<id>repo.jenkins-ci.org</id>
<url>http://repo.jenkins-ci.org/public/</url>
</repository>
</repositories>
<reporting> <reporting>
<plugins> <plugins>
<plugin> <plugin>

View File

@@ -1,9 +1,5 @@
package org.kohsuke.github; package org.kohsuke.github;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.IOException; import java.io.IOException;
import java.util.AbstractList; import java.util.AbstractList;
import java.util.ArrayList; import java.util.ArrayList;
@@ -50,6 +46,30 @@ public class GHOrganization extends GHPerson {
return r; return r;
} }
/**
* Checks if this organization has the specified user as a member.
*/
public boolean hasMember(GHUser user) {
try {
root.retrieve().to("/orgs/" + login + "/members/" + user.getLogin());
return true;
} catch (IOException ignore) {
return false;
}
}
/**
* Checks if this organization has the specified user as a public member.
*/
public boolean hasPublicMember(GHUser user) {
try {
root.retrieve().to("/orgs/" + login + "/public_members/" + user.getLogin());
return true;
} catch (IOException ignore) {
return false;
}
}
/** /**
* Publicizes the membership. * Publicizes the membership.
*/ */
@@ -112,13 +132,12 @@ public class GHOrganization extends GHPerson {
* List up repositories that has some open pull requests. * List up repositories that has some open pull requests.
*/ */
public List<GHRepository> getRepositoriesWithOpenPullRequests() throws IOException { public List<GHRepository> getRepositoriesWithOpenPullRequests() throws IOException {
WebClient wc = root.createWebClient();
HtmlPage pg = (HtmlPage)wc.getPage("https://github.com/organizations/"+login+"/dashboard/pulls");
List<GHRepository> r = new ArrayList<GHRepository>(); List<GHRepository> r = new ArrayList<GHRepository>();
for (HtmlAnchor e : pg.getElementById("js-issue-list").<HtmlAnchor>selectNodes(".//UL[@class='smallnav']/LI[not(@class='zeroed')]/A")) { for (GHRepository repository : root.retrieve().to("/orgs/" + login + "/repos", GHRepository[].class)) {
String a = e.getHrefAttribute(); List<GHPullRequest> pullRequests = repository.getPullRequests(GHIssueState.OPEN);
String name = a.substring(a.lastIndexOf('/')+1); if (pullRequests.size() > 0) {
r.add(getRepository(name)); r.add(repository);
}
} }
return r; return r;
} }

View File

@@ -23,12 +23,6 @@
*/ */
package org.kohsuke.github; package org.kohsuke.github;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlCheckBoxInput;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import java.io.IOException; import java.io.IOException;
@@ -266,15 +260,10 @@ public class GHRepository {
} }
public void setEmailServiceHook(String address) throws IOException { public void setEmailServiceHook(String address) throws IOException {
WebClient wc = root.createWebClient(); Map<String, String> config = new HashMap<String, String>();
HtmlPage pg = (HtmlPage)wc.getPage(getUrl()+"/admin"); config.put("address", address);
HtmlInput email = (HtmlInput)pg.getElementById("email_address"); new Requester(root).method("POST").with("name", "email").with("config", config).with("active", "true")
email.setValueAttribute(address); .to(String.format("/repos/%s/%s/hooks", owner.login, name));
HtmlCheckBoxInput active = (HtmlCheckBoxInput)pg.getElementById("email[active]");
active.setChecked(true);
final HtmlForm f = email.getEnclosingFormOrDie();
f.submit((HtmlButton) f.getElementsByTagName("button").get(0));
} }
private void edit(String key, String value) throws IOException { private void edit(String key, String value) throws IOException {

View File

@@ -69,6 +69,20 @@ public class GHUser extends GHPerson {
return new GHPersonSet<GHUser>(Arrays.asList(wrap(followers,root))); return new GHPersonSet<GHUser>(Arrays.asList(wrap(followers,root)));
} }
/**
* Returns true if this user belongs to the specified organization.
*/
public boolean isMemberOf(GHOrganization org) {
return org.hasMember(this);
}
/**
* Returns true if this user belongs to the specified organization as a public member.
*/
public boolean isPublicMemberOf(GHOrganization org) {
return org.hasPublicMember(this);
}
/*package*/ static GHUser[] wrap(GHUser[] users, GitHub root) { /*package*/ static GHUser[] wrap(GHUser[] users, GitHub root) {
for (GHUser f : users) for (GHUser f : users)
f.root = root; f.root = root;

View File

@@ -23,15 +23,12 @@
*/ */
package org.kohsuke.github; package org.kohsuke.github;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods; import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.DeserializationConfig.Feature; import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.introspect.VisibilityChecker.Std; import org.codehaus.jackson.map.introspect.VisibilityChecker.Std;
import sun.misc.BASE64Encoder;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@@ -58,43 +55,45 @@ import static org.codehaus.jackson.annotate.JsonAutoDetect.Visibility.*;
*/ */
public class GitHub { public class GitHub {
/*package*/ final String login; /*package*/ final String login;
/*package*/ final String encodedAuthorization; /*package*/ final String encodedAuthorization;
/*package*/ final String password;
/*package*/ final String apiToken; /*package*/ final String apiToken;
private final Map<String,GHUser> users = new HashMap<String, GHUser>(); private final Map<String,GHUser> users = new HashMap<String, GHUser>();
private final Map<String,GHOrganization> orgs = new HashMap<String, GHOrganization>(); private final Map<String,GHOrganization> orgs = new HashMap<String, GHOrganization>();
/*package*/ String oauthAccessToken; /*package*/ String oauthAccessToken;
private final String githubServer; private final String apiUrl;
private GitHub(String login, String apiToken, String password) { private GitHub(String login, String apiToken, String password) {
this ("github.com", login, apiToken, password); this (GITHUB_URL, login, apiToken, password);
} }
/** /**
* *
* @param githubServer * @param apiUrl
* The host name of the GitHub (or GitHub enterprise) server, such as "github.com". * 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 <tt>/api/v3</tt> in the URL.
* For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated.
* Password is also considered deprecated as it is no longer required for api usage.
*/ */
private GitHub(String githubServer, String login, String apiToken, String password) { private GitHub(String apiUrl, String login, String apiToken, String password) {
this.githubServer = githubServer; if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length()-1); // normalize
this.apiUrl = apiUrl;
this.login = login; this.login = login;
this.apiToken = apiToken; this.apiToken = apiToken;
this.password = password;
BASE64Encoder enc = new sun.misc.BASE64Encoder();
if (apiToken!=null || password!=null) { if (apiToken!=null || password!=null) {
String userpassword = password==null ? (login + "/token" + ":" + apiToken) : (login + ':'+password); String authorization = password==null ? (login + "/token" + ":" + apiToken) : (login + ':'+password);
encodedAuthorization = enc.encode(userpassword.getBytes()); encodedAuthorization = new String(Base64.encodeBase64(authorization.getBytes()));
} else } else
encodedAuthorization = null; encodedAuthorization = null;
} }
private GitHub (String githubServer, String oauthAccessToken) throws IOException { private GitHub (String apiUrl, String oauthAccessToken) throws IOException {
this.githubServer = githubServer; this.apiUrl = apiUrl;
this.password = null;
this.encodedAuthorization = null; this.encodedAuthorization = null;
this.oauthAccessToken = oauthAccessToken; this.oauthAccessToken = oauthAccessToken;
@@ -115,7 +114,23 @@ public class GitHub {
} finally { } finally {
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
} }
return new GitHub(props.getProperty("login"),props.getProperty("token"),props.getProperty("password")); String oauth = props.getProperty("oauth");
if (oauth!=null)
return new GitHub(GITHUB_URL,oauth);
else
return new GitHub(props.getProperty("login"),props.getProperty("token"),props.getProperty("password"));
}
/**
* 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 <tt>/api/v3</tt> in the URL.
* For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated.
*/
public static GitHub connectToEnterprise(String apiUrl, String login, String apiToken) {
return new GitHub(apiUrl,login,apiToken,null);
} }
public static GitHub connect(String login, String apiToken){ public static GitHub connect(String login, String apiToken){
@@ -153,10 +168,15 @@ public class GitHub {
tailApiUrl = tailApiUrl + (tailApiUrl.indexOf('?')>=0 ?'&':'?') + "access_token=" + oauthAccessToken; tailApiUrl = tailApiUrl + (tailApiUrl.indexOf('?')>=0 ?'&':'?') + "access_token=" + oauthAccessToken;
} }
if (tailApiUrl.startsWith("/")) if (tailApiUrl.startsWith("/")) {
return new URL("https://api."+githubServer+tailApiUrl); if ("github.com".equals(apiUrl)) {// backward compatibility
else return new URL(GITHUB_URL + tailApiUrl);
} else {
return new URL(apiUrl + tailApiUrl);
}
} else {
return new URL(tailApiUrl); return new URL(tailApiUrl);
}
} }
/*package*/ Requester retrieve() { /*package*/ Requester retrieve() {
@@ -227,7 +247,7 @@ public class GitHub {
*/ */
public GHRepository getRepository(String name) throws IOException { public GHRepository getRepository(String name) throws IOException {
String[] tokens = name.split("/"); String[] tokens = name.split("/");
return getUser(tokens[0]).getRepository(tokens[1]); return retrieve().to("/repos/" + tokens[0] + '/' + tokens[1], GHRepository.class).wrap(this);
} }
/** /**
@@ -250,7 +270,7 @@ public class GitHub {
* Public events visible to you. Equivalent of what's displayed on https://github.com/ * Public events visible to you. Equivalent of what's displayed on https://github.com/
*/ */
public List<GHEventInfo> getEvents() throws IOException { public List<GHEventInfo> getEvents() throws IOException {
// TODO: pagenation // TODO: pagination
GHEventInfo[] events = retrieve().to("/events", GHEventInfo[].class); GHEventInfo[] events = retrieve().to("/events", GHEventInfo[].class);
for (GHEventInfo e : events) for (GHEventInfo e : events)
e.wrapUp(this); e.wrapUp(this);
@@ -295,18 +315,6 @@ public class GitHub {
} }
} }
WebClient createWebClient() throws IOException {
WebClient wc = new WebClient();
wc.setJavaScriptEnabled(false);
wc.setCssEnabled(false);
HtmlPage pg = (HtmlPage)wc.getPage("https://github.com/login");
HtmlForm f = pg.getForms().get(0);
f.getInputByName("login").setValueAttribute(login);
f.getInputByName("password").setValueAttribute(password);
f.submit();
return wc;
}
/*package*/ static URL parseURL(String s) { /*package*/ static URL parseURL(String s) {
try { try {
return s==null ? null : new URL(s); return s==null ? null : new URL(s);
@@ -337,4 +345,6 @@ public class GitHub {
MAPPER.setVisibilityChecker(new Std(NONE, NONE, NONE, NONE, ANY)); MAPPER.setVisibilityChecker(new Std(NONE, NONE, NONE, NONE, ANY));
MAPPER.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
} }
private static final String GITHUB_URL = "https://api.github.com";
} }

View File

@@ -107,6 +107,10 @@ class Requester {
return _with(key, value); return _with(key, value);
} }
public Requester with(String key, Map<String, String> value) {
return _with(key, value);
}
public Requester _with(String key, Object value) { public Requester _with(String key, Object value) {
if (value!=null) { if (value!=null) {
args.add(new Entry(key,value)); args.add(new Entry(key,value));

View File

@@ -1,25 +0,0 @@
What is this?
This library defines an object oriented representation of the GitHub API. The library doesn't yet cover the entirety of the GitHub API, but it's implemented with the right abstractions and libraries to make it very easy to improve the coverage.
Sample Usage
------------------
GitHub github = GitHub.connect();
GHRepository repo = github.createRepository(
"new-repository","this is my new repository",
"http://www.kohsuke.org/",true/*public*/);
repo.addCollaborators(github.getUser("abayer"),github.getUser("rtyler"));
repo.delete();
------------------
Credential
This library allows the caller to supply the credential as parameters, but it also defines a common convention
so that applications using this library will look at the consistent location. In this convention, the library
looks at "~/.github" property file, which should have the following two values:
------------------
login=kohsuke
token=012345678
------------------

View File

@@ -0,0 +1,36 @@
What is this?
=====
This library defines an object oriented representation of the GitHub API. By "object oriented" we mean
there are classes that correspond to the domain model of GitHub (such as `GHUser` and `GHRepository`),
operations that act on them as defined as methods (such as `GHUser.follow()`), and those object references
are used in favor of using string handle (such as `GHUser.isMemberOf(GHOrganization)` instead of
`GHUser.isMemberOf(String)`)
There are some corners of the GitHub API that's not yet implemented, but
the library is implemented with the right abstractions and libraries to make it very easy to improve the coverage.
Sample Usage
-----
GitHub github = GitHub.connect();
GHRepository repo = github.createRepository(
"new-repository","this is my new repository",
"http://www.kohsuke.org/",true/*public*/);
repo.addCollaborators(github.getUser("abayer"),github.getUser("rtyler"));
repo.delete();
Credential
----
This library allows the caller to supply the credential as parameters, but it also defines a common convention
so that applications using this library will look at the consistent location. In this convention, the library
looks at `~/.github` property file, which should have the following two values:
login=kohsuke
password=012345678
Alternatively, you can have just the OAuth token in this file:
oauth=4d98173f7c075527cb64878561d1fe70

View File

@@ -36,34 +36,42 @@ import java.util.List;
* Unit test for simple App. * Unit test for simple App.
*/ */
public class AppTest extends TestCase { public class AppTest extends TestCase {
private GitHub gitHub;
@Override
public void setUp() throws Exception {
super.setUp();
gitHub = GitHub.connect();
}
public void testRepoCRUD() throws Exception { public void testRepoCRUD() throws Exception {
GitHub hub = GitHub.connect(); GHRepository r = gitHub.createRepository("github-api-test", "a test repository", "http://github-api.kohsuke.org/", true);
GHRepository r = hub.createRepository("github-api-test", "a test repository", "http://github-api.kohsuke.org/", true);
r.enableIssueTracker(false); r.enableIssueTracker(false);
r.enableDownloads(false); r.enableDownloads(false);
r.enableWiki(false); r.enableWiki(false);
r.renameTo("github-api-test2"); r.renameTo("github-api-test2");
hub.getMyself().getRepository("github-api-test2").delete(); gitHub.getMyself().getRepository("github-api-test2").delete();
} }
public void testCredentialValid() throws IOException { public void testCredentialValid() throws IOException {
assertTrue(GitHub.connect().isCredentialValid()); assertTrue(gitHub.isCredentialValid());
assertFalse(GitHub.connect("totally", "bogus").isCredentialValid()); assertFalse(GitHub.connect("totally", "bogus").isCredentialValid());
} }
public void testIssueWithNoComment() throws IOException { public void testIssueWithNoComment() throws IOException {
GHRepository repository = GitHub.connect().getRepository("kohsuke/test"); GHRepository repository = gitHub.getRepository("kohsuke/test");
List<GHIssueComment> v = repository.getIssue(4).getComments(); List<GHIssueComment> v = repository.getIssue(4).getComments();
System.out.println(v); System.out.println(v);
assertTrue(v.isEmpty()); assertTrue(v.isEmpty());
v = repository.getIssue(3).getComments(); v = repository.getIssue(3).getComments();
System.out.println(v); System.out.println(v);
assertTrue(v.size()==3); assertTrue(v.size() == 3);
} }
public void testCreateIssue() throws IOException { public void testCreateIssue() throws IOException {
GHUser u = GitHub.connect().getUser("kohsuke"); GHUser u = gitHub.getUser("kohsuke");
GHRepository r = u.getRepository("test"); GHRepository r = u.getRepository("test");
GHMilestone someMilestone = r.listMilestones(GHIssueState.CLOSED).iterator().next(); GHMilestone someMilestone = r.listMilestones(GHIssueState.CLOSED).iterator().next();
GHIssue o = r.createIssue("testing").body("this is body").assignee(u).label("bug").label("question").milestone(someMilestone).create(); GHIssue o = r.createIssue("testing").body("this is body").assignee(u).label("bug").label("question").milestone(someMilestone).create();
@@ -72,26 +80,24 @@ public class AppTest extends TestCase {
} }
public void testRateLimit() throws IOException { public void testRateLimit() throws IOException {
System.out.println(GitHub.connect().getRateLimit()); System.out.println(gitHub.getRateLimit());
} }
public void testMyOrganizations() throws IOException { public void testMyOrganizations() throws IOException {
Map<String, GHOrganization> org = GitHub.connect().getMyOrganizations(); Map<String, GHOrganization> org = gitHub.getMyOrganizations();
assertFalse(org.keySet().contains(null)); assertFalse(org.keySet().contains(null));
System.out.println(org); System.out.println(org);
} }
public void testFetchPullRequest() throws Exception { public void testFetchPullRequest() throws Exception {
GitHub gh = GitHub.connect(); GHRepository r = gitHub.getOrganization("jenkinsci").getRepository("jenkins");
GHRepository r = gh.getOrganization("jenkinsci").getRepository("jenkins");
assertEquals("master",r.getMasterBranch()); assertEquals("master",r.getMasterBranch());
r.getPullRequest(1); r.getPullRequest(1);
r.getPullRequests(GHIssueState.OPEN); r.getPullRequests(GHIssueState.OPEN);
} }
public void testFetchPullRequestAsList() throws Exception { public void testFetchPullRequestAsList() throws Exception {
GitHub gh = GitHub.connect(); GHRepository r = gitHub.getOrganization("symfony").getRepository("symfony-docs");
GHRepository r = gh.getOrganization("symfony").getRepository("symfony-docs");
assertEquals("master", r.getMasterBranch()); assertEquals("master", r.getMasterBranch());
PagedIterable<GHPullRequest> i = r.listPullRequests(GHIssueState.CLOSED); PagedIterable<GHPullRequest> i = r.listPullRequests(GHIssueState.CLOSED);
List<GHPullRequest> prs = i.asList(); List<GHPullRequest> prs = i.asList();
@@ -100,19 +106,17 @@ public class AppTest extends TestCase {
} }
public void testRepoPermissions() throws Exception { public void testRepoPermissions() throws Exception {
GitHub gh = GitHub.connect(); GHRepository r = gitHub.getOrganization("jenkinsci").getRepository("jenkins");
GHRepository r = gh.getOrganization("jenkinsci").getRepository("jenkins");
assertTrue(r.hasPullAccess()); assertTrue(r.hasPullAccess());
r = gh.getOrganization("github").getRepository("tire"); r = gitHub.getOrganization("github").getRepository("tire");
assertFalse(r.hasAdminAccess()); assertFalse(r.hasAdminAccess());
} }
public void testGetMyself() throws Exception { public void testGetMyself() throws Exception {
GitHub hub = GitHub.connect(); GHMyself me = gitHub.getMyself();
GHMyself me = hub.getMyself();
System.out.println(me); System.out.println(me);
GHUser u = hub.getUser("kohsuke2"); GHUser u = gitHub.getUser("kohsuke2");
System.out.println(u); System.out.println(u);
for (List<GHRepository> lst : me.iterateRepositories(100)) { for (List<GHRepository> lst : me.iterateRepositories(100)) {
for (GHRepository r : lst) { for (GHRepository r : lst) {
@@ -122,36 +126,30 @@ public class AppTest extends TestCase {
} }
public void testPublicKeys() throws Exception { public void testPublicKeys() throws Exception {
GitHub gh = GitHub.connect(); List<GHKey> keys = gitHub.getMyself().getPublicKeys();
List<GHKey> keys = gh.getMyself().getPublicKeys();
System.out.println(keys); System.out.println(keys);
} }
public void tryOrgFork() throws Exception { public void tryOrgFork() throws Exception {
GitHub gh = GitHub.connect(); gitHub.getUser("kohsuke").getRepository("rubywm").forkTo(gitHub.getOrganization("jenkinsci"));
gh.getUser("kohsuke").getRepository("rubywm").forkTo(gh.getOrganization("jenkinsci"));
} }
public void tryGetTeamsForRepo() throws Exception { public void tryGetTeamsForRepo() throws Exception {
GitHub gh = GitHub.connect(); Set<GHTeam> o = gitHub.getOrganization("jenkinsci").getRepository("rubywm").getTeams();
Set<GHTeam> o = gh.getOrganization("jenkinsci").getRepository("rubywm").getTeams();
System.out.println(o); System.out.println(o);
} }
public void testMembership() throws Exception { public void testMembership() throws Exception {
GitHub gitHub = GitHub.connect();
Set<String> members = gitHub.getOrganization("jenkinsci").getRepository("violations-plugin").getCollaboratorNames(); Set<String> members = gitHub.getOrganization("jenkinsci").getRepository("violations-plugin").getCollaboratorNames();
System.out.println(members.contains("kohsuke")); System.out.println(members.contains("kohsuke"));
} }
public void testMemberOrgs() throws Exception { public void testMemberOrgs() throws Exception {
GitHub gitHub = GitHub.connect();
Set<GHOrganization> o = gitHub.getUser("kohsuke").getOrganizations(); Set<GHOrganization> o = gitHub.getUser("kohsuke").getOrganizations();
System.out.println(o); System.out.println(o);
} }
public void testCommit() throws Exception { public void testCommit() throws Exception {
GitHub gitHub = GitHub.connect();
GHCommit commit = gitHub.getUser("jenkinsci").getRepository("jenkins").getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7"); GHCommit commit = gitHub.getUser("jenkinsci").getRepository("jenkins").getCommit("08c1c9970af4d609ae754fbe803e06186e3206f7");
System.out.println(commit); System.out.println(commit);
assertEquals(1, commit.getParents().size()); assertEquals(1, commit.getParents().size());
@@ -160,11 +158,10 @@ public class AppTest extends TestCase {
File f = commit.getFiles().get(0); File f = commit.getFiles().get(0);
assertEquals(48,f.getLinesChanged()); assertEquals(48,f.getLinesChanged());
assertEquals("modified",f.getStatus()); assertEquals("modified",f.getStatus());
assertEquals("changelog.html",f.getFileName()); assertEquals("changelog.html", f.getFileName());
} }
public void testListCommits() throws Exception { public void testListCommits() throws Exception {
GitHub gitHub = GitHub.connect();
List<String> sha1 = new ArrayList<String>(); List<String> sha1 = new ArrayList<String>();
for (GHCommit c : gitHub.getUser("kohsuke").getRepository("empty-commit").listCommits()) { for (GHCommit c : gitHub.getUser("kohsuke").getRepository("empty-commit").listCommits()) {
System.out.println(c.getSHA1()); System.out.println(c.getSHA1());
@@ -175,14 +172,12 @@ public class AppTest extends TestCase {
} }
public void testBranches() throws Exception { public void testBranches() throws Exception {
GitHub gitHub = GitHub.connect();
Map<String,GHBranch> b = Map<String,GHBranch> b =
gitHub.getUser("jenkinsci").getRepository("jenkins").getBranches(); gitHub.getUser("jenkinsci").getRepository("jenkins").getBranches();
System.out.println(b); System.out.println(b);
} }
public void testCommitComment() throws Exception { public void testCommitComment() throws Exception {
GitHub gitHub = GitHub.connect();
GHRepository r = gitHub.getUser("jenkinsci").getRepository("jenkins"); GHRepository r = gitHub.getUser("jenkinsci").getRepository("jenkins");
PagedIterable<GHCommitComment> comments = r.listCommitComments(); PagedIterable<GHCommitComment> comments = r.listCommitComments();
List<GHCommitComment> batch = comments.iterator().nextPage(); List<GHCommitComment> batch = comments.iterator().nextPage();
@@ -193,7 +188,6 @@ public class AppTest extends TestCase {
} }
public void testCreateCommitComment() throws Exception { public void testCreateCommitComment() throws Exception {
GitHub gitHub = GitHub.connect();
GHCommit commit = gitHub.getUser("kohsuke").getRepository("sandbox-ant").getCommit("8ae38db0ea5837313ab5f39d43a6f73de3bd9000"); GHCommit commit = gitHub.getUser("kohsuke").getRepository("sandbox-ant").getCommit("8ae38db0ea5837313ab5f39d43a6f73de3bd9000");
GHCommitComment c = commit.createComment("[testing](http://kohsuse.org/)"); GHCommitComment c = commit.createComment("[testing](http://kohsuse.org/)");
System.out.println(c); System.out.println(c);
@@ -203,7 +197,6 @@ public class AppTest extends TestCase {
} }
public void tryHook() throws Exception { public void tryHook() throws Exception {
GitHub gitHub = GitHub.connect();
GHRepository r = gitHub.getMyself().getRepository("test2"); GHRepository r = gitHub.getMyself().getRepository("test2");
GHHook hook = r.createWebHook(new URL("http://www.google.com/")); GHHook hook = r.createWebHook(new URL("http://www.google.com/"));
System.out.println(hook); System.out.println(hook);
@@ -213,7 +206,6 @@ public class AppTest extends TestCase {
} }
public void testEventApi() throws Exception { public void testEventApi() throws Exception {
GitHub gitHub = GitHub.connect();
for (GHEventInfo ev : gitHub.getEvents()) { for (GHEventInfo ev : gitHub.getEvents()) {
System.out.println(ev); System.out.println(ev);
if (ev.getType()==GHEvent.PULL_REQUEST) { if (ev.getType()==GHEvent.PULL_REQUEST) {
@@ -225,10 +217,9 @@ public class AppTest extends TestCase {
} }
public void testApp() throws IOException { public void testApp() throws IOException {
GitHub gitHub = GitHub.connect();
System.out.println(gitHub.getMyself().getEmails()); System.out.println(gitHub.getMyself().getEmails());
// GHRepository r = gitHub.connect().getOrganization("jenkinsci").createRepository("kktest4", "Kohsuke's test", "http://kohsuke.org/", "Everyone", true); // GHRepository r = gitHub.getOrganization("jenkinsci").createRepository("kktest4", "Kohsuke's test", "http://kohsuke.org/", "Everyone", true);
// r.fork(); // r.fork();
// tryDisablingIssueTrackers(gitHub); // tryDisablingIssueTrackers(gitHub);
@@ -255,7 +246,7 @@ public class AppTest extends TestCase {
// t.remove(gitHub.getMyself()); // t.remove(gitHub.getMyself());
// System.out.println(t.getMembers()); // System.out.println(t.getMembers());
// GHRepository r = GitHub.connect().getOrganization("HudsonLabs").createRepository("auto-test", "some description", "http://kohsuke.org/", "Plugin Developers", true); // GHRepository r = gitHub.getOrganization("HudsonLabs").createRepository("auto-test", "some description", "http://kohsuke.org/", "Plugin Developers", true);
// r. // r.
// GitHub hub = GitHub.connectAnonymously(); // GitHub hub = GitHub.connectAnonymously();
@@ -314,7 +305,6 @@ public class AppTest extends TestCase {
} }
public void testOrgRepositories() throws IOException { public void testOrgRepositories() throws IOException {
GitHub gitHub = GitHub.connect();
GHOrganization j = gitHub.getOrganization("jenkinsci"); GHOrganization j = gitHub.getOrganization("jenkinsci");
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
Map<String, GHRepository> repos = j.getRepositories(); Map<String, GHRepository> repos = j.getRepositories();
@@ -323,7 +313,6 @@ public class AppTest extends TestCase {
} }
public void testOrganization() throws IOException { public void testOrganization() throws IOException {
GitHub gitHub = GitHub.connect();
GHOrganization j = gitHub.getOrganization("jenkinsci"); GHOrganization j = gitHub.getOrganization("jenkinsci");
GHTeam t = j.getTeams().get("Core Developers"); GHTeam t = j.getTeams().get("Core Developers");
@@ -333,7 +322,6 @@ public class AppTest extends TestCase {
} }
public void testCommitStatus() throws Exception { public void testCommitStatus() throws Exception {
GitHub gitHub = GitHub.connect();
GHRepository r = gitHub.getUser("kohsuke").getRepository("test"); GHRepository r = gitHub.getUser("kohsuke").getRepository("test");
GHCommitStatus state; GHCommitStatus state;
// state = r.createCommitStatus("edacdd76b06c5f3f0697a22ca75803169f25f296", GHCommitState.FAILURE, "http://jenkins-ci.org/", "oops!"); // state = r.createCommitStatus("edacdd76b06c5f3f0697a22ca75803169f25f296", GHCommitState.FAILURE, "http://jenkins-ci.org/", "oops!");
@@ -346,10 +334,21 @@ public class AppTest extends TestCase {
} }
public void testPullRequestPopulate() throws Exception { public void testPullRequestPopulate() throws Exception {
GitHub gitHub = GitHub.connect();
GHRepository r = gitHub.getUser("kohsuke").getRepository("github-api"); GHRepository r = gitHub.getUser("kohsuke").getRepository("github-api");
GHPullRequest p = r.getPullRequest(17); GHPullRequest p = r.getPullRequest(17);
GHUser u = p.getUser(); GHUser u = p.getUser();
assertNotNull(u.getName()); assertNotNull(u.getName());
} }
public void testCheckMembership() throws Exception {
GHOrganization j = gitHub.getOrganization("jenkinsci");
GHUser kohsuke = gitHub.getUser("kohsuke");
GHUser a = gitHub.getUser("a");
assertTrue(j.hasMember(kohsuke));
assertFalse(j.hasMember(a));
assertTrue(j.hasPublicMember(kohsuke));
assertFalse(j.hasPublicMember(a));
}
} }

View File

@@ -0,0 +1,24 @@
package org.kohsuke.github;
import junit.framework.TestCase;
/**
* Unit test for {@link GitHub}.
*/
public class GitHubTest extends TestCase {
public void testGitHubServerWithHttp() throws Exception {
GitHub hub = GitHub.connectToEnterprise("http://enterprise.kohsuke.org/api/v3", "kohsuke", "token");
assertEquals("http://enterprise.kohsuke.org/api/v3/test", hub.getApiURL("/test").toString());
}
public void testGitHubServerWithHttps() throws Exception {
GitHub hub = GitHub.connectToEnterprise("https://enterprise.kohsuke.org/api/v3", "kohsuke", "token");
assertEquals("https://enterprise.kohsuke.org/api/v3/test", hub.getApiURL("/test").toString());
}
public void testGitHubServerWithoutServer() throws Exception {
GitHub hub = GitHub.connect("kohsuke", "token", "password");
assertEquals("https://api.github.com/test", hub.getApiURL("/test").toString());
}
}