Rework the CLI using 'flag'
This commit is contained in:
parent
b0791af5c6
commit
5b46248ff2
49
cli.go
49
cli.go
|
@ -1,7 +1,9 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
)
|
)
|
||||||
|
@ -13,8 +15,8 @@ type CLI struct {
|
||||||
|
|
||||||
func (cli *CLI) printUsage() {
|
func (cli *CLI) printUsage() {
|
||||||
fmt.Println("Usage:")
|
fmt.Println("Usage:")
|
||||||
fmt.Println(" addBlock BLOCK_DATA - add a block to the blockchain")
|
fmt.Println(" addblock -data BLOCK_DATA - add a block to the blockchain")
|
||||||
fmt.Println(" printChain - print all the blocks of the blockchain")
|
fmt.Println(" printchain - print all the blocks of the blockchain")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cli *CLI) validateArgs() {
|
func (cli *CLI) validateArgs() {
|
||||||
|
@ -24,12 +26,8 @@ func (cli *CLI) validateArgs() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cli *CLI) addBlock() {
|
func (cli *CLI) addBlock(data string) {
|
||||||
if len(os.Args) < 3 {
|
cli.bc.AddBlock(data)
|
||||||
fmt.Println("Error: BLOCK_DATA is not specified.")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
cli.bc.AddBlock(os.Args[2])
|
|
||||||
fmt.Println("Success!")
|
fmt.Println("Success!")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -52,17 +50,40 @@ func (cli *CLI) printChain() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProcessArgs parses command line arguments and processes commands
|
// Run parses command line arguments and processes commands
|
||||||
func (cli *CLI) ProcessArgs() {
|
func (cli *CLI) Run() {
|
||||||
cli.validateArgs()
|
cli.validateArgs()
|
||||||
|
|
||||||
|
addBlockCmd := flag.NewFlagSet("addblock", flag.ExitOnError)
|
||||||
|
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
|
||||||
|
|
||||||
|
addBlockData := addBlockCmd.String("data", "", "Block data")
|
||||||
|
|
||||||
switch os.Args[1] {
|
switch os.Args[1] {
|
||||||
case "addBlock":
|
case "addblock":
|
||||||
cli.addBlock()
|
err := addBlockCmd.Parse(os.Args[2:])
|
||||||
case "printChain":
|
if err != nil {
|
||||||
cli.printChain()
|
log.Panic(err)
|
||||||
|
}
|
||||||
|
case "printchain":
|
||||||
|
err := printChainCmd.Parse(os.Args[2:])
|
||||||
|
if err != nil {
|
||||||
|
log.Panic(err)
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
cli.printUsage()
|
cli.printUsage()
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if addBlockCmd.Parsed() {
|
||||||
|
if *addBlockData == "" {
|
||||||
|
addBlockCmd.Usage()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
cli.addBlock(*addBlockData)
|
||||||
|
}
|
||||||
|
|
||||||
|
if printChainCmd.Parsed() {
|
||||||
|
cli.printChain()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue