Compare commits

...

22 Commits

Author SHA1 Message Date
Kohsuke Kawaguchi
2b9d47cea8 [maven-release-plugin] prepare release github-api-1.59 2014-10-08 12:17:49 -07:00
Kohsuke Kawaguchi
5db90d3fc4 This test is invalid if ~/.github file exists, which is quite common 2014-10-08 12:15:32 -07:00
Kohsuke Kawaguchi
372d5ff758 Fixed a test regression
Presumably due to the behaviour change on GitHub API?
2014-10-08 12:07:09 -07:00
Kohsuke Kawaguchi
ebf39eaea1 [INFRA-142]
Reworked version of https://github.com/kohsuke/github-api/pull/133/files
2014-10-08 11:29:17 -07:00
Michael O'Cleirigh
556786f2e1 Merge pull request #131 from mocleiri/resolve-credentials-from-environment
Modify GitHubBuilder to resolve user credentials from the system environ...
2014-09-30 14:07:35 -04:00
Michael O'Cleirigh
0f64994537 Make Github.connect() fail if no credentials are setup
With the previous change if no credentials were defined Github.connect() would
fall back on an anonymous connection.

This commit changes the behaviour back to what it was before so that if there
are no credentials defined in the ~/.github file and no credentials defined
in the environment an IOException is thrown to alert the method caller.

The caller can call Github.connectAnonymously() if that scenario is allowed.

This should handle most cases unless callers are depending on the
FileNotFoundException being specifically thrown instead of an IOException.
2014-09-30 13:58:06 -04:00
Michael O'Cleirigh
ac64c2022b Merge pull request #132 from mocleiri/add-getFiles-method-to-GHCompare
Add GHCompare.getFiles() method to be able to see the precise files chan...
2014-09-30 12:03:54 -04:00
Michael O'Cleirigh
9802132b6f Add GHCompare.getFiles() method to be able to see the precise files changed.
There is a file field inside of GHCompare but no getter to extract the values
for analysis.

There are contents in that field so I've added a new get method so that they
can be extracted.
2014-09-30 11:51:57 -04:00
Michael O'Cleirigh
4d6c5c14f1 Modify GitHubBuilder to resolve user credentials from the system environment
Using the Jenkins EnvInject or Credentials Binding Plugins its possible to
pass credentials as Environment Variables.

Its useful for Github.connect() to be able to directly read the values of the
'login', 'password' and 'oauth' properties directly from the environment.

This commit modifies the base Github.connect() method to resolve credentials
in two steps:

1. ~/.github credentials file if it exists.
2. login, password or oauth variables from the environment

A further fromEnvironment() method is provided to support
loading from non-standard variable names.

The old Github.connect() method would throw an IOException if the ~/.github file
did not exist.  Now it will fail silently instead dropping back to the anonymous
users access level.

Added new unit tests into GitHubTest.
2014-09-29 13:42:28 -04:00
Kohsuke Kawaguchi
d228a5fb93 Merge pull request #128 from ndeloof/patch-1
Update github scopes according to https://developer.github.com/v3/oauth/#scopes
2014-09-26 18:10:15 -07:00
Michael O'Cleirigh
7b46ef10c8 Merge pull request #129 from mocleiri/fix-pull-request-remote-repo-get-commit
Allow pullRequest.getHead().getRepository().getCommit(headSha1) to work
2014-09-26 15:14:25 -04:00
Michael O'Cleirigh
8eb9fba051 Allow pullRequest.getHead().getRepository().getCommit(headSha1) to work
The wrong .wrap method was used for pull requests initialized by state
(GHRepository.getPullReqests).

The wrong wrap call was introduced in 9fd34aec7f

This commit sets it back to the .wrapUp method which makes sure the pull request
substructure has the repo object set properly.

Without this change a NullPointerException is thrown on the last line of this
code because the repo object inside of the remoteRepository object is null:

GHRepository repo = github.getRepository(targetRepository);

List<GHPullRequest> openPullRequests = repo.getPullRequests(GHIssueState.OPEN);

for (GHPullRequest pullRequest : openPullRequests) {

    GHCommitPointer head = pullRequest.getHead();

	GHRepository remoteRepository = head.getRepository();

	String commitId = head.getSha();

	GHCommit headCommit = remoteRepository.getCommit(commitId);
2014-09-22 10:53:13 -04:00
Nicolas De loof
7b58182683 Update github scopes according to https://developer.github.com/v3/oauth/#scopes 2014-09-12 23:16:43 +02:00
Kohsuke Kawaguchi
95fbf9274b Merge pull request #124 from ohtake/connector
Allow to use custom HttpConnector when only OAuth token is given
2014-09-04 10:32:11 -07:00
Kohsuke Kawaguchi
09557dfa0f Merge pull request #123 from rtyley/use-issues-endpoints-for-pull-requests
Use issues endpoints for pull requests
2014-09-04 10:31:25 -07:00
Kohsuke Kawaguchi
4029fcc1ca Merge pull request #122 from tbruyelle/browserDownloadUrl
Add missing field browser_download_url in GHAsset
2014-09-04 10:29:23 -07:00
OHTAKE Tomohiro
d6627b1e34 Use custom HttpConnector when only OAuth token is given 2014-09-04 13:18:35 +09:00
OHTAKE Tomohiro
86d75fd767 Introduce GitHubBuilder for flexible GitHub instance creation 2014-09-04 13:17:43 +09:00
Roberto Tyley
e2220bb3b3 Fix setting labels and assignee on PullRequests
Setting labels and assignee on Pull requests failed silently, because
the API endpoint being hit contained '/pulls/' rather than '/issues/'.

"Every pull request is an issue, but not every issue is a pull request.
For this reason, “shared” actions for both features, like manipulating
assignees, labels and milestones, are provided within the Issues API."

https://developer.github.com/v3/pulls/#labels-assignees-and-milestones
2014-09-03 23:34:58 +01:00
Roberto Tyley
1a9b8bd1da Separate out clean-up of Pull requests created during test
If the test assertion fails, we want the pull-request to be closed anyway.
You can't have more than one pull-request merging a given branch into
another, so leaving the PR hanging will cause subsequent test runs to fail
in setup.
2014-09-03 23:18:22 +01:00
Thomas Bruyelle
9eda2d3f77 Add missing field browser_download_url in GHAsset 2014-09-03 22:01:43 +02:00
Kohsuke Kawaguchi
e6d59df705 [maven-release-plugin] prepare for next development iteration 2014-08-30 14:15:29 -07:00
12 changed files with 349 additions and 46 deletions

View File

@@ -7,7 +7,7 @@
</parent> </parent>
<artifactId>github-api</artifactId> <artifactId>github-api</artifactId>
<version>1.58</version> <version>1.59</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>
@@ -16,7 +16,7 @@
<connection>scm:git:git@github.com/kohsuke/${project.artifactId}.git</connection> <connection>scm:git:git@github.com/kohsuke/${project.artifactId}.git</connection>
<developerConnection>scm:git:ssh://git@github.com/kohsuke/${project.artifactId}.git</developerConnection> <developerConnection>scm:git:ssh://git@github.com/kohsuke/${project.artifactId}.git</developerConnection>
<url>http://${project.artifactId}.kohsuke.org/</url> <url>http://${project.artifactId}.kohsuke.org/</url>
<tag>github-api-1.58</tag> <tag>HEAD</tag>
</scm> </scm>
<distributionManagement> <distributionManagement>

View File

@@ -21,6 +21,7 @@ public class GHAsset {
private long download_count; private long download_count;
private Date created_at; private Date created_at;
private Date updated_at; private Date updated_at;
private String browser_download_url;
public String getContentType() { public String getContentType() {
return content_type; return content_type;
@@ -80,6 +81,10 @@ public class GHAsset {
return url; return url;
} }
public String getBrowserDownloadUrl() {
return browser_download_url;
}
private void edit(String key, Object value) throws IOException { private void edit(String key, Object value) throws IOException {
new Requester(root)._with(key, value).method("PATCH").to(getApiRoute()); new Requester(root)._with(key, value).method("PATCH").to(getApiRoute());
} }

View File

@@ -22,6 +22,15 @@ public class GHAuthorization {
public static final String DELETE_REPO = "delete_repo"; public static final String DELETE_REPO = "delete_repo";
public static final String NOTIFICATIONS = "notifications"; public static final String NOTIFICATIONS = "notifications";
public static final String GIST = "gist"; public static final String GIST = "gist";
public static final String READ_HOOK = "read:repo_hook";
public static final String WRITE_HOOK = "write:repo_hook";
public static final String AMIN_HOOK = "admin:repo_hook";
public static final String READ_ORG = "read:org";
public static final String WRITE_ORG = "write:org";
public static final String ADMIN_ORG = "admin:org";
public static final String READ_KEY = "read:public_key";
public static final String WRITE_KEY = "write:public_key";
public static final String ADMIN_KEY = "admin:public_key";
private GitHub root; private GitHub root;
private int id; private int id;

View File

@@ -68,9 +68,12 @@ public class GHCompare {
public Commit[] getCommits() { public Commit[] getCommits() {
return commits; return commits;
} }
public GHCommit.File[] getFiles() {
return files;
}
public GHCompare wrap(GHRepository owner) {
public GHCompare wrap(GHRepository owner) {
this.owner = owner; this.owner = owner;
for (Commit commit : commits) { for (Commit commit : commits) {
commit.wrapUp(owner); commit.wrapUp(owner);

View File

@@ -129,7 +129,7 @@ public class GHIssue {
return Enum.valueOf(GHIssueState.class, state.toUpperCase(Locale.ENGLISH)); return Enum.valueOf(GHIssueState.class, state.toUpperCase(Locale.ENGLISH));
} }
public Collection<Label> getLabels() { public Collection<Label> getLabels() throws IOException {
if(labels == null){ if(labels == null){
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
@@ -163,6 +163,10 @@ public class GHIssue {
new Requester(root)._with(key, value).method("PATCH").to(getApiRoute()); new Requester(root)._with(key, value).method("PATCH").to(getApiRoute());
} }
private void editIssue(String key, Object value) throws IOException {
new Requester(root)._with(key, value).method("PATCH").to(getIssuesApiRoute());
}
/** /**
* Closes this issue. * Closes this issue.
*/ */
@@ -186,11 +190,11 @@ public class GHIssue {
} }
public void assignTo(GHUser user) throws IOException { public void assignTo(GHUser user) throws IOException {
edit("assignee",user.getLogin()); editIssue("assignee",user.getLogin());
} }
public void setLabels(String... labels) throws IOException { public void setLabels(String... labels) throws IOException {
edit("labels",labels); editIssue("labels",labels);
} }
/** /**
@@ -222,7 +226,7 @@ public class GHIssue {
return getIssuesApiRoute(); return getIssuesApiRoute();
} }
private String getIssuesApiRoute() { protected String getIssuesApiRoute() {
return "/repos/"+owner.getOwnerName()+"/"+owner.getName()+"/issues/"+number; return "/repos/"+owner.getOwnerName()+"/"+owner.getName()+"/issues/"+number;
} }

View File

@@ -52,6 +52,13 @@ public class GHPullRequest extends GHIssue {
private String mergeable_state; private String mergeable_state;
private int changed_files; private int changed_files;
/**
* GitHub doesn't return some properties of {@link GHIssue} when requesting the GET on the 'pulls' API
* route as opposed to 'issues' API route. This flag remembers whether we made the GET call on the 'issues' route
* on this object to fill in those missing details
*/
private transient boolean fetchedIssueDetails;
GHPullRequest wrapUp(GHRepository owner) { GHPullRequest wrapUp(GHRepository owner) {
this.wrap(owner); this.wrap(owner);
@@ -120,11 +127,12 @@ public class GHPullRequest extends GHIssue {
} }
@Override @Override
public Collection<Label> getLabels() { public Collection<Label> getLabels() throws IOException {
fetchIssue();
return super.getLabels(); return super.getLabels();
} }
@Override @Override
public GHUser getClosedBy() { public GHUser getClosedBy() {
return null; return null;
} }
@@ -218,4 +226,10 @@ public class GHPullRequest extends GHIssue {
new Requester(root).method("PUT").with("commit_message",msg).to(getApiRoute()+"/merge"); new Requester(root).method("PUT").with("commit_message",msg).to(getApiRoute()+"/merge");
} }
private void fetchIssue() throws IOException {
if (!fetchedIssueDetails) {
new Requester(root).to(getIssuesApiRoute(), this);
fetchedIssueDetails = true;
}
}
} }

View File

@@ -514,7 +514,7 @@ public class GHRepository {
@Override @Override
protected void wrapUp(GHPullRequest[] page) { protected void wrapUp(GHPullRequest[] page) {
for (GHPullRequest pr : page) for (GHPullRequest pr : page)
pr.wrap(GHRepository.this); pr.wrapUp(GHRepository.this);
} }
}; };
} }

View File

@@ -78,9 +78,13 @@ public class GHTeam {
/** /**
* Adds a member to the team. * Adds a member to the team.
*
* The user will be invited to the organization if required.
*
* @since 1.59
*/ */
public void add(GHUser u) throws IOException { public void add(GHUser u) throws IOException {
org.root.retrieve().method("PUT").to(api("/members/" + u.getLogin()), null); org.root.retrieve().method("PUT").to(api("/memberships/" + u.getLogin()), null);
} }
/** /**

View File

@@ -26,8 +26,6 @@ package org.kohsuke.github;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.Reader; import java.io.Reader;
@@ -42,12 +40,10 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@@ -74,13 +70,6 @@ public class GitHub {
private HttpConnector connector = HttpConnector.DEFAULT; private HttpConnector connector = HttpConnector.DEFAULT;
/**
* Connects to GitHub.com
*/
private GitHub(String login, String oauthAccessToken, String password) throws IOException {
this (GITHUB_URL, login, oauthAccessToken, password);
}
/** /**
* Creates a client API root object. * Creates a client API root object.
* *
@@ -114,10 +103,13 @@ public class GitHub {
* Secret OAuth token. * Secret OAuth token.
* @param password * @param password
* User's password. Always used in conjunction with the {@code login} parameter * User's password. Always used in conjunction with the {@code login} parameter
* @param connector
* HttpConnector to use. Pass null to use default connector.
*/ */
private GitHub(String apiUrl, String login, String oauthAccessToken, String password) throws IOException { /* package */ GitHub(String apiUrl, String login, String oauthAccessToken, String password, HttpConnector connector) throws IOException {
if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length()-1); // normalize if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length()-1); // normalize
this.apiUrl = apiUrl; this.apiUrl = apiUrl;
if (null != connector) this.connector = connector;
if (oauthAccessToken!=null) { if (oauthAccessToken!=null) {
encodedAuthorization = "token "+oauthAccessToken; encodedAuthorization = "token "+oauthAccessToken;
@@ -136,18 +128,10 @@ public class GitHub {
} }
/** /**
* Obtains the credential from "~/.github" * Obtains the credential from "~/.github" or from the System Environment Properties.
*/ */
public static GitHub connect() throws IOException { public static GitHub connect() throws IOException {
Properties props = new Properties(); return GitHubBuilder.fromCredentials().build();
File homeDir = new File(System.getProperty("user.home"));
FileInputStream in = new FileInputStream(new File(homeDir, ".github"));
try {
props.load(in);
} finally {
IOUtils.closeQuietly(in);
}
return new GitHub(GITHUB_URL,props.getProperty("login"), props.getProperty("oauth"),props.getProperty("password"));
} }
/** /**
@@ -159,15 +143,15 @@ public class GitHub {
* For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated. * For historical reasons, this parameter still accepts the bare domain name, but that's considered deprecated.
*/ */
public static GitHub connectToEnterprise(String apiUrl, String oauthAccessToken) throws IOException { public static GitHub connectToEnterprise(String apiUrl, String oauthAccessToken) throws IOException {
return connectUsingOAuth(apiUrl, oauthAccessToken); return new GitHubBuilder().withEndpoint(apiUrl).withOAuthToken(oauthAccessToken).build();
} }
public static GitHub connectToEnterprise(String apiUrl, String login, String password) throws IOException { public static GitHub connectToEnterprise(String apiUrl, String login, String password) throws IOException {
return new GitHub(apiUrl, login, null, password); return new GitHubBuilder().withEndpoint(apiUrl).withPassword(login, password).build();
} }
public static GitHub connect(String login, String oauthAccessToken) throws IOException { public static GitHub connect(String login, String oauthAccessToken) throws IOException {
return new GitHub(login,oauthAccessToken,null); return new GitHubBuilder().withOAuthToken(oauthAccessToken, login).build();
} }
/** /**
@@ -176,19 +160,19 @@ public class GitHub {
* Use {@link #connectUsingPassword(String, String)} or {@link #connectUsingOAuth(String)}. * Use {@link #connectUsingPassword(String, String)} or {@link #connectUsingOAuth(String)}.
*/ */
public static GitHub connect(String login, String oauthAccessToken, String password) throws IOException { public static GitHub connect(String login, String oauthAccessToken, String password) throws IOException {
return new GitHub(login,oauthAccessToken,password); return new GitHubBuilder().withOAuthToken(oauthAccessToken, login).withPassword(login, password).build();
} }
public static GitHub connectUsingPassword(String login, String password) throws IOException { public static GitHub connectUsingPassword(String login, String password) throws IOException {
return new GitHub(login,null,password); return new GitHubBuilder().withPassword(login, password).build();
} }
public static GitHub connectUsingOAuth(String oauthAccessToken) throws IOException { public static GitHub connectUsingOAuth(String oauthAccessToken) throws IOException {
return new GitHub(null, oauthAccessToken, null); return new GitHubBuilder().withOAuthToken(oauthAccessToken).build();
} }
public static GitHub connectUsingOAuth(String githubServer, String oauthAccessToken) throws IOException { public static GitHub connectUsingOAuth(String githubServer, String oauthAccessToken) throws IOException {
return new GitHub(githubServer,null, oauthAccessToken,null); return new GitHubBuilder().withEndpoint(githubServer).withOAuthToken(oauthAccessToken).build();
} }
/** /**
* Connects to GitHub anonymously. * Connects to GitHub anonymously.
@@ -196,7 +180,7 @@ public class GitHub {
* All operations that requires authentication will fail. * All operations that requires authentication will fail.
*/ */
public static GitHub connectAnonymously() throws IOException { public static GitHub connectAnonymously() throws IOException {
return new GitHub(null,null,null); return new GitHubBuilder().build();
} }
/** /**
@@ -475,5 +459,5 @@ public class GitHub {
MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
} }
private static final String GITHUB_URL = "https://api.github.com"; /* package */ static final String GITHUB_URL = "https://api.github.com";
} }

View File

@@ -0,0 +1,159 @@
package org.kohsuke.github;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
/**
* @since 1.59
*/
public class GitHubBuilder {
private String endpoint = GitHub.GITHUB_URL;
// default scoped so unit tests can read them.
/* private */ String user;
/* private */ String password;
/* private */ String oauthToken;
private HttpConnector connector;
public GitHubBuilder() {
}
/**
* First check if the credentials are configured using the ~/.github properties file.
*
* If no user is specified it means there is no configuration present so check the environment instead.
*
* If there is still no user it means there are no credentials defined and throw an IOException.
*
* @return the configured Builder from credentials defined on the system or in the environment.
*
* @throws IOException If there are no credentials defined in the ~/.github properties file or the process environment.
*/
public static GitHubBuilder fromCredentials() throws IOException {
GitHubBuilder builder;
try {
builder = fromPropertyFile();
if (builder.user != null)
return builder;
else {
// this is the case where the ~/.github file exists but has no content.
builder = fromEnvironment();
if (builder.user != null)
return builder;
else
throw new IOException("Failed to resolve credentials from ~/.github or the environment.");
}
} catch (FileNotFoundException e) {
builder = fromEnvironment();
if (builder.user != null)
return builder;
else
throw new IOException("Failed to resolve credentials from ~/.github or the environment.", e);
}
}
public static GitHubBuilder fromEnvironment(String loginVariableName, String passwordVariableName, String oauthVariableName) throws IOException {
Properties env = new Properties();
Object loginValue = System.getenv(loginVariableName);
if (loginValue != null)
env.put("login", loginValue);
Object passwordValue = System.getenv(passwordVariableName);
if (passwordValue != null)
env.put("password", passwordValue);
Object oauthValue = System.getenv(oauthVariableName);
if (oauthValue != null)
env.put("oauth", oauthValue);
return fromProperties(env);
}
public static GitHubBuilder fromEnvironment() throws IOException {
Properties props = new Properties();
Map<String, String> env = System.getenv();
for (Map.Entry<String, String> element : env.entrySet()) {
props.put(element.getKey(), element.getValue());
}
return fromProperties(props);
}
public static GitHubBuilder fromPropertyFile() throws IOException {
File homeDir = new File(System.getProperty("user.home"));
File propertyFile = new File(homeDir, ".github");
return fromPropertyFile(propertyFile.getPath());
}
public static GitHubBuilder fromPropertyFile(String propertyFileName) throws IOException {
Properties props = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(propertyFileName);
props.load(in);
} finally {
IOUtils.closeQuietly(in);
}
return fromProperties(props);
}
public static GitHubBuilder fromProperties(Properties props) {
GitHubBuilder self = new GitHubBuilder();
self.withOAuthToken(props.getProperty("oauth"), props.getProperty("login"));
self.withPassword(props.getProperty("login"), props.getProperty("password"));
return self;
}
public GitHubBuilder withEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public GitHubBuilder withPassword(String user, String password) {
this.user = user;
this.password = password;
return this;
}
public GitHubBuilder withOAuthToken(String oauthToken) {
return withOAuthToken(oauthToken, null);
}
public GitHubBuilder withOAuthToken(String oauthToken, String user) {
this.oauthToken = oauthToken;
this.user = user;
return this;
}
public GitHubBuilder withConnector(HttpConnector connector) {
this.connector = connector;
return this;
}
public GitHub build() throws IOException {
return new GitHub(endpoint, user, oauthToken, password, connector);
}
}

View File

@@ -1,5 +1,12 @@
package org.kohsuke.github; package org.kohsuke.github;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase; import junit.framework.TestCase;
/** /**
@@ -21,4 +28,85 @@ public class GitHubTest extends TestCase {
GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus"); GitHub hub = GitHub.connectUsingPassword("kohsuke", "bogus");
assertEquals("https://api.github.com/test", hub.getApiURL("/test").toString()); assertEquals("https://api.github.com/test", hub.getApiURL("/test").toString());
} }
public void testGitHubBuilderFromEnvironment() throws IOException {
Map<String, String>props = new HashMap<String, String>();
props.put("login", "bogus");
props.put("oauth", "bogus");
props.put("password", "bogus");
setupEnvironment(props);
GitHubBuilder builder = GitHubBuilder.fromEnvironment();
assertEquals("bogus", builder.user);
assertEquals("bogus", builder.oauthToken);
assertEquals("bogus", builder.password);
}
/*
* Copied from StackOverflow: http://stackoverflow.com/a/7201825/2336755
*
* This allows changing the in memory process environment.
*
* Its used to wire in values for the github credentials to test that the GitHubBuilder works properly to resolve them.
*/
private void setupEnvironment(Map<String, String> newenv) {
try
{
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
}
catch (NoSuchFieldException e)
{
try {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for(Class cl : classes) {
if("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
public void testGitHubBuilderFromCustomEnvironment() throws IOException {
Map<String, String>props = new HashMap<String, String>();
props.put("customLogin", "bogusLogin");
props.put("customOauth", "bogusOauth");
props.put("customPassword", "bogusPassword");
setupEnvironment(props);
GitHubBuilder builder = GitHubBuilder.fromEnvironment("customLogin", "customPassword", "customOauth");
assertEquals("bogusLogin", builder.user);
assertEquals("bogusOauth", builder.oauthToken);
assertEquals("bogusPassword", builder.password);
}
} }

View File

@@ -1,18 +1,51 @@
package org.kohsuke.github; package org.kohsuke.github;
import org.junit.After;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
/** /**
* @author Kohsuke Kawaguchi * @author Kohsuke Kawaguchi
*/ */
public class PullRequestTest extends AbstractGitHubApiTestBase { public class PullRequestTest extends AbstractGitHubApiTestBase {
@Test @Test
public void createPullRequest() throws Exception { public void createPullRequest() throws Exception {
GHRepository j = gitHub.getOrganization("github-api-test-org").getRepository("jenkins");
String name = rnd.next(); String name = rnd.next();
GHPullRequest p = j.createPullRequest(name, "stable", "master", "## test"); GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl()); System.out.println(p.getUrl());
assertEquals(name, p.getTitle()); assertEquals(name, p.getTitle());
p.close(); }
@Test // Requires push access to the test repo to pass
public void setLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
String label = rnd.next();
p.setLabels(label);
Collection<GHIssue.Label> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(1, labels.size());
assertEquals(label, labels.iterator().next().getName());
}
@Test // Requires push access to the test repo to pass
public void setAssignee() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHMyself user = gitHub.getMyself();
p.assignTo(user);
assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee());
}
@After
public void cleanUp() throws Exception {
for (GHPullRequest pr : getRepository().getPullRequests(GHIssueState.OPEN)) {
pr.close();
}
}
private GHRepository getRepository() throws IOException {
return gitHub.getOrganization("github-api-test-org").getRepository("jenkins");
} }
} }