From b017d59df4bab7f5e3ad85e647d70cb769750df3 Mon Sep 17 00:00:00 2001 From: DJ Schleen Date: Wed, 5 May 2021 10:46:16 -0600 Subject: [PATCH] Won't init if there are pre-existing hookz (#37) --- cmd/init.go | 14 ++++++++++++++ lib/hookwriter.go | 22 ++++++++++++++++++++++ lib/hookwriter_test.go | 15 +++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/cmd/init.go b/cmd/init.go index af2a0d3..4bb9ab1 100644 --- a/cmd/init.go +++ b/cmd/init.go @@ -1,6 +1,9 @@ package cmd import ( + "fmt" + "os" + "github.com/devops-kung-fu/hookz/lib" "github.com/gookit/color" "github.com/spf13/cobra" @@ -12,6 +15,17 @@ var ( Aliases: []string{"init"}, Short: "Initializes the hooks as defined in the .hookz.yaml file.", Long: "Initializes the hooks as defined in the .hookz.yaml file.", + PreRun: func(cmd *cobra.Command, args []string) { + existingHookz := lib.NewDeps().HasExistingHookz() + if existingHookz { + fmt.Println("Existing hookz files detected") + fmt.Println("\nDid you mean to reset?") + fmt.Println(" hookz reset [--verbose]") + fmt.Println("\nRun 'hookz --help' for usage.") + fmt.Println() + os.Exit(1) + } + }, Run: func(cmd *cobra.Command, args []string) { deps := lib.NewDeps() color.Style{color.FgLightBlue, color.OpBold}.Println("Initializing Hooks") diff --git a/lib/hookwriter.go b/lib/hookwriter.go index 0a8e131..6deb142 100644 --- a/lib/hookwriter.go +++ b/lib/hookwriter.go @@ -4,6 +4,7 @@ package lib import ( "fmt" "os" + "strings" "text/template" "github.com/segmentio/ksuid" @@ -145,6 +146,27 @@ func (f FileSystem) writeTemplate(commands []command, hookType string) (err erro return } +func (f FileSystem) HasExistingHookz() (exists bool) { + path, _ := os.Getwd() + ext := ".hookz" + p := fmt.Sprintf("%s/%s", path, ".git/hooks") + dirFiles, _ := f.Afero().ReadDir(p) + + for index := range dirFiles { + file := dirFiles[index] + + name := file.Name() + fullPath := fmt.Sprintf("%s/%s", p, name) + info, _ := f.Afero().Stat(fullPath) + isHookzFile := strings.Contains(info.Name(), ext) + if isHookzFile { + return true + } + } + + return false +} + func genTemplate(hookType string) (t *template.Template) { content := `#!/bin/bash diff --git a/lib/hookwriter_test.go b/lib/hookwriter_test.go index a9b15d8..55db47f 100644 --- a/lib/hookwriter_test.go +++ b/lib/hookwriter_test.go @@ -65,3 +65,18 @@ func Test_writeTemplate(t *testing.T) { err := f.writeTemplate(nil, "") assert.Error(t, err, "writeTemplate should throw an error if there is no file created") } + +func Test_HasExistingHookz(t *testing.T) { + exists := f.HasExistingHookz() + assert.False(t, exists, "No hookz files should exist") + + config, err := f.createConfig(version) + assert.NoError(t, err, "createConfig should not have generated an error") + + err = f.WriteHooks(config, true) + assert.NoError(t, err, "WriteHooks should not have generated an error") + + exists = f.HasExistingHookz() + assert.True(t, exists, "hookz files should exist") + +}