Skip to content

Commit

Permalink
feat(client/v2): add autocli run + simapp example (#13867)
Browse files Browse the repository at this point in the history
Co-authored-by: Julien Robert <[email protected]>
  • Loading branch information
aaronc and julienrbrt authored Dec 31, 2022
1 parent 02ca843 commit ebfd057
Show file tree
Hide file tree
Showing 37 changed files with 1,232 additions and 57 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Features

* (client) [#13867](https://github.com/cosmos/cosmos-sdk/pull/13867/) Wire AutoCLI commands with SimApp.
* (x/distribution) [#14322](https://github.com/cosmos/cosmos-sdk/pull/14322) Introduce a new gRPC message handler, `DepositValidatorRewardsPool`, that allows explicit funding of a validator's reward pool.
* (x/slashing, x/staking) [#14363](https://github.com/cosmos/cosmos-sdk/pull/14363) Add the infraction a validator committed type as an argument to a `SlashWithInfractionReason` keeper method.
* (x/evidence) [#13740](https://github.com/cosmos/cosmos-sdk/pull/13740) Add new proto field `hash` of type `string` to `QueryEvidenceRequest` which helps to decode the hash properly while using query API.
Expand Down
2 changes: 1 addition & 1 deletion client/flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ var LineBreak = &cobra.Command{Run: func(*cobra.Command, []string) {}}
func AddQueryFlagsToCmd(cmd *cobra.Command) {
cmd.Flags().String(FlagNode, "tcp://localhost:26657", "<host>:<port> to Tendermint RPC interface for this chain")
cmd.Flags().String(FlagGRPC, "", "the gRPC endpoint to use for this chain")
cmd.Flags().Bool(FlagGRPCInsecure, false, "allow gRPC over insecure channels, if not TLS the server must use TLS")
cmd.Flags().Bool(FlagGRPCInsecure, false, "allow gRPC over insecure channels, if not the server must use TLS")
cmd.Flags().Int64(FlagHeight, 0, "Use a specific height to query state at (this can error if the node is pruning state)")
cmd.Flags().StringP(FlagOutput, "o", "text", "Output format (text|json)")

Expand Down
103 changes: 103 additions & 0 deletions client/v2/autocli/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package autocli

import (
autocliv1 "cosmossdk.io/api/cosmos/autocli/v1"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/spf13/cobra"
"google.golang.org/grpc"
)

// AppOptions are autocli options for an app. These options can be built via depinject based on an app config. Ex:
// Ex:
//
// var autoCliOpts autocli.AppOptions
// err := depinject.Inject(appConfig, &encodingConfig.InterfaceRegistry, &autoCliOpts)
//
// If depinject isn't used, options can be provided manually or extracted from modules. One method for extracting autocli
// options is via the github.com/cosmos/cosmos-sdk/runtime/services.ExtractAutoCLIOptions function.
type AppOptions struct {
depinject.In

// Modules are the AppModule implementations for the modules in the app.
Modules map[string]appmodule.AppModule

// ModuleOptions are autocli options to be used for modules instead of what
// is specified on the module's AppModule implementation. This allows an
// app to override module options if they are either not provided by a
// module or need to be improved.
ModuleOptions map[string]*autocliv1.ModuleOptions `optional:"true"`
}

// RootCmd generates a root command for an app based on the AppOptions. This
// command currently only includes query commands but will be enhanced over
// time to cover the full scope of an app CLI.
func (appOptions AppOptions) RootCmd() (*cobra.Command, error) {
rootCmd := &cobra.Command{}
err := appOptions.EnhanceRootCommand(rootCmd)
return rootCmd, err
}

// EnhanceRootCommand enhances the provided root command with autocli AppOptions,
// only adding missing query commands and doesn't override commands already
// in the root command. This allows for the graceful integration of autocli with
// existing app CLI commands where autocli simply automatically adds things that
// weren't manually provided. It does take into account custom query commands
// provided by modules with the HasCustomQueryCommand extension interface.
// Example Usage:
//
// var autoCliOpts autocli.AppOptions
// err := depinject.Inject(appConfig, &autoCliOpts)
// if err != nil {
// panic(err)
// }
// rootCmd := initRootCmd()
// err = autoCliOpts.EnhanceRootCommand(rootCmd)
func (appOptions AppOptions) EnhanceRootCommand(rootCmd *cobra.Command) error {
builder := &Builder{
GetClientConn: func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
return client.GetClientQueryContext(cmd)
},
AddQueryConnFlags: flags.AddQueryFlagsToCmd,
}

moduleOptions := appOptions.ModuleOptions
if moduleOptions == nil {
moduleOptions = map[string]*autocliv1.ModuleOptions{}

for name, module := range appOptions.Modules {
if module, ok := module.(HasAutoCLIConfig); ok {
moduleOptions[name] = module.AutoCLIOptions()
}
}
}

customQueryCmds := map[string]*cobra.Command{}
for name, module := range appOptions.Modules {
if module, ok := module.(HasCustomQueryCommand); ok {
cmd := module.GetQueryCmd()
// filter any nil commands
if cmd != nil {
customQueryCmds[name] = cmd
}
}
}

// if we have an existing query command, enhance it or build a custom one
if queryCmd := findSubCommand(rootCmd, "query"); queryCmd != nil {
if err := builder.EnhanceQueryCommand(queryCmd, moduleOptions, customQueryCmds); err != nil {
return err
}
} else {
queryCmd, err := builder.BuildQueryCommand(moduleOptions, customQueryCmds)
if err != nil {
return err
}

rootCmd.AddCommand(queryCmd)
}

return nil
}
7 changes: 4 additions & 3 deletions client/v2/autocli/builder.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package autocli

import (
"context"

"github.com/spf13/cobra"
"google.golang.org/grpc"

"cosmossdk.io/client/v2/autocli/flag"
Expand All @@ -15,5 +14,7 @@ type Builder struct {

// GetClientConn specifies how CLI commands will resolve a grpc.ClientConnInterface
// from a given context.
GetClientConn func(context.Context) grpc.ClientConnInterface
GetClientConn func(*cobra.Command) (grpc.ClientConnInterface, error)

AddQueryConnFlags func(*cobra.Command)
}
59 changes: 48 additions & 11 deletions client/v2/autocli/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,57 @@ import (
func (b *Builder) BuildQueryCommand(moduleOptions map[string]*autocliv1.ModuleOptions, customCmds map[string]*cobra.Command) (*cobra.Command, error) {
queryCmd := topLevelCmd("query", "Querying subcommands")
queryCmd.Aliases = []string{"q"}
for moduleName, modOpts := range moduleOptions {
if customCmds[moduleName] != nil {
if err := b.EnhanceQueryCommand(queryCmd, moduleOptions, customCmds); err != nil {
return nil, err
}

return queryCmd, nil
}

// EnhanceQueryCommand enhances the provided query command with either generated commands based on the provided module
// options or the provided custom commands for each module. If the provided query command already contains a command
// for a module, that command is not over-written by this method. This allows a graceful addition of autocli to
// automatically fill in missing commands.
func (b *Builder) EnhanceQueryCommand(queryCmd *cobra.Command, moduleOptions map[string]*autocliv1.ModuleOptions, customCmds map[string]*cobra.Command) error {
allModuleNames := map[string]bool{}
for moduleName := range moduleOptions {
allModuleNames[moduleName] = true
}
for moduleName := range customCmds {
allModuleNames[moduleName] = true
}

for moduleName := range allModuleNames {
// if we have an existing command skip adding one here
if existing := findSubCommand(queryCmd, moduleName); existing != nil {
continue
}

// if we have a custom command use that instead of generating one
if custom := customCmds[moduleName]; custom != nil {
// custom commands get added lower down
queryCmd.AddCommand(custom)
continue
}

// check for autocli options
modOpts := moduleOptions[moduleName]
if modOpts == nil {
continue
}

queryCmdDesc := modOpts.Query
if queryCmdDesc != nil {
cmd, err := b.BuildModuleQueryCommand(moduleName, queryCmdDesc)
if err != nil {
return nil, err
return err
}

queryCmd.AddCommand(cmd)
}
}

for _, cmd := range customCmds {
queryCmd.AddCommand(cmd)
}

return queryCmd, nil
return nil
}

// BuildModuleQueryCommand builds the query command for a single module.
Expand Down Expand Up @@ -74,7 +103,7 @@ func (b *Builder) AddQueryServiceCommands(cmd *cobra.Command, cmdDescriptor *aut
rpcOptMap[name] = option
// make sure method exists
if m := methods.ByName(name); m == nil {
return fmt.Errorf("rpc method %s not found for service %s", name, service.FullName())
return fmt.Errorf("rpc method %q not found for service %q", name, service.FullName())
}
}

Expand Down Expand Up @@ -163,14 +192,18 @@ func (b *Builder) BuildQueryMethodCommand(descriptor protoreflect.MethodDescript
}

cmd.RunE = func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
clientConn := getClientConn(ctx)
clientConn, err := getClientConn(cmd)
if err != nil {
return err
}

input, err := binder.BuildMessage(args)
if err != nil {
return err
}

output := outputType.New()
ctx := cmd.Context()
err = clientConn.Invoke(ctx, methodName, input.Interface(), output.Interface())
if err != nil {
return err
Expand All @@ -185,6 +218,10 @@ func (b *Builder) BuildQueryMethodCommand(descriptor protoreflect.MethodDescript
return err
}

if b.AddQueryConnFlags != nil {
b.AddQueryConnFlags(cmd)
}

return cmd, nil
}

Expand Down
4 changes: 2 additions & 2 deletions client/v2/autocli/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ func testExec(t *testing.T, args ...string) *testClientConn {
out: &bytes.Buffer{},
}
b := &Builder{
GetClientConn: func(ctx context.Context) grpc.ClientConnInterface {
return conn
GetClientConn: func(*cobra.Command) (grpc.ClientConnInterface, error) {
return conn, nil
},
}
cmd, err := b.BuildModuleQueryCommand("test", testCmdDesc)
Expand Down
19 changes: 19 additions & 0 deletions client/v2/autocli/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package autocli

import (
"strings"

"github.com/spf13/cobra"
)

// findSubCommand finds a sub-command of the provided command whose Use
// string is or begins with the provided subCmdName.
func findSubCommand(cmd *cobra.Command, subCmdName string) *cobra.Command {
for _, subCmd := range cmd.Commands() {
use := subCmd.Use
if use == subCmdName || strings.HasPrefix(use, subCmdName+" ") {
return subCmd
}
}
return nil
}
File renamed without changes.
95 changes: 91 additions & 4 deletions client/v2/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ go 1.19
require (
cosmossdk.io/api v0.2.6
cosmossdk.io/core v0.4.0
cosmossdk.io/depinject v1.0.0-alpha.3
github.com/cosmos/cosmos-proto v1.0.0-beta.1
github.com/cosmos/cosmos-sdk v0.47.0-alpha2.0.20221219231612-5ed4075ba219
github.com/spf13/cobra v1.6.1
github.com/spf13/pflag v1.0.5
google.golang.org/grpc v1.51.0
Expand All @@ -14,15 +16,100 @@ require (
)

require (
cosmossdk.io/depinject v1.0.0-alpha.3 // indirect
cosmossdk.io/errors v1.0.0-beta.7 // indirect
cosmossdk.io/math v1.0.0-beta.4 // indirect
filippo.io/edwards25519 v1.0.0-rc.1 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
github.com/99designs/keyring v1.2.1 // indirect
github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/confio/ics23/go v0.9.0 // indirect
github.com/cosmos/btcutil v1.0.5 // indirect
github.com/cosmos/go-bip39 v1.0.0 // indirect
github.com/cosmos/gogoproto v1.4.3 // indirect
github.com/cosmos/gorocksdb v1.2.0 // indirect
github.com/cosmos/iavl v0.19.4 // indirect
github.com/cosmos/ledger-cosmos-go v0.12.1 // indirect
github.com/danieljoos/wincred v1.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect
github.com/dgraph-io/badger/v2 v2.2007.4 // indirect
github.com/dgraph-io/ristretto v0.1.1 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/dvsekhvalnov/jose2go v1.5.0 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-kit/kit v0.12.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.0.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/google/go-cmp v0.5.9 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/gtank/merlin v0.1.1 // indirect
github.com/gtank/ristretto255 v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20220222234857-c00d1f31bab3 // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/klauspost/compress v1.15.12 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-isatty v0.0.16 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/mimoo/StrobeGo v0.0.0-20210601165009-122bf33a46e0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.14.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/viper v1.14.0 // indirect
github.com/stretchr/testify v1.8.1 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect
github.com/tendermint/btcd v0.1.1 // indirect
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tendermint/tendermint v0.37.0-rc2 // indirect
github.com/tendermint/tm-db v0.6.7 // indirect
github.com/tidwall/btree v1.5.2 // indirect
github.com/zondax/hid v0.9.1 // indirect
github.com/zondax/ledger-go v0.14.0 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/crypto v0.4.0 // indirect
golang.org/x/exp v0.0.0-20221019170559-20944726eadf // indirect
golang.org/x/net v0.2.0 // indirect
golang.org/x/sys v0.2.0 // indirect
golang.org/x/text v0.4.0 // indirect
golang.org/x/net v0.3.0 // indirect
golang.org/x/sys v0.3.0 // indirect
golang.org/x/term v0.3.0 // indirect
golang.org/x/text v0.5.0 // indirect
google.golang.org/genproto v0.0.0-20221118155620-16455021b5e6 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
pgregory.net/rapid v0.5.3 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)
Loading

0 comments on commit ebfd057

Please sign in to comment.