/
root.go
97 lines (80 loc) · 1.97 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright © 2020 Jonathan Whitaker <jonathan@whitaker.io>
package cmd
import (
"fmt"
"go/build"
"log"
"os"
"path/filepath"
"strings"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/whitaker-io/machine/cmd/templates"
)
var cfgFile string
var force bool
var rootCmd = &cobra.Command{
Use: "machine",
Short: "Tool for creating boilerplate projects and streams based on github.com/whitaker-io/machine",
Long: ``,
}
// Execute func for running the commands
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.machine.yaml)")
rootCmd.PersistentFlags().BoolVar(&force, "force", false, "override files")
}
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
viper.AddConfigPath(home)
viper.SetConfigName(".machine")
}
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
func addFN(project templates.Project) func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
if err := templates.GenerateProject(getCurrentDir(), project, force, config(args)); err != nil {
fmt.Printf("cannot create project - err: %v", err)
os.Exit(1)
}
}
}
func getCurrentDir() string {
ex, err := os.Getwd()
if err != nil {
log.Fatalln(err)
}
return ex
}
func config(args []string) map[string]interface{} {
gosrc := os.Getenv("GOSRC")
gopath := os.Getenv("GOPATH")
if gopath == "" {
gopath = build.Default.GOPATH
}
if gosrc == "" {
gosrc = filepath.Join(gopath, "src")
}
currentDir := getCurrentDir()
return map[string]interface{}{
"Path": strings.TrimPrefix(currentDir, gosrc+"/"),
"Name": args[0],
}
}