Skip to content

Commit

Permalink
Add deleteFile() to GHGist
Browse files Browse the repository at this point in the history
Related to hub4j#484 and hub4j#466
  • Loading branch information
bitwiseman committed Apr 22, 2020
1 parent 09977ba commit eb05ec8
Show file tree
Hide file tree
Showing 19 changed files with 657 additions and 133 deletions.
4 changes: 3 additions & 1 deletion src/main/java/org/kohsuke/github/GHGistBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import java.util.Collections;
import java.util.LinkedHashMap;

import javax.annotation.Nonnull;

/**
* Builder pattern for creating a new Gist.
*
Expand Down Expand Up @@ -59,7 +61,7 @@ public GHGistBuilder public_(boolean v) {
* the content
* @return Adds a new file.
*/
public GHGistBuilder file(String fileName, String content) {
public GHGistBuilder file(@Nonnull String fileName, @Nonnull String content) {
files.put(fileName, Collections.singletonMap("content", content));
return this;
}
Expand Down
94 changes: 74 additions & 20 deletions src/main/java/org/kohsuke/github/GHGistUpdater.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package org.kohsuke.github;

import com.fasterxml.jackson.annotation.JsonInclude;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Nonnull;

/**
* Builder pattern for updating a Gist.
Expand All @@ -12,13 +17,31 @@
public class GHGistUpdater {
private final GHGist base;
private final Requester builder;
LinkedHashMap<String, Object> files;
private final GistUpdate updateRecord;

@SuppressFBWarnings("URF_UNREAD_FIELD")
private static class GistUpdate {

@JsonInclude(JsonInclude.Include.NON_NULL)
String description = null;

@JsonInclude
Map<String, GistFileUpdate> files = new HashMap<>();
}

@SuppressFBWarnings("URF_UNREAD_FIELD")
private static class GistFileUpdate {
@JsonInclude(JsonInclude.Include.NON_NULL)
String filename = null;

@JsonInclude(JsonInclude.Include.NON_NULL)
String content = null;
}

GHGistUpdater(GHGist base) {
this.base = base;
this.builder = base.root.createRequest();

files = new LinkedHashMap<>();
builder = base.root.createRequest();
updateRecord = new GistUpdate();
}

/**
Expand All @@ -32,16 +55,15 @@ public class GHGistUpdater {
* @throws IOException
* the io exception
*/
public GHGistUpdater addFile(String fileName, String content) throws IOException {
public GHGistUpdater addFile(@Nonnull String fileName, @Nonnull String content) throws IOException {
updateFile(fileName, content);
return this;
}

// // This method does not work.
// public GHGistUpdater deleteFile(String fileName) throws IOException {
// files.put(fileName, Collections.singletonMap("filename", null));
// return this;
// }
public GHGistUpdater deleteFile(@Nonnull String fileName) throws IOException {
updateRecord.files.put(fileName, null);
return this;
}

/**
* Rename file gh gist updater.
Expand All @@ -54,13 +76,14 @@ public GHGistUpdater addFile(String fileName, String content) throws IOException
* @throws IOException
* the io exception
*/
public GHGistUpdater renameFile(String fileName, String newFileName) throws IOException {
files.put(fileName, Collections.singletonMap("filename", newFileName));
public GHGistUpdater renameFile(@Nonnull String fileName, @Nonnull String newFileName) throws IOException {
GistFileUpdate file = getGistFileUpdate(fileName);
file.filename = newFileName;
return this;
}

/**
* Update file gh gist updater.
* Update file content
*
* @param fileName
* the file name
Expand All @@ -70,11 +93,43 @@ public GHGistUpdater renameFile(String fileName, String newFileName) throws IOEx
* @throws IOException
* the io exception
*/
public GHGistUpdater updateFile(String fileName, String content) throws IOException {
files.put(fileName, Collections.singletonMap("content", content));
public GHGistUpdater updateFile(@Nonnull String fileName, @Nonnull String content) throws IOException {
GistFileUpdate file = getGistFileUpdate(fileName);
file.content = content;
return this;
}

/**
* Update file name and content
*
* @param fileName
* the file name
* @param newFileName
* the new file name
* @param content
* the content
* @return the gh gist updater
* @throws IOException
* the io exception
*/
public GHGistUpdater updateFile(@Nonnull String fileName, @Nonnull String newFileName, @Nonnull String content)
throws IOException {
GistFileUpdate file = getGistFileUpdate(fileName);
file.filename = newFileName;
file.content = content;
return this;
}

@Nonnull
private GistFileUpdate getGistFileUpdate(@Nonnull String fileName) {
GistFileUpdate file = updateRecord.files.get(fileName);
if (file == null) {
file = new GistFileUpdate();
updateRecord.files.put(fileName, file);
}
return file;
}

/**
* Description gh gist updater.
*
Expand All @@ -83,7 +138,7 @@ public GHGistUpdater updateFile(String fileName, String content) throws IOExcept
* @return the gh gist updater
*/
public GHGistUpdater description(String desc) {
builder.with("description", desc);
updateRecord.description = desc;
return this;
}

Expand All @@ -95,7 +150,6 @@ public GHGistUpdater description(String desc) {
* the io exception
*/
public GHGist update() throws IOException {
builder.with("files", files);
return builder.method("PATCH").withUrlPath(base.getApiTailUrl("")).fetch(GHGist.class);
return builder.method("PATCH").withUrlPath(base.getApiTailUrl("")).withBody(updateRecord).fetch(GHGist.class);
}
}
2 changes: 1 addition & 1 deletion src/main/java/org/kohsuke/github/GHRelease.java
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ public GHAsset uploadAsset(String filename, InputStream stream, String contentTy
// strip the helpful garbage from the url
url = url.substring(0, url.indexOf('{'));
url += "?name=" + URLEncoder.encode(filename, "UTF-8");
return builder.contentType(contentType).with(stream).withUrlPath(url).fetch(GHAsset.class).wrap(this);
return builder.contentType(contentType).withBodyStream(stream).withUrlPath(url).fetch(GHAsset.class).wrap(this);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/kohsuke/github/GitHub.java
Original file line number Diff line number Diff line change
Expand Up @@ -1185,7 +1185,7 @@ public PagedIterable<GHRepository> listAllPublicRepositories(final String since)
public Reader renderMarkdown(String text) throws IOException {
return new InputStreamReader(
createRequest().method("POST")
.with(new ByteArrayInputStream(text.getBytes("UTF-8")))
.withBodyStream(new ByteArrayInputStream(text.getBytes("UTF-8")))
.contentType("text/plain;charset=UTF-8")
.withUrlPath("/markdown/raw")
.fetchStream(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.kohsuke.github;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
Expand Down Expand Up @@ -126,6 +127,7 @@ static HttpURLConnection setupConnection(@Nonnull GitHubClient client, @Nonnull
/**
* Set up the request parameters or POST payload.
*/
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE")
private static void buildRequest(GitHubRequest request, HttpURLConnection connection) throws IOException {
for (Map.Entry<String, String> e : request.headers().entrySet()) {
String v = e.getValue();
Expand All @@ -137,24 +139,28 @@ private static void buildRequest(GitHubRequest request, HttpURLConnection connec
if (request.inBody()) {
connection.setDoOutput(true);

try (InputStream body = request.body()) {
if (body != null) {
Object body = request.body();
if (body instanceof InputStream) {
try (InputStream stream = (InputStream) body) {
connection.setRequestProperty("Content-type",
defaultString(request.contentType(), "application/x-www-form-urlencoded"));
byte[] bytes = new byte[32768];
int read;
while ((read = body.read(bytes)) != -1) {
while ((read = stream.read(bytes)) != -1) {
connection.getOutputStream().write(bytes, 0, read);
}
} else {
connection.setRequestProperty("Content-type",
defaultString(request.contentType(), "application/json"));
}
} else {
connection.setRequestProperty("Content-type",
defaultString(request.contentType(), "application/json"));
if (body == null) {
Map<String, Object> json = new HashMap<>();
for (GitHubRequest.Entry e : request.args()) {
json.put(e.key, e.value);
}
getMappingObjectWriter().writeValue(connection.getOutputStream(), json);
body = json;
}
getMappingObjectWriter().writeValue(connection.getOutputStream(), body);
}
}
}
Expand Down
28 changes: 20 additions & 8 deletions src/main/java/org/kohsuke/github/GitHubRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class GitHubRequest {
private final String apiUrl;
private final String urlPath;
private final String method;
private final InputStream body;
private final Object body;
private final boolean forceBody;

private final URL url;
Expand All @@ -56,7 +56,7 @@ private GitHubRequest(@Nonnull List<Entry> args,
@Nonnull String apiUrl,
@Nonnull String urlPath,
@Nonnull String method,
@CheckForNull InputStream body,
@CheckForNull Object body,
boolean forceBody) throws MalformedURLException {
this.args = Collections.unmodifiableList(new ArrayList<>(args));
this.headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers));
Expand Down Expand Up @@ -182,12 +182,12 @@ public String contentType() {
}

/**
* The {@link InputStream} to be sent as the body of this request.
* The {@link Object} to be sent as the body of this request.
*
* @return the {@link InputStream}.
* @return the {@link Object}.
*/
@CheckForNull
public InputStream body() {
public Object body() {
return body;
}

Expand Down Expand Up @@ -281,7 +281,7 @@ static class Builder<B extends Builder<B>> {
*/
@Nonnull
private String method;
private InputStream body;
private Object body;
private boolean forceBody;

/**
Expand All @@ -304,7 +304,7 @@ private Builder(@Nonnull List<Entry> args,
@Nonnull String apiUrl,
@Nonnull String urlPath,
@Nonnull String method,
@CheckForNull @WillClose InputStream body,
@CheckForNull Object body,
boolean forceBody) {
this.args = new ArrayList<>(args);
this.headers = new LinkedHashMap<>(headers);
Expand Down Expand Up @@ -496,7 +496,19 @@ public B with(String key, Map<?, ?> value) {
* the body
* @return the request builder
*/
public B with(@WillClose /* later */ InputStream body) {
public B withBodyStream(@WillClose /* later */ InputStream body) {
this.body = body;
return (B) this;
}

/**
* With requester.
*
* @param body
* the body
* @return the request builder
*/
public B withBody(Object body) {
this.body = body;
return (B) this;
}
Expand Down
39 changes: 34 additions & 5 deletions src/test/java/org/kohsuke/github/GHGistTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@

import java.io.FileNotFoundException;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;

/**
Expand All @@ -20,10 +19,12 @@ public void lifecycleTest() throws Exception {
.description("Test Gist")
.file("abc.txt", "abc")
.file("def.txt", "def")
.file("ghi.txt", "ghi")
.create();

assertThat(gist.getCreatedAt(), is(notNullValue()));
assertThat(gist.getDescription(), equalTo("Test Gist"));
assertThat(gist.getFiles().size(), equalTo(3));

assertNotNull(gist.getUpdatedAt());
assertNotNull(gist.getCommentsUrl());
Expand All @@ -34,9 +35,37 @@ public void lifecycleTest() throws Exception {

String id = gist.getGistId();

GHGist gistRead = gitHub.getGist(id);
assertThat(gistRead.getGistId(), equalTo(gist.getGistId()));
assertThat(gistRead.getDescription(), equalTo(gist.getDescription()));
GHGist gistUpdate = gitHub.getGist(id);
assertThat(gistUpdate.getGistId(), equalTo(gist.getGistId()));
assertThat(gistUpdate.getDescription(), equalTo(gist.getDescription()));
assertThat(gistUpdate.getFiles().size(), equalTo(3));

gistUpdate = gistUpdate.update().description("Gist Test").addFile("jkl.txt", "jkl").update();

assertThat(gistUpdate.getGistId(), equalTo(gist.getGistId()));
assertThat(gistUpdate.getDescription(), equalTo("Gist Test"));
assertThat(gistUpdate.getFiles().size(), equalTo(4));

gistUpdate = gistUpdate.update()
.renameFile("abc.txt", "ab.txt")
.deleteFile("def.txt")
.updateFile("ghi.txt", "gh")
.updateFile("jkl.txt", "klm.txt", "nop")
.update();

assertThat(gistUpdate.getGistId(), equalTo(gist.getGistId()));
assertThat(gistUpdate.getDescription(), equalTo("Gist Test"));
assertThat(gistUpdate.getFiles().size(), equalTo(3));

// verify delete works
assertThat(gistUpdate.getFile("def.txt"), nullValue());

// verify rename
assertThat(gistUpdate.getFile("ab.txt").getContent(), equalTo("abc"));

// verify updates
assertThat(gistUpdate.getFile("ghi.txt").getContent(), equalTo("gh"));
assertThat(gistUpdate.getFile("klm.txt").getContent(), equalTo("nop"));

try {
gist.getId();
Expand Down
Loading

0 comments on commit eb05ec8

Please sign in to comment.