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 stack and component autocompletion for commands #820

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

RoseSecurity
Copy link
Contributor

@RoseSecurity RoseSecurity commented Dec 5, 2024

what

atmos_autocomplete

  • Refactor pkg/list functions to include configuration initialization so that the outputted component and stack lists could be easily used by Cobra valid argument functions and flag completion functions
  • Add ValidArgsFunction and RegisterFlagCompletionFunc for stacks and components in the following commands:
    • atmos describe component
    • atmos describe dependents
    • atmos docs
    • atmos list components
    • atmos list stacks
    • atmos validate component
    • atmos vendor pull

why

  • Create a positive user experience by making it easier to view and autocomplete stacks and components

testing

  • Conducted make build after each command autocompletion addition and tested

references

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced command-line experience with autocompletion for component and stack names across multiple commands.
  • Bug Fixes

    • Improved error handling and messaging for various commands when fetching components and stacks.
  • Chores

    • Streamlined command logic by removing unnecessary initializations and focusing on core functionalities.

@RoseSecurity RoseSecurity requested review from a team as code owners December 5, 2024 16:16
@aknysh aknysh added the minor New features that do not break anything label Dec 5, 2024
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

📝 Walkthrough

Walkthrough

This pull request introduces several enhancements across multiple command files, primarily focusing on adding autocompletion functionality for various flags related to components and stacks. New functions are implemented to provide dynamic suggestions based on user input, improving the command-line experience. Additionally, existing functions are modified to streamline error handling and output formatting, ensuring a more efficient retrieval of components and stacks.

Changes

File Change Summary
cmd/describe_component.go Added ValidArgsFunction for component names autocompletion and registered a flag completion function for "stack".
cmd/describe_dependents.go Added import for l and implemented a flag completion function for "stack".
cmd/docs.go Introduced ValidArgsFunction for component names autocompletion and updated imports.
cmd/list_components.go Removed CLI config initialization; simplified logic to call l.FilterAndListComponents. Added autocompletion for "stack".
cmd/list_stacks.go Removed CLI config initialization; streamlined logic to call l.FilterAndListStacks. Added autocompletion for "component".
cmd/validate_component.go Added ValidArgsFunction for component names autocompletion and registered a flag completion function for "stack".
cmd/vendor_pull.go Registered autocompletion functions for "stack" and "component" flags.
pkg/list/list_components.go Updated FilterAndListComponents function signature and logic for improved error handling and output format.
pkg/list/list_stacks.go Updated FilterAndListStacks function signature and logic for enhanced error handling and consistent output.

Possibly related PRs

Suggested reviewers

  • osterman
  • Gowiem
  • aknysh

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>, 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 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 or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title anywhere in the PR title to generate the title automatically.

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: 4

🧹 Outside diff range and nitpick comments (6)
pkg/list/list_stacks.go (2)

19-23: Consider removing error printing from utility functions

Avoid printing error messages within FilterAndListStacks. Let the caller handle logging by returning a wrapped error.

Suggested change:

-       u.PrintMessageInColor(fmt.Sprintf("Error initializing CLI config: %v", err), color.New(color.FgRed))
-       return nil, err
+       return nil, fmt.Errorf("error initializing CLI config: %w", err)

25-29: Avoid printing errors inside utility functions

Similarly, remove the error printing when describing stacks. Return the error for the caller to handle.

Suggested change:

-       u.PrintMessageInColor(fmt.Sprintf("Error describing stacks: %v", err), color.New(color.FgRed))
-       return nil, err
+       return nil, fmt.Errorf("error describing stacks: %w", err)
cmd/vendor_pull.go (1)

52-65: Consider consolidating duplicate error handling logic.

Both completion functions share identical error handling patterns. Consider extracting this into a helper function to promote DRY principles.

+ func handleCompletionError(err error) ([]string, cobra.ShellCompDirective) {
+     if err != nil {
+         u.LogErrorAndExit(schema.CliConfiguration{}, err)
+     }
+     return nil, cobra.ShellCompDirectiveNoFileComp
+ }
cmd/validate_component.go (1)

71-74: Consider more graceful error handling.

The current implementation exits the program on error during autocompletion. Consider a more graceful approach that returns an empty list instead of terminating the program.

- if err != nil {
-     u.LogErrorAndExit(schema.CliConfiguration{}, err)
- }
+ if err != nil {
+     u.LogError(err)
+     return []string{}, cobra.ShellCompDirectiveNoFileComp
+ }
cmd/docs.go (2)

30-41: Consider enhancing the error handling and performance

Your ValidArgsFunction stands strong, but we can make it even mightier!

  1. Consider making the error message more specific:
 componentList, err := l.FilterAndListComponents(toComplete)
 if err != nil {
-    u.LogErrorAndExit(schema.CliConfiguration{}, err)
+    u.LogErrorAndExit(schema.CliConfiguration{}, fmt.Errorf("failed to list components for autocompletion: %w", err))
 }
  1. For optimal performance in battle, consider implementing caching for the component list if it's frequently accessed.

Line range hint 42-156: Strategic architectural improvements to consider

Brave warrior, your implementation is solid! For even greater glory, consider these tactical improvements:

  1. Extract the browser opening logic into a utility function like openBrowser(url string) error. This would make the code more reusable and easier to test.

  2. If markdown rendering is used in other commands, consider creating a shared configuration in a separate package:

// pkg/markdown/renderer.go
func NewAtmosRenderer(screenWidth int) (*glamour.TermRenderer, error) {
    return glamour.NewTermRenderer(
        glamour.WithColorProfile(lipgloss.ColorProfile()),
        glamour.WithAutoStyle(),
        glamour.WithPreservedNewLines(),
        glamour.WithWordWrap(screenWidth),
    )
}

These changes would make your code more maintainable and battle-ready! 🗡️

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 31d7c5e and 4be8ab9.

📒 Files selected for processing (9)
  • cmd/describe_component.go (3 hunks)
  • cmd/describe_dependents.go (2 hunks)
  • cmd/docs.go (2 hunks)
  • cmd/list_components.go (1 hunks)
  • cmd/list_stacks.go (1 hunks)
  • cmd/validate_component.go (3 hunks)
  • cmd/vendor_pull.go (2 hunks)
  • pkg/list/list_components.go (3 hunks)
  • pkg/list/list_stacks.go (2 hunks)
🔇 Additional comments (6)
pkg/list/list_components.go (2)

41-44: Remove error printing from utility function

As before, avoid printing errors within FilterAndListComponents. Return the error instead.


48-50: Avoid printing errors inside utility functions

Consistent with prior suggestions, remove the error printing here.

cmd/vendor_pull.go (1)

37-50: LGTM! Stack autocompletion implementation looks solid.

The implementation follows Cobra's best practices for flag completion. The args validation and error handling are appropriate.

cmd/describe_component.go (1)

53-66: Verify the argument validation requirement.

The stack completion function requires exactly one argument (len(args) != 1), while vendor_pull.go checks for zero arguments. This difference in validation logic seems intentional since a component name is required before selecting a stack, but it's worth verifying.

✅ Verification successful

Stack argument validation is correctly implemented

The validation logic in describe_component.go requiring exactly one argument is correct and consistent with the command's purpose. Here's what the codebase reveals:

  • Commands that operate on a specific component (describe_component.go, validate_component.go) require exactly one argument (len(args) != 1)
  • Commands that list or pull components (list_components.go, vendor_pull.go, describe_dependents.go) require zero arguments (len(args) != 0)

This pattern makes perfect sense as commands operating on specific components need the component name before stack selection, while listing commands don't.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check argument validation consistency across commands
# Look for other stack completion implementations to verify the pattern

rg -A 5 "RegisterFlagCompletionFunc.*stack" cmd/

Length of output: 2219

cmd/docs.go (2)

16-16: LGTM! Clean import addition.

The new import for the list package is well-organized and properly aliased. Stand strong, warrior! 💪


25-29: Well-structured command definition, warrior!

The command definition is clear, concise, and well-documented. The example and usage instructions provide excellent guidance for our fellow warriors.

cmd/list_components.go Show resolved Hide resolved
cmd/list_stacks.go Show resolved Hide resolved
cmd/describe_dependents.go Show resolved Hide resolved
Comment on lines +23 to +34
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) != 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}

componentList, err := l.FilterAndListComponents(toComplete)
if err != nil {
u.LogErrorAndExit(schema.CliConfiguration{}, err)
}

return componentList, cobra.ShellCompDirectiveNoFileComp
},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider creating shared autocompletion utilities.

The autocompletion implementations are identical across multiple command files. Consider creating shared utility functions to:

  1. Reduce code duplication
  2. Ensure consistent validation logic
  3. Centralize error handling

Create a new file cmd/completion_utils.go:

package cmd

import (
    "github.com/spf13/cobra"
    l "github.com/cloudposse/atmos/pkg/list"
    "github.com/cloudposse/atmos/pkg/schema"
    u "github.com/cloudposse/atmos/pkg/utils"
)

func ComponentCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    if len(args) != 0 {
        return nil, cobra.ShellCompDirectiveNoFileComp
    }

    componentList, err := l.FilterAndListComponents(toComplete)
    if err != nil {
        u.LogErrorAndExit(schema.CliConfiguration{}, err)
    }

    return componentList, cobra.ShellCompDirectiveNoFileComp
}

func StackCompletionWithComponent(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
    if len(args) != 1 {
        return nil, cobra.ShellCompDirectiveNoFileComp
    }

    stacksList, err := l.FilterAndListStacks(toComplete)
    if err != nil {
        u.LogErrorAndExit(schema.CliConfiguration{}, err)
    }

    return stacksList, cobra.ShellCompDirectiveNoFileComp
}

Also applies to: 65-78

@osterman
Copy link
Member

osterman commented Dec 5, 2024

@RoseSecurity thanks for this! Excited for it.

Should this work?

atmos list components --stack de<tab>
image

@RoseSecurity RoseSecurity marked this pull request as draft December 5, 2024 17:00
@aknysh
Copy link
Member

aknysh commented Dec 5, 2024

@RoseSecurity thanks for this! Excited for it.

Should this work?

atmos list components --stack de<tab>
image

Cobra can do autocompletion only for the configured Cobra commands.
It can't do autocompletion for Atmos components and stacks b/c it does not know anything about them.
Implementing autocompletion for components and stacks is tricky and will require writting not only Go code, but some shell scripts as well

@osterman
Copy link
Member

osterman commented Dec 5, 2024

@aknysh cobra supports completion functions for handling flags.

Wouldn't that work?


package main

import (
	"fmt"
	"github.com/spf13/cobra"
)

func main() {
	var rootCmd = &cobra.Command{
		Use:   "example",
		Short: "An example for Cobra flag auto-completion",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("Run the example command")
		},
	}

	// Adding a flag
	rootCmd.Flags().String("resource", "", "Specify a resource type")

	// Registering auto-completion for the `--resource` flag
	rootCmd.RegisterFlagCompletionFunc("resource", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		// Provide dynamic options for the `--resource` flag
		return []string{"pod", "service", "deployment"}, cobra.ShellCompDirectiveNoFileComp
	})

	// Execute the root command
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
	}
}

https://github.com/spf13/cobra/blob/main/site/content/completions/_index.md#completions-for-flags

https://github.com/spf13/cobra/blob/main/completions.go

See flag completions.

@RoseSecurity
Copy link
Contributor Author

RoseSecurity commented Dec 6, 2024

Interestingly, this was working for me locally yesterday, but today, it doesn't produce the same result. My goal is to restructure the list packages to include configuration initialization so that the function can be used with Cobra's Valid Arguments functions and flag completion features.

Going to keep working at this!

@osterman
Copy link
Member

osterman commented Dec 6, 2024

Thanks, @RoseSecurity! This will be a huge QoL improvement. Out of curiosity, will you take a stab at atmos terraform commands? If not, I'll add it to our backlog.

@RoseSecurity
Copy link
Contributor Author

Closing this until the improved list stacks view is completed and I will rework based off of that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
minor New features that do not break anything
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants