Skip to content

Commit

Permalink
feat: watcher works
Browse files Browse the repository at this point in the history
  • Loading branch information
bsach64 committed Dec 7, 2024
1 parent 83928bb commit 150677e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 48 deletions.
54 changes: 53 additions & 1 deletion cmd/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/bsach64/goback/server"
"github.com/bsach64/goback/utils"
"github.com/charmbracelet/huh"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -80,11 +81,15 @@ func ClientLoop(cmd *cobra.Command, args []string) {
}

case "Add Directory to Sync":
_, err := promptForDirectory()
dir, err := promptForDirectory()
if err != nil {
log.Error("Could not get directory for sync", "err", err)
continue
}
err = watchAndUpload(dir, sshC, worker)
if err != nil {
log.Error("Watcher with error", "err", err)
}

case "Exit":
fmt.Println("Exiting client.")
Expand All @@ -98,6 +103,53 @@ func ClientLoop(cmd *cobra.Command, args []string) {
}
}

func watchAndUpload(dir string, sshC *ssh.Client, worker server.Worker) error {
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}

watcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}

log.Info("Starting to watch directory:", dir)

go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
log.Error("Watcher events channel closed")
return
}
if event.Has(fsnotify.Create) {
err = uploadFile(sshC, event.Name, worker)
if err != nil {
log.Error("Could not upload newly created file", "file", event.Name, "err", err)
}
log.Info("Successfully Uploaded", "file", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
log.Error("Watcher errors channel closed")
return
}
log.Errorf("Watcher error: %v", err)
}
}
}()

err = watcher.Add(dir)
if err != nil {
watcher.Close() // Clean up if watcher.Add fails
return fmt.Errorf("failed to add directory to watcher: %v", err)
}

select {}
}

func uploadFile(sshC *ssh.Client, path string, worker server.Worker) error {
stat, err := os.Stat(path)
if err != nil {
Expand Down
47 changes: 0 additions & 47 deletions utils/watcher.go

This file was deleted.

0 comments on commit 150677e

Please sign in to comment.