1// Copyright © 2015 Steve Francia <spf@spf13.com>. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// http://www.apache.org/licenses/LICENSE-2.0 7// 8// Unless required by applicable law or agreed to in writing, software 9// distributed under the License is distributed on an "AS IS" BASIS, 10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11// See the License for the specific language governing permissions and 12// limitations under the License. 13 14package cmd 15 16import ( 17 "fmt" 18 "os" 19 "path" 20 21 "github.com/spf13/cobra" 22 "github.com/spf13/viper" 23) 24 25var ( 26 pkgName string 27 28 initCmd = &cobra.Command{ 29 Use: "init [name]", 30 Aliases: []string{"initialize", "initialise", "create"}, 31 Short: "Initialize a Cobra Application", 32 Long: `Initialize (cobra init) will create a new application, with a license 33and the appropriate structure for a Cobra-based CLI application. 34 35 * If a name is provided, a directory with that name will be created in the current directory; 36 * If no name is provided, the current directory will be assumed; 37`, 38 39 Run: func(_ *cobra.Command, args []string) { 40 41 projectPath, err := initializeProject(args) 42 cobra.CheckErr(err) 43 fmt.Printf("Your Cobra application is ready at\n%s\n", projectPath) 44 }, 45 } 46) 47 48func init() { 49 initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name") 50 cobra.CheckErr(initCmd.MarkFlagRequired("pkg-name")) 51} 52 53func initializeProject(args []string) (string, error) { 54 wd, err := os.Getwd() 55 if err != nil { 56 return "", err 57 } 58 59 if len(args) > 0 { 60 if args[0] != "." { 61 wd = fmt.Sprintf("%s/%s", wd, args[0]) 62 } 63 } 64 65 project := &Project{ 66 AbsolutePath: wd, 67 PkgName: pkgName, 68 Legal: getLicense(), 69 Copyright: copyrightLine(), 70 Viper: viper.GetBool("useViper"), 71 AppName: path.Base(pkgName), 72 } 73 74 if err := project.Create(); err != nil { 75 return "", err 76 } 77 78 return project.AbsolutePath, nil 79} 80