Skip to content

Commit

Permalink
refactor: inject watch use case dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
lucaschain committed Dec 3, 2023
1 parent 6459fb3 commit 79da97d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
10 changes: 9 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"os"
"strings"

"github.com/lucaschain/beholder/infrastructure"
"github.com/lucaschain/beholder/use_case"
"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -33,5 +34,12 @@ func init() {
func Run(cmd *cobra.Command, args []string) {
paths := strings.Split(args[0], ",")
command := args[1:]
use_case.Watch(paths, command, types, allowFailing)

watchConfig := use_case.WatchConfig{
Paths: paths,
Command: command,
AllowedTypes: types,
AllowFailing: allowFailing,
}
use_case.Watch(watchConfig, infrastructure.FileWatcher, infrastructure.Command)
}
34 changes: 21 additions & 13 deletions use_case/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,41 @@ import (

"github.com/lucaschain/beholder/core"
"github.com/lucaschain/beholder/core/event_types"
"github.com/lucaschain/beholder/infrastructure"
)

func onFileChange(command []string, allowedTypes []string, allowFailing bool) core.ChangeCallback {
type WatchConfig struct {
Paths []string
Command []string
AllowedTypes []string
AllowFailing bool
}

type FileWatcher func(paths []string, callback core.ChangeCallback)
type CommandRunner func(command []string) error

func onFileChange(c WatchConfig, commandRunner CommandRunner) core.ChangeCallback {
return func(event *core.ChangeEvent, err *error) {
if err != nil {
log.Fatal(err)
}

if event_types.Filter(event.Type, allowedTypes) {
command := core.CommandTokens(command, event)
commandError := infrastructure.Command(command)
if event_types.Filter(event.Type, c.AllowedTypes) {
command := core.CommandTokens(c.Command, event)
commandError := commandRunner(command)

if commandError != nil && !allowFailing {
if commandError != nil && !c.AllowFailing {
log.Fatal(commandError)
}
}
}
}

func Watch(
paths []string,
command []string,
allowedTypes []string,
allowFailing bool,
c WatchConfig,
fileWatcher FileWatcher,
commandRunner CommandRunner,
) {
fmt.Printf("Watching path: %s and running command: '%s'\n", paths, command)
callback := onFileChange(command, allowedTypes, allowFailing)
infrastructure.FileWatcher(paths, callback)
fmt.Printf("Watching path: %s and running command: '%s'\n", c.Paths, c.Command)
callback := onFileChange(c, commandRunner)
fileWatcher(c.Paths, callback)
}

0 comments on commit 79da97d

Please sign in to comment.