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

feat: add deployment reset command #89

Merged
merged 1 commit into from
Jan 14, 2025

Conversation

zulkhair
Copy link
Collaborator

@zulkhair zulkhair commented Jan 9, 2025

Closes: WORLD-1327 & WORLD-1328

Overview

Check destroy command and add reset command

Brief Changelog

  • merge the deploy, destroy func

Testing and Verifying

Manual test runing world forge deployment reset command

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new project reset functionality.
    • Enhanced deployment commands with more flexible action types.
  • Improvements

    • Consolidated deployment-related actions into a single method.
    • Improved error handling and context for deployment operations.
  • Changes

    • Updated deployment command structure to support deploy, destroy, and reset actions.
    • Standardized deployment method signature across different operations.

The release introduces more flexible project management capabilities with a unified deployment approach.

Copy link
Collaborator Author

zulkhair commented Jan 9, 2025


How to use the Graphite Merge Queue

Add the label graphite/merge to this PR to add it to the merge queue.

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@zulkhair zulkhair marked this pull request as ready for review January 9, 2025 07:54
Copy link

coderabbitai bot commented Jan 9, 2025

Walkthrough

The pull request introduces a significant refactoring of deployment functionality across multiple files in the cmd/world/forge directory. The primary change is the consolidation of deployment-related actions (deploy, destroy, reset) into a single deployment function that accepts a deployType parameter. This modification simplifies the command structure, allowing for more flexible deployment operations. The changes span deployment.go, forge.go, and forge_test.go, updating function signatures, adding a new reset command, and modifying the corresponding test suite to support the new approach.

Changes

File Change Summary
cmd/world/forge/deployment.go - Renamed deploy function to deployment
- Added deployType parameter
- Modified URL construction and error handling to include deployType
cmd/world/forge/forge.go - Updated deployCmd and destroyCmd to use new deployment function
- Added new resetCmd
- Registered resetCmd under deploymentCmd
cmd/world/forge/forge_test.go - Added handleReset method
- Created TestReset test method
- Updated TestDeploy and TestDestroy to use new deployment function

Sequence Diagram

sequenceDiagram
    participant User
    participant CLI
    participant DeploymentService
    
    User->>CLI: Execute deployment command
    CLI->>DeploymentService: deployment(context, deployType)
    alt deployType is "deploy"
        DeploymentService-->>CLI: Deploy project
    else deployType is "destroy"
        DeploymentService-->>CLI: Destroy project
    else deployType is "reset"
        DeploymentService-->>CLI: Reset project
    end
    CLI-->>User: Display operation result
Loading

Possibly related PRs

Suggested reviewers

  • ezavada

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 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.

@zulkhair zulkhair requested a review from ezavada January 9, 2025 07:56
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

🧹 Nitpick comments (6)
cmd/world/forge/deployment.go (3)

14-14: Fix the function comment for clarity

The function comment has a typo and is unclear. It currently reads "// Deployment a project". Consider revising it for better readability.

Suggestion:

-// Deployment a project
+// Deploys a project based on the given deployment type

53-56: Enhance error handling with specific context

While wrapping the error provides context, it might be beneficial to include the HTTP status code or response body if available. This can help diagnose issues more effectively when a deployment fails.

Consider modifying the error handling to capture more details:

if err != nil {
    // If 'sendRequest' returns detailed error information, include it here
    return eris.Wrapf(err, "Failed to %s project: %v", deployType, err)
}

59-60: Improve output message formatting

To enhance the user experience, consider formatting the command in the output message as code for better readability.

Apply this change:

-fmt.Println("  $ 'world forge deployment status'")
+fmt.Println("  $ world forge deployment status")

Alternatively, you can use backticks or color coding if your CLI supports it.

cmd/world/forge/project.go (1)

190-192: Define 'maxNameLength' as a constant for reusability

Consider defining maxNameLength as a package-level constant to improve maintainability and reuse across functions if needed.

Suggestion:

At the top of the file, add:

const maxNameLength = 50

Then in the function:

-maxNameLength := 50
cmd/world/forge/forge_test.go (2)

239-245: Consider standardizing error responses across handlers.

The implementation is correct, but there's an opportunity to improve error handling consistency.

Consider extracting the method check and error response to a shared helper function:

+func methodNotAllowed(w http.ResponseWriter) {
+    http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+}
+
 func (s *ForgeTestSuite) handleReset(w http.ResponseWriter, r *http.Request) {
     if r.Method != http.MethodPost {
-        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+        methodNotAllowed(w)
         return
     }
     s.writeJSON(w, map[string]interface{}{"data": "reset started"})
 }

616-694: Enhance reset test coverage.

While the test implementation is thorough, consider these improvements:

  1. Add a test case for cancelled reset operation (input "n")
  2. Make test case descriptions more specific (e.g., "Success - Reset with valid credentials and confirmation")
  3. Consider consolidating similar error cases

Example test case to add:

+		{
+			name: "Success - Reset cancelled by user",
+			config: globalconfig.GlobalConfig{
+				OrganizationID: "test-org-id",
+				ProjectID:      "test-project-id",
+				Credential: globalconfig.Credential{
+					Token: "test-token",
+				},
+			},
+			input:         "n",
+			expectedError: false,
+		},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8326d1 and d44c4b3.

📒 Files selected for processing (4)
  • cmd/world/forge/deployment.go (2 hunks)
  • cmd/world/forge/forge.go (3 hunks)
  • cmd/world/forge/forge_test.go (4 hunks)
  • cmd/world/forge/project.go (1 hunks)
🔇 Additional comments (7)
cmd/world/forge/forge.go (4)

162-162: Consolidated deployment functions improve maintainability

Refactoring to use the unified deployment function enhances code reuse and simplifies maintenance.


173-173: Consolidated deployment functions improve maintainability

The destroy command now correctly calls deployment with "destroy", aligning with the refactored design.


177-184: 'reset' command implementation is consistent and correct

The new reset command is added appropriately and follows the existing pattern for deployment commands.


220-220: Registered 'reset' command successfully

The resetCmd is correctly added to deploymentCmd, ensuring the command is available in the CLI.

cmd/world/forge/forge_test.go (3)

64-65: LGTM! Reset endpoint handler is properly integrated.

The new reset endpoint follows the established API path pattern and is correctly wired to its handler.


606-614: LGTM! TestDestroy properly adapted to use deployment function.

The change maintains test coverage while aligning with the new unified deployment approach.


518-518: Verify deployment type constant usage.

The change to use deployment() with "deploy" type is correct. However, we should verify if there's a constant defined for deployment types.

✅ Verification successful

String literal "deploy" usage is consistent

The usage of "deploy" as a string literal is consistent across both the test file and its implementation in forge.go. No constants are defined or used for deployment types in the codebase, indicating this is the intended pattern.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for deployment type constants
rg -g '*.go' -B 2 -A 2 'const.*[Dd]eploy[Tt]ype'

Length of output: 50


Script:

#!/bin/bash
# Search for "deploy" string usage in function calls
rg -g '*.go' 'deployment\(.*"deploy".*\)'

# Search for deployment type definitions or enums
ast-grep --pattern 'type $_ struct {
  $$$
  Type string
  $$$
}'

Length of output: 734

Copy link

codecov bot commented Jan 13, 2025

Codecov Report

Attention: Patch coverage is 38.46154% with 8 lines in your changes missing coverage. Please review.

Project coverage is 50.00%. Comparing base (1e66dd9) to head (ea0a524).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
cmd/world/forge/forge.go 12.50% 7 Missing ⚠️
cmd/world/forge/deployment.go 80.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #89      +/-   ##
==========================================
- Coverage   50.48%   50.00%   -0.49%     
==========================================
  Files          63       63              
  Lines        4431     4612     +181     
==========================================
+ Hits         2237     2306      +69     
- Misses       1904     1984      +80     
- Partials      290      322      +32     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@zulkhair zulkhair force-pushed the daim/add_deployment_reset_command branch from d44c4b3 to b2ac2f6 Compare January 14, 2025 07:48
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: 2

🧹 Nitpick comments (2)
cmd/world/forge/deployment.go (1)

19-20: Consider improving function documentation.

The function comment "Deployment a project" is grammatically incorrect and lacks details about the possible deployment types.

Apply this diff to improve the documentation:

-// Deployment a project
+// deployment executes a deployment operation (deploy/destroy/reset) on a project.
+// deployType must be one of: "deploy", "destroy", "reset"
cmd/world/forge/forge_test.go (1)

Line range hint 866-950: Consider adding test cases for invalid deployment type.

The test suite should verify that the deployment function properly handles invalid deployment types.

Add a test case for invalid deployment type:

 func (s *ForgeTestSuite) TestReset() {
     testCases := []struct {
         name          string
         config        globalconfig.GlobalConfig
         input         string
         expectedError bool
     }{
+        {
+            name: "Error - Invalid deployment type",
+            config: globalconfig.GlobalConfig{
+                OrganizationID: "test-org-id",
+                ProjectID:      "test-project-id",
+                Credential: globalconfig.Credential{
+                    Token: "test-token",
+                },
+            },
+            input:         "y",
+            expectedError: true,
+        },
         // ... existing test cases ...
     }

     for _, tc := range testCases {
         s.Run(tc.name, func() {
             err := globalconfig.SaveGlobalConfig(tc.config)
             s.Require().NoError(err)

             getInput = func() (string, error) {
                 return tc.input, nil
             }
             defer func() { getInput = originalGetInput }()

-            err = deployment(s.ctx, "reset")
+            deployType := "reset"
+            if tc.name == "Error - Invalid deployment type" {
+                deployType = "invalid"
+            }
+            err = deployment(s.ctx, deployType)
             if tc.expectedError {
                 s.Require().Error(err)
             } else {
                 s.Require().NoError(err)
             }
         })
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d44c4b3 and b2ac2f6.

📒 Files selected for processing (3)
  • cmd/world/forge/deployment.go (2 hunks)
  • cmd/world/forge/forge.go (3 hunks)
  • cmd/world/forge/forge_test.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Unit & Coverage
  • GitHub Check: Analyze (go)
🔇 Additional comments (6)
cmd/world/forge/forge.go (2)

162-162: Consistent refactoring of deployment commands.

The deployment and destroy commands have been refactored to use the unified deployment function, which improves code maintainability by centralizing deployment logic.

Also applies to: 173-174


232-232: LGTM!

The reset command is properly added to the deployment command group.

cmd/world/forge/deployment.go (1)

65-66: LGTM!

The status messages are properly updated to use the dynamic deployType.

cmd/world/forge/forge_test.go (3)

64-65: LGTM!

The reset endpoint is properly added to the test server handler.


380-386: LGTM!

The reset handler follows the same pattern as other handlers, properly checking the HTTP method and returning appropriate responses.


665-665: LGTM!

The deployment test cases are properly updated to use the new deployment function with appropriate deployment types.

Also applies to: 856-861

cmd/world/forge/forge.go Show resolved Hide resolved
cmd/world/forge/deployment.go Show resolved Hide resolved
Copy link

graphite-app bot commented Jan 14, 2025

Merge activity

Closes: WORLD-1327 & WORLD-1328

## Overview

Check destroy command and add reset command

## Brief Changelog

- merge the deploy, destroy func

## Testing and Verifying

Manual test runing `world forge deployment reset` command

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

## Release Notes

- **New Features**
    - Added a new project reset functionality
    - Enhanced deployment commands with more flexible action types

- **Improvements**
    - Consolidated deployment-related actions into a single method
    - Improved error handling and context for deployment operations

- **Changes**
    - Updated deployment command structure to support deploy, destroy, and reset actions
    - Standardized deployment method signature across different operations

The release introduces more flexible project management capabilities with a unified deployment approach.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@zulkhair zulkhair force-pushed the daim/add_deployment_reset_command branch from b2ac2f6 to ea0a524 Compare January 14, 2025 17:31
@graphite-app graphite-app bot merged commit ea0a524 into main Jan 14, 2025
8 of 12 checks passed
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

♻️ Duplicate comments (1)
cmd/world/forge/deployment.go (1)

59-62: ⚠️ Potential issue

Validate deployType parameter before making API call.

The function should validate the deployType parameter to prevent invalid API calls.

🧹 Nitpick comments (2)
cmd/world/forge/deployment.go (1)

19-20: Enhance function documentation.

The docstring should be more descriptive to help users understand the function's purpose and usage.

-// Deployment a project
+// Deployment manages project deployment operations based on the specified type.
+//
+// Parameters:
+//   - ctx: The context for the operation
+//   - deployType: The type of deployment operation ("deploy", "destroy", or "reset")
+//
+// Returns an error if the operation fails.
cmd/world/forge/forge_test.go (1)

866-944: Add test case for user cancellation.

The test suite should include a case where the user cancels the reset operation by entering "n" when prompted, similar to the destroy test cases.

 func (s *ForgeTestSuite) TestReset() {
     testCases := []struct {
         name          string
         config        globalconfig.GlobalConfig
         input         string
         expectedError bool
     }{
+        {
+            name: "Success - Cancelled reset",
+            config: globalconfig.GlobalConfig{
+                OrganizationID: "test-org-id",
+                ProjectID:      "test-project-id",
+                Credential: globalconfig.Credential{
+                    Token: "test-token",
+                },
+            },
+            input:         "n",
+            expectedError: false,
+        },
         // ... existing test cases ...
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2ac2f6 and ea0a524.

📒 Files selected for processing (3)
  • cmd/world/forge/deployment.go (2 hunks)
  • cmd/world/forge/forge.go (3 hunks)
  • cmd/world/forge/forge_test.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/world/forge/forge.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Go
  • GitHub Check: Go
  • GitHub Check: Analyze (go)
🔇 Additional comments (4)
cmd/world/forge/deployment.go (1)

65-66: LGTM! Clear and helpful output messages.

The messages are well-formatted, consistent, and provide useful next steps for the user.

cmd/world/forge/forge_test.go (3)

64-65: LGTM! Reset handler properly registered.

The reset handler follows the same pattern as other deployment handlers.


380-386: LGTM! Consistent handler implementation.

The handleReset function follows the same pattern as other handlers and maintains consistency in:

  • HTTP method validation
  • Response format
  • Error handling

856-864: LGTM! Test updated correctly.

The test has been properly updated to use the new deployment function while maintaining the same test coverage.

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.

2 participants