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

Introduce terraform subcommand #221

Merged
merged 2 commits into from
Aug 6, 2024

Conversation

zzaakiirr
Copy link
Contributor

@zzaakiirr zzaakiirr commented Jul 30, 2024

What does this PR do?

This PR adds possibility to add subcommands to cpflow cli tool and adds cpflow terraform generate command which does nothing (for now)

Note

  • Fixed CommandHelpers#run_cpflow_command so that cpflow help shows cpflow <command_name> i/o rspec <command_name>
  • Command::Terraform::Generate will be implemented in feature PRs

Screenshots

Screenshot 2024-07-30 at 13 29 22 Screenshot 2024-07-30 at 13 30 06 Screenshot 2024-07-30 at 13 30 38

Summary by CodeRabbit

  • New Features

    • Introduced a new generate command to automate Terraform configuration file creation in the CLI.
  • Bug Fixes

    • Enhanced command discovery to include files in nested directories, improving the accessibility of commands.
  • Tests

    • Added a new test case to verify proper handling of subcommands within the CLI.
  • Chores

    • Improved command execution context management and introduced a utility method for better code organization.

Copy link

coderabbitai bot commented Jul 30, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The updates introduce significant enhancements to the cpflow CLI by adding a new generate command for Terraform configuration, improving command discovery and handling of subcommands, and structuring subcommands more effectively. These changes streamline the user experience, making it easier to manage infrastructure as code and facilitating better organization within the command-line application. Testing enhancements ensure that the new functionalities work as intended.

Changes

File Change Summary
docs/commands.md Added generate command documentation for generating Terraform configuration files from controlplane.yml.
lib/command/base.rb Enhanced all_commands to support recursive file discovery and proper namespace handling for commands.
lib/command/base_sub_command.rb Introduced BaseSubCommand class for structured definition of subcommands, including methods for command banners and subcommand prefixes.
lib/command/terraform/generate.rb Created Generate class within Command::Terraform for generating Terraform configurations; includes command metadata and placeholders for future implementation.
lib/cpflow.rb Added subcommand_names and klass_for methods to dynamically handle subcommands and improve command processing.
spec/cpflow_spec.rb Added tests to verify correct handling of subcommands and their help output in the CLI.
spec/support/command_helpers.rb Enhanced run_cpflow_command to manage the global $PROGRAM_NAME; introduced package_name method for better code organization.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Command
    participant Terraform

    User->>CLI: cpflow terraform generate
    CLI->>Command: Initialize Generate Command
    Command->>Terraform: Generate configuration files
    Terraform-->>Command: Return generated files
    Command-->>CLI: Display success message
    CLI-->>User: Show confirmation of files generated
Loading

🐰 In the warren where changes bloom,
New commands bring joy, dispelling gloom.
With subcommands now in their place,
Infrastructure flows with grace.
A hop, a skip, we generate with glee,
Oh, what a wondrous CLI, come see! 🎉


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

@zzaakiirr
Copy link
Contributor Author

@coderabbitai review

Copy link

coderabbitai bot commented Jul 30, 2024

Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 66e532b and 0c4d2a6.

Files selected for processing (7)
  • docs/commands.md (1 hunks)
  • lib/command/base.rb (1 hunks)
  • lib/command/base_sub_command.rb (1 hunks)
  • lib/command/terraform/generate.rb (1 hunks)
  • lib/cpflow.rb (4 hunks)
  • spec/cpflow_spec.rb (1 hunks)
  • spec/support/command_helpers.rb (3 hunks)
Additional context used
Markdownlint
docs/commands.md

447-447: null
Multiple headings with the same content

(MD024, no-duplicate-heading)

Additional comments not posted (12)
lib/command/base_sub_command.rb (2)

9-14: LGTM!

The self.subcommand_prefix method correctly transforms the class name to a subcommand prefix.


5-7: Verify the necessity of rubocop:disable.

The rubocop:disable Style/OptionalBooleanParameter comment might be necessary, but it's good to verify if there's a better way to handle this.

spec/cpflow_spec.rb (1)

23-36: LGTM!

The test case correctly verifies the handling of subcommands, ensuring that the help command and each subcommand return the expected results.

spec/support/command_helpers.rb (3)

188-189: Ensure the global state is restored correctly.

The ensure block correctly restores the original value of $PROGRAM_NAME.


266-268: LGTM!

The new package_name method improves code readability and encapsulation.


160-162: Ensure the global state is preserved correctly.

The changes to capture and set $PROGRAM_NAME are correct. Ensure that this does not affect other parts of the system.

Verification successful

The global state of $PROGRAM_NAME is preserved correctly.

The changes to capture and set $PROGRAM_NAME are confined to the run_cpflow_command method, and the original value is restored properly. No unintended side effects were found in other parts of the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the global state of $PROGRAM_NAME is preserved correctly.

# Test: Search for the usage of $PROGRAM_NAME. Expect: No unintended side effects.
rg --type ruby -A 5 '\$PROGRAM_NAME'

Length of output: 752

lib/cpflow.rb (2)

116-119: LGTM!

The changes ensure that the help functionality correctly handles subcommands.


168-176: LGTM!

The klass_for method enhances the extensibility of the command structure by allowing subcommands to be defined dynamically.

lib/command/base.rb (1)

47-61: LGTM!

The changes to the all_commands method improve the command discovery mechanism by supporting a hierarchical module structure and enabling the inclusion of commands from nested directories.

docs/commands.md (3)

447-447: LGTM!

The new generate command heading is correctly placed.

Tools
Markdownlint

447-447: null
Multiple headings with the same content

(MD024, no-duplicate-heading)


449-450: LGTM!

The description for the generate command is clear and concise.


451-453: LGTM!

The usage example for the generate command is correctly formatted and clear.

lib/command/terraform/generate.rb Show resolved Hide resolved
@zzaakiirr zzaakiirr marked this pull request as ready for review July 30, 2024 10:45
Copy link
Collaborator

@rafaelgomesxyz rafaelgomesxyz left a comment

Choose a reason for hiding this comment

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

Just a partial review so far, but I almost wonder if it wouldn't be easier to just use : like we do for ps:start, ps:stop, etc. Like terraform:generate. Are subcommands preferrable?

docs/commands.md Outdated Show resolved Hide resolved
lib/command/base.rb Show resolved Hide resolved
lib/command/terraform/generate.rb Outdated Show resolved Hide resolved
lib/command/terraform/generate.rb Outdated Show resolved Hide resolved
lib/cpflow.rb Outdated Show resolved Hide resolved
lib/cpflow.rb Outdated Show resolved Hide resolved
lib/cpflow.rb Show resolved Hide resolved
spec/support/command_helpers.rb Outdated Show resolved Hide resolved
@zzaakiirr
Copy link
Contributor Author

Just a partial review so far, but I almost wonder if it wouldn't be easier to just use : like we do for ps:start, ps:stop, etc. Like terraform:generate. Are subcommands preferrable?

I missed that 🥲

I still prefer subcommands because user can get all terraform commands by invoking cpflow terraform --help. The problem with : approach is that user needs to invoke cpflow help for each command in this namespace

Another issue with this approach is class names which must include subcommand namespace in class names (class Ps<CommandName> for example), declaring separate module is better (IMHO)

I won't push on subcommand approach @rafaelgomesxyz @borela WDYT?

@borela
Copy link
Member

borela commented Jul 31, 2024

@zzaakiirr I am in favor of your design as it is more common in UNIX for CLIs that support subcommands.

@justin808 @rafaelgomesxyz @dzirtusss @zzaakiirr I would prefer to change the loading logic to just reopen the CLI class for each command and declare them like Thor docs says, e.g.:

# command_1.rb
class CLI < Thor
  desc "usage", "desc"
  long_desc "long desc"
  def command_1
  end
end

# command_2.rb
class CLI < Thor
  desc "usage", "desc"
  long_desc "long desc"
  def command_2
  end
end

...

By reopening the class this way, you can still share state, methods etc... and still follow Thor's design.

@rafaelgomesxyz
Copy link
Collaborator

rafaelgomesxyz commented Jul 31, 2024

@borela We have a bunch of custom logic that benefits from the current loading logic, as you can see in https://github.com/shakacode/control-plane-flow/blob/main/lib/cpflow.rb#L168.

What are the benefits of switching to your proposed logic?

Thor doesn't really have a design for defining commands in separate files, so I'm not sure what you mean by that.

I think we should keep it the way it is.

@borela
Copy link
Member

borela commented Jul 31, 2024

@rafaelgomesxyz, it looks like you are re-implementing Thor's features; Which features that custom logic implement that Thor already doesn't support? Validations? That could be extracted to a method that accepts a value and pattern to validate against.

Copy link
Collaborator

@rafaelgomesxyz rafaelgomesxyz left a comment

Choose a reason for hiding this comment

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

@zzaakiirr Let's keep the subdomain approach then. I've finished reviewing the entire PR and added some more comments.

spec/support/command_helpers.rb Outdated Show resolved Hide resolved
spec/cpflow_spec.rb Outdated Show resolved Hide resolved
spec/cpflow_spec.rb Outdated Show resolved Hide resolved
spec/cpflow_spec.rb Outdated Show resolved Hide resolved
spec/cpflow_spec.rb Outdated Show resolved Hide resolved
full_classname = [*namespaces, classname].join("::").prepend("::")

command_key = File.basename(file, ".rb")
prefix = namespaces[1..1].map(&:downcase).join("_")
Copy link
Collaborator

Choose a reason for hiding this comment

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

Did you mean namespaces[1..]? Because namespaces[1..1] should be the same as namespaces[1], no?

Copy link
Contributor Author

@zzaakiirr zzaakiirr Aug 1, 2024

Choose a reason for hiding this comment

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

You are right, I meant namespaces[1..]. We don't need first namespace (which is Command)

Copy link
Collaborator

Choose a reason for hiding this comment

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

It's still namespaces[1..1] by the way.

lib/cpflow.rb Outdated Show resolved Hide resolved
lib/cpflow.rb Outdated Show resolved Hide resolved
lib/cpflow.rb Outdated Show resolved Hide resolved
lib/cpflow.rb Outdated Show resolved Hide resolved
@rafaelgomesxyz
Copy link
Collaborator

@borela We're not though, we just have a layer on top of Thor to make things easier. It's not just validations, but also handling of deprecated commands and special args / options cases, as well as setting some fallback values here and there.

Regardless, if we were to reopen the class in every command file, we'd have to repeat all of this logic for each file. Sure, we could move some logic to common helpers, but we'd still have repetition, which is why this way seems better to me. I don't see any benefits in switching to the way you proposed.

@borela
Copy link
Member

borela commented Jul 31, 2024

@rafaelgomesxyz The code for each command would be linear and less magical. A little bit of repetition is fine if the end result is simpler to read.

In an example scenario, command x is having a validation issue. I will go to the command x file and see how validation is being performed (either directly or by calling an accessory function) inside the command's method.

That does not happen with the current design, it is not immediately obvious where simple stuff like validations are happening or that those options are being validated. In contrast, other projects using thor just do simple ||= for fallback values and validate the option on the command itself, which again can be extracted to a method and called by the command.

@rafaelgomesxyz
Copy link
Collaborator

Let's see what Sergey and Justin think, but I still think we should keep it as is.

I think once you understand the constants defined at the top of the command classes and how options are defined in Base, it becomes pretty straightforward to figure out how something is being validated.

Another thing I like about the current approach is that we have a somewhat centralized place for all Thor stuff, which allows us to have a better separation of concerns, and detaches our app from Thor. It would be a lot easier to adapt the code if we wanted to replace Thor with something else - I know Justin was considering moving to an npm package so we have both the CPLN CLI and our CLI in the same place, and although that wouldn't help too much in this case, because we'd still need to convert from Ruby to JavaScript, I think it would definitely make things easier.

We also have some configs set on the class level based on the commands, which benefits from the current approach:

disable_required_check!(*@commands_with_required_options)
check_unknown_options!(except: @commands_with_extra_options)
stop_on_unknown_option!

These cannot be set individually, so we'd still need a way to go through all command classes looking for matches.

@borela
Copy link
Member

borela commented Aug 1, 2024

@rafaelgomesxyz Looking at the source, just build image has ACCEPTS_EXTRA_OPTIONS set to true, and it looks like it only does this because it forwards them to docker.

Why not declare the docker options supported? The error message will be better and when somebody does cpflow build-image --help they will see them too.

@borela
Copy link
Member

borela commented Aug 5, 2024

@rafaelgomesxyz if zakir pr is following the current pattern and working we can merge this pr and I can move my suggestions to an issue.

Copy link
Collaborator

@rafaelgomesxyz rafaelgomesxyz left a comment

Choose a reason for hiding this comment

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

@zzaakiirr Just one thing that you said you changed, but probably forgot to. Feel free to merge after changing it.

full_classname = [*namespaces, classname].join("::").prepend("::")

command_key = File.basename(file, ".rb")
prefix = namespaces[1..1].map(&:downcase).join("_")
Copy link
Collaborator

Choose a reason for hiding this comment

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

It's still namespaces[1..1] by the way.

@zzaakiirr zzaakiirr force-pushed the inroduce-terraform-subcommand branch from ab93ec4 to 7eaf5ca Compare August 6, 2024 10:27
@zzaakiirr zzaakiirr merged commit d55ed1f into terraform-feature Aug 6, 2024
5 checks passed
@zzaakiirr zzaakiirr deleted the inroduce-terraform-subcommand branch August 6, 2024 10:32
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.

3 participants