Skip to content
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

Feature/7929/git info endpoint #7937

Merged
merged 15 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
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
1 change: 1 addition & 0 deletions core/src/main/java/greencity/constant/HttpStatuses.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ public class HttpStatuses {
public static final String NOT_FOUND = "Not Found";
public static final String SEE_OTHER = "See Other";
public static final String FOUND = "Found";
public static final String INTERNAL_SERVER_ERROR = "Internal Server Error";
}
61 changes: 61 additions & 0 deletions core/src/main/java/greencity/controller/CommitInfoController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package greencity.controller;

import greencity.constant.HttpStatuses;
import greencity.dto.commitinfo.CommitInfoDto;
import greencity.dto.commitinfo.CommitInfoErrorDto;
import greencity.service.CommitInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Controller for fetching Git commit information.
*/
@RestController
@RequestMapping("/commit-info")
@RequiredArgsConstructor
public class CommitInfoController {
private final CommitInfoService commitInfoService;

/**
* Endpoint to fetch the latest Git commit hash and date.
*
* @return {@link CommitInfoDto}, either success or error
*/
@Operation(summary = "Get the latest commit hash and date.")
@ApiResponse(
responseCode = "200",
description = HttpStatuses.OK,
content = @Content(
mediaType = "application/json",
examples = @ExampleObject(
value = """
{
"commitHash": "d6e70c46b39857846f3f13ca9756c39448ab3d6f",
"commitDate": "16/12/2024 10:55:00"
}""")))
@ApiResponse(
responseCode = "500",
description = HttpStatuses.INTERNAL_SERVER_ERROR,
content = @Content(
mediaType = "application/json",
examples = @ExampleObject(
value = """
{
"error": "Failed to fetch commit info: Repository not found"
}""")))
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
@GetMapping
public ResponseEntity<CommitInfoDto> getCommitInfo() {
CommitInfoDto commitInfo = commitInfoService.getLatestCommitInfo();
if (commitInfo instanceof CommitInfoErrorDto) {
KizerovDmitriy marked this conversation as resolved.
Show resolved Hide resolved
return ResponseEntity.internalServerError().body(commitInfo);
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
}
return ResponseEntity.ok(commitInfo);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package greencity.controller;

import greencity.dto.commitinfo.CommitInfoDto;
import greencity.dto.commitinfo.CommitInfoErrorDto;
import greencity.dto.commitinfo.CommitInfoSuccessDto;
import greencity.service.CommitInfoService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@ExtendWith(MockitoExtension.class)
class CommitInfoControllerTest {
@InjectMocks
private CommitInfoController commitInfoController;

@Mock
private CommitInfoService commitInfoService;

private MockMvc mockMvc;

@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(commitInfoController).build();
}

private static final String COMMIT_INFO_URL = "/commit-info";
private static final String COMMIT_HASH = "abc123";
private static final String COMMIT_DATE = "16/12/2024 12:06:32";
private static final String ERROR_MESSAGE = "Failed to fetch commit info due to I/O error: Missing object";

@Test
void getCommitInfoReturnsSuccessTest() throws Exception {
CommitInfoDto commitInfoDto = new CommitInfoSuccessDto(COMMIT_HASH, COMMIT_DATE);
when(commitInfoService.getLatestCommitInfo()).thenReturn(commitInfoDto);

mockMvc.perform(get(COMMIT_INFO_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.commitHash").value(COMMIT_HASH))
.andExpect(jsonPath("$.commitDate").value(COMMIT_DATE));

verify(commitInfoService, times(1)).getLatestCommitInfo();
}

@Test
void getCommitInfoReturnsErrorTest() throws Exception {
CommitInfoDto commitInfoDto = new CommitInfoErrorDto(ERROR_MESSAGE);
when(commitInfoService.getLatestCommitInfo()).thenReturn(commitInfoDto);

mockMvc.perform(get(COMMIT_INFO_URL).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isInternalServerError())
.andExpect(jsonPath("$.error").value(ERROR_MESSAGE));

verify(commitInfoService, times(1)).getLatestCommitInfo();
}
}
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
<jjwt.version>0.12.3</jjwt.version>
<commons.collections4.version>4.4</commons.collections4.version>
<commons.lang3.version>3.13.0</commons.lang3.version>
<org.eclipse.jgit.version>7.1.0.202411261347-r</org.eclipse.jgit.version>
</properties>

<profiles>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package greencity.dto.commitinfo;

import lombok.Data;
import lombok.NoArgsConstructor;

/**
* Base class for commit information DTO.
*/
@Data
@NoArgsConstructor
public abstract class CommitInfoDto {
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
}
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package greencity.dto.commitinfo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
* DTO for error response.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
public class CommitInfoErrorDto extends CommitInfoDto {
private String error;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package greencity.dto.commitinfo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

/**
* DTO for successful commit information response.
*/
@EqualsAndHashCode(callSuper = true)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommitInfoSuccessDto extends CommitInfoDto {
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
private String commitHash;
private String commitDate;
}
15 changes: 15 additions & 0 deletions service-api/src/main/java/greencity/service/CommitInfoService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package greencity.service;

import greencity.dto.commitinfo.CommitInfoDto;

/**
* Interface for fetching Git commit information.
*/
public interface CommitInfoService {
/**
* Fetches the latest Git commit hash and date.
*
* @return {@link CommitInfoDto}, either success or error
*/
CommitInfoDto getLatestCommitInfo();
}
5 changes: 5 additions & 0 deletions service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -123,5 +123,10 @@
<artifactId>commons-collections4</artifactId>
<version>${commons.collections4.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>${org.eclipse.jgit.version}</version>
</dependency>
</dependencies>
</project>
55 changes: 55 additions & 0 deletions service/src/main/java/greencity/service/CommitInfoServiceImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package greencity.service;

import greencity.constant.AppConstant;
import greencity.dto.commitinfo.CommitInfoDto;
import greencity.dto.commitinfo.CommitInfoErrorDto;
import greencity.dto.commitinfo.CommitInfoSuccessDto;
import jakarta.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.springframework.stereotype.Service;

/**
* Service implementation for fetching Git commit information.
*/
@Service
public class CommitInfoServiceImpl implements CommitInfoService {
private Repository repository;

@PostConstruct
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
private void init() {
try {
repository = new FileRepositoryBuilder()
.setGitDir(new File(".git"))
.readEnvironment()
.findGitDir()
.build();
} catch (IOException e) {
throw new IllegalStateException("Failed to initialize repository", e);
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
}
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* {@inheritDoc}
*/
@Override
public CommitInfoDto getLatestCommitInfo() {
try (RevWalk revWalk = new RevWalk(repository)) {
RevCommit latestCommit = revWalk.parseCommit(repository.resolve("HEAD"));
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
String latestCommitHash = latestCommit.name();
String latestCommitDate = DateTimeFormatter.ofPattern(AppConstant.DATE_FORMAT)
.withZone(ZoneId.of(AppConstant.UKRAINE_TIMEZONE))
.format(latestCommit.getAuthorIdent().getWhenAsInstant());

return new CommitInfoSuccessDto(latestCommitHash, latestCommitDate);
} catch (IOException e) {
return new CommitInfoErrorDto("Failed to fetch commit info due to I/O error: " + e.getMessage());
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
}
LazarenkoDmytro marked this conversation as resolved.
Show resolved Hide resolved
}
}
Loading
Loading