Skip to content

Commit

Permalink
🚧 Create hook package
Browse files Browse the repository at this point in the history
Add a package that will handle creation, removal and commiting when a
Git prepare message hook exists.
  • Loading branch information
mikelorant committed Feb 16, 2023
1 parent 348b3e2 commit cee22d8
Show file tree
Hide file tree
Showing 2 changed files with 154 additions and 0 deletions.
58 changes: 58 additions & 0 deletions internal/hook/hook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package hook

import (
"errors"
)

type Hook struct {
Action Action
}

type Options struct {
Install bool
Uninstall bool
Commit bool
}

type (
Action int
)

var ErrAction = errors.New("invalid hook action")

const (
ActionUnset Action = iota
ActionInstall
ActionUninstall
ActionCommit
)

func New(opts Options) Hook {
return Hook{
Action: action(opts),
}
}

func (h *Hook) Do() error {
switch h.Action {
case ActionInstall:
return nil
case ActionUninstall:
return nil
}

return ErrAction
}

func action(opts Options) Action {
switch {
case opts.Install:
return ActionInstall
case opts.Uninstall:
return ActionUninstall
case opts.Commit:
return ActionCommit
default:
return ActionUnset
}
}
96 changes: 96 additions & 0 deletions internal/hook/hook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package hook_test

import (
"testing"

"github.com/mikelorant/committed/internal/hook"
"github.com/stretchr/testify/assert"
)

func TestNew(t *testing.T) {
t.Parallel()

tests := []struct {
name string
input hook.Options
output hook.Hook
}{
{
name: "empty",
output: hook.Hook{},
},
{
name: "install",
input: hook.Options{Install: true},
output: hook.Hook{Action: hook.ActionInstall},
},
{
name: "uninstall",
input: hook.Options{Uninstall: true},
output: hook.Hook{Action: hook.ActionUninstall},
},
{
name: "commit",
input: hook.Options{Commit: true},
output: hook.Hook{Action: hook.ActionCommit},
},
}

for _, tt := range tests {
tt := tt

t.Run(tt.name, func(t *testing.T) {
t.Parallel()

got := hook.New(tt.input)

assert.Equal(t, tt.output, got)
})
}
}

func TestDo(t *testing.T) {
t.Parallel()

tests := []struct {
name string
input hook.Hook
err error
}{
{
name: "empty",
input: hook.Hook{},
err: hook.ErrAction,
},
{
name: "install",
input: hook.Hook{Action: hook.ActionInstall},
},
{
name: "uninstall",
input: hook.Hook{Action: hook.ActionUninstall},
},
{
name: "commit",
input: hook.Hook{Action: hook.ActionCommit},
err: hook.ErrAction,
},
{
name: "nil",
input: hook.Hook{},
err: hook.ErrAction,
},
}

for _, tt := range tests {
tt := tt

t.Run(tt.name, func(t *testing.T) {
t.Parallel()

err := tt.input.Do()

assert.ErrorIs(t, err, tt.err)
})
}
}

0 comments on commit cee22d8

Please sign in to comment.