diff --git a/cmd/init.go b/cmd/init.go index 40a3612..70dcf88 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1,6 +1,7 @@ package cmd import ( + "fmt" "os" "github.com/markbates/refresh/refresh" @@ -14,7 +15,10 @@ func init() { var initCmd = &cobra.Command{ Use: "init", Short: "generates a default configuration file for you.", - Run: func(cmd *cobra.Command, args []string) { + RunE: func(cmd *cobra.Command, args []string) error { + // Do not report errors as wrong usage + cmd.SilenceUsage = true + c := refresh.Configuration{ AppRoot: ".", IgnoredFolders: []string{"vendor", "log", "logs", "tmp", "node_modules", "bin", "templates"}, @@ -27,6 +31,16 @@ var initCmd = &cobra.Command{ CommandEnv: []string{}, EnableColors: true, } - c.Dump(cfgFile) + + if cfgFile == "" { + cfgFile = "refresh.yml" + } + + _, err := os.Stat(cfgFile) + if !os.IsNotExist(err) { + return fmt.Errorf("config file %q already exists, skipping init", cfgFile) + } + + return c.Dump(cfgFile) }, } diff --git a/cmd/root.go b/cmd/root.go index c3b99e2..66582cc 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -16,14 +16,13 @@ var RootCmd = &cobra.Command{ PersistentPreRun: func(cmd *cobra.Command, args []string) { fmt.Printf("Refresh (%s)\n\n", Version) }, - Run: func(cmd *cobra.Command, args []string) { - Run(cfgFile) + RunE: func(cmd *cobra.Command, args []string) error { + return Run(cfgFile) }, } func Execute() { if err := RootCmd.Execute(); err != nil { - fmt.Println(err) os.Exit(-1) } } diff --git a/cmd/run.go b/cmd/run.go index 5729274..673805f 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -26,18 +26,17 @@ var runCmd = &cobra.Command{ }, } -func Run(cfgFile string) { +func Run(cfgFile string) error { ctx := context.Background() - RunWithContext(cfgFile, ctx) + return RunWithContext(cfgFile, ctx) } -func RunWithContext(cfgFile string, ctx context.Context) { +func RunWithContext(cfgFile string, ctx context.Context) error { c := &refresh.Configuration{} if err := loadConfig(c, cfgFile); err != nil { if err != ErrConfigNotExist { - log.Fatalln(err) - os.Exit(-1) + return err } log.Println("No configuration loaded, proceeding with defaults") @@ -52,10 +51,7 @@ func RunWithContext(cfgFile string, ctx context.Context) { } r := refresh.NewWithContext(c, ctx) - if err := r.Start(); err != nil { - log.Fatalln(err) - os.Exit(-1) - } + return r.Start() } func loadConfig(c *refresh.Configuration, path string) error {