Skip to content

Commit b017d59

Browse files
authored
Won't init if there are pre-existing hookz (#37)
1 parent 85c9d33 commit b017d59

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

cmd/init.go

+14
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package cmd
22

33
import (
4+
"fmt"
5+
"os"
6+
47
"github.com/devops-kung-fu/hookz/lib"
58
"github.com/gookit/color"
69
"github.com/spf13/cobra"
@@ -12,6 +15,17 @@ var (
1215
Aliases: []string{"init"},
1316
Short: "Initializes the hooks as defined in the .hookz.yaml file.",
1417
Long: "Initializes the hooks as defined in the .hookz.yaml file.",
18+
PreRun: func(cmd *cobra.Command, args []string) {
19+
existingHookz := lib.NewDeps().HasExistingHookz()
20+
if existingHookz {
21+
fmt.Println("Existing hookz files detected")
22+
fmt.Println("\nDid you mean to reset?")
23+
fmt.Println(" hookz reset [--verbose]")
24+
fmt.Println("\nRun 'hookz --help' for usage.")
25+
fmt.Println()
26+
os.Exit(1)
27+
}
28+
},
1529
Run: func(cmd *cobra.Command, args []string) {
1630
deps := lib.NewDeps()
1731
color.Style{color.FgLightBlue, color.OpBold}.Println("Initializing Hooks")

lib/hookwriter.go

+22
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package lib
44
import (
55
"fmt"
66
"os"
7+
"strings"
78
"text/template"
89

910
"github.com/segmentio/ksuid"
@@ -145,6 +146,27 @@ func (f FileSystem) writeTemplate(commands []command, hookType string) (err erro
145146
return
146147
}
147148

149+
func (f FileSystem) HasExistingHookz() (exists bool) {
150+
path, _ := os.Getwd()
151+
ext := ".hookz"
152+
p := fmt.Sprintf("%s/%s", path, ".git/hooks")
153+
dirFiles, _ := f.Afero().ReadDir(p)
154+
155+
for index := range dirFiles {
156+
file := dirFiles[index]
157+
158+
name := file.Name()
159+
fullPath := fmt.Sprintf("%s/%s", p, name)
160+
info, _ := f.Afero().Stat(fullPath)
161+
isHookzFile := strings.Contains(info.Name(), ext)
162+
if isHookzFile {
163+
return true
164+
}
165+
}
166+
167+
return false
168+
}
169+
148170
func genTemplate(hookType string) (t *template.Template) {
149171

150172
content := `#!/bin/bash

lib/hookwriter_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,18 @@ func Test_writeTemplate(t *testing.T) {
6565
err := f.writeTemplate(nil, "")
6666
assert.Error(t, err, "writeTemplate should throw an error if there is no file created")
6767
}
68+
69+
func Test_HasExistingHookz(t *testing.T) {
70+
exists := f.HasExistingHookz()
71+
assert.False(t, exists, "No hookz files should exist")
72+
73+
config, err := f.createConfig(version)
74+
assert.NoError(t, err, "createConfig should not have generated an error")
75+
76+
err = f.WriteHooks(config, true)
77+
assert.NoError(t, err, "WriteHooks should not have generated an error")
78+
79+
exists = f.HasExistingHookz()
80+
assert.True(t, exists, "hookz files should exist")
81+
82+
}

0 commit comments

Comments
 (0)