Skip to content

Update GitCheck to include error handling and move to java 17. #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 18 additions & 20 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
plugins {
`java-library`
`maven-publish`
id("com.github.johnrengelman.shadow") version "8.1.0"
}

group = "com.eternalcode"
Expand All @@ -11,51 +10,50 @@ val artifactId = "gitcheck"
java {
withJavadocJar()
withSourcesJar()

sourceCompatibility = JavaVersion.VERSION_1_9
targetCompatibility = JavaVersion.VERSION_1_9
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}

repositories {
mavenCentral()
}

dependencies {
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
api("com.googlecode.json-simple:json-simple:1.1.1") {
exclude(group = "junit")
}

api("org.jetbrains:annotations:24.0.1")
api("org.jetbrains:annotations:26.0.2")

testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.2")
testImplementation("nl.jqno.equalsverifier:equalsverifier:3.14.1")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
}

publishing {
publications {
create<MavenPublication>("maven") {
groupId = "$group"
artifactId = artifactId
version = "${project.version}"

from(components["java"])
}
}
repositories {
mavenLocal()

maven {
name = "eternalcode-repository"
url = uri("https://repo.eternalcode.pl/releases")

if (version.toString().endsWith("-SNAPSHOT")) {
url = uri("https://repo.eternalcode.pl/snapshots")
}

credentials {
username = System.getenv("ETERNALCODE_REPO_USERNAME")
password = System.getenv("ETERNALCODE_REPO_PASSWORD")
username = System.getenv("ETERNAL_CODE_MAVEN_USERNAME")
password = System.getenv("ETERNAL_CODE_MAVEN_PASSWORD")
}
}
}

publications {
create<MavenPublication>("maven") {
from(components["java"])
}
}
}

tasks.getByName<Test>("test") {
tasks.test {
useJUnitPlatform()
}
4 changes: 4 additions & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
org.gradle.configuration-cache=true
org.gradle.caching=true
org.gradle.parallel=true
org.gradle.vfs.watch=false
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
135 changes: 123 additions & 12 deletions src/main/java/com/eternalcode/gitcheck/GitCheck.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,11 @@

/**
* Service for checking if the latest release is up to date.
* <p>
* This service uses {@link GitReleaseProvider} to get the latest release and compares it with the current tag.
* The current tag is provided by {@link GitTag#of(String)}
* <br>
*/
public class GitCheck {

private final GitReleaseProvider versionProvider;
private GitCheckErrorHandler errorHandler;

/**
* Creates a new instance of {@link GitCheck} with the default {@link GitHubReleaseProvider}.
Expand All @@ -34,25 +31,92 @@ public GitCheck() {
public GitCheck(@NotNull GitReleaseProvider versionProvider) {
Preconditions.notNull(versionProvider, "release provider");
this.versionProvider = versionProvider;
this.errorHandler = GitCheckErrorHandler.noOp();
}

/**
* Sets the error handler for this GitCheck instance.
*
* @param errorHandler the error handler
* @return this instance for method chaining
*/
@NotNull
public GitCheck onError(@NotNull GitCheckErrorHandler errorHandler) {
Preconditions.notNull(errorHandler, "error handler");
this.errorHandler = errorHandler;
return this;
}

/**
* Sets error handler for specific status codes.
*
* @param statusCode the status code to handle
* @param handler the handler for this status code
* @return this instance for method chaining
*/
@NotNull
public GitCheck onStatusCode(int statusCode, @NotNull GitCheckErrorHandler handler) {
Preconditions.notNull(handler, "handler");

GitCheckErrorHandler previousHandler = this.errorHandler;
this.errorHandler = error -> {
if (error.hasStatusCode() && error.getStatusCode() == statusCode) {
handler.handle(error);
}
else {
previousHandler.handle(error);
}
};
return this;
}

/**
* Sets error handler for specific error types.
*
* @param errorType the error type to handle
* @param handler the handler for this error type
* @return this instance for method chaining
*/
@NotNull
public GitCheck onErrorType(@NotNull GitCheckErrorType errorType, @NotNull GitCheckErrorHandler handler) {
Preconditions.notNull(errorType, "error type");
Preconditions.notNull(handler, "handler");

GitCheckErrorHandler previousHandler = this.errorHandler;
this.errorHandler = error -> {
if (error.getType() == errorType) {
handler.handle(error);
}
else {
previousHandler.handle(error);
}
};
return this;
}

/**
* Gets the latest release for the given repository.
*
* @param repository the repository
* @return the latest release
* @return the latest release, or null if error occurred
*/
@NotNull
public GitRelease getLatestRelease(@NotNull GitRepository repository) {
public GitCheckResult getLatestRelease(@NotNull GitRepository repository) {
Preconditions.notNull(repository, "repository");

return this.versionProvider.getLatestRelease(repository);
try {
GitRelease release = this.versionProvider.getLatestRelease(repository);
return GitCheckResult.success(release, GitTag.of("unknown"));
}
catch (Exception exception) {
GitCheckError error = mapExceptionToError(exception);
this.errorHandler.handle(error);
return GitCheckResult.failure(error);
}
}

/**
* Creates a new instance of {@link GitCheckResult} for the given repository and tag.
* Result contains the latest release and the current tag.
* Use {@link GitCheckResult#isUpToDate()} to check if the latest release is up to date.
*
* @param repository the repository
* @param currentTag the current tag
Expand All @@ -63,8 +127,55 @@ public GitCheckResult checkRelease(@NotNull GitRepository repository, @NotNull G
Preconditions.notNull(repository, "repository");
Preconditions.notNull(currentTag, "current tag");

GitRelease latestRelease = this.getLatestRelease(repository);
return new GitCheckResult(latestRelease, currentTag);
try {
GitRelease latestRelease = this.versionProvider.getLatestRelease(repository);
return GitCheckResult.success(latestRelease, currentTag);
}
catch (Exception exception) {
GitCheckError error = mapExceptionToError(exception);
this.errorHandler.handle(error);
return GitCheckResult.failure(error);
}
}

}
private GitCheckError mapExceptionToError(Exception exception) {
String message = exception.getMessage();

if (message.contains("404")) {
if (message.contains("repository")) {
return new GitCheckError(GitCheckErrorType.REPOSITORY_NOT_FOUND, message, 404, exception);
}
else {
return new GitCheckError(GitCheckErrorType.RELEASE_NOT_FOUND, message, 404, exception);
}
}

if (message.contains("403")) {
return new GitCheckError(GitCheckErrorType.RATE_LIMIT_EXCEEDED, message, 403, exception);
}

if (message.contains("401")) {
return new GitCheckError(GitCheckErrorType.AUTHENTICATION_REQUIRED, message, 401, exception);
}

if (message.contains("Unexpected response code")) {
try {
int statusCode = Integer.parseInt(message.replaceAll(".*: (\\d+).*", "$1"));
return new GitCheckError(GitCheckErrorType.HTTP_ERROR, message, statusCode, exception);
}
catch (NumberFormatException e) {
return new GitCheckError(GitCheckErrorType.HTTP_ERROR, message, exception);
}
}

if (message.contains("Invalid JSON") || message.contains("not a JSON object")) {
return new GitCheckError(GitCheckErrorType.INVALID_RESPONSE, message, exception);
}

if (exception instanceof java.io.IOException) {
return new GitCheckError(GitCheckErrorType.NETWORK_ERROR, message, exception);
}

return new GitCheckError(GitCheckErrorType.UNKNOWN, message, exception);
}
}
67 changes: 67 additions & 0 deletions src/main/java/com/eternalcode/gitcheck/GitCheckError.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.eternalcode.gitcheck;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* Represents an error that occurred during git check operation.
*/
public class GitCheckError {

private final GitCheckErrorType type;
private final String message;
private final int statusCode;
private final Throwable cause;

public GitCheckError(
@NotNull GitCheckErrorType type,
@NotNull String message,
int statusCode,
@Nullable Throwable cause
) {
this.type = type;
this.message = message;
this.statusCode = statusCode;
this.cause = cause;
}

public GitCheckError(@NotNull GitCheckErrorType type, @NotNull String message, @Nullable Throwable cause) {
this(type, message, -1, cause);
}

public GitCheckError(@NotNull GitCheckErrorType type, @NotNull String message) {
this(type, message, -1, null);
}

@NotNull
public GitCheckErrorType getType() {
return type;
}

@NotNull
public String getMessage() {
return message;
}

public int getStatusCode() {
return statusCode;
}

@Nullable
public Throwable getCause() {
return cause;
}

public boolean hasStatusCode() {
return statusCode != -1;
}

@Override
public String toString() {
return "GitCheckError{" +
"type=" + type +
", message='" + message + '\'' +
(hasStatusCode() ? ", statusCode=" + statusCode : "") +
'}';
}
}
46 changes: 46 additions & 0 deletions src/main/java/com/eternalcode/gitcheck/GitCheckErrorHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.eternalcode.gitcheck;

import org.jetbrains.annotations.NotNull;

/**
* Interface for handling git check errors.
*/
@FunctionalInterface
public interface GitCheckErrorHandler {

/**
* Creates a no-op error handler.
*
* @return no-op error handler
*/
@NotNull
static GitCheckErrorHandler noOp() {
return error -> {};
}
/**
* Creates an error handler that prints to console.
*
* @return console error handler
*/
@NotNull
static GitCheckErrorHandler console() {
return error -> System.err.println("GitCheck Error: " + error);
}
/**
* Creates an error handler that throws exceptions.
*
* @return throwing error handler
*/
@NotNull
static GitCheckErrorHandler throwing() {
return error -> {
throw new GitCheckException(error.getMessage(), error.getCause());
};
}
/**
* Handles the error.
*
* @param error the error to handle
*/
void handle(@NotNull GitCheckError error);
}
Loading
Loading