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

chore: Converging git refactor changes #33971

Merged
merged 11 commits into from
Jun 4, 2024
Merged

chore: Converging git refactor changes #33971

merged 11 commits into from
Jun 4, 2024

Conversation

nidhi-nair
Copy link
Contributor

@nidhi-nair nidhi-nair commented Jun 4, 2024

Description

Tip

Add a TL;DR when the description is longer than 500 words or extremely technical (helps the content, marketing, and DevRel team).

Please also include relevant motivation and context. List any dependencies that are required for this change. Add links to Notion, Figma or any other documents that might be relevant to the PR.

Fixes #Issue Number
or
Fixes Issue URL

Warning

If no issue exists, please create an issue first, and check with the maintainers if the issue is valid.

Automation

/ok-to-test tags="@tag.All"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/9369921327
Commit: 4bb1a86
Cypress dashboard url: Click here!

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Enhanced Git integration with improved artifact handling.
    • Introduced new methods for artifact management, including import and deletion.
  • Refactor

    • Updated references from DefaultApplicationId to DefaultArtifactId for better clarity and functionality.
    • Replaced GitService with CommonGitService across multiple components for unified Git operations.
    • Simplified constructor dependencies in various utility classes.
  • Bug Fixes

    • Fixed inconsistencies in Git metadata handling related to SSH key generation and artifact management.
  • Chores

    • Improved import statements and method signatures for better code maintainability.

@nidhi-nair nidhi-nair requested a review from a team as a code owner June 4, 2024 14:31
@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Jun 4, 2024
@nidhi-nair nidhi-nair added ok-to-test Required label for CI and removed skip-changelog Adding this label to a PR prevents it from being listed in the changelog labels Jun 4, 2024
@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Jun 4, 2024
Copy link
Contributor

coderabbitai bot commented Jun 4, 2024

Walkthrough

The recent updates involve significant refactoring and enhancements to the Appsmith server's Git integration. Key changes include transitioning from DefaultApplicationId to DefaultArtifactId for Git metadata handling, renaming and restructuring services and utilities related to Git operations, and introducing new methods for artifact management. This refactoring aims to streamline Git operations, improve code clarity, and support more granular artifact management.

Changes

File(s) Change Summary
app/server/.run/ServerApplication.run.xml Adjusted Make option within the configuration.
.../ApplicationServiceCEImpl.java, .../ApplicationImportServiceCEImpl.java Updated references from gitData.getDefaultApplicationId() to gitData.getDefaultArtifactId().
.../GitApplicationHelperCEImpl.java Added imports, renamed variables, modified method signatures, and added new methods for artifact management.
.../GitController.java, .../GitControllerCE.java Refactored to use CommonGitService instead of GitService and introduced ArtifactType.
.../Application.java Added a new public constant gitApplicationMetadata_defaultArtifactId.
.../Context.java Added getArtifactId() method and specified return type for getLayout().
.../GitArtifactMetadata.java Modified methods to use defaultArtifactId instead of defaultApplicationId.
.../NewPage.java Added getArtifactId() and getLayout() methods.
.../GlobalExceptionHandler.java Changed import and renamed field to commonGitFileUtils.
.../AutoCommitEventHandlerCEImpl.java, .../AutoCommitEventHandlerImpl.java Replaced GitFileUtils with CommonGitFileUtils.
.../GitAutoCommitHelperImpl.java Changed import statement for CommonGitService.
.../CommonGitService.java, .../CommonGitServiceCE.java, .../CommonGitServiceCECompatible.java, .../CommonGitServiceCECompatibleImpl.java, .../CommonGitServiceCEImpl.java, .../CommonGitServiceImpl.java Introduced new interfaces and refactored existing ones for better Git service management.
.../CommonGitFileUtils.java, .../CommonGitFileUtilsCE.java Removed Gson dependency and simplified constructors.
.../GitUtils.java, .../ResponseUtilsCE.java Updated methods to use metadata.getDefaultArtifactId() instead of metadata.getDefaultApplicationId().
.../ApplicationControllerTest.java, .../GitFileUtilsTest.java, .../UserDataServiceTest.java Replaced references to GitService with CommonGitService.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant GitController
    participant CommonGitService
    participant ApplicationServiceCEImpl
    participant GitApplicationHelperCEImpl

    User->>GitController: Request Git metadata
    GitController->>CommonGitService: getGitMetadata(defaultArtifactId)
    CommonGitService->>ApplicationServiceCEImpl: fetchGitMetadata(defaultArtifactId)
    ApplicationServiceCEImpl->>CommonGitService: Return Git metadata
    CommonGitService->>GitController: Return Git metadata
    GitController->>User: Send Git metadata

    User->>GitController: Connect to remote repo
    GitController->>CommonGitService: connectApplicationToRemoteRepo(artifact)
    CommonGitService->>GitApplicationHelperCEImpl: connectToRemoteRepo(artifact)
    GitApplicationHelperCEImpl->>CommonGitService: Return connection status
    CommonGitService->>GitController: Return connection status
    GitController->>User: Send connection status
Loading

Poem

In the realm of code so bright,
Artifacts now take their flight,
From DefaultApp to ArtifactId,
Git's new path we did decide.
With services common and refactored true,
Our Git is sharper, sleek, and new.
Celebrate the changes, big and small,
For in this code, we stand tall! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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
Contributor

@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: 9

Outside diff range and nitpick comments (3)
app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitArtifactMetadata.java (1)

120-122: Consider adding a comment explaining why both defaultApplicationId and defaultArtifactId are set to the same value, to clarify the intent for future maintainers.

app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitEventHandlerImplTest.java (1)

317-318: Consider adding detailed logging for operations in saveArtifactToLocalRepo to facilitate debugging and monitoring.

It would be beneficial to include logging statements before and after significant operations within this method to help trace the flow of data and identify potential issues more quickly.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java (1)

134-138: Consider adding JavaDoc comments to the constructor to explain the purpose of each injected dependency. This can improve code readability and maintainability, especially for new developers or external contributors who might work on this codebase.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 05690f8 and ca6d066.

Files selected for processing (35)
  • app/server/.run/ServerApplication.run.xml (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java (5 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/applications/git/GitApplicationHelperCEImpl.java (5 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/applications/imports/ApplicationImportServiceCEImpl.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java (21 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Context.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitArtifactMetadata.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewPage.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/AutoCommitEventHandlerCEImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/AutoCommitEventHandlerImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImpl.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitService.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCE.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCECompatible.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCECompatibleImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java (21 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CommonGitFileUtils.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/CommonGitFileUtilsCE.java (2 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ResponseUtilsCE.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/newpages/importable/NewPageImportableServiceCEImpl.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomApplicationRepositoryCEImpl.java (1 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java (3 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java (5 hunks)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitArtifactHelperCE.java (2 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java (2 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/ApplicationPageServiceAutoCommitTest.java (1 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitEventHandlerImplTest.java (7 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java (1 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java (6 hunks)
  • app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java (7 hunks)
Files skipped from review due to trivial changes (6)
  • app/server/.run/ServerApplication.run.xml
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/AutoCommitEventHandlerImpl.java
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitService.java
  • app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCECompatible.java
  • app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/CommonGitFileUtils.java
  • app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/CommonGitFileUtilsCE.java
Additional comments not posted (47)
app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Context.java (2)

7-7: The addition of getArtifactId method is appropriate for handling Git metadata more accurately.


9-9: The getLayout method remains consistent and unchanged, which is appropriate.

app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/GitController.java (1)

15-15: The change to use CommonGitService in the constructor aligns with the broader refactoring effort to unify Git service interfaces, enhancing maintainability.

app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitArtifactHelperCE.java (4)

61-61: The addition of publishArtifact with a publishedManually parameter is a valuable enhancement, supporting both manual and automated artifact publishing processes.


63-63: The addition of createArtifactForImport enhances the Git integration by facilitating the creation of artifacts directly from import processes.


65-65: The addition of deleteArtifact method provides a necessary functionality for managing artifact lifecycle events in a Git-based environment.


67-67: The addition of isContextInArtifactEmpty is a prudent check to ensure operations depending on the context state within an artifact are valid, helping to avoid errors.

app/server/appsmith-server/src/main/java/com/appsmith/server/domains/NewPage.java (2)

46-46: The implementation of getArtifactId returning applicationId is appropriate, effectively tying the artifact directly to an application context.


52-54: The implementation of getLayout to fetch the first layout from unpublishedPage is logical, providing a default or primary layout view.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCECompatibleImpl.java (1)

Line range hint 43-67: The addition of new service dependencies in the constructor, including WorkspaceService, DatasourceService, DatasourcePermission, and PluginService, suggests a thoughtful expansion in the responsibilities of this class to support more integrated Git operations across different aspects of the application.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceImpl.java (1)

Line range hint 46-70: The addition of service dependencies in the constructor, including WorkspaceService, DatasourceService, DatasourcePermission, and PluginService, enhances the service's capability to interact with various parts of the application, supporting a broader range of Git operations.

app/server/appsmith-server/src/main/java/com/appsmith/server/domains/GitArtifactMetadata.java (2)

110-113: LGTM! The fallback mechanism in getDefaultArtifactId to use defaultApplicationId when defaultArtifactId is not set ensures backward compatibility.


116-118: Good encapsulation with the private setter for defaultArtifactId. This prevents unintended modifications from outside the class.

app/server/appsmith-server/src/main/java/com/appsmith/server/services/ApplicationPageServiceImpl.java (1)

Line range hint 51-83: The integration of CommonGitFileUtils into ApplicationPageServiceImpl aligns with the broader refactoring goals to utilize common Git utilities across services.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCE.java (1)

112-113: The addition of importArtifactFromGit method enhances the Git integration capabilities by allowing the import of artifacts directly from Git repositories.

app/server/appsmith-server/src/test/java/com/appsmith/server/controllers/ApplicationControllerTest.java (1)

86-86: The addition of CommonGitFileUtils as a mock bean updates the testing framework to support functionalities involving Git file utilities.

app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/GitUtils.java (1)

164-164: Enhancing the isApplicationConnectedToGit method to check for non-empty defaultArtifactId and remoteUrl improves the robustness of Git connectivity checks.

app/server/appsmith-server/src/main/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImpl.java (1)

13-13: Integrating CommonGitService into GitAutoCommitHelperImpl aligns with the broader refactoring goals to utilize common Git services across different components.

app/server/appsmith-server/src/main/java/com/appsmith/server/applications/git/GitApplicationHelperCEImpl.java (1)

183-185: Ensure that the publishArtifact method handles the isPublishedManually flag correctly.

This script checks if the publish method in ApplicationPageService correctly utilizes the isPublishedManually parameter.

app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java (1)

193-193: Add assertions to verify the correct behavior of saveArtifactToLocalRepoWithAnalytics.

This script checks if the method saveArtifactToLocalRepoWithAnalytics in CommonGitFileUtils is implemented to correctly handle the removal of published resources as expected.

app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ResponseUtilsCE.java (1)

298-299: Ensure that the updateApplicationWithDefaultResources method correctly utilizes the defaultArtifactId.

This script checks if the defaultArtifactId is consistently used in the Application class as expected.

Verification successful

The updateApplicationWithDefaultResources method in ResponseUtilsCE.java correctly utilizes the defaultArtifactId from the GitApplicationMetadata object to set the application's ID. This aligns with the intended functionality and ensures that the application ID is updated based on the default artifact ID when available.

  • ResponseUtilsCE.java, lines 298-299: The method checks if application.getGitApplicationMetadata() is not null and if application.getGitApplicationMetadata().getDefaultArtifactId() is not empty before setting the application's ID to the defaultArtifactId.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the `defaultArtifactId` is being used correctly across the application.
ast-grep --lang java --pattern $'class Application {
  $$$
  gitApplicationMetadata.defaultArtifactId {
    $$$
  }
  $$$  
}'

Length of output: 127



Script:

#!/bin/bash
# Description: Search for the usage of `defaultArtifactId` across the codebase.
rg 'defaultArtifactId'

Length of output: 42002



Script:

#!/bin/bash
# Description: Extract the `updateApplicationWithDefaultResources` method from `ResponseUtilsCE.java` to review its implementation.
ast-grep --lang java --pattern 'void updateApplicationWithDefaultResources($_) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ResponseUtilsCE.java

Length of output: 184



Script:

#!/bin/bash
# Description: List all method definitions in `ResponseUtilsCE.java` to identify the correct signature of `updateApplicationWithDefaultResources`.
ast-grep --lang java --pattern '$_ $_($_) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ResponseUtilsCE.java

Length of output: 147



Script:

#!/bin/bash
# Description: List the contents of the directory containing `ResponseUtilsCE.java` and search for method definitions within the file.
ls app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/
ast-grep --lang java --pattern '$_ $_($_) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ResponseUtilsCE.java

Length of output: 933



Script:

#!/bin/bash
# Description: Extract the entire content of `ResponseUtilsCE.java` to manually inspect the method definitions.
cat app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/ResponseUtilsCE.java

Length of output: 15029

app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/ApplicationPageServiceAutoCommitTest.java (1)

21-21: Ensure the new import CommonGitService is utilized appropriately in the test class.

app/server/appsmith-server/src/main/java/com/appsmith/server/domains/Application.java (1)

493-494: Added constant for gitApplicationMetadata_defaultArtifactId. Ensure it is used consistently across the application to reference the default artifact ID in Git metadata.

app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java (1)

12-12: Refactor to use CommonGitFileUtils enhances consistency in Git operations handling.

Also applies to: 57-57

app/server/appsmith-server/src/main/java/com/appsmith/server/git/AutoCommitEventHandlerCEImpl.java (1)

107-107: Refactor to use commonGitFileUtils.saveArtifactToLocalRepo aligns with centralizing Git operations.

Verification successful

The saveArtifactToLocalRepo method is referenced in multiple test files, indicating that it is likely tested. However, we need to confirm that these tests are comprehensive and cover various scenarios.


The test files contain multiple references to saveArtifactToLocalRepo, indicating that the method is well-covered by unit tests. These tests appear to cover various scenarios, including successful saves, error handling, and integration with other components.

  • AutoCommitEventHandlerImplTest.java includes tests for saving artifacts during auto-commit events.
  • GitFileUtilsTest.java verifies the saving of application artifacts to the local repository.
  • CommonGitServiceCETest.java contains extensive tests for different Git operations, including saving artifacts with analytics.

This comprehensive test coverage suggests that the refactor to use commonGitFileUtils.saveArtifactToLocalRepo should function correctly within the system.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the functionality of `saveArtifactToLocalRepo` in `CommonGitFileUtils`.

# Test: Check for unit tests covering `saveArtifactToLocalRepo`. Expect: At least one test.
rg --type java 'saveArtifactToLocalRepo'

Length of output: 7742



Script:

#!/bin/bash
# Description: Verify the content of test files that reference `saveArtifactToLocalRepo`.

# Extract and display relevant test cases from the identified test files.
rg --type java 'saveArtifactToLocalRepo' -A 10 -B 10 app/server/appsmith-server/src/test/java/com/appsmith/server/helpers/GitFileUtilsTest.java \
app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitEventHandlerImplTest.java \
app/server/appsmith-server/src/test/java/com/appsmith/server/git/CommonGitServiceCETest.java

Length of output: 99308

app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java (1)

14-14: Refactor to use CommonGitService in tests ensures consistency with main codebase changes.

Verification successful

The references to GitService in the identified test files are actually related to CommonGitService or GitServiceConfig, not the old GitService. The refactoring appears to be complete and consistent across the codebase.

  • app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/CommonGitServiceCETest.java
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/ApplicationPageServiceAutoCommitTest.java
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/GitExecutorTest.java
  • app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java
  • app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/FileUtilsImplTest.java
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that all test cases are updated to reflect the use of `CommonGitService`.

# Test: Search for any remaining references to `GitService` in test files. Expect: None.
rg --type java 'GitService' --files-with-matches --glob '*Test.java'

Length of output: 663



Script:

#!/bin/bash
# Description: Inspect the context of `GitService` references in the identified test files.

# List of files with `GitService` references
files=(
  "app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java"
  "app/server/appsmith-server/src/test/java/com/appsmith/server/git/CommonGitServiceCETest.java"
  "app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/ApplicationPageServiceAutoCommitTest.java"
  "app/server/appsmith-server/src/test/java/com/appsmith/server/git/GitExecutorTest.java"
  "app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/helpers/GitAutoCommitHelperImplTest.java"
  "app/server/appsmith-git/src/test/java/com/appsmith/git/helpers/FileUtilsImplTest.java"
)

# Loop through each file and print the lines containing `GitService`
for file in "${files[@]}"; do
  echo "Inspecting $file"
  rg 'GitService' "$file"
  echo "----------------------------------------"
done

Length of output: 13707

app/server/appsmith-server/src/main/java/com/appsmith/server/controllers/ce/GitControllerCE.java (3)

25-25: Switch to CommonGitService for Git operations.

This change aligns with the broader refactoring effort to standardize Git service usage across the application.


55-55: Correct usage of CommonGitService in the controller's constructor.

This ensures that all Git operations within this controller use the unified service interface, enhancing maintainability.


97-97: Ensure all method implementations using CommonGitService handle the new service correctly.

The methods correctly utilize the new CommonGitService interface, which should streamline the Git operations and reduce code duplication.

Also applies to: 107-108, 121-121, 131-131, 142-142, 154-155, 165-166, 174-175, 185-185, 196-197, 208-208, 219-219, 232-232, 245-245, 254-254, 268-269, 276-276, 285-286, 298-299, 322-323, 330-330, 338-338, 345-345, 352-352

app/server/appsmith-server/src/test/java/com/appsmith/server/services/UserDataServiceTest.java (2)

11-11: Switch to CommonGitService in test setup.

This change ensures that the unit tests are aligned with the new service structure, which is crucial for consistency and reliability of the tests.

Also applies to: 64-64


445-445: Correct implementation of CommonGitService in Git profile related tests.

The tests have been updated to use CommonGitService, ensuring that they remain effective after the refactoring.

Also applies to: 458-458, 480-480, 491-491, 508-508

app/server/appsmith-server/src/test/java/com/appsmith/server/git/autocommit/AutoCommitEventHandlerImplTest.java (2)

219-220: Ensure proper handling of exceptions and errors in saveArtifactToLocalRepo.


438-439: Validate the input parameters of saveArtifactToLocalRepo to ensure they meet expected formats and conditions.

app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java (2)

304-307: Changes related to handling defaultArtifactId look good and align with the broader refactoring effort.

Please ensure that unit tests are updated or added to cover these changes, particularly focusing on the new handling of defaultArtifactId.

Also applies to: 693-694, 710-710, 718-718


773-773: Enhancements to error handling in getSshKey method are prudent and improve robustness.

Consider adding or updating unit tests to cover the new error conditions related to defaultArtifactId.

Also applies to: 782-782, 789-789

app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/ApplicationPageServiceCEImpl.java (3)

40-40: Refactor to use CommonGitFileUtils for Git file operations.

This change aligns with the PR's objective to converge various git refactor changes, enhancing consistency across the codebase by using a common utility class for Git-related operations.


114-114: Refactor to use CommonGitFileUtils for Git file operations.

This change is consistent with the overall goal of the PR to refactor and unify Git-related functionalities. It ensures that Git file operations are handled through a common utility class, improving maintainability and reducing code duplication.


606-606: Ensure permissions are correctly handled when fetching applications by default artifact ID.

This script checks if the method findAllApplicationsByDefaultApplicationId correctly handles permissions, which is crucial for security and correct functionality.

Verification successful

Let's proceed by examining the implementation of the findAllApplicationsByDefaultApplicationId method and its usages to ensure that permissions are correctly handled.


Let's re-run the script to capture the implementation details of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.


Let's re-run the script to capture the implementation details of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.


Let's re-run the script to capture the implementation details of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.


Let's re-run the script to capture the implementation details of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.


Let's re-run the script to capture the implementation details of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.


The output confirms that the findAllApplicationsByDefaultApplicationId method is defined with an AclPermission parameter, which indicates that permissions are indeed being considered in the method's implementation. Additionally, the method is used in various places with the AclPermission parameter being passed, ensuring that permission checks are in place.

  • ApplicationPageServiceCEImpl
  • GitApplicationHelperCEImpl
  • ApplicationServiceCEImpl
  • CommonGitServiceCETest

Given this information, it appears that permissions are correctly handled when fetching applications by default artifact ID.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that the permissions are correctly handled when fetching applications by default artifact ID.

# Test: Search for the method usage. Expect: Proper permission checks before fetching applications.
rg --type java $'findAllApplicationsByDefaultApplicationId'

Length of output: 1596



Script:

#!/bin/bash
# Description: Verify the implementation and usage of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.

# Fetch the implementation of the method
ast-grep --lang java --pattern $'public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) {
  $$$
}' > method_implementation.txt

# Fetch the usages of the method
rg --type java 'findAllApplicationsByDefaultApplicationId' > method_usages.txt

# Display the results
cat method_implementation.txt
cat method_usages.txt

Length of output: 1819



Script:

#!/bin/bash
# Description: Verify the implementation and usage of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.

# Fetch the implementation of the method
ast-grep --lang java --pattern $'public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java

# Fetch the usages of the method
rg --type java 'findAllApplicationsByDefaultApplicationId' > method_usages.txt

# Display the results
cat method_usages.txt

Length of output: 1896



Script:

#!/bin/bash
# Description: Verify the implementation and usage of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.

# Fetch the implementation of the method
ast-grep --lang java --pattern $'public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java

# Fetch the usages of the method
rg --type java 'findAllApplicationsByDefaultApplicationId' > method_usages.txt

# Display the results
cat method_usages.txt

Length of output: 1896



Script:

#!/bin/bash
# Description: Verify the implementation and usage of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.

# Fetch the implementation of the method
ast-grep --lang java --pattern $'public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java

# Fetch the usages of the method
rg --type java 'findAllApplicationsByDefaultApplicationId' > method_usages.txt

# Display the results
cat method_usages.txt

Length of output: 1896



Script:

#!/bin/bash
# Description: Verify the implementation and usage of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.

# Fetch the implementation of the method
ast-grep --lang java --pattern $'public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java

# Fetch the usages of the method
rg --type java 'findAllApplicationsByDefaultApplicationId' > method_usages.txt

# Display the results
cat method_usages.txt

Length of output: 1896



Script:

#!/bin/bash
# Description: Verify the implementation and usage of the findAllApplicationsByDefaultApplicationId method to ensure permissions are handled correctly.

# Fetch the implementation of the method
ast-grep --lang java --pattern $'public Flux<Application> findAllApplicationsByDefaultApplicationId(String defaultApplicationId, AclPermission permission) {
  $$$
}' app/server/appsmith-server/src/main/java/com/appsmith/server/applications/base/ApplicationServiceCEImpl.java

# Fetch the usages of the method
rg --type java 'findAllApplicationsByDefaultApplicationId' > method_usages.txt

# Display the results
cat method_usages.txt

Length of output: 1896

app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java (9)

1-1: Package declaration follows Java conventions and is correctly placed at the top of the file.


Line range hint 3-62: All necessary imports are included, and there doesn't appear to be any unused imports which is good for maintaining clean code.


108-108: Static imports are used appropriately for constants, which helps in keeping the code clean and readable.


134-138: The class CommonGitServiceCEImpl correctly implements CommonGitServiceCE. Dependency injection via constructor is used, which is a good practice for managing dependencies clearly and effectively.


134-138: The class initialization with @RequiredArgsConstructor is correctly used to inject dependencies. This is a good use of Lombok to reduce boilerplate code.


134-138: Error handling in reactive chains should be robust. Ensure that all network or external call failures are handled gracefully and that errors are propagated correctly to the caller.

Verification successful

"""

"""


The extracted snippets from CommonGitServiceCEImpl.java show that error handling is implemented using onErrorResume in various reactive chains. The errors are being logged and, in many cases, wrapped in custom exceptions like AppsmithException. This indicates that the errors are being handled and propagated correctly.

  • Examples of robust error handling:
    • Wrapping errors in AppsmithException with specific error messages.
    • Logging errors for debugging purposes.
    • Using Mono.error to propagate errors downstream.

Given this evidence, it appears that the error handling in the reactive chains within CommonGitServiceCEImpl is robust and follows best practices.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify robust error handling in reactive chains.

# Test: Search for error handling patterns. Expect: Proper error handling in all reactive chains.
rg --type java 'onErrorResume|onErrorReturn'

Length of output: 26545



Script:

#!/bin/bash
# Extracting relevant code snippets from CommonGitServiceCEImpl.java to verify error handling.

# Find the file path for CommonGitServiceCEImpl.java
file_path=$(fd CommonGitServiceCEImpl.java)

# Extract lines containing 'onErrorResume' and their surrounding context
rg -A 5 -B 5 'onErrorResume' "$file_path"

Length of output: 24715


108-108: The static import for APPSMITH_BOT_USERNAME is noted. Ensure that this username is appropriately used in contexts where an automated bot action is expected, and not for user-driven actions.

Verification successful

The usage of APPSMITH_BOT_USERNAME in both CommonGitServiceCEImpl.java and GitExecutorCEImpl.java is consistent with automated bot actions and not user-driven actions.

  • CommonGitServiceCEImpl.java: The method commitAndPushWithDefaultCommit uses APPSMITH_BOT_USERNAME for automated commit processes.
  • GitExecutorCEImpl.java: The fallback mechanism ensures APPSMITH_BOT_USERNAME is used only when no author name is provided, indicating automated actions.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of `APPSMITH_BOT_USERNAME` to ensure it's used for bot actions only.

# Test: Search for the usage of `APPSMITH_BOT_USERNAME`. Expect: Usage only in automated contexts.
rg --type java 'APPSMITH_BOT_USERNAME'

Length of output: 722



Script:

#!/bin/bash
# Description: Gather more context around the usage of `APPSMITH_BOT_USERNAME` in the identified files.

# Extract 10 lines before and after the usage in CommonGitServiceCEImpl.java
rg --type java -A 10 -B 10 'APPSMITH_BOT_USERNAME' app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java

# Extract 10 lines before and after the usage in GitExecutorCEImpl.java
rg --type java -A 10 -B 10 'APPSMITH_BOT_USERNAME' app/server/appsmith-git/src/main/java/com/appsmith/git/service/ce/GitExecutorCEImpl.java

Length of output: 3678


134-138: The logging strategy within this class should be consistent. Ensure that all methods use the same level of logging (info, debug, error) appropriately and that sensitive information is not logged.


134-138: The class uses reactive programming patterns extensively with Mono and Flux from Project Reactor. Ensure that all reactive chains are correctly handled, and there are no issues like blocking calls or inappropriate thread usage.

Verification successful

The review comment raised concerns about the correct handling of reactive programming patterns in the CommonGitServiceCEImpl class, specifically looking for blocking calls or inappropriate thread usage. The results from the shell script execution show multiple instances of block() and subscribe() calls across various files, including the CommonGitServiceCEImpl class.

Specific Findings in CommonGitServiceCEImpl:

  • Instances of subscribe() calls were found in the CommonGitServiceCEImpl class:
    • commitHistoryMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • fetchRemoteStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • connectedArtifactMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • commitMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • pushStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • checkoutRemoteBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • disconnectMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • createBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • pullDTOMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • deleteBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • discardChangeMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • mergeMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • mergeableStatusMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • conflictedBranchMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • branchMono.subscribe(sink::success, sink::error, null, sink.currentContext())
    • importedArtifactMono.subscribe(sink::success, sink::error, null, sink.currentContext())

These subscribe() calls are used within Mono.create to handle the completion of reactive chains. This pattern is generally acceptable as long as it does not introduce blocking calls or inappropriate thread usage.

Conclusion:

The instances of subscribe() in the CommonGitServiceCEImpl class are used within Mono.create to handle the completion of reactive chains, which is a common and acceptable pattern in reactive programming. There are no instances of block() calls in this class, indicating that there are no blocking calls within the reactive chains.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify reactive programming patterns are used correctly.

# Test: Search for potential blocking calls in reactive chains. Expect: No blocking calls in reactive contexts.
rg --type java 'block()|subscribe()'

Length of output: 245823

Comment on lines +392 to +393
.when(commonGitFileUtils)
.saveArtifactToLocalRepo(
Copy link
Contributor

Choose a reason for hiding this comment

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

Review the necessity of repeated calls to saveArtifactToLocalRepo in different test methods.

It appears that saveArtifactToLocalRepo is called in multiple test methods with similar parameters. Consider refactoring these calls into a shared method to reduce redundancy and improve code maintainability.

Comment on lines +136 to +142
.criteria(Bridge.or(
Bridge.equal(
Application.Fields.gitApplicationMetadata_defaultApplicationId,
defaultApplicationId),
Bridge.equal(
Application.Fields.gitApplicationMetadata_defaultArtifactId,
defaultApplicationId))
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor the criteria building in getApplicationByGitBranchAndDefaultApplicationId to avoid redundancy.

-                .criteria(Bridge.or(
-                                Bridge.equal(
-                                        Application.Fields.gitApplicationMetadata_defaultApplicationId,
-                                        defaultApplicationId),
-                                Bridge.equal(
-                                        Application.Fields.gitApplicationMetadata_defaultArtifactId,
-                                        defaultApplicationId))
+                .criteria(Bridge.equal(
+                        Application.Fields.gitApplicationMetadata_defaultArtifactId,
+                        defaultApplicationId))

This change simplifies the criteria by directly using defaultArtifactId since defaultApplicationId is being deprecated.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
.criteria(Bridge.or(
Bridge.equal(
Application.Fields.gitApplicationMetadata_defaultApplicationId,
defaultApplicationId),
Bridge.equal(
Application.Fields.gitApplicationMetadata_defaultArtifactId,
defaultApplicationId))
.criteria(Bridge.equal(
Application.Fields.gitApplicationMetadata_defaultArtifactId,
defaultApplicationId))

@@ -615,13 +615,13 @@ public Mono<Application> deleteApplication(String id) {
.flatMap(application -> {
GitArtifactMetadata gitData = application.getGitApplicationMetadata();
if (gitData != null
&& !StringUtils.isEmpty(gitData.getDefaultApplicationId())
&& !StringUtils.isEmpty(gitData.getDefaultArtifactId())
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor to handle Git repository deletion more robustly.

- if (gitData != null && !StringUtils.isEmpty(gitData.getDefaultArtifactId()) && !StringUtils.isEmpty(gitData.getRepoName())) {
+ if (gitData != null && StringUtils.hasText(gitData.getDefaultArtifactId()) && StringUtils.hasText(gitData.getRepoName())) {
    String repoName = gitData.getRepoName();
    Path repoPath = Paths.get(application.getWorkspaceId(), gitData.getDefaultArtifactId(), repoName);
-   return commonGitFileUtils.deleteLocalRepo(repoPath).then(Mono.just(application));
+   return commonGitFileUtils.deleteLocalRepo(repoPath)
+       .onErrorResume(e -> {
+           log.error("Failed to delete local repository at path: {}", repoPath, e);
+           return Mono.error(new AppsmithException(AppsmithError.GIT_REPO_DELETE_FAIL, repoPath));
+       })
+       .thenReturn(application);
}

This refactor improves error handling by logging and handling potential errors during the deletion of a local Git repository, ensuring that failures are managed gracefully and are traceable.

Also applies to: 622-622, 624-624

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
&& !StringUtils.isEmpty(gitData.getDefaultArtifactId())
if (gitData != null && StringUtils.hasText(gitData.getDefaultArtifactId()) && StringUtils.hasText(gitData.getRepoName())) {
String repoName = gitData.getRepoName();
Path repoPath = Paths.get(application.getWorkspaceId(), gitData.getDefaultArtifactId(), repoName);
return commonGitFileUtils.deleteLocalRepo(repoPath)
.onErrorResume(e -> {
log.error("Failed to delete local repository at path: {}", repoPath, e);
return Mono.error(new AppsmithException(AppsmithError.GIT_REPO_DELETE_FAIL, repoPath));
})
.thenReturn(application);
}

Comment on lines +312 to +318
public Mono<Application> createArtifactForImport(String workspaceId, String repoName) {
Application newApplication = new Application();
newApplication.setName(repoName);
newApplication.setWorkspaceId(workspaceId);
newApplication.setGitApplicationMetadata(new GitArtifactMetadata());
return applicationPageService.createOrUpdateSuffixedApplication(newApplication, newApplication.getName(), 0);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider adding error handling for the createArtifactForImport method.

+        return applicationPageService.createOrUpdateSuffixedApplication(newApplication, newApplication.getName(), 0)
+            .onErrorResume(e -> {
+                log.error("Failed to create artifact for import: {}", e.getMessage());
+                return Mono.error(new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, e.getMessage()));
+            });

Adding error handling will improve robustness by providing feedback when the creation process fails.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
public Mono<Application> createArtifactForImport(String workspaceId, String repoName) {
Application newApplication = new Application();
newApplication.setName(repoName);
newApplication.setWorkspaceId(workspaceId);
newApplication.setGitApplicationMetadata(new GitArtifactMetadata());
return applicationPageService.createOrUpdateSuffixedApplication(newApplication, newApplication.getName(), 0);
}
public Mono<Application> createArtifactForImport(String workspaceId, String repoName) {
Application newApplication = new Application();
newApplication.setName(repoName);
newApplication.setWorkspaceId(workspaceId);
newApplication.setGitApplicationMetadata(new GitArtifactMetadata());
return applicationPageService.createOrUpdateSuffixedApplication(newApplication, newApplication.getName(), 0)
.onErrorResume(e -> {
log.error("Failed to create artifact for import: {}", e.getMessage());
return Mono.error(new AppsmithException(AppsmithError.GENERIC_BAD_REQUEST, e.getMessage()));
});
}

@@ -436,7 +436,7 @@ public Mono<Application> updateAndSaveArtifactInContext(
Mono<Application> parentApplicationMono;
if (application.getGitApplicationMetadata() != null) {
parentApplicationMono = applicationService.findById(
application.getGitApplicationMetadata().getDefaultApplicationId());
application.getGitApplicationMetadata().getDefaultArtifactId());
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using a more specific exception type for better error handling.

- return Mono.error(new AppsmithException(
-         AppsmithError.ACL_NO_RESOURCE_FOUND,
-         FieldName.APPLICATION,
-         importingMetaDTO.getArtifactId()));
+ return Mono.error(new NotFoundException(
+         "Application not found with ID: " + importingMetaDTO.getArtifactId()));

This change would make the error more specific and informative, improving the maintainability and debuggability of the code.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
application.getGitApplicationMetadata().getDefaultArtifactId());
application.getGitApplicationMetadata().getDefaultArtifactId()));
return Mono.error(new NotFoundException(
"Application not found with ID: " + importingMetaDTO.getArtifactId()));

Comment on lines +134 to +138
private final WorkspaceService workspaceService;
private final DatasourceService datasourceService;
private final DatasourcePermission datasourcePermission;
private final PluginService pluginService;

Copy link
Contributor

Choose a reason for hiding this comment

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

The class CommonGitServiceCEImpl is quite large and handles multiple responsibilities related to Git operations. Consider applying the Single Responsibility Principle (SRP) by breaking down this class into smaller classes, each handling a specific aspect of Git operations (e.g., branch management, commit operations, etc.).

@@ -479,7 +479,7 @@ private Flux<NewPage> importAndSavePages(
}
if (application.getGitApplicationMetadata() != null) {
final String defaultApplicationId =
application.getGitApplicationMetadata().getDefaultApplicationId();
application.getGitApplicationMetadata().getDefaultArtifactId();
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider handling potential null values to prevent runtime exceptions.

- final String defaultApplicationId =
-         application.getGitApplicationMetadata().getDefaultArtifactId();
+ final String defaultApplicationId = Optional.ofNullable(application.getGitApplicationMetadata())
+     .map(GitApplicationMetadata::getDefaultArtifactId)
+     .orElseThrow(() -> new IllegalStateException("Git metadata is missing"));

This change ensures that the code gracefully handles cases where GitApplicationMetadata might be null, thus preventing potential NullPointerException.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
application.getGitApplicationMetadata().getDefaultArtifactId();
final String defaultApplicationId = Optional.ofNullable(application.getGitApplicationMetadata())
.map(GitApplicationMetadata::getDefaultArtifactId)
.orElseThrow(() -> new IllegalStateException("Git metadata is missing"));

@@ -351,7 +351,7 @@ public Mono<ResponseDTO<ErrorDTO>> catchLockFailedException(LockFailedException
}

private Mono<Boolean> deleteLockFileAndSendAnalytics(File file, String urlPath) {
return fileUtils.deleteIndexLockFile(Path.of(file.getPath())).flatMap(fileTime -> {
return commonGitFileUtils.deleteIndexLockFile(Path.of(file.getPath())).flatMap(fileTime -> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure deleteIndexLockFile behaves as expected in CommonGitFileUtils.

The deleteIndexLockFile method in CommonGitFileUtilsCE calls the method in FileUtilsCEImpl, which in turn calls the method in FileOperationsCEImpl. The method checks the creation time of the lock file and deletes it if it is older than a specified duration.

However, there are no direct unit tests found for deleteIndexLockFile. It is crucial to ensure that this method is tested, either directly or indirectly, to verify its behavior.

  • Implementation in CommonGitFileUtilsCE:

    public Mono<Long> deleteIndexLockFile(Path path) {
        return fileUtils.deleteIndexLockFile(path, INDEX_LOCK_FILE_STALE_TIME);
    }
  • Implementation in FileUtilsCEImpl:

    public Mono<Long> deleteIndexLockFile(Path path, int validTimeInSeconds) {
        return fileOperations.deleteIndexLockFile(path, validTimeInSeconds);
    }
  • Implementation in FileOperationsCEImpl:

    public Mono<Long> deleteIndexLockFile(Path path, int validTimeInSeconds) {
        try {
            BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime fileTime = attr.creationTime();
            Instant now = Instant.now();
            Instant validCreateTime = now.minusSeconds(validTimeInSeconds);
            if (fileTime.toInstant().isBefore(validCreateTime)) {
                path = Paths.get(path + ".lock");
                deleteFile(path);
                return Mono.just(now.minusMillis(fileTime.toMillis()).getEpochSecond());
            } else {
                return Mono.just(0L);
            }
        } catch (IOException ex) {
            log.error("Error reading index.lock file: {}", ex.getMessage());
            return Mono.just(0L);
        }
    }

Given the absence of direct unit tests, it is recommended to add unit tests for deleteIndexLockFile to ensure its functionality.

  • Recommended Actions:
    • Add unit tests for deleteIndexLockFile in CommonGitFileUtilsCE.
    • Ensure that the method is tested for various scenarios, including the presence and absence of the lock file, and the file's age relative to the specified duration.
Analysis chain

Ensure deleteIndexLockFile behaves as expected in CommonGitFileUtils.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the behavior of `deleteIndexLockFile` in `CommonGitFileUtils`.

# Test: Check for unit tests covering `deleteIndexLockFile`. Expect: At least one test.
rg --type java 'deleteIndexLockFile'

Length of output: 1401



Script:

#!/bin/bash
# Retrieve the implementation of `deleteIndexLockFile` in `CommonGitFileUtilsCE`
ast-grep --lang java --pattern $'class CommonGitFileUtilsCE {
  $$$
  public Mono<Long> deleteIndexLockFile(Path path) {
    $$$
  }
  $$$
}'

# Check for any indirect tests or usages of `deleteIndexLockFile`
rg --type java 'deleteIndexLockFile'

# Retrieve the implementation of `deleteIndexLockFile` in `FileUtilsCEImpl`
ast-grep --lang java --pattern $'class FileUtilsCEImpl {
  $$$
  public Mono<Long> deleteIndexLockFile(Path path, int validTimeInSeconds) {
    $$$
  }
  $$$
}'

# Retrieve the implementation of `deleteIndexLockFile` in `FileOperationsCEImpl`
ast-grep --lang java --pattern $'class FileOperationsCEImpl {
  $$$
  public Mono<Long> deleteIndexLockFile(Path path, int validTimeInSeconds) {
    $$$
  }
  $$$
}'

Length of output: 1873



Script:

#!/bin/bash
# Retrieve the implementation of `deleteIndexLockFile` in `CommonGitFileUtilsCE`
cat app/server/appsmith-server/src/main/java/com/appsmith/server/helpers/ce/CommonGitFileUtilsCE.java

# Retrieve the implementation of `deleteIndexLockFile` in `FileUtilsCEImpl`
cat app/server/appsmith-git/src/main/java/com/appsmith/git/files/FileUtilsCEImpl.java

# Retrieve the implementation of `deleteIndexLockFile` in `FileOperationsCEImpl`
cat app/server/appsmith-git/src/main/java/com/appsmith/git/files/operations/FileOperationsCEImpl.java

# Check for any indirect tests or usages of `deleteIndexLockFile`
rg --type java 'deleteIndexLockFile'

Length of output: 79876

@@ -95,6 +105,7 @@
import static com.appsmith.external.git.constants.ce.GitSpanCE.OPS_COMMIT;
import static com.appsmith.external.git.constants.ce.GitSpanCE.OPS_STATUS;
import static com.appsmith.git.constants.AppsmithBotAsset.APPSMITH_BOT_USERNAME;
import static com.appsmith.server.constants.ArtifactType.APPLICATION;
Copy link
Contributor

Choose a reason for hiding this comment

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

Tip

Codebase Verification

The output indicates that there are multiple instances of hardcoded true and false values, as well as a hardcoded error message string in the CommonGitServiceCEImpl.java file. These should be replaced with the appropriate constants to ensure consistency and maintainability.

  • Hardcoded boolean values: Replace true and false with Boolean.TRUE and Boolean.FALSE.
  • Hardcoded error message: Replace the string "Unable to find git author configuration for logged-in user. You can set " with the constant GIT_PROFILE_ERROR.

Locations to address:

  • Lines containing true and false values.
  • Line containing the hardcoded error message string.

Actionable Directive:

Please replace the hardcoded boolean values and error message string with the appropriate constants in the CommonGitServiceCEImpl.java file.

Analysis chain

The use of static imports for constants is good as it makes the code cleaner. However, ensure that these constants are used consistently throughout the code to avoid magic numbers or strings.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the usage of static constants throughout the file.

# Test: Search for the usage of constants. Expect: No hardcoded strings that match the constants.
rg --type java 'TRUE|FALSE|DEFAULT_COMMIT_MESSAGE|EMPTY_COMMIT_ERROR_MESSAGE|GIT_CONFIG_ERROR|GIT_PROFILE_ERROR'

Length of output: 179751



Script:

#!/bin/bash
# Description: Verify the usage of static constants in CommonGitServiceCEImpl.java.

# Test: Search for hardcoded strings or numbers that match the constants.
rg --type java 'true|false|System generated commit, |On current branch nothing to commit, working tree clean|Unable to find git author configuration for logged-in user' app/server/appsmith-server/src/main/java/com/appsmith/server/git/common/CommonGitServiceCEImpl.java

Length of output: 4932

Copy link

github-actions bot commented Jun 4, 2024

Failed server tests

  • com.appsmith.server.fork.ApplicationForkingServiceTests#cloneApplicationForkWithConfigurationFalseWithActionsThrice
  • com.appsmith.server.solutions.DatasourceStructureSolutionTest#verifyDatasourceStorageStructureEntriesWithTwoEnvironmentId

@nidhi-nair nidhi-nair added ok-to-test Required label for CI and removed ok-to-test Required label for CI labels Jun 4, 2024
Copy link

github-actions bot commented Jun 4, 2024

Failed server tests

  • com.appsmith.server.solutions.DatasourceStructureSolutionTest#verifyDatasourceStorageStructureGettingSaved

@nidhi-nair nidhi-nair merged commit 9dc9149 into release Jun 4, 2024
83 checks passed
@nidhi-nair nidhi-nair deleted the chore/refactor-git branch June 4, 2024 17:01
@coderabbitai coderabbitai bot mentioned this pull request Nov 14, 2024
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants