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(client/v2): support definitions of inner messages #22890

Merged
merged 12 commits into from
Dec 18, 2024

Conversation

JulianToledano
Copy link
Contributor

@JulianToledano JulianToledano commented Dec 16, 2024

Description

Closes: #18310


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Support for flattening inner message fields in AutoCLI as positional arguments.
    • Enhanced documentation for GeneratorParams struct fields.
  • Bug Fixes

    • Resolved issues with *big.Int unmarshalling in transactions.
  • Documentation

    • Updated changelog for client/v2 with new features, improvements, and breaking changes.
    • Expanded README documentation for autocli, detailing usage of flattened fields in positional arguments.
  • Tests

    • Added new test function TestMsgWithFlattenFields to validate command execution.
    • Updated test cases to reflect changes in permission level representations.
  • Chores

    • Introduced a new JSON structure in flatten-output.golden for parameter updates.

Copy link
Contributor

coderabbitai bot commented Dec 16, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces enhancements to the AutoCLI functionality in the Cosmos SDK client/v2 module. The changes focus on improving the handling of positional arguments, particularly for nested message fields. The modifications include updates to the flag builder, message binder, and associated test cases. A new method for flattening inner message fields has been implemented, allowing more flexible command argument parsing and improved user experience when working with complex message structures.

Changes

File Change Summary
api/cosmos/benchmark/module/v1/module.pulsar.go Added comprehensive field documentation for GeneratorParams struct
client/v2/CHANGELOG.md Updated with new features, API breaking changes, and improvements
client/v2/autocli/flag/builder.go Added methods addFlattenFieldBindingToArgs and addFieldBindingToArgs for improved argument handling
client/v2/autocli/flag/messager_binder.go Added bindNestedField method and path field to support nested field binding
client/v2/autocli/msg_test.go Added TestMsgWithFlattenFields test function
client/v2/autocli/testdata/flatten-output.golden New golden file for testing flattened message output
proto/cosmos/autocli/v1/options.proto Added go_package option and annotated gov_proposal field
client/v2/README.md Enhanced documentation for the autocli package
x/circuit/autocli.go Updated command options for AuthorizeCircuitBreaker RPC method

Assessment against linked issues

Objective Addressed Explanation
Support definitions of inner messages
Flatten inner message fields as positional arguments

Suggested labels

C:x/circuit

Suggested reviewers

  • akhilkumarpilli
  • testinginprod
  • sontrinh16
  • tac0turtle

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

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.

@github-actions github-actions bot added the C:CLI label Dec 16, 2024
field := fields.ByName(protoreflect.Name(arg.ProtoField))
if field == nil {
return nil, fmt.Errorf("can't find field %s on %s", arg.ProtoField, messageType.Descriptor().FullName())
if arg.FlattenFields {
Copy link
Member

Choose a reason for hiding this comment

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

We actually don't want the user to have to precise this in their autocli options.
I think ideally it should just work.

if you put permissions you it set the whole struct. If you put permissions.level it it checks the inner field. I think splitting by . may do the job here right.
The big q is how many layer do we accept. Can you do permissions.foo.bar as well?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

ok. If you set only permissions should it flatten the whole struct or should expect a json?

In the first case, should we provide an option to specify a json file? it may be better ux if message is really big.

About the layer that's a good question. I'll try to find a recursive way so there's no limit to it.

Copy link
Member

Choose a reason for hiding this comment

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

I meant, it should expect a json yeah, like today

Copy link
Member

Choose a reason for hiding this comment

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

In the first case, should we provide an option to specify a json file? it may be better ux if message is really big.

It can get messy if you have multiple input expecting a json, so to simplify things I'd say no.
If you want a better UX you break out the json in multiple inputs by using the feature added here

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Dec 17, 2024
@JulianToledano JulianToledano marked this pull request as ready for review December 17, 2024 17:57
@JulianToledano JulianToledano requested a review from a team as a code owner December 17, 2024 17:57
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: 0

🧹 Nitpick comments (6)
client/v2/autocli/flag/messager_binder.go (2)

94-125: Enhance error messages by including the full field path

Including the full field path in error messages within the bindNestedField function would provide better context for debugging when a field is not found.

Consider updating the error message on line 104:

- return fmt.Errorf("field %q not found", path[0])
+ return fmt.Errorf("field %q not found in path %q", path[0], strings.Join(path, "."))

Line range hint 301-301: Address the TODO by enhancing the error message

The TODO comment suggests including msg.Descriptor().FullName() in the error message to improve clarity. Implementing this change would provide more context about the message where the field is missing.

Consider updating the error message on line 301:

- return fieldBinding{}, fmt.Errorf("can't find field %s", name) // TODO: it will improve error if msg.FullName() was included.`
+ return fieldBinding{}, fmt.Errorf("can't find field %s in message %s", name, msg.Descriptor().FullName())

Would you like me to open a GitHub issue for this enhancement?

client/v2/autocli/flag/builder.go (1)

276-294: Consider renaming variable s to fieldPathSegments for clarity

In the addFlattenFieldBindingToArgs function, renaming the variable s to fieldPathSegments would improve readability by making the purpose of the variable clearer.

Apply this diff to rename the variable:

- func (b *Builder) addFlattenFieldBindingToArgs(ctx *context.Context, path string, s []string, msg protoreflect.MessageType, messageBinder *MessageBinder) error {
+ func (b *Builder) addFlattenFieldBindingToArgs(ctx *context.Context, path string, fieldPathSegments []string, msg protoreflect.MessageType, messageBinder *MessageBinder) error {

    // update usages of 's' within the function
- if len(s) == 1 {
+ if len(fieldPathSegments) == 1 {

- fd := fields.ByName(protoreflect.Name(s[0]))
+ fd := fields.ByName(protoreflect.Name(fieldPathSegments[0]))

- return b.addFlattenFieldBindingToArgs(ctx, path, s[1:], innerMsg, messageBinder)
+ return b.addFlattenFieldBindingToArgs(ctx, path, fieldPathSegments[1:], innerMsg, messageBinder)
client/v2/CHANGELOG.md (1)

49-49: Ensure consistent capitalization of 'AutoCLI'

For consistency, 'autocli' should be capitalized as 'AutoCLI' to match the project's naming convention.

Apply this diff to correct the capitalization:

- * [#22890](https://github.com/cosmos/cosmos-sdk/pull/22890)  Added support for flattening inner message fields in autocli as positional arguments.
+ * [#22890](https://github.com/cosmos/cosmos-sdk/pull/22890)  Added support for flattening inner message fields in AutoCLI as positional arguments.
client/v2/autocli/msg_test.go (1)

131-156: Enhance test coverage for flattened fields.

While the test validates the basic functionality of flattened fields, consider adding the following test cases:

  1. Invalid input validation (e.g., missing required fields)
  2. Error cases (e.g., malformed nested field paths)
  3. Edge cases (e.g., deeply nested fields, multiple array indices)

Add test cases for error scenarios:

 func TestMsgWithFlattenFields(t *testing.T) {
     fixture := initFixture(t)
+
+    // Test happy path
     out, err := runCmd(fixture, buildCustomModuleMsgCommand(&autocliv1.ServiceCommandDescriptor{
         Service: bankv1beta1.Msg_ServiceDesc.ServiceName,
         RpcCommandOptions: []*autocliv1.RpcCommandOptions{
             {
                 RpcMethod: "UpdateParams",
                 PositionalArgs: []*autocliv1.PositionalArgDescriptor{
                     {ProtoField: "authority"},
                     {ProtoField: "params.send_enabled.denom"},
                     {ProtoField: "params.send_enabled.enabled"},
                     {ProtoField: "params.default_send_enabled"},
                 },
             },
         },
         EnhanceCustomCommand: true,
     }), "update-params",
         "cosmos1y74p8wyy4enfhfn342njve6cjmj5c8dtl6emdk", "stake", "true", "true",
         "--generate-only",
         "--output", "json",
         "--chain-id", fixture.chainID,
     )
     assert.NilError(t, err)
     assertNormalizedJSONEqual(t, out.Bytes(), goldenLoad(t, "flatten-output.golden"))
+
+    // Test invalid nested field path
+    _, err = runCmd(fixture, buildCustomModuleMsgCommand(&autocliv1.ServiceCommandDescriptor{
+        Service: bankv1beta1.Msg_ServiceDesc.ServiceName,
+        RpcCommandOptions: []*autocliv1.RpcCommandOptions{
+            {
+                RpcMethod: "UpdateParams",
+                PositionalArgs: []*autocliv1.PositionalArgDescriptor{
+                    {ProtoField: "params.invalid.path"},
+                },
+            },
+        },
+    }), "update-params", "value",
+        "--generate-only",
+    )
+    assert.ErrorContains(t, err, "invalid field path")
+
+    // Test missing required fields
+    _, err = runCmd(fixture, buildCustomModuleMsgCommand(&autocliv1.ServiceCommandDescriptor{
+        Service: bankv1beta1.Msg_ServiceDesc.ServiceName,
+        RpcCommandOptions: []*autocliv1.RpcCommandOptions{
+            {
+                RpcMethod: "UpdateParams",
+                PositionalArgs: []*autocliv1.PositionalArgDescriptor{
+                    {ProtoField: "params.send_enabled.denom"},
+                },
+            },
+        },
+    }), "update-params", "stake",
+        "--generate-only",
+    )
+    assert.ErrorContains(t, err, "missing required field")
 }
api/cosmos/benchmark/module/v1/module.pulsar.go (1)

1364-1384: Enhance field documentation with units and valid ranges.

The documentation is clear but could be more helpful by including:

  1. Units for numeric fields (e.g., bytes for sizes)
  2. Valid value ranges
  3. Examples of typical values

Example improvements for selected fields:

-    // key_mean is the mean size (in normal distribution) of keys in each bucket.
+    // key_mean is the mean size in bytes (in normal distribution) of keys in each bucket.
+    // Valid range: 1-1024. Typical value: 32.
     KeyMean uint64 `protobuf:"varint,3,opt,name=key_mean,json=keyMean,proto3" json:"key_mean,omitempty"`

-    // insert_weight is the weight of insert operations.
+    // insert_weight is the weight of insert operations.
+    // Valid range: 0.0-1.0. The sum of all weights should equal 1.0.
+    // Example: 0.25 means 25% of operations will be inserts.
     InsertWeight float32 `protobuf:"fixed32,9,opt,name=insert_weight,json=insertWeight,proto3" json:"insert_weight,omitempty"`
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5799c15 and 9f01468.

📒 Files selected for processing (7)
  • api/cosmos/benchmark/module/v1/module.pulsar.go (1 hunks)
  • client/v2/CHANGELOG.md (1 hunks)
  • client/v2/autocli/flag/builder.go (3 hunks)
  • client/v2/autocli/flag/messager_binder.go (4 hunks)
  • client/v2/autocli/msg_test.go (1 hunks)
  • client/v2/autocli/testdata/flatten-output.golden (1 hunks)
  • proto/cosmos/autocli/v1/options.proto (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • client/v2/autocli/testdata/flatten-output.golden
🧰 Additional context used
📓 Path-based instructions (5)
client/v2/autocli/msg_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

client/v2/autocli/flag/messager_binder.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/autocli/flag/builder.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/CHANGELOG.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

api/cosmos/benchmark/module/v1/module.pulsar.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🔇 Additional comments (4)
client/v2/autocli/flag/builder.go (1)

301-301: Address the TODO by enhancing the error message

The TODO comment suggests including msg.FullName() in the error message for better clarity. Implementing this would provide additional context when a field cannot be found.

Consider updating the error message on line 301:

- return fieldBinding{}, fmt.Errorf("can't find field %s", name) // TODO: it will improve error if msg.FullName() was included.`
+ return fieldBinding{}, fmt.Errorf("can't find field %s in message %s", name, msg.FullName())

Would you like me to open a GitHub issue for this enhancement?

proto/cosmos/autocli/v1/options.proto (2)

6-6: LGTM!

The addition of the go_package option aligns with best practices for Go code generation from proto files.


Line range hint 79-79: Ensure correct syntax for field annotations

The annotation for gov_proposal on line 79 appears correct. Just double-check that the version string matches the intended release.

🧰 Tools
🪛 buf (1.47.2)

5-5: import "cosmos_proto/cosmos.proto": file does not exist

(COMPILE)

client/v2/CHANGELOG.md (1)

Line range hint 69-69: Correct the capitalization of 'GitHub'

In the usage instructions, 'Github' should be capitalized as 'GitHub' to reflect the proper branding.

Apply this diff:

- The issue numbers will later be link-ified during the release process so you do
- not have to worry about including a link manually, but you can if you wish.
+ The issue numbers will later be link-ified during the release process so you do
+ not have to worry about including a link manually, but you can if you wish.

Note: It seems there is already correct capitalization, so please disregard if 'GitHub' is already properly capitalized.

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

Can you migrate some commands directly in this PR as well? It will make testing easier and improve the UX. I should have left todos to the relevant ones. I think circuit is the easiest to validate.

@julienrbrt
Copy link
Member

$ simd tx circuit authorize alice super-admin "/cosmos.bank.v1beta1.MsgSend,/cosmos.bank.v1beta1.MsgMultiSend"
...
  messages:
  - '@type': /cosmos.circuit.v1.MsgAuthorizeCircuitBreaker
    grantee: alice
    granter: cosmos1r7e7rme2mrqdvju2qxtgcxp3f0ckevyj9p3e76
    permissions:
      level: LEVEL_SUPER_ADMIN
      limit_type_urls:
      - /cosmos.bank.v1beta1.MsgSend
      - /cosmos.bank.v1beta1.MsgMultiSend
...
diff --git a/x/circuit/autocli.go b/x/circuit/autocli.go
index a1cb8ada74..2d45d28072 100644
--- a/x/circuit/autocli.go
+++ b/x/circuit/autocli.go
@@ -37,16 +37,14 @@ func (am AppModule) AutoCLIOptions() *autocliv1.ModuleOptions {
 			RpcCommandOptions: []*autocliv1.RpcCommandOptions{
 				{
 					RpcMethod: "AuthorizeCircuitBreaker",
-					Use:       "authorize <grantee> <permissions_json> --from <granter>",
+					Use:       "authorize <grantee> <level> <msg_type_urls> --from <granter>",
 					Short:     "Authorize an account to trip the circuit breaker.",
-					Long: `Authorize an account to trip the circuit breaker.
-"SOME_MSGS" =     1,
-"ALL_MSGS" =      2,
-"SUPER_ADMIN" =   3,`,
-					Example: fmt.Sprintf(`%s tx circuit authorize [address] '{"level":1,"limit_type_urls":["/cosmos.bank.v1beta1.MsgSend", "/cosmos.bank.v1beta1.MsgMultiSend"]}'"`, version.AppName),
+					Long:      `Authorize an account to trip the circuit breaker. Level can be: some-msgs, all-msgs or super-admin.`,
+					Example:   fmt.Sprintf(`%s tx circuit authorize [address] super-admin "/cosmos.bank.v1beta1.MsgSend, /cosmos.bank.v1beta1.MsgMultiSend"`, version.AppName),
 					PositionalArgs: []*autocliv1.PositionalArgDescriptor{
 						{ProtoField: "grantee"},
-						{ProtoField: "permissions"}, // TODO(@julienrbrt) Support flattening msg for setting each field as a positional arg
+						{ProtoField: "permissions.level"},
+						{ProtoField: "permissions.limit_type_urls"},
 					},
 				},
 				{

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

tACK! Super nice 💪🏾

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

Let's add some docs about it in the README as well please. Can we maybe add flag support in a follow-up?

So that this can work for instance:

PositionalArgs: []*autocliv1.PositionalArgDescriptor{
	{ProtoField: "grantee"},
	{ProtoField: "permissions.limit_type_urls"},
},
FlagOptions: map[string]*autocliv1.FlagOptions{
	"permissions.level": {Name: "level", DefaultValue: "some-msgs"},
},

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

🧹 Nitpick comments (4)
client/v2/README.md (3)

173-176: Consider adding field descriptions in the protobuf example.

While the protobuf messages are well-structured, adding comments to describe the purpose of each field would improve clarity:

 message Permissions {
+    // level defines the permission level (e.g., "super-admin", "some-msgs")
     string level = 1;
+    // limit_type_urls defines the list of message type URLs that the grantee can manage
     repeated string limit_type_urls = 2;
 }

186-196: Consider adding explanatory comments to the AutoCLI configuration.

The configuration example would be more educational with inline comments explaining each option:

 {
     RpcMethod: "AuthorizeCircuitBreaker",
+    // Define command usage with clear parameter descriptions
     Use:       "authorize <grantee> <level> <msg_type_urls>",
     PositionalArgs: []*autocliv1.PositionalArgDescriptor{
+        // Map grantee address to the first position
         {ProtoField: "grantee"},
+        // Map nested permission level to the second position
         {ProtoField: "permissions.level"},
+        // Map nested type URLs to the third position
         {ProtoField: "permissions.limit_type_urls"},
     },
 }

198-204: Consider adding a comparison with the non-flattened alternative.

To better illustrate the benefits, show how the same command would look without flattening:

 This allows users to provide values for nested fields directly as positional arguments:

 ```bash
 <appd> tx circuit authorize cosmos1... super-admin "/cosmos.bank.v1beta1.MsgSend,/cosmos.bank.v1beta1.MsgMultiSend"

+Without flattening, users would need to provide a JSON structure:
+bash +<appd> tx circuit authorize cosmos1... '{"level":"super-admin","limit_type_urls":["/cosmos.bank.v1beta1.MsgSend","/cosmos.bank.v1beta1.MsgMultiSend"]}' +


</blockquote></details>
<details>
<summary>x/circuit/autocli.go (1)</summary><blockquote>

`40-40`: **LGTM! Consider making the example more generic.**

The command structure and documentation are clear and well-organized. However, the example uses specific message types that might become outdated.


Consider using placeholder text to make the example more maintainable:

```diff
-Example:   fmt.Sprintf(`%s tx circuit authorize [address] super-admin "/cosmos.bank.v1beta1.MsgSend,/cosmos.bank.v1beta1.MsgMultiSend"`, version.AppName),
+Example:   fmt.Sprintf(`%s tx circuit authorize [address] super-admin "[msg-type-url-1],[msg-type-url-2]"`, version.AppName),

Also applies to: 42-43

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f01468 and e805791.

📒 Files selected for processing (2)
  • client/v2/README.md (1 hunks)
  • x/circuit/autocli.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
x/circuit/autocli.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

client/v2/README.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

🔇 Additional comments (2)
client/v2/README.md (1)

164-169: LGTM! Clear and well-structured introduction.

The section header and introduction effectively explain the concept of flattened fields in positional arguments.

x/circuit/autocli.go (1)

46-48: Verify the necessity of both parent and nested permission fields.

The positional arguments include both the parent permissions field and its nested fields (level and limit_type_urls). This structure might cause confusion about how to provide these arguments.

Let's check how these fields are used in the codebase:

✅ Verification successful

Let me gather more information about how these fields are used in the actual implementation.


Let me search for more specific information about the flattening configuration.


Let me check one more thing about the CLI command implementation and its usage.


Based on the gathered information, I can now provide a final response about the positional arguments configuration.

The parent and nested permission fields are correctly configured

The configuration is intentional and matches the CLI command's usage pattern. This is evidenced by:

  1. The example command shows the expected usage:
tx circuit authorize [address] super-admin "/cosmos.bank.v1beta1.MsgSend,/cosmos.bank.v1beta1.MsgMultiSend"
  1. The positional arguments match this pattern:
  • grantee for the address
  • permissions.level for the admin level
  • permissions.limit_type_urls for the message types

The parent permissions field is included to maintain the proper message structure, while the nested fields are flattened for CLI usability.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of these fields in message definitions and tests
ast-grep --pattern 'message Permissions {
  $$$
  Level level = $_;
  repeated string limit_type_urls = $_;
  $$$
}'

# Search for related test cases
rg -A 5 'TestAuthorizeCircuitBreaker|TestMsgWithFlattenFields'

Length of output: 1482


Script:

#!/bin/bash
# Search for the message definition and its usage
rg -A 10 "message MsgAuthorizeCircuitBreaker"

# Search for any flattened field configurations
rg -B 2 -A 2 "FlattenOptions|flatten:"

# Look for CLI command implementations
ast-grep --pattern 'func NewMsgAuthorizeCircuitBreakerCmd() *cobra.Command {
  $$$
}'

Length of output: 67790


Script:

#!/bin/bash
# Search for flattening configuration in autocli
rg -B 2 -A 2 'FlattenOptions|flatten:' x/circuit/

# Search for the Permissions message definition
ast-grep --pattern 'message Permissions {
  $$$
}'

# Look for any CLI command implementations that use these fields
rg -A 5 'permissions.level|permissions.limit_type_urls' x/circuit/

Length of output: 514


Script:

#!/bin/bash
# Search for the CLI command usage and examples
rg -A 10 'Example:|Usage:' x/circuit/

# Look for test cases that demonstrate the field usage
rg -A 10 'TestCmd|TestAuthorize.*Circuit' x/circuit/

# Check if there are any comments about flattening in the code
rg -B 2 'permissions.*{' x/circuit/

Length of output: 5345

@julienrbrt
Copy link
Member

Can you update the system tests to match the new command?

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

🧹 Nitpick comments (1)
tests/systemtests/circuit_test.go (1)

133-133: Consider adding negative test cases

While the happy path is well tested, consider adding test cases for:

  • Invalid permission levels
  • Malformed message type URLs
  • Empty message type URLs list when required
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e805791 and bc53fd1.

📒 Files selected for processing (2)
  • tests/systemtests/circuit_test.go (1 hunks)
  • x/circuit/autocli.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
x/circuit/autocli.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

tests/systemtests/circuit_test.go (3)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (3)
x/circuit/autocli.go (2)

40-40: Improved CLI command structure and documentation

The command structure has been simplified and made more intuitive by:

  • Replacing JSON input with clear positional arguments
  • Adding explicit documentation for permission levels
  • Providing a more straightforward example

Also applies to: 42-43


46-47: Verify backward compatibility of the new command structure

While the new positional arguments improve usability, we should ensure existing scripts using the old JSON format are properly handled.

✅ Verification successful

Based on the extensive codebase analysis, I can now provide a definitive response regarding the backward compatibility concern:

No backward compatibility concerns with the new command structure

The circuit authorize command's new positional arguments structure is safe to implement because:

  1. There are no existing shell scripts in the codebase using the old JSON format for the circuit authorize command
  2. The AutoCLI documentation explicitly shows this is a new feature for flattening nested message fields as positional arguments
  3. The underlying protobuf message structure remains unchanged, so any existing programmatic usage would continue to work
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing usage of the circuit authorize command in scripts
rg -g '*.{sh,bash,zsh}' 'circuit.*authorize.*permissions'

Length of output: 59


Script:

#!/bin/bash
# Let's search for any test files or documentation that might show usage examples
rg -g '*.{go,md}' -i 'circuit.*authorize.*permissions'

# Also search for any CLI tests specifically
fd -e go test.*cli -x rg -l 'circuit.*authorize'

# Look for any existing circuit authorization related code
ast-grep --pattern 'func $_($$$ *cobra.Command $$$) {
  $$$
  authorize $$$
}'

Length of output: 1082


Script:

#!/bin/bash
# Let's check for any existing CLI tests specifically for circuit authorization
rg -g '*.go' -B 5 -A 5 'TestCmd.*Circuit.*Authorize'

# Look for any examples or documentation of the command usage
fd -e md -x rg -l 'circuit.*authorize'

# Check the actual CLI command implementation
ast-grep --pattern 'func NewAuthorizeCommand() *cobra.Command {
  $$$
}'

Length of output: 192


Script:

#!/bin/bash
# Let's check the content of the README that mentions circuit authorize
cat ./client/v2/README.md

# Let's also check for any recent changes to circuit authorization related files
rg -g '*.go' -B 3 -A 3 'MsgAuthorizeCircuitBreaker'

Length of output: 96488

tests/systemtests/circuit_test.go (1)

104-104: Enhanced test readability with descriptive permission levels

The change from numeric to string-based permission levels improves code readability and maintainability. The values now directly correspond to the CLI documentation.

Also applies to: 111-111, 118-118, 125-125

@julienrbrt julienrbrt added this pull request to the merge queue Dec 18, 2024
Merged via the queue into main with commit cb56c6e Dec 18, 2024
81 of 82 checks passed
@julienrbrt julienrbrt deleted the julian/autocli-inner-messages branch December 18, 2024 11:03
mergify bot pushed a commit that referenced this pull request Dec 18, 2024
julienrbrt pushed a commit that referenced this pull request Dec 18, 2024
julienrbrt pushed a commit that referenced this pull request Dec 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:CLI C:x/circuit
Projects
None yet
Development

Successfully merging this pull request may close these issues.

AutoCLI Enhancements
6 participants