spf13--cobra/cobra/cmd/init.go

235 lines
6.6 KiB
Go
Raw Permalink Normal View History

2015-10-28 16:51:48 +00:00
// Copyright © 2015 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"fmt"
2015-10-28 16:51:48 +00:00
"os"
2017-04-29 10:02:02 +00:00
"path"
"path/filepath"
2015-10-28 16:51:48 +00:00
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var initCmd = &cobra.Command{
Use: "init [name]",
Aliases: []string{"initialize", "initialise", "create"},
Short: "Initialize a Cobra Application",
Long: `Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.
2015-10-28 16:51:48 +00:00
* If a name is provided, it will be created in the current directory;
* If no name is provided, the current directory will be assumed;
* If a relative path is provided, it will be created inside $GOPATH
(e.g. github.com/spf13/hugo);
* If an absolute path is provided, it will be created;
* If the directory already exists but is empty, it will be used.
2015-10-28 16:51:48 +00:00
2015-12-17 21:43:23 +00:00
Init will not use an existing directory with contents.`,
2015-10-28 16:51:48 +00:00
Run: func(cmd *cobra.Command, args []string) {
wd, err := os.Getwd()
if err != nil {
er(err)
}
2017-04-29 10:02:02 +00:00
var project *Project
if len(args) == 0 {
project = NewProjectFromPath(wd)
} else if len(args) == 1 {
2017-05-05 08:06:10 +00:00
arg := args[0]
if arg[0] == '.' {
arg = filepath.Join(wd, arg)
}
2017-05-05 08:06:10 +00:00
if filepath.IsAbs(arg) {
project = NewProjectFromPath(arg)
} else {
project = NewProject(arg)
}
2017-04-29 10:02:02 +00:00
} else {
er("please provide only one argument")
2015-10-28 16:51:48 +00:00
}
2017-04-29 10:02:02 +00:00
2017-05-05 08:06:10 +00:00
initializeProject(project)
fmt.Fprintln(cmd.OutOrStdout(), `Your Cobra application is ready at
`+project.AbsPath()+`.
Give it a try by going there and running `+"`go run main.go`."+`
Add commands to it by running `+"`cobra add [cmdname]`.")
2015-10-28 16:51:48 +00:00
},
}
2017-05-05 08:06:10 +00:00
func initializeProject(project *Project) {
2017-04-29 10:02:02 +00:00
if !exists(project.AbsPath()) { // If path doesn't yet exist, create it
err := os.MkdirAll(project.AbsPath(), os.ModePerm)
2015-10-28 16:51:48 +00:00
if err != nil {
er(err)
}
2017-04-29 10:02:02 +00:00
} else if !isEmpty(project.AbsPath()) { // If path exists and is not empty don't use it
2017-04-29 12:53:52 +00:00
er("Cobra will not create a new project in a non empty directory: " + project.AbsPath())
2015-10-28 16:51:48 +00:00
}
2017-04-29 12:53:52 +00:00
// We have a directory and it's empty. Time to initialize it.
createLicenseFile(project.License(), project.AbsPath())
2017-04-29 10:02:02 +00:00
createMainFile(project)
createRootCmdFile(project)
2015-10-28 16:51:48 +00:00
}
2017-04-29 12:53:52 +00:00
func createLicenseFile(license License, path string) {
2017-04-29 10:02:02 +00:00
data := make(map[string]interface{})
data["copyright"] = copyrightLine()
2017-04-29 10:02:02 +00:00
// Generate license template from text and data.
2017-04-29 12:53:52 +00:00
text, err := executeTemplate(license.Text, data)
2017-04-29 10:02:02 +00:00
if err != nil {
er(err)
}
2017-04-29 10:02:02 +00:00
// Write license text to LICENSE file.
2017-04-29 12:53:52 +00:00
err = writeStringToFile(filepath.Join(path, "LICENSE"), text)
2017-04-29 10:02:02 +00:00
if err != nil {
er(err)
}
2015-10-28 16:51:48 +00:00
}
2017-04-29 10:02:02 +00:00
func createMainFile(project *Project) {
mainTemplate := `{{ comment .copyright }}
{{if .license}}{{ comment .license }}{{end}}
2015-10-28 16:51:48 +00:00
package main
import "{{ .importpath }}"
func main() {
cmd.Execute()
}
`
data := make(map[string]interface{})
2015-10-28 16:51:48 +00:00
data["copyright"] = copyrightLine()
2017-04-29 10:02:02 +00:00
data["license"] = project.License().Header
2017-04-29 12:53:52 +00:00
data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath()))
2017-04-29 10:02:02 +00:00
mainScript, err := executeTemplate(mainTemplate, data)
if err != nil {
er(err)
}
2015-10-28 16:51:48 +00:00
2017-04-29 10:02:02 +00:00
err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript)
if err != nil {
er(err)
}
2015-10-28 16:51:48 +00:00
}
2017-04-29 10:02:02 +00:00
func createRootCmdFile(project *Project) {
template := `{{comment .copyright}}
{{if .license}}{{comment .license}}{{end}}
2015-10-28 16:51:48 +00:00
package cmd
import (
"fmt"
"os"
2017-06-12 06:36:10 +00:00
{{if .viper}}
homedir "github.com/mitchellh/go-homedir"{{end}}
2017-06-12 06:36:10 +00:00
"github.com/spf13/cobra"{{if .viper}}
"github.com/spf13/viper"{{end}}
){{if .viper}}
2017-04-29 10:02:02 +00:00
var cfgFile string{{end}}
2017-04-29 10:02:02 +00:00
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
2017-04-29 10:02:02 +00:00
Use: "{{.appName}}",
2015-10-28 16:51:48 +00:00
Short: "A brief description of your application",
Long: ` + "`" + `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.` + "`" + `,
2017-04-29 10:02:02 +00:00
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
2015-10-28 16:51:48 +00:00
}
2017-06-21 17:26:46 +00:00
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
2015-10-28 16:51:48 +00:00
func Execute() {
if err := rootCmd.Execute(); err != nil {
2015-10-28 16:51:48 +00:00
fmt.Println(err)
os.Exit(1)
2015-10-28 16:51:48 +00:00
}
}
func init() { {{- if .viper}}
cobra.OnInitialize(initConfig)
2017-06-12 06:36:10 +00:00
{{end}}
2017-04-29 10:02:02 +00:00
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
2017-04-29 10:02:02 +00:00
// will be global for your application.{{ if .viper }}
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ else }}
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ end }}
2017-04-29 10:02:02 +00:00
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
2017-04-29 10:02:02 +00:00
}{{ if .viper }}
// initConfig reads in config file and ENV variables if set.
2015-10-28 16:51:48 +00:00
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
2015-10-28 16:51:48 +00:00
viper.SetConfigFile(cfgFile)
2017-04-29 10:02:02 +00:00
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".{{ .appName }}" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".{{ .appName }}")
2015-10-28 16:51:48 +00:00
}
viper.AutomaticEnv() // read in environment variables that match
2015-10-28 16:51:48 +00:00
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
2017-04-29 10:02:02 +00:00
}{{ end }}
`
2015-10-28 16:51:48 +00:00
data := make(map[string]interface{})
2015-10-28 16:51:48 +00:00
data["copyright"] = copyrightLine()
data["viper"] = viper.GetBool("useViper")
2017-04-29 10:02:02 +00:00
data["license"] = project.License().Header
2017-04-29 12:53:52 +00:00
data["appName"] = path.Base(project.Name())
2017-04-29 10:02:02 +00:00
rootCmdScript, err := executeTemplate(template, data)
if err != nil {
er(err)
}
2015-10-28 16:51:48 +00:00
2017-04-29 12:53:52 +00:00
err = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript)
2015-10-28 16:51:48 +00:00
if err != nil {
er(err)
}
2015-10-28 16:51:48 +00:00
}