Skip to content

Commit

Permalink
Merge pull request #34 from devops-kung-fu/unit_tests
Browse files Browse the repository at this point in the history
refactor: Additional unit tests and refactoring
  • Loading branch information
djschleen authored May 5, 2021
2 parents 163a8db + 07af5d5 commit 85c9d33
Show file tree
Hide file tree
Showing 10 changed files with 193 additions and 79 deletions.
2 changes: 1 addition & 1 deletion .hookz.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
args: ["-ignoretests", "./..."]
- name: "gocyclo: Check cyclomatic complexities"
exec: gocyclo
args: ["-over", "13", "."]
args: ["-over", "9", "."]
- name: "go: Build (Ensure pulled modules do not break the build)"
exec: go
args: ["build", "-v"]
Expand Down
2 changes: 1 addition & 1 deletion cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ var (
if lib.IsErrorBool(err, "[ERROR]") {
return
}
if lib.IsErrorBool(lib.UpdateExecutables(config), "[ERROR]") {
if lib.IsErrorBool(lib.NewDeps().UpdateExecutables(config), "[ERROR]") {
return
}
color.Style{color.FgLightGreen}.Println("\nDone!")
Expand Down
36 changes: 25 additions & 11 deletions lib/configreader.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"log"
"os"
"path/filepath"
"reflect"
"strings"

"github.com/manifoldco/promptui"
Expand All @@ -16,7 +17,6 @@ import (
func (f FileSystem) ReadConfig(version string) (config Configuration, err error) {

filename, _ := filepath.Abs(".hookz.yaml")
//yamlFile, readErr := ioutil.ReadFile(filename)
yamlFile, readErr := f.Afero().ReadFile(filename)
if readErr != nil {
config, err = f.promptCreateConfig(version)
Expand All @@ -40,6 +40,10 @@ func checkVersion(config Configuration, version string) (err error) {
err = errors.New("no configuration version value found in .hookz.yaml")
return
}
if version == "" {
err = errors.New("a version should not be empty")
return
}
ver := strings.Split(config.Version, ".")
verMatch := strings.Split(version, ".")
if fmt.Sprintf("%v.%v", ver[0], ver[1]) != fmt.Sprintf("%v.%v", verMatch[0], verMatch[1]) {
Expand All @@ -49,27 +53,37 @@ func checkVersion(config Configuration, version string) (err error) {
}

func (f FileSystem) promptCreateConfig(version string) (config Configuration, err error) {
fmt.Println("\nHookz was unable to find a .hookz.yaml file. Would you like")
fmt.Println("to create a starter configuration?")
var result string
fsType := reflect.TypeOf(f.fs)

prompt := promptui.Prompt{
Label: "Create starter .hookz.yaml?",
IsConfirm: true,
}
if fsType.String() == "*afero.OsFs" {
var promptErr error

fmt.Println("\nHookz was unable to find a .hookz.yaml file. Would you like")
fmt.Println("to create a starter configuration?")

prompt := promptui.Prompt{
Label: "Create starter .hookz.yaml?",
IsConfirm: true,
}

result, promptErr := prompt.Run()
result, promptErr = prompt.Run()

if promptErr != nil {
goto CONFIG_ERR
if promptErr != nil {
goto CONFIG_ERR
}
} else {
result = "y"
}

if result == "y" {
config, err = f.createConfig(version)
}

return

CONFIG_ERR:
log.Println("[ERROR]: Hookz cannot run without a .hookz.yaml file. Create one and try again")
os.Exit(1)

return
}
17 changes: 17 additions & 0 deletions lib/configreader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ func TestDeps_ReadConfig(t *testing.T) {

assert.NoError(t, err, "ReadConfig should not have generated an error")
assert.Equal(t, version, readConfig.Version, "Versions should match")

_, err = f.ReadConfig("")
assert.Error(t, err, "Passing an empty string should cause an error")
}

func TestDeps_checkVersion(t *testing.T) {
Expand All @@ -31,4 +34,18 @@ func TestDeps_checkVersion(t *testing.T) {

err = checkVersion(readConfig, version)
assert.NoError(t, err, "Check version should not have generated an error")

err = checkVersion(readConfig, "2.0")
assert.Error(t, err, "Version mismatch not caught")

readConfig.Version = ""
err = checkVersion(readConfig, version)
assert.Error(t, err, "An empty config version should throw an error")
}

func Test_promptCreateConfig(t *testing.T) {

config, err := f.promptCreateConfig(version)
assert.Equal(t, version, config.Version, "Version mismatch")
assert.NoError(t, err, "Expected no error to be thrown")
}
22 changes: 12 additions & 10 deletions lib/hookdeleter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,40 @@ package lib

import (
"fmt"
"regexp"
"os"
"strings"
)

func (f FileSystem) RemoveHooks() (err error) {

path, _ := os.Getwd()

ext := ".hookz"
p := ".git/hooks/"
p := fmt.Sprintf("%s/%s", path, ".git/hooks")

dirFiles, err := f.Afero().ReadDir(p)
if err != nil {
return err
}
dirFiles, _ := f.Afero().ReadDir(p)

for index := range dirFiles {
file := dirFiles[index]

name := file.Name()
fullPath := fmt.Sprintf("%s%s", p, name)
r, err := regexp.MatchString(ext, fullPath)
if err == nil && r {
fullPath := fmt.Sprintf("%s/%s", p, name)
info, _ := f.Afero().Stat(fullPath)
isHookzFile := strings.Contains(info.Name(), ext)
if isHookzFile {
var hookName = fullPath[0 : len(fullPath)-len(ext)]
removeErr := f.fs.Remove(fullPath)
if removeErr != nil {
return removeErr
}
var hookName = fullPath[0 : len(fullPath)-len(ext)]
removeErr = f.fs.Remove(hookName)
if removeErr != nil {
return removeErr
}
parts := strings.Split(hookName, "/")
fmt.Printf(" Deleted %s\n", parts[len(parts)-1])
}

}
fmt.Println("[*] Successfully removed existing hooks!")

Expand Down
28 changes: 28 additions & 0 deletions lib/hookdeleter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//Package lib Functionality for the Hookz CLI
package lib

import (
"fmt"
"os"
"testing"

"github.com/stretchr/testify/assert"
)

func TestFileSystem_RemoveHooks(t *testing.T) {
path, _ := os.Getwd()

content := "Test Script"
f.CreateScriptFile(content)

p := fmt.Sprintf("%s/%s", path, ".git/hooks")
dirFiles, _ := f.Afero().ReadDir(p)
assert.Equal(t, 2, len(dirFiles), "Incorrect number of created script files")

err := f.RemoveHooks()
assert.NoError(t, err, "RemoveHooks should not have generated an error")

dirFiles, _ = f.Afero().ReadDir(p)
assert.Equal(t, 0, len(dirFiles), "Incorrect number of created script files")

}
93 changes: 44 additions & 49 deletions lib/hookwriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package lib
import (
"fmt"
"os"
"path/filepath"
"text/template"

"github.com/segmentio/ksuid"
Expand Down Expand Up @@ -34,35 +33,28 @@ func (f FileSystem) CreateFile(name string) (err error) {
func (f FileSystem) CreateScriptFile(content string) (name string, err error) {

k, idErr := ksuid.NewRandom()
name, _ = filepath.Abs(fmt.Sprintf(".git/hooks/%s", k.String()))
name = k.String()
if IsErrorBool(idErr, "ERROR") {
err = idErr
return
}
hookzFile, hookzFileErr := filepath.Abs(fmt.Sprintf(".git/hooks/%s.hookz", k.String()))
if hookzFileErr != nil {
err = hookzFileErr
return
}
path, _ := os.Getwd()
p := fmt.Sprintf("%s/%s", path, ".git/hooks")

hookzFile := fmt.Sprintf("%s/%s.hookz", p, name)
scriptName := fmt.Sprintf("%s/%s", p, name)

err = f.CreateFile(hookzFile)
if err != nil {
return
}

file, err := f.fs.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
err = f.Afero().WriteFile(scriptName, []byte(content), 0644)
if err != nil {
return
}
_, err = file.WriteString(content)
if err != nil {
return
}

defer func() {
err = file.Close()
}()

err = f.fs.Chmod(name, 0777)
err = f.fs.Chmod(scriptName, 0777)
if err != nil {
return
}
Expand Down Expand Up @@ -90,38 +82,19 @@ func (f FileSystem) WriteHooks(config Configuration, verbose bool) (err error) {
for _, hook := range config.Hooks {
var commands []command

filename, _ := filepath.Abs(fmt.Sprintf(".git/hooks/%s", hook.Type))
hookzFile, _ := filepath.Abs(fmt.Sprintf(".git/hooks/%s.hookz", hook.Type))

err = f.CreateFile(hookzFile)
if err != nil {
return err
}

var file, err = f.fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}

defer func() {
err = file.Close()
}()

fmt.Printf("\n[*] Writing %s \n", hook.Type)

for _, action := range hook.Actions {

if action.Exec == nil && action.URL != nil {
filename, _ := DownloadURL(*action.URL)
filename, _ := f.DownloadURL(*action.URL)
action.Exec = &filename
}

if action.Exec == nil && action.Script != nil {
scriptFileName, err := f.CreateScriptFile(*action.Script)
if err != nil {
return err
}
action.Exec = &scriptFileName
path, _ := os.Getwd()
fullScriptFileName := fmt.Sprintf("%s/%s/%s", path, ".git/hooks", scriptFileName)
action.Exec = &fullScriptFileName
}

fmt.Printf(" Adding %s action: %s\n", hook.Type, action.Name)
Expand All @@ -135,21 +108,43 @@ func (f FileSystem) WriteHooks(config Configuration, verbose bool) (err error) {
FullCommand: fullCommand,
})
}

t := genTemplate(hook.Type)
err = t.ExecuteTemplate(file, hook.Type, commands)
if err != nil {
return err
}
err = f.fs.Chmod(filename, 0777)
err = f.writeTemplate(commands, hook.Type)
if err != nil {
return err
return
}
fmt.Println("[*] Successfully wrote " + hook.Type)
}
return nil
}

func (f FileSystem) writeTemplate(commands []command, hookType string) (err error) {
path, _ := os.Getwd()
p := fmt.Sprintf("%s/%s", path, ".git/hooks")

hookzFile := fmt.Sprintf("%s/%s.hookz", p, hookType)
err = f.CreateFile(hookzFile)
if err != nil {
return
}

fmt.Printf("\n[*] Writing %s \n", hookType)
filename := fmt.Sprintf("%s/%s", p, hookType)
file, err := f.Afero().Create(filename)
if err != nil {
return err
}
t := genTemplate(hookType)
err = t.ExecuteTemplate(file, hookType, commands)
if err != nil {
return err
}
err = f.fs.Chmod(filename, 0777)
if err != nil {
return err
}
fmt.Println("[*] Successfully wrote " + hookType)
return
}

func genTemplate(hookType string) (t *template.Template) {

content := `#!/bin/bash
Expand Down
22 changes: 22 additions & 0 deletions lib/hookwriter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
package lib

import (
"fmt"
"os"
"path/filepath"
"testing"

Expand All @@ -13,6 +15,11 @@ func TestDeps_CreateScriptFile(t *testing.T) {
filename, err := f.CreateScriptFile(content)
assert.NoError(t, err, "CreateScriptFile should not have generated an error")
assert.NotEmpty(t, filename, "A filename should have been returned")

path, _ := os.Getwd()
fullFileName := fmt.Sprintf("%s/%s/%s", path, ".git/hooks", filename)
contains, _ := f.Afero().FileContainsBytes(fullFileName, []byte(content))
assert.True(t, contains, "Script file should have the phrase `Test Script` in it")
}

func Test_genTemplate(t *testing.T) {
Expand Down Expand Up @@ -43,3 +50,18 @@ func Test_WriteHooks(t *testing.T) {
contains, _ := f.Afero().FileContainsBytes(filename, []byte("Hookz"))
assert.True(t, contains, "Generated hook should have the word Hookz in it")
}

func Test_createFile(t *testing.T) {
err := f.CreateFile("test")
assert.NoError(t, err, "Create file should not generate an error")
// assert.FileExists(t, "./test", "A file should have been created")

// err = f.CreateFile("")
// assert.Error(t, err, "A file should have not been created and an error thrown")

}

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")
}
Loading

0 comments on commit 85c9d33

Please sign in to comment.