Skip to content

feat: API get workspace#10

Merged
zacharyblasczyk merged 2 commits into
mainfrom
zacharyb/get-workspace-by-id-or-slug
Mar 22, 2025
Merged

feat: API get workspace#10
zacharyblasczyk merged 2 commits into
mainfrom
zacharyb/get-workspace-by-id-or-slug

Conversation

@zacharyblasczyk
Copy link
Copy Markdown
Member

@zacharyblasczyk zacharyblasczyk commented Mar 22, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a command that retrieves workspace details. Users can now fetch workspace information by providing either a workspace ID or a slug.
    • Improved input validation ensures that only one parameter is accepted at a time, enhancing usability.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 22, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

A new Cobra command is introduced in the workspace package to retrieve workspace details. The command accepts either a workspace ID (validated as a UUID) or a slug, but not both simultaneously. It retrieves API credentials from the configuration to initialize the API client. Depending on the provided flag, it invokes the appropriate method to fetch workspace details and processes the response, including error handling for various failure scenarios.

Changes

File Summary
cmd/ctrlc/.../workspace.go Added NewGetWorkspaceCmd() which creates a Cobra command to fetch a workspace by ID or slug. Implements parameter validation, API client creation, and response handling.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant C as CLI Command
    participant CFG as Config Service
    participant API as API Client

    U->>C: Execute get workspace command (--id or --slug)
    C->>CFG: Retrieve API URL and Key
    CFG-->>C: Return credentials
    C->>API: Initialize API client with credentials
    alt Workspace ID provided
        C->>API: Validate UUID and fetch workspace by ID
    else Slug provided
        C->>API: Fetch workspace by slug
    end
    API-->>C: Return workspace details or error
    C-->>U: Display result
Loading

Poem

Oh, what a hop, a joyful spree,
I’m a little rabbit, full of glee.
New commands bloom like springtime air,
With flags and checks beyond compare.
Carrots and code, a perfect pair!
🥕🐇 Celebrate changes with flair!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d6fb805 and 4707482.

📒 Files selected for processing (1)
  • cmd/ctrlc/root/api/get/workspace/workspace.go (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, 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.
  • @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.

@zacharyblasczyk zacharyblasczyk merged commit bfd73ac into main Mar 22, 2025
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (4)
cmd/ctrlc/root/api/get/workspace/workspace.go (4)

41-46: Add verification for API configuration presence.

You're retrieving API URL and key from viper, but not verifying if these values exist before creating the client.

 apiURL := viper.GetString("url")
 apiKey := viper.GetString("api-key")
+
+if apiURL == "" {
+    return fmt.Errorf("API URL not configured. Run 'ctrlc config set url <api-url>' to set it")
+}
+
+if apiKey == "" {
+    return fmt.Errorf("API key not configured. Run 'ctrlc config set api-key <your-api-key>' to set it")
+}
+
 client, err := api.NewAPIKeyClientWithResponses(apiURL, apiKey)

62-67: Consider adding slug format validation.

If there's a specific format expected for workspaceSlug, consider adding validation before making the API call.

 // Get workspace by slug
+if !isValidSlug(workspaceSlug) {
+    return fmt.Errorf("invalid workspace slug format: %s", workspaceSlug)
+}
+
 resp, err := client.GetWorkspaceBySlug(cmd.Context(), workspaceSlug)

You would need to add a helper function like:

func isValidSlug(slug string) bool {
    // Implement validation logic based on your slug format requirements
    // For example: only alphanumeric characters and hyphens
    slugRegex := regexp.MustCompile(`^[a-z0-9]([a-z0-9\-]*[a-z0-9])?$`)
    return slugRegex.MatchString(slug)
}

71-73: Consider adding more descriptive flag usage information.

The flag definitions could benefit from more detailed descriptions to guide users.

 // Add flags
-cmd.Flags().StringVar(&workspaceId, "id", "", "ID of the workspace")
-cmd.Flags().StringVar(&workspaceSlug, "slug", "", "Slug of the workspace")
+cmd.Flags().StringVar(&workspaceId, "id", "", "UUID of the workspace to retrieve")
+cmd.Flags().StringVar(&workspaceSlug, "slug", "", "URL-friendly slug of the workspace to retrieve")

32-69: Consider refactoring the RunE function for better readability.

The RunE function is somewhat lengthy. Consider extracting the workspace retrieval logic into separate helper functions to improve readability and maintainability.

 RunE: func(cmd *cobra.Command, args []string) error {
     if workspaceId == "" && workspaceSlug == "" {
         return fmt.Errorf("either --id or --slug must be provided")
     }

     if workspaceId != "" && workspaceSlug != "" {
         return fmt.Errorf("--id and --slug are mutually exclusive")
     }

     apiURL := viper.GetString("url")
     apiKey := viper.GetString("api-key")
     
     if apiURL == "" {
         return fmt.Errorf("API URL not configured. Run 'ctrlc config set url <api-url>' to set it")
     }
     
     if apiKey == "" {
         return fmt.Errorf("API key not configured. Run 'ctrlc config set api-key <your-api-key>' to set it")
     }
     
     client, err := api.NewAPIKeyClientWithResponses(apiURL, apiKey)
     if err != nil {
         return fmt.Errorf("failed to create API client: %w", err)
     }

+    return getWorkspace(cmd, client, workspaceId, workspaceSlug)
+},
+
+// Helper function to get workspace by either ID or slug
+func getWorkspace(cmd *cobra.Command, client *api.ClientWithResponses, workspaceId, workspaceSlug string) error {
     if workspaceId != "" {
         // Get workspace by ID
         wsId, err := uuid.Parse(workspaceId)
         if err != nil {
             return fmt.Errorf("invalid workspace ID: %w", err)
         }

         resp, err := client.GetWorkspace(cmd.Context(), wsId)
         if err != nil {
             return fmt.Errorf("failed to get workspace by ID: %w", err)
         }
         return cliutil.HandleOutput(cmd, resp)
     }

     // Get workspace by slug
     resp, err := client.GetWorkspaceBySlug(cmd.Context(), workspaceSlug)
     if err != nil {
         return fmt.Errorf("failed to get workspace by slug: %w", err)
     }
     return cliutil.HandleOutput(cmd, resp)
-},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69389db and d6fb805.

📒 Files selected for processing (1)
  • cmd/ctrlc/root/api/get/workspace/workspace.go (1 hunks)
🔇 Additional comments (5)
cmd/ctrlc/root/api/get/workspace/workspace.go (5)

3-12: LGTM! Good import organization.

The imports are organized appropriately, separating standard library and third-party packages with a blank line, which improves readability.


14-31: Command definition looks clean with good documentation.

The command definition includes detailed examples that demonstrate different usage patterns, which is excellent for user experience.


33-39: Good input validation checks.

The mutual exclusivity check between ID and slug is well-implemented, ensuring users don't provide conflicting parameters.


48-60: UUID validation properly implemented.

Good job validating the workspace ID as a UUID before making the API call. The error messages are clear and helpful.


14-76:

Details

✅ Verification successful

Consider adding global template flag.

The example shows how to use a template flag, but it's not defined in the command. Either add the template flag or update the example to match the actual implementation.


🏁 Script executed:

#!/bin/bash
# Check if template flag is already defined globally in the cliutil package

grep -r "template" --include="*.go" ./internal/cliutil/

Length of output: 557


Global Template Flag Confirmed

The global --template flag is already registered and handled in the CLI’s global output utility (see internal/cliutil/output.go), so the example usage is valid as is—no local flag addition is required in the workspace command.

@dacbd dacbd deleted the zacharyb/get-workspace-by-id-or-slug branch April 13, 2026 22:10
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.

1 participant