Skip to content

Commit

Permalink
Won't init if there are pre-existing hookz (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
djschleen authored May 5, 2021
1 parent 85c9d33 commit b017d59
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions cmd/init.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cmd

import (
"fmt"
"os"

"github.com/devops-kung-fu/hookz/lib"
"github.com/gookit/color"
"github.com/spf13/cobra"
Expand All @@ -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")
Expand Down
22 changes: 22 additions & 0 deletions lib/hookwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package lib
import (
"fmt"
"os"
"strings"
"text/template"

"github.com/segmentio/ksuid"
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions lib/hookwriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")

}

0 comments on commit b017d59

Please sign in to comment.