github.com/woremacx/kocha@v0.7.1-0.20150731103243-a5889322afc9/cmd/kocha-new/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"go/build"
     6  	"os"
     7  	"path/filepath"
     8  	"runtime"
     9  	"strings"
    10  
    11  	"github.com/woremacx/kocha/util"
    12  )
    13  
    14  type newCommand struct {
    15  	option struct {
    16  		Help bool `short:"h" long:"help"`
    17  	}
    18  }
    19  
    20  func (c *newCommand) Name() string {
    21  	return "kocha new"
    22  }
    23  
    24  func (c *newCommand) Usage() string {
    25  	return fmt.Sprintf(`Usage: %s [OPTIONS] APP_PATH
    26  
    27  Create a new application.
    28  
    29  Options:
    30      -h, --help        display this help and exit
    31  
    32  `, c.Name())
    33  }
    34  
    35  func (c *newCommand) Option() interface{} {
    36  	return &c.option
    37  }
    38  
    39  func (c *newCommand) Run(args []string) error {
    40  	if len(args) < 1 || args[0] == "" {
    41  		return fmt.Errorf("no APP_PATH given")
    42  	}
    43  	appPath := args[0]
    44  	dstBasePath := filepath.Join(filepath.SplitList(build.Default.GOPATH)[0], "src", appPath)
    45  	_, filename, _, _ := runtime.Caller(0)
    46  	baseDir := filepath.Dir(filename)
    47  	skeletonDir := filepath.Join(baseDir, "skeleton", "new")
    48  	if _, err := os.Stat(filepath.Join(dstBasePath, "config", "app.go")); err == nil {
    49  		return fmt.Errorf("Kocha application is already exists")
    50  	}
    51  	data := map[string]interface{}{
    52  		"appName":   filepath.Base(appPath),
    53  		"appPath":   appPath,
    54  		"secretKey": fmt.Sprintf("%q", string(util.GenerateRandomKey(32))), // AES-256
    55  		"signedKey": fmt.Sprintf("%q", string(util.GenerateRandomKey(16))),
    56  	}
    57  	return filepath.Walk(skeletonDir, func(path string, info os.FileInfo, err error) error {
    58  		if err != nil {
    59  			return err
    60  		}
    61  		if info.IsDir() {
    62  			return nil
    63  		}
    64  		dstPath := filepath.Join(dstBasePath, strings.TrimSuffix(strings.TrimPrefix(path, skeletonDir), util.TemplateSuffix))
    65  		dstDir := filepath.Dir(dstPath)
    66  		dirCreated, err := mkdirAllIfNotExists(dstDir)
    67  		if err != nil {
    68  			return fmt.Errorf("failed to create directory: %v", err)
    69  		}
    70  		if dirCreated {
    71  			util.PrintCreateDirectory(dstDir)
    72  		}
    73  		return util.CopyTemplate(path, dstPath, data)
    74  	})
    75  }
    76  
    77  func mkdirAllIfNotExists(dstDir string) (created bool, err error) {
    78  	if _, err := os.Stat(dstDir); os.IsNotExist(err) {
    79  		if err := os.MkdirAll(dstDir, 0755); err != nil {
    80  			return false, err
    81  		}
    82  		return true, nil
    83  	}
    84  	return false, nil
    85  }
    86  
    87  func main() {
    88  	util.RunCommand(&newCommand{})
    89  }