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			if err != nil {
43				er(err)
44			}
45			fmt.Printf("Your Cobra application is ready at\n%s\n", projectPath)
46		},
47	}
48)
49
50func init() {
51	initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")
52	initCmd.MarkFlagRequired("pkg-name")
53}
54
55func initializeProject(args []string) (string, error) {
56	wd, err := os.Getwd()
57	if err != nil {
58		return "", err
59	}
60
61	if len(args) > 0 {
62		if args[0] != "." {
63			wd = fmt.Sprintf("%s/%s", wd, args[0])
64		}
65	}
66
67	project := &Project{
68		AbsolutePath: wd,
69		PkgName:      pkgName,
70		Legal:        getLicense(),
71		Copyright:    copyrightLine(),
72		Viper:        viper.GetBool("useViper"),
73		AppName:      path.Base(pkgName),
74	}
75
76	if err := project.Create(); err != nil {
77		return "", err
78	}
79
80	return project.AbsolutePath, nil
81}
82