From 3fc25e14311c6480ae82d2e921d62c9dc9ac6b70 Mon Sep 17 00:00:00 2001 From: Ankur Srivastava Date: Sat, 25 Aug 2018 16:40:15 +0200 Subject: [PATCH] fixes CityOfZion/neo-storm#16 * A new command `cli init --name testcontract` now creates a directory testcontract/main.go Imported from CityOfZion/neo-storm (331585e51ce13b6fe902b7a352b150c5b457a4f5). --- cli/smartcontract/smart_contract.go | 62 ++++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/cli/smartcontract/smart_contract.go b/cli/smartcontract/smart_contract.go index 57a4a4a2b..14d81da6b 100644 --- a/cli/smartcontract/smart_contract.go +++ b/cli/smartcontract/smart_contract.go @@ -4,16 +4,33 @@ import ( "context" "encoding/hex" "encoding/json" + "errors" "fmt" "io/ioutil" + "os" + "path/filepath" "github.com/CityOfZion/neo-go/pkg/rpc" "github.com/CityOfZion/neo-go/pkg/vm/compiler" "github.com/urfave/cli" ) -const ( - errNoInput = "Input file is mandatory and should be passed using -i flag." +var ( + errNoInput = errors.New("No input file was found, specify an input file with the '--in or -i' flag") + errNoSmartContractName = errors.New("No name was provided, specify the '--name or -n' flag") + errFileExist = errors.New("A file with given smart-contract name already exists") +) + +var ( + // smartContractTmpl is written to a file when used with `init` command. + // %s is parsed to be the smartContractName + smartContractTmpl = `package %s + +import "github.com/CityOfZion/neo-storm/interop/runtime" + +func Main(op string, args []interface{}) { + runtime.Notify("Hello world!") +}` ) // NewCommand returns a new contract command. @@ -63,10 +80,51 @@ func NewCommand() cli.Command { }, }, }, + { + Name: "init", + Usage: "initialize a new smart-contract in a directory with boiler plate code", + Action: initSmartContract, + Flags: []cli.Flag{ + cli.StringFlag{ + Name: "name, n", + Usage: "name of the smart-contract to be initialized", + }, + }, + }, }, } } +// initSmartContract initializes a given directory with some boiler plate code. +func initSmartContract(ctx *cli.Context) error { + scName := ctx.String("name") + if scName == "" { + return cli.NewExitError(errNoSmartContractName, 1) + } + + // Check if the file already exists, if yes, exit + if _, err := os.Stat(scName); err == nil { + return cli.NewExitError(errFileExist, 1) + } + + basePath := scName + fileName := "main.go" + + // create base directory + err := os.Mkdir(basePath, os.ModePerm) + if err != nil { + return cli.NewExitError(err, 1) + } + + data := []byte(fmt.Sprintf(smartContractTmpl, scName)) + err = ioutil.WriteFile(filepath.Join(basePath, fileName), data, 0644) + if err != nil { + return cli.NewExitError(err, 1) + } + fmt.Printf("Successfully initialized smart contract [%s]\n", scName) + return nil +} + func contractCompile(ctx *cli.Context) error { src := ctx.String("in") if len(src) == 0 {