Lint internal/cli

This commit is contained in:
Jerry 2022-05-20 13:49:37 -07:00
parent 12ab0f0240
commit 45a72bc49e
20 changed files with 113 additions and 17 deletions

View file

@ -19,6 +19,7 @@ func (a *Account) MarkDown() string {
"- [```account list```](./account_list.md): List the wallets in the Bor client.",
"- [```account import```](./account_import.md): Import an account to the Bor client.",
}
return strings.Join(items, "\n\n")
}

View file

@ -20,6 +20,7 @@ func (a *AccountImportCommand) MarkDown() string {
"The ```account import``` command imports an account in Json format to the Bor data directory.",
a.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -58,7 +59,9 @@ func (a *AccountImportCommand) Run(args []string) int {
a.UI.Error("Expected one argument")
return 1
}
key, err := crypto.LoadECDSA(args[0])
if err != nil {
a.UI.Error(fmt.Sprintf("Failed to load the private key '%s': %v", args[0], err))
return 1
@ -80,6 +83,8 @@ func (a *AccountImportCommand) Run(args []string) int {
if err != nil {
utils.Fatalf("Could not create the account: %v", err)
}
a.UI.Output(fmt.Sprintf("Account created: %s", acct.Address.String()))
return 0
}

View file

@ -19,6 +19,7 @@ func (a *AccountListCommand) MarkDown() string {
"The `account list` command lists all the accounts in the Bor data directory.",
a.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -53,7 +54,9 @@ func (a *AccountListCommand) Run(args []string) int {
a.UI.Error(fmt.Sprintf("Failed to get keystore: %v", err))
return 1
}
a.UI.Output(formatAccounts(keystore.Accounts()))
return 0
}
@ -64,10 +67,12 @@ func formatAccounts(accts []accounts.Account) string {
rows := make([]string, len(accts)+1)
rows[0] = "Index|Address"
for i, d := range accts {
rows[i+1] = fmt.Sprintf("%d|%s",
i,
d.Address.String())
}
return formatList(rows)
}

View file

@ -18,6 +18,7 @@ func (a *AccountNewCommand) MarkDown() string {
"The `account new` command creates a new local account file on the Bor data directory. Bor should not be running to execute this command.",
a.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}

View file

@ -6,12 +6,12 @@ import (
"path/filepath"
"strings"
"github.com/ethereum/go-ethereum/internal/cli/flagset"
"github.com/ethereum/go-ethereum/rpc"
"github.com/ethereum/go-ethereum/cmd/utils"
"github.com/ethereum/go-ethereum/console"
"github.com/ethereum/go-ethereum/internal/cli/flagset"
"github.com/ethereum/go-ethereum/node"
"github.com/ethereum/go-ethereum/rpc"
"github.com/mitchellh/cli"
)
@ -33,6 +33,7 @@ func (c *AttachCommand) MarkDown() string {
"Connect to remote Bor IPC console.",
c.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -49,7 +50,6 @@ func (c *AttachCommand) Synopsis() string {
}
func (c *AttachCommand) Flags() *flagset.Flagset {
f := flagset.NewFlagSet("attach")
f.StringFlag(&flagset.StringFlag{
@ -75,13 +75,13 @@ func (c *AttachCommand) Flags() *flagset.Flagset {
// Run implements the cli.Command interface
func (c *AttachCommand) Run(args []string) int {
flags := c.Flags()
//check if first arg is flag or IPC location
if len(args) == 0 {
args = append(args, "")
}
if args[0] != "" && strings.HasPrefix(args[0], "--") {
if err := flags.Parse(args); err != nil {
c.UI.Error(err.Error())
@ -94,6 +94,7 @@ func (c *AttachCommand) Run(args []string) int {
return 1
}
}
if err := c.remoteConsole(); err != nil {
c.UI.Error(err.Error())
return 1
@ -104,25 +105,30 @@ func (c *AttachCommand) Run(args []string) int {
// remoteConsole will connect to a remote bor instance, attaching a JavaScript
// console to it.
// nolint: unparam
func (c *AttachCommand) remoteConsole() error {
// Attach to a remotely running geth instance and start the JavaScript console
path := node.DefaultDataDir()
if c.Endpoint == "" {
if c.Meta.dataDir != "" {
path = c.Meta.dataDir
}
if path != "" {
homeDir, _ := os.UserHomeDir()
path = filepath.Join(homeDir, "/.bor/data")
}
c.Endpoint = fmt.Sprintf("%s/bor.ipc", path)
}
client, err := dialRPC(c.Endpoint)
if err != nil {
utils.Fatalf("Unable to attach to remote bor: %v", err)
}
config := console.Config{
DataDir: path,
DocRoot: c.JSpathFlag,
@ -134,7 +140,12 @@ func (c *AttachCommand) remoteConsole() error {
if err != nil {
utils.Fatalf("Failed to start the JavaScript console: %v", err)
}
defer console.Stop(false)
defer func() {
if err := console.Stop(false); err != nil {
c.UI.Error(err.Error())
}
}()
if c.ExecCMD != "" {
console.Evaluate(c.ExecCMD)
@ -159,6 +170,7 @@ func dialRPC(endpoint string) (*rpc.Client, error) {
// these prefixes.
endpoint = endpoint[4:]
}
return rpc.Dial(endpoint)
}
@ -175,5 +187,6 @@ func (c *AttachCommand) makeConsolePreloads() []string {
for _, file := range strings.Split(c.PreloadJSFlag, ",") {
preloads = append(preloads, strings.TrimSpace(file))
}
return preloads
}

View file

@ -19,6 +19,7 @@ import (
"github.com/ethereum/go-ethereum/p2p/discover"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/nat"
"github.com/mitchellh/cli"
)
@ -45,6 +46,7 @@ func (c *BootnodeCommand) MarkDown() string {
"# Bootnode",
c.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -103,6 +105,7 @@ func (b *BootnodeCommand) Synopsis() string {
}
// Run implements the cli.Command interface
// nolint: gocognit
func (b *BootnodeCommand) Run(args []string) int {
flags := b.Flags()
if err := flags.Parse(args); err != nil {
@ -118,6 +121,7 @@ func (b *BootnodeCommand) Run(args []string) int {
} else {
glogger.Verbosity(log.LvlInfo)
}
log.Root().SetHandler(glogger)
natm, err := nat.Parse(b.nat)
@ -128,6 +132,7 @@ func (b *BootnodeCommand) Run(args []string) int {
// create a one time key
var nodeKey *ecdsa.PrivateKey
// nolint: nestif
if b.nodeKey != "" {
// try to read the key either from file or command line
if _, err := os.Stat(b.nodeKey); errors.Is(err, os.ErrNotExist) {
@ -157,7 +162,7 @@ func (b *BootnodeCommand) Run(args []string) int {
}
// save the public key
pubRaw := fmt.Sprintf("%x", crypto.FromECDSAPub(&nodeKey.PublicKey)[1:])
if err := ioutil.WriteFile(filepath.Join(path, "pub.key"), []byte(pubRaw), 0755); err != nil {
if err := ioutil.WriteFile(filepath.Join(path, "pub.key"), []byte(pubRaw), 0600); err != nil {
b.UI.Error(fmt.Sprintf("failed to write node pub key: %v", err))
return 1
}
@ -169,7 +174,9 @@ func (b *BootnodeCommand) Run(args []string) int {
b.UI.Error(fmt.Sprintf("could not resolve udp addr '%s': %v", b.listenAddr, err))
return 1
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
b.UI.Error(fmt.Sprintf("failed to listen udp addr '%s': %v", b.listenAddr, err))
return 1
@ -180,7 +187,9 @@ func (b *BootnodeCommand) Run(args []string) int {
if !realaddr.IP.IsLoopback() {
go nat.Map(natm, nil, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
}
if ext, err := natm.ExternalIP(); err == nil {
// nolint: govet
realaddr = &net.UDPAddr{IP: ext, Port: realaddr.Port}
}
}
@ -198,6 +207,7 @@ func (b *BootnodeCommand) Run(args []string) int {
PrivateKey: nodeKey,
Log: log.Root(),
}
if b.v5 {
if _, err := discover.ListenV5(conn, ln, cfg); err != nil {
utils.Fatalf("%v", err)

View file

@ -7,6 +7,7 @@ import (
"strings"
"github.com/ethereum/go-ethereum/params"
"github.com/mitchellh/cli"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
@ -25,6 +26,7 @@ func (c *FingerprintCommand) MarkDown() string {
"# Fingerprint",
"Display the system fingerprint",
}
return strings.Join(items, "\n\n")
}
@ -45,6 +47,7 @@ func getCoresCount(cp []cpu.InfoStat) int {
for i := 0; i < len(cp); i++ {
cores += int(cp[i].Cores)
}
return cores
}
@ -76,6 +79,7 @@ func formatFingerprint(borFingerprint *BorFingerprint) string {
fmt.Sprintf("RAM :: total : %v GB, free : %v GB, used : %v GB", borFingerprint.MemoryDetails.TotalMem, borFingerprint.MemoryDetails.FreeMem, borFingerprint.MemoryDetails.UsedMem),
fmt.Sprintf("STORAGE :: total : %v GB, free : %v GB, used : %v GB", borFingerprint.DiskDetails.TotalDisk, borFingerprint.DiskDetails.FreeDisk, borFingerprint.DiskDetails.UsedDisk),
})
return base
}
@ -85,13 +89,13 @@ func convertBytesToGB(bytesValue uint64) float64 {
// Checks if fio exists on the node
func (c *FingerprintCommand) checkFio() error {
cmd := exec.Command("/bin/sh", "-c", "fio -v")
_, err := cmd.CombinedOutput()
if err != nil {
message := "\nFio package not installed. Install Fio for IOPS Benchmarking :\n\nDebianOS : 'sudo apt-get update && sudo apt-get install fio -y'\nAWS AMI/CentOS : 'sudo yum install fio -y'\nOracle LinuxOS : 'sudo dnf install fio -y'\n"
c.UI.Output(message)
return err
}
@ -101,9 +105,12 @@ func (c *FingerprintCommand) checkFio() error {
// Run the IOPS benchmark for the node
func (c *FingerprintCommand) benchmark() error {
var b []byte
err := c.checkFio()
if err != nil {
return nil
// Missing Fio is not a fatal error. A message will be logged in console when it is missing in "checkFio()".
return nil //nolint:nilerr
}
c.UI.Output("\nRunning a 10 second test...\n")
@ -123,7 +130,6 @@ func (c *FingerprintCommand) benchmark() error {
// Run implements the cli.Command interface
func (c *FingerprintCommand) Run(args []string) int {
v, err := mem.VirtualMemory()
if err != nil {
c.UI.Error(err.Error())

View file

@ -19,6 +19,7 @@ func (c *ChainCommand) MarkDown() string {
"- [```chain sethead```](./chain_sethead.md): Set the current chain to a certain block.",
"- [```chain watch```](./chain_watch.md): Watch the chainHead, reorg and fork events in real-time.",
}
return strings.Join(items, "\n\n")
}

View file

@ -26,6 +26,7 @@ func (a *ChainSetHeadCommand) MarkDown() string {
"- ```number```: The block number to roll back.",
a.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -45,6 +46,7 @@ func (c *ChainSetHeadCommand) Flags() *flagset.Flagset {
Default: false,
Value: &c.yes,
})
return flags
}
@ -88,6 +90,7 @@ func (c *ChainSetHeadCommand) Run(args []string) int {
c.UI.Error(err.Error())
return 1
}
if response != "y" {
c.UI.Output("set head aborted")
return 0
@ -100,5 +103,6 @@ func (c *ChainSetHeadCommand) Run(args []string) int {
}
c.UI.Output("Done!")
return 0
}

View file

@ -24,6 +24,7 @@ func (c *ChainWatchCommand) MarkDown() string {
"# Chain watch",
"The ```chain watch``` command is used to view the chainHead, reorg and fork events in real-time.",
}
return strings.Join(items, "\n\n")
}
@ -70,7 +71,10 @@ func (c *ChainWatchCommand) Run(args []string) int {
go func() {
<-signalCh
sub.CloseSend()
if err := sub.CloseSend(); err != nil {
c.UI.Error(err.Error())
}
}()
for {
@ -80,6 +84,7 @@ func (c *ChainWatchCommand) Run(args []string) int {
c.UI.Output(err.Error())
break
}
c.UI.Output(formatHeadEvent(msg))
}
@ -95,5 +100,6 @@ func formatHeadEvent(msg *proto.ChainWatchResponse) string {
} else if msg.Type == core.Chain2HeadReorgEvent {
out = fmt.Sprintf("Reorg Detected \nAdded : %v \nRemoved : %v", msg.Newchain, msg.Oldchain)
}
return out
}

View file

@ -9,11 +9,16 @@ import (
"github.com/ethereum/go-ethereum/internal/cli/server"
"github.com/ethereum/go-ethereum/internal/cli/server/proto"
"github.com/ethereum/go-ethereum/node"
"github.com/mitchellh/cli"
"github.com/ryanuber/columnize"
"google.golang.org/grpc"
)
const (
emptyPlaceHolder = "<none>"
)
type MarkDownCommand interface {
MarkDown
cli.Command
@ -48,6 +53,7 @@ func Run(args []string) int {
fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err.Error())
return 1
}
return exitCode
}
@ -64,6 +70,7 @@ func Commands() map[string]MarkDownCommandFactory {
meta := &Meta{
UI: ui,
}
return map[string]MarkDownCommandFactory{
"server": func() (MarkDownCommand, error) {
return &server.Command{
@ -180,6 +187,7 @@ func (m *Meta2) NewFlagSet(n string) *flagset.Flagset {
Usage: "Address of the grpc endpoint",
Default: "127.0.0.1:3131",
})
return f
}
@ -188,6 +196,7 @@ func (m *Meta2) Conn() (*grpc.ClientConn, error) {
if err != nil {
return nil, fmt.Errorf("failed to connect to server: %v", err)
}
return conn, nil
}
@ -196,6 +205,7 @@ func (m *Meta2) BorConn() (proto.BorClient, error) {
if err != nil {
return nil, err
}
return proto.NewBorClient(conn), nil
}
@ -243,18 +253,21 @@ func (m *Meta) GetKeystore() (*keystore.KeyStore, error) {
scryptP := keystore.StandardScryptP
keys := keystore.NewKeyStore(keydir, scryptN, scryptP)
return keys, nil
}
func formatList(in []string) string {
columnConf := columnize.DefaultConfig()
columnConf.Empty = "<none>"
columnConf.Empty = emptyPlaceHolder
return columnize.Format(in, columnConf)
}
func formatKV(in []string) string {
columnConf := columnize.DefaultConfig()
columnConf.Empty = "<none>"
columnConf.Empty = emptyPlaceHolder
columnConf.Glue = " = "
return columnize.Format(in, columnConf)
}

View file

@ -18,8 +18,9 @@ import (
"github.com/ethereum/go-ethereum/internal/cli/flagset"
"github.com/ethereum/go-ethereum/internal/cli/server/proto"
"github.com/golang/protobuf/jsonpb"
gproto "github.com/golang/protobuf/proto"
"github.com/golang/protobuf/jsonpb" // nolint:staticcheck
gproto "github.com/golang/protobuf/proto" // nolint:staticcheck
"github.com/golang/protobuf/ptypes/empty"
grpc_net_conn "github.com/mitchellh/go-grpc-net-conn"
)
@ -55,6 +56,7 @@ func (d *DebugCommand) MarkDown() string {
d.Flags().MarkDown(),
}
items = append(items, examples...)
return strings.Join(items, "\n\n")
}
@ -112,6 +114,7 @@ func (d *DebugCommand) Run(args []string) int {
// User specified output directory
tmp = filepath.Join(d.output, stamped)
_, err := os.Stat(tmp)
if !os.IsNotExist(err) {
d.UI.Error("Output directory already exists")
return 1
@ -139,6 +142,7 @@ func (d *DebugCommand) Run(args []string) int {
req := &proto.PprofRequest{
Seconds: int64(d.seconds),
}
switch profile {
case "cpu":
req.Type = proto.PprofRequest_CPU
@ -148,7 +152,9 @@ func (d *DebugCommand) Run(args []string) int {
req.Type = proto.PprofRequest_LOOKUP
req.Profile = profile
}
stream, err := clt.Pprof(ctx, req)
if err != nil {
return err
}
@ -157,6 +163,7 @@ func (d *DebugCommand) Run(args []string) int {
if err != nil {
return err
}
if _, ok := msg.Event.(*proto.PprofResponse_Open_); !ok {
return fmt.Errorf("expected open message")
}
@ -179,6 +186,7 @@ func (d *DebugCommand) Run(args []string) int {
if _, err := io.Copy(file, conn); err != nil {
return err
}
return nil
}
@ -210,7 +218,7 @@ func (d *DebugCommand) Run(args []string) int {
d.UI.Output(err.Error())
return 1
}
if err := ioutil.WriteFile(filepath.Join(tmp, "status.json"), []byte(data), 0644); err != nil {
if err := ioutil.WriteFile(filepath.Join(tmp, "status.json"), []byte(data), 0600); err != nil {
d.UI.Output(fmt.Sprintf("Failed to write status: %v", err))
return 1
}
@ -230,6 +238,7 @@ func (d *DebugCommand) Run(args []string) int {
}
d.UI.Output(fmt.Sprintf("Created debug archive: %s", archiveFile))
return 0
}

View file

@ -7,6 +7,7 @@ import (
)
func TestCodeBlock(t *testing.T) {
t.Parallel()
assert := assert.New(t)
lines := []string{

View file

@ -21,6 +21,7 @@ func (a *PeersCommand) MarkDown() string {
"- [```peers remove```](./peers_remove.md): Disconnects the local client from a connected peer if exists.",
"- [```peers status```](./peers_status.md): Display the status of a peer by its id.",
}
return strings.Join(items, "\n\n")
}

View file

@ -22,6 +22,7 @@ func (p *PeersAddCommand) MarkDown() string {
"The ```peers add <enode>``` command joins the local client to another remote peer.",
p.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -79,5 +80,6 @@ func (c *PeersAddCommand) Run(args []string) int {
c.UI.Error(err.Error())
return 1
}
return 0
}

View file

@ -21,6 +21,7 @@ func (p *PeersListCommand) MarkDown() string {
"The ```peers list``` command lists the connected peers.",
p.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -60,12 +61,14 @@ func (c *PeersListCommand) Run(args []string) int {
req := &proto.PeersListRequest{}
resp, err := borClt.PeersList(context.Background(), req)
if err != nil {
c.UI.Error(err.Error())
return 1
}
c.UI.Output(formatPeers(resp.Peers))
return 0
}
@ -76,6 +79,7 @@ func formatPeers(peers []*proto.Peer) string {
rows := make([]string, len(peers)+1)
rows[0] = "ID|Enode|Name|Caps|Static|Trusted"
for i, d := range peers {
enode := strings.TrimPrefix(d.Enode, "enode://")
@ -87,5 +91,6 @@ func formatPeers(peers []*proto.Peer) string {
d.Static,
d.Trusted)
}
return formatList(rows)
}

View file

@ -22,6 +22,7 @@ func (p *PeersRemoveCommand) MarkDown() string {
"The ```peers remove <enode>``` command disconnects the local client from a connected peer if exists.",
p.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -79,5 +80,6 @@ func (c *PeersRemoveCommand) Run(args []string) int {
c.UI.Error(err.Error())
return 1
}
return 0
}

View file

@ -21,6 +21,7 @@ func (p *PeersStatusCommand) MarkDown() string {
"The ```peers status <peer id>``` command displays the status of a peer by its id.",
p.Flags().MarkDown(),
}
return strings.Join(items, "\n\n")
}
@ -68,12 +69,14 @@ func (c *PeersStatusCommand) Run(args []string) int {
Enode: args[0],
}
resp, err := borClt.PeersStatus(context.Background(), req)
if err != nil {
c.UI.Error(err.Error())
return 1
}
c.UI.Output(formatPeer(resp.Peer))
return 0
}
@ -87,5 +90,6 @@ func formatPeer(peer *proto.Peer) string {
fmt.Sprintf("Static|%v", peer.Static),
fmt.Sprintf("Trusted|%v", peer.Trusted),
})
return base
}

View file

@ -6,6 +6,7 @@ import (
"strings"
"github.com/ethereum/go-ethereum/internal/cli/server/proto"
"github.com/golang/protobuf/ptypes/empty"
)
@ -20,6 +21,7 @@ func (p *StatusCommand) MarkDown() string {
"# Status",
"The ```status``` command outputs the status of the client.",
}
return strings.Join(items, "\n\n")
}
@ -56,6 +58,7 @@ func (c *StatusCommand) Run(args []string) int {
}
c.UI.Output(printStatus(status))
return 0
}
@ -69,6 +72,7 @@ func printStatus(status *proto.StatusResponse) string {
forks := make([]string, len(status.Forks)+1)
forks[0] = "Name|Block|Enabled"
for i, d := range status.Forks {
forks[i+1] = fmt.Sprintf("%s|%d|%v", d.Name, d.Block, !d.Disabled)
}
@ -92,5 +96,6 @@ func printStatus(status *proto.StatusResponse) string {
"\nForks",
formatList(forks),
}
return strings.Join(full, "\n")
}

View file

@ -4,6 +4,7 @@ import (
"strings"
"github.com/ethereum/go-ethereum/params"
"github.com/mitchellh/cli"
)
@ -27,6 +28,7 @@ func (d *VersionCommand) MarkDown() string {
"The ```bor version``` command outputs the version of the binary.",
}
items = append(items, examples...)
return strings.Join(items, "\n\n")
}