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

Commit info #436

Closed
wants to merge 1 commit into from
Closed

Conversation

LazarenkoDmytro
Copy link
Contributor

@LazarenkoDmytro LazarenkoDmytro commented Jan 4, 2025

#7929

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new /commit-info endpoint to retrieve the latest Git commit information
    • Introduced time zone configuration for Jackson serialization (Europe/Kyiv)
  • Documentation

    • Enhanced error messaging for Git repository and commit information scenarios
  • Chores

    • Updated project dependencies to include Eclipse JGit library
    • Added new constants and data transfer objects to support commit information retrieval

The release introduces a new feature to expose Git commit details through a RESTful API, with comprehensive error handling and testing.

Removed the requirement along with adding more tests to cover more edge cases
Copy link

coderabbitai bot commented Jan 4, 2025

Walkthrough

This pull request introduces a new feature for retrieving Git commit information in the application. A new /commit-info endpoint has been added to expose the latest commit hash and date. The implementation leverages the Eclipse JGit library to fetch commit details, with comprehensive error handling and logging. The changes include creating a new controller, service, DTO, and supporting configuration to enable this functionality across different layers of the application.

Changes

File Change Summary
core/src/main/java/greencity/config/SecurityConfig.java Added /commit-info to permitted request matchers
core/src/main/java/greencity/controller/CommitInfoController.java New REST controller for commit information endpoint
core/src/main/resources/application.properties Added Jackson time zone configuration for Europe/Kyiv
service-api/src/main/java/greencity/constant/AppConstant.java Added DATE_FORMAT constant
service-api/src/main/java/greencity/constant/ErrorMessage.java Added error message constants for Git repository scenarios
service-api/src/main/java/greencity/dto/commitinfo/CommitInfoDto.java New DTO for commit information
service-api/src/main/java/greencity/exception/exceptions/ResourceNotFoundException.java New exception for resource not found scenarios
service-api/src/main/java/greencity/service/CommitInfoService.java New service interface for commit information
service/pom.xml Added JGit library dependency
service/src/main/java/greencity/service/CommitInfoServiceImpl.java Implemented commit information retrieval service

Sequence Diagram

sequenceDiagram
    Client->>CommitInfoController: GET /commit-info
    CommitInfoController->>CommitInfoService: getLatestCommitInfo()
    CommitInfoService->>GitRepository: Retrieve latest commit
    GitRepository-->>CommitInfoService: Return commit details
    CommitInfoService-->>CommitInfoController: Return CommitInfoDto
    CommitInfoController-->>Client: Respond with commit information
Loading

Poem

🐰 A Rabbit's Git Commit Tale 🐰

In lines of code, a story unfolds,
Of commits tracked, both new and old,
A RESTful dance of hash and date,
Where Git's sweet secrets we now relate!

Commit on, brave developers! 🚀


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
service/pom.xml (1)

Update dependencies to their latest stable versions

Based on the verification results, here are the recommended version updates:

  1. spring-boot-starter-mail: Update from 2.2.2.RELEASE to 3.2.2 (matching your Spring Boot version)
  2. commons-fileupload: Update from 1.3 to 1.5
  3. google-http-client-jackson2: Update from 1.38.1 to 1.45.3
  4. awaitility: Update from 3.1.6 to 4.2.2

While no active security vulnerabilities were found through GitHub's advisory database, updating these dependencies is still important for:

  • Maintaining compatibility with Spring Boot 3.x
  • Getting bug fixes and performance improvements
  • Following best practices for dependency management

Note: For spring-boot-starter-mail, use version 3.2.2 to match your Spring Boot version instead of the latest 3.4.1, as mixing Spring Boot versions can lead to compatibility issues.

🔗 Analysis chain

Line range hint 1-165: Update outdated dependencies for security and compatibility

Several dependencies are significantly outdated and should be updated:

  1. spring-boot-starter-mail:2.2.2.RELEASE - This version is from Spring Boot 2.x while the project uses Spring Boot 3.2.2
  2. commons-fileupload:1.3 - Known vulnerabilities exist in this version
  3. google-http-client-jackson2:1.38.1 - Outdated version
  4. awaitility:3.1.6 - Much newer versions available

Please update these dependencies to their latest compatible versions to ensure security and proper integration with Spring Boot 3.2.2.

Let's verify the latest versions and security advisories for these dependencies:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check latest versions and security advisories for outdated dependencies

# Check Maven Central for latest versions
echo "Latest versions from Maven Central:"
for dep in "org.springframework.boot:spring-boot-starter-mail" "commons-fileupload:commons-fileupload" "com.google.http-client:google-http-client-jackson2" "org.awaitility:awaitility"; do
  echo "$dep:"
  curl -s "https://search.maven.org/solrsearch/select?q=g:${dep%:*}+AND+a:${dep#*:}&rows=1&wt=json" | jq -r '.response.docs[].latestVersion'
done

# Check for security advisories
for pkg in "spring-boot-starter-mail" "commons-fileupload" "google-http-client-jackson2" "awaitility"; do
  echo "Security advisories for $pkg:"
  gh api graphql -f query="
  {
    securityVulnerabilities(first: 5, ecosystem: MAVEN, package: \"$pkg\") {
      nodes {
        advisory {
          summary
          severity
          publishedAt
        }
        vulnerableVersionRange
        firstPatchedVersion {
          identifier
        }
      }
    }
  }"
done

Length of output: 4220

🧹 Nitpick comments (13)
service-api/src/main/java/greencity/constant/ErrorMessage.java (2)

61-62: Consider consistent naming and messaging conventions.
Most constants simply describe the scenario without the "WARNING:" prefix. You could align this message to the style of the other error messages by removing the "WARNING:" annotation in the string.

- public static final String WARNING_GIT_DIRECTORY_NOT_FOUND =
-     "WARNING: .git directory not found. Git commit info will be unavailable.";
+ public static final String GIT_DIRECTORY_NOT_FOUND =
+     ".git directory not found. Git commit info will be unavailable.";

65-65: Remove trailing colon or provide placeholder for exception details.
The message currently ends with a colon, implying further details would be appended. Consider removing it or appending a placeholder (e.g., %s) if more context is provided later.

- public static final String FAILED_TO_FETCH_COMMIT_INFO = "Failed to fetch commit info due to I/O error: ";
+ public static final String FAILED_TO_FETCH_COMMIT_INFO = "Failed to fetch commit info due to I/O error";
service-api/src/main/java/greencity/exception/exceptions/ResourceNotFoundException.java (1)

7-9: Consider adding a serialVersionUID.
Since this class extends RuntimeException (which implements Serializable), including a serialVersionUID is often recommended to avoid potential InvalidClassException issues when deserializing in certain environments. It’s optional but considered best practice for custom exceptions.

 @StandardException
 @ResponseStatus(HttpStatus.NOT_FOUND)
-public class ResourceNotFoundException extends RuntimeException {
+public class ResourceNotFoundException extends RuntimeException {
+    private static final long serialVersionUID = 1L;
 }
service-api/src/main/java/greencity/service/CommitInfoService.java (1)

8-15: Document potential exceptions thrown.
Although this interface is straightforward, consider indicating that an implementation may throw ResourceNotFoundException if the repository cannot be accessed or found. This improves clarity for API consumers and maintainers.

service-api/src/main/java/greencity/dto/commitinfo/CommitInfoDto.java (1)

12-21: Use explicit validation messages for @NotNull.
Providing custom messages for the @NotNull annotations can help clients and maintainers quickly identify which field is invalid. For example:

 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 @EqualsAndHashCode
 public class CommitInfoDto {
-    @NotNull
+    @NotNull(message = "Commit hash must not be null")
     private String commitHash;
-    @NotNull
+    @NotNull(message = "Commit date must not be null")
     private String commitDate;
 }
service-api/src/main/java/greencity/constant/AppConstant.java (1)

8-8: Consider using ISO 8601 format for better interoperability.
While "dd/MM/yyyy HH:mm:ss" may be satisfactory for some use cases, the ISO 8601 date format ("yyyy-MM-dd'T'HH:mm:ss'Z'") is more conventional for services that may interact globally.

service/src/main/java/greencity/service/CommitInfoServiceImpl.java (3)

28-39: Handle repository initialization failure more gracefully.
When the FileRepositoryBuilder fails to locate .git, the repository is set to null and a log warning is recorded. This choice is acceptable, but consider providing a more descriptive log or fallback strategy, such as prompting for configuration or referencing environment variables.


45-48: Validate the repository state earlier.
You are throwing ResourceNotFoundException only in getLatestCommitInfo(). Consider an additional check after the repository is constructed to fail fast if no valid .git directory is found, avoiding postponed errors at runtime.


50-60: Employ more specific exception handling.
Both repository resolution and commit parsing trigger a ResourceNotFoundException. If it’s important to differentiate between initialization failures vs. commit resolution errors, consider leveraging different exception messages or dedicated exception types to help pinpoint root causes.

core/src/main/java/greencity/controller/CommitInfoController.java (2)

19-20: Controller endpoint organization best practice.
It is common to prefix all endpoints with a version (e.g. /api/v1/commit-info) to help manage future backward incompatibilities.


59-60: Return a descriptive response entity.
Optionally, you can include additional information or standard success messages in your response body or headers, though returning just the DTO is also valid.

core/src/test/java/greencity/controller/CommitInfoControllerTest.java (1)

56-64: Verify 404 error response structure.
While you confirm the status code, verifying the response content could provide a more robust test, ensuring the error message remains consistent with expected behavior.

service/src/test/java/greencity/service/CommitInfoServiceImplTest.java (1)

77-92: Test the logged warning.
Consider verifying whether a warning log is emitted (using a mock logging framework) when .git is absent and an IOException is thrown. This ensures consistent feedback to developers/operators.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1272149 and 5c51df9.

📒 Files selected for processing (13)
  • core/src/main/java/greencity/config/SecurityConfig.java (2 hunks)
  • core/src/main/java/greencity/controller/CommitInfoController.java (1 hunks)
  • core/src/main/resources/application.properties (1 hunks)
  • core/src/test/java/greencity/controller/CommitInfoControllerTest.java (1 hunks)
  • pom.xml (1 hunks)
  • service-api/src/main/java/greencity/constant/AppConstant.java (1 hunks)
  • service-api/src/main/java/greencity/constant/ErrorMessage.java (1 hunks)
  • service-api/src/main/java/greencity/dto/commitinfo/CommitInfoDto.java (1 hunks)
  • service-api/src/main/java/greencity/exception/exceptions/ResourceNotFoundException.java (1 hunks)
  • service-api/src/main/java/greencity/service/CommitInfoService.java (1 hunks)
  • service/pom.xml (1 hunks)
  • service/src/main/java/greencity/service/CommitInfoServiceImpl.java (1 hunks)
  • service/src/test/java/greencity/service/CommitInfoServiceImplTest.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • core/src/main/resources/application.properties
🔇 Additional comments (11)
service-api/src/main/java/greencity/constant/ErrorMessage.java (1)

63-64: No issues found.
The naming convention for this constant is clear and follows the existing patterns.

core/src/main/java/greencity/controller/CommitInfoController.java (1)

30-56: OpenAPI/Swagger annotations are well-applied.
The use of @Operation and @ApiResponse annotations provides a clear and detailed API specification. Keep it up!

core/src/test/java/greencity/controller/CommitInfoControllerTest.java (1)

44-55: Good test coverage for the success scenario.
It thoroughly verifies the JSON structure. Checks for each field are accurate and well-aligned with the service’s contract.

service/src/test/java/greencity/service/CommitInfoServiceImplTest.java (4)

60-75: Commendable approach to mocking the FileRepositoryBuilder.
Using mockConstruction is a good way to verify the builder logic without polluting other tests. The test clearly distinguishes success vs. failure.


95-107: Accurate error message validation.
Verifying that the thrown ResourceNotFoundException includes the correct message improves maintainability and clarity, ensuring that changing error messages intentionally breaks the test.


109-130: Great coverage of date/format consistency.
The test ensures that the commit date is formatted properly. Maintaining these tests will help detect regressions if the format changes inadvertently.


132-158: Robust negative path checks.
Testing IOException scenarios (from repository.resolve and revWalk.parseCommit) ensures reliable error handling. This improves resiliency of the commit info fetching mechanism.

core/src/main/java/greencity/config/SecurityConfig.java (2)

55-55: Constant name is descriptive and consistent.
No issues found with naming convention or usage so far.


123-124: Ensure no sensitive data is exposed by /commit-info.
Allowing unrestricted public access to commit metadata could reveal sensitive information (e.g., commit hashes or branch references). Verify that this endpoint doesn’t leak details unintended for general users.

Below is a script to locate all references to COMMIT_INFO in the codebase. Ensure that usage is limited to safe exposures:

✅ Verification successful

Let me gather more information about the implementation of the commit info service and controller to understand what information is being exposed.


Let me try a different approach using ripgrep to find the implementations.


Let me check one more thing to see the complete endpoint implementation and the DTO structure.


The /commit-info endpoint exposes limited, non-sensitive metadata

Based on the implementation review:

  • The endpoint only returns basic commit metadata (hash and date)
  • The service uses the local .git directory to fetch only the latest commit information
  • The exposed data is already publicly available to anyone with repository access
  • No sensitive information like branch names, commit messages, or file changes is exposed

The current implementation appears to be safe as it:

  1. Only exposes the commit hash and date of the HEAD commit
  2. Uses proper error handling for failed Git operations
  3. Has a well-defined DTO that limits the exposed fields
  4. Is properly documented with OpenAPI annotations

The original security concern about sensitive data exposure is not warranted in this case, as the implementation follows secure practices and only exposes non-sensitive metadata that is typically public in nature.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching references to COMMIT_INFO
rg -A 3 'COMMIT_INFO'

Length of output: 3795


Script:

#!/bin/bash
# Find CommitInfoController implementation
ast-grep --pattern 'class CommitInfoController {
  $$$
}'

# Find CommitInfoService interface and implementation
ast-grep --pattern 'interface CommitInfoService {
  $$$
}'

ast-grep --pattern 'class CommitInfoServiceImpl $_ {
  $$$
}'

Length of output: 184


Script:

#!/bin/bash
# Search for CommitInfo related implementations
rg -A 10 "class CommitInfoController"
rg -A 10 "class CommitInfoServiceImpl"
rg -A 10 "interface CommitInfoService"

# Also search for the actual endpoint implementation
rg -A 10 "@GetMapping.*commit-info"

Length of output: 5040


Script:

#!/bin/bash
# Find the complete CommitInfoController endpoint implementation
rg -A 15 '@Operation\(summary = "Get the latest commit hash and date."\)'

# Find CommitInfoDto structure
rg -A 10 'class CommitInfoDto'

Length of output: 2308

pom.xml (1)

40-40: Consider simplifying the JGit version number

The current timestamp-based version 7.1.0.202411261347-r could be simplified to 7.1.0 for better maintainability while still ensuring compatibility with Java 21 and Spring Boot 3.2.2.

Let's verify the latest stable version and any security advisories:

service/pom.xml (1)

161-165: LGTM! JGit dependency is correctly configured.

The dependency is properly added with the version reference from the parent POM.

@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class CommitInfoDto {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe use 'record' in this case?

@LazarenkoDmytro LazarenkoDmytro deleted the feature/7929/commit-info-endpoint branch January 9, 2025 11:12
@LazarenkoDmytro LazarenkoDmytro restored the feature/7929/commit-info-endpoint branch January 30, 2025 09:28
@LazarenkoDmytro
Copy link
Contributor Author

LazarenkoDmytro commented Jan 30, 2025

NOT THE ACTUAL PR: CHECK #441

@LazarenkoDmytro LazarenkoDmytro deleted the feature/7929/commit-info-endpoint branch January 30, 2025 09:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants