* A new command `cli init --name testcontract` now creates a directory testcontract/main.go

Imported from CityOfZion/neo-storm (331585e51ce13b6fe902b7a352b150c5b457a4f5).
This commit is contained in:
Ankur Srivastava 2018-08-25 16:40:15 +02:00 committed by Roman Khimov
parent df173c295d
commit 3fc25e1431

View file

@ -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 {