Skip to content

Commit

Permalink
Add GitHub Action to format Java code on every push and pull request(#68
Browse files Browse the repository at this point in the history
)
  • Loading branch information
dzieciou authored Aug 22, 2021
1 parent 69af0ea commit a0efbd1
Show file tree
Hide file tree
Showing 16 changed files with 600 additions and 549 deletions.
21 changes: 21 additions & 0 deletions .github/workflows/format.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Example workflow
name: Format

on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]

jobs:

formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2 # v2 minimum required
with:
ref: ${{ github.event.pull_request.head.ref }}
- uses: axel-op/googlejavaformat-action@v3
with:
args: "--replace"
132 changes: 72 additions & 60 deletions src/main/java/com/github/dzieciou/testing/curl/CurlCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

package com.github.dzieciou.testing.curl;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
Expand Down Expand Up @@ -117,12 +116,17 @@ public String toString() {
return asString(Platform.RECOGNIZE_AUTOMATICALLY, false, true, true);
}

public String asString(Platform targetPlatform, boolean useShortForm, boolean printMultiliner, boolean escapeNonAscii) {
return new Serializer(targetPlatform, useShortForm, printMultiliner, escapeNonAscii).serialize(this);
public String asString(
Platform targetPlatform,
boolean useShortForm,
boolean printMultiliner,
boolean escapeNonAscii) {
return new Serializer(targetPlatform, useShortForm, printMultiliner, escapeNonAscii)
.serialize(this);
}

public boolean hasData() {
return !datasBinary.isEmpty();
return !datasBinary.isEmpty();
}

public static class Header {
Expand Down Expand Up @@ -201,8 +205,11 @@ private static class Serializer {
SHORT_PARAMETER_NAMES.put("--verbose", "-v");
}


public Serializer(Platform targetPlatform, boolean useShortForm, boolean printMultiliner, boolean escapeNonAscii) {
public Serializer(
Platform targetPlatform,
boolean useShortForm,
boolean printMultiliner,
boolean escapeNonAscii) {
this.targetPlatform = targetPlatform;
this.useShortForm = useShortForm;
this.printMultiliner = printMultiliner;
Expand All @@ -211,14 +218,14 @@ public Serializer(Platform targetPlatform, boolean useShortForm, boolean printMu

private static String parameterName(String longParameterName, boolean useShortForm) {
return useShortForm
? (SHORT_PARAMETER_NAMES.get(longParameterName) == null ? longParameterName
: SHORT_PARAMETER_NAMES
.get(longParameterName))
? (SHORT_PARAMETER_NAMES.get(longParameterName) == null
? longParameterName
: SHORT_PARAMETER_NAMES.get(longParameterName))
: longParameterName;
}

private static List<String> line(boolean useShortForm, String longParameterName,
String... arguments) {
private static List<String> line(
boolean useShortForm, String longParameterName, String... arguments) {
List<String> line = new ArrayList<>(Arrays.asList(arguments));
line.add(0, parameterName(longParameterName, useShortForm));
return line;
Expand All @@ -227,55 +234,56 @@ private static List<String> line(boolean useShortForm, String longParameterName,
/**
* Replace quote by double quote (but not by \") because it is recognized by both cmd.exe and MS
* Crt arguments parser.
* <p>
* Replace % by "%" because it could be expanded to an environment variable value. So %% becomes
* "%""%". Even if an env variable "" (2 doublequotes) is declared, the cmd.exe will not
*
* <p>Replace % by "%" because it could be expanded to an environment variable value. So %%
* becomes "%""%". Even if an env variable "" (2 doublequotes) is declared, the cmd.exe will not
* substitute it with its value.
* <p>
* Replace each backslash with double backslash to make sure MS Crt arguments parser won't
*
* <p>Replace each backslash with double backslash to make sure MS Crt arguments parser won't
* collapse them.
* <p>
* Replace new line outside of quotes since cmd.exe doesn't let to do it inside.
*
* <p>Replace new line outside of quotes since cmd.exe doesn't let to do it inside.
*/
private static String escapeStringWin(String s) {
// Escaping non-printable ASCII characters is limited only to few characters
// Escaping non-ASCII characters is not supported
return "\""
+ s
.replaceAll("\"", "\"\"")
.replaceAll("%", "\"%\"")
.replaceAll("\\\\", "\\\\")
.replaceAll("[\r\n]+", "\"^\r\n$0\"")
+ s.replaceAll("\"", "\"\"")
.replaceAll("%", "\"%\"")
.replaceAll("\\\\", "\\\\")
.replaceAll("[\r\n]+", "\"^\r\n$0\"")
+ "\"";
}

private String escapeStringPosix(String s) {

String escaped = s.chars()
.mapToObj(c -> escape((char) c))
.collect(Collectors.joining());
String escaped = s.chars().mapToObj(c -> escape((char) c)).collect(Collectors.joining());

if (!escaped.equals(s)) {
// ANSI-C Quoting performed
return "$'" + escaped + "'";
} else {
return "'" + escaped + "'";
}

}

private String escape(char c) {
if (isAscii(c)) {
// Perform ANSI-C Quoting for ASCII characters
// https://www.gnu.org/software/bash/manual/html_node/ANSI_002dC-Quoting.html
switch(c) {
case '\n': return "\\n";
case '\'': return "\\'";
case '\t': return "\\t";
case '\r': return "\\r";
// '@' character has a special meaning in --data-binary (loading a file)
// So we need to escape it
case '@': return escapeAsHex(c);
switch (c) {
case '\n':
return "\\n";
case '\'':
return "\\'";
case '\t':
return "\\t";
case '\r':
return "\\r";
// '@' character has a special meaning in --data-binary (loading a file)
// So we need to escape it
case '@':
return escapeAsHex(c);
default:
return isAsciiPrintable(c) ? String.valueOf(c) : escapeAsHex(c);
}
Expand All @@ -297,36 +305,46 @@ private static boolean isAsciiPrintable(char c) {
private static String escapeAsHex(char c) {
int code = c;
if (code < 256) {
return String.format("\\x%02x", (int)c);
return String.format("\\x%02x", (int) c);
}
return String.format("\\u%04x", (int) c);
}

public String serialize(CurlCommand curl) {
List<List<String>> command = new ArrayList<>();

command
.add(line(useShortForm, "curl", quoteString(curl.url).replaceAll("[[{}\\\\]]", "\\$&")));
command.add(
line(useShortForm, "curl", quoteString(curl.url).replaceAll("[[{}\\\\]]", "\\$&")));

curl.method.ifPresent(method -> command.add(line(useShortForm, "--request", method)));

curl.cookieHeader.ifPresent(
cookieHeader -> command.add(line(useShortForm, "--cookie", quoteString(cookieHeader))));

curl.headers.forEach(header
-> command.add(line(useShortForm, "--header",
quoteString(header.getName() + ": " + header.getValue()))));

curl.formParts.forEach(formPart
-> command.add(line(useShortForm, "--form",
quoteString(formPart.getName() + "=" + formPart.getContent()))));

curl.datasBinary
.forEach(data -> command.add(line(useShortForm, "--data-binary", escapeString(data))));

curl.serverAuthentication.ifPresent(sa
-> command
.add(line(useShortForm, "--user", quoteString(sa.getUser() + ":" + sa.getPassword()))));
curl.headers.forEach(
header ->
command.add(
line(
useShortForm,
"--header",
quoteString(header.getName() + ": " + header.getValue()))));

curl.formParts.forEach(
formPart ->
command.add(
line(
useShortForm,
"--form",
quoteString(formPart.getName() + "=" + formPart.getContent()))));

curl.datasBinary.forEach(
data -> command.add(line(useShortForm, "--data-binary", escapeString(data))));

curl.serverAuthentication.ifPresent(
sa ->
command.add(
line(
useShortForm, "--user", quoteString(sa.getUser() + ":" + sa.getPassword()))));

if (curl.compressed) {
command.add(line(useShortForm, "--compressed"));
Expand Down Expand Up @@ -361,17 +379,11 @@ private String quoteString(String s) {
}

private static String quoteStringWin(String s) {
return "\""
+ s
+ "\"";
return "\"" + s + "\"";
}

private static String quoteStringPosix(String s) {
return "'"
+ s
+ "'";
return "'" + s + "'";
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
* Logs each HTTP request as CURL command in "curl" log.
*/
/** Logs each HTTP request as CURL command in "curl" log. */
public class CurlGeneratingInterceptor implements HttpRequestInterceptor {

private static final Logger log = LoggerFactory.getLogger("curl");
Expand Down Expand Up @@ -54,6 +51,4 @@ public void process(HttpRequest request, HttpContext context) throws HttpExcepti
log.warn("Failed to generate CURL command for HTTP request", e);
}
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,4 @@ public interface CurlHandler {
* @param options options used to generate curl.
*/
void handle(String curl, Options options);

}
38 changes: 19 additions & 19 deletions src/main/java/com/github/dzieciou/testing/curl/CurlLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,24 @@ public class CurlLogger implements CurlHandler {

@Override
public void handle(String message, Options options) {
switch (options.logLevel()) {
case DEBUG:
log.debug(message);
break;
case ERROR:
log.error(message);
break;
case INFO:
log.info(message);
break;
case TRACE:
log.trace(message);
break;
case WARN:
log.warn(message);
break;
default:
throw new IllegalArgumentException("Unknown log level: " + options.logLevel());
switch (options.logLevel()) {
case DEBUG:
log.debug(message);
break;
case ERROR:
log.error(message);
break;
case INFO:
log.info(message);
break;
case TRACE:
log.trace(message);
break;
case WARN:
log.warn(message);
break;
default:
throw new IllegalArgumentException("Unknown log level: " + options.logLevel());
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package com.github.dzieciou.testing.curl;


import io.restassured.config.HttpClientConfig;
import io.restassured.config.RestAssuredConfig;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.http.client.HttpClient;
Expand Down Expand Up @@ -91,8 +89,8 @@ public static RestAssuredConfig updateConfig(RestAssuredConfig config, Options o
* @param handlers handlers that can log or process in any other way the generated curl command.
* @return updated configuration; note original configuration remain unchanged.
*/
public static RestAssuredConfig updateConfig(RestAssuredConfig config,
List<CurlHandler> handlers) {
public static RestAssuredConfig updateConfig(
RestAssuredConfig config, List<CurlHandler> handlers) {
return updateConfig(config, getDefaultOptions(), handlers);
}

Expand All @@ -104,13 +102,13 @@ public static RestAssuredConfig updateConfig(RestAssuredConfig config,
* @param handlers handlers that can log or process in any other way the generated curl command.
* @return updated configuration; note original configuration remain unchanged.
*/
public static RestAssuredConfig updateConfig(RestAssuredConfig config, Options options,
List<CurlHandler> handlers) {
public static RestAssuredConfig updateConfig(
RestAssuredConfig config, Options options, List<CurlHandler> handlers) {
HttpClientConfig.HttpClientFactory originalFactory = getHttpClientFactory(config);
CurlGeneratingInterceptor interceptor = new CurlGeneratingInterceptor(options,
handlers);
return config
.httpClient(config.getHttpClientConfig()
CurlGeneratingInterceptor interceptor = new CurlGeneratingInterceptor(options, handlers);
return config.httpClient(
config
.getHttpClientConfig()
.dontReuseHttpClientInstance()
.httpClientFactory(new MyHttpClientFactory(originalFactory, interceptor)));
}
Expand All @@ -133,8 +131,8 @@ private static HttpClientConfig.HttpClientFactory getHttpClientFactory(RestAssur
Field f = HttpClientConfig.class.getDeclaredField("httpClientFactory");
f.setAccessible(true);
HttpClientConfig httpClientConfig = config.getHttpClientConfig();
HttpClientConfig.HttpClientFactory httpClientFactory = (HttpClientConfig.HttpClientFactory) f
.get(httpClientConfig);
HttpClientConfig.HttpClientFactory httpClientFactory =
(HttpClientConfig.HttpClientFactory) f.get(httpClientConfig);
f.setAccessible(false);
return httpClientFactory;
} catch (NoSuchFieldException | IllegalAccessException e) {
Expand All @@ -147,7 +145,8 @@ private static class MyHttpClientFactory implements HttpClientConfig.HttpClientF
private final HttpClientConfig.HttpClientFactory wrappedFactory;
private final CurlGeneratingInterceptor curlGeneratingInterceptor;

public MyHttpClientFactory(HttpClientConfig.HttpClientFactory wrappedFactory,
public MyHttpClientFactory(
HttpClientConfig.HttpClientFactory wrappedFactory,
CurlGeneratingInterceptor curlGeneratingInterceptor) {
this.wrappedFactory = wrappedFactory;
this.curlGeneratingInterceptor = curlGeneratingInterceptor;
Expand All @@ -161,6 +160,4 @@ public HttpClient createHttpClient() {
return client;
}
}


}
Loading

0 comments on commit a0efbd1

Please sign in to comment.