Skip to content

Commit 7ea5e43

Browse files
feat(cmd): check if config exists in create cmd
* add replace flag to overwrite
1 parent 500e4a9 commit 7ea5e43

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

cmd/callback.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package cmd
22

33
import (
44
"fmt"
5+
"os"
56
"path/filepath"
67

78
"github.com/urfave/cli/v2"
@@ -46,9 +47,15 @@ func hookCreate(confPath string, isReplace bool) error {
4647
}
4748

4849
// configCreate is the callback function for create config command
49-
func configCreate(onlyEnabled bool) error {
50+
func configCreate(onlyEnabled, isReplace bool) error {
5051
defConf := config.GetDefaultConf(onlyEnabled)
5152
outPath := filepath.Join(".", config.DefaultFile)
53+
// if config file already exists skip creating or overwriting it
54+
if _, err := os.Stat(outPath); !os.IsNotExist(err) {
55+
if !isReplace {
56+
return errConfigExist
57+
}
58+
}
5259
return config.WriteConfToFile(outPath, defConf)
5360
}
5461

cmd/cmd.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,27 @@ func configCmd() *cli.Command {
104104
Usage: "writes only default enabled rules",
105105
Value: false,
106106
},
107+
&cli.BoolFlag{
108+
Name: "replace",
109+
Aliases: []string{"r"},
110+
Usage: "Replace conf file if already exists",
111+
Value: false,
112+
},
107113
},
108114
Action: func(ctx *cli.Context) error {
109115
isOnlyEnabled := ctx.Bool("enabled")
110-
return configCreate(isOnlyEnabled)
116+
isReplace := ctx.Bool("replace")
117+
err := configCreate(isOnlyEnabled, isReplace)
118+
if err != nil {
119+
if isConfExists(err) {
120+
fmt.Println("config create failed")
121+
fmt.Println("run with --replace to replace existing file")
122+
return nil
123+
}
124+
return err
125+
}
126+
fmt.Println("config file created")
127+
return nil
111128
},
112129
}
113130

cmd/hook.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const (
1414
)
1515

1616
var errHooksExist = errors.New("hooks already exists")
17+
var errConfigExist = errors.New("config file already exists")
1718

1819
func initHooks(confPath string, isGlobal, isReplace bool) (string, error) {
1920
hookDir, err := getHookDir(hookBaseDir, isGlobal)
@@ -74,3 +75,7 @@ func getHookDir(baseDir string, isGlobal bool) (string, error) {
7475
func isHookExists(err error) bool {
7576
return err == errHooksExist
7677
}
78+
79+
func isConfExists(err error) bool {
80+
return err == errConfigExist
81+
}

0 commit comments

Comments
 (0)