-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: Drop
handlePanic
dependency from file watcher and instead…
… use `errors.Join` like usual Signed-off-by: Felicitas Pojtinger <felicitas@pojtinger.com>
- Loading branch information
Showing
2 changed files
with
38 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,51 +1,51 @@ | ||
package utils | ||
|
||
import ( | ||
"errors" | ||
"os" | ||
|
||
"github.com/fsnotify/fsnotify" | ||
) | ||
|
||
func WaitForFileRemoval(path string, handlePanic func(msg string, err error)) { | ||
var ( | ||
ErrCouldNotStartFileWatcher = errors.New("could not start file watcher") | ||
ErrCouldNotAddPathToFileWatcher = errors.New("could not add path to file watcher") | ||
ErrCouldNotWatchFile = errors.New("could not watch file") | ||
) | ||
|
||
func WaitForFileRemoval(path string) error { | ||
if _, err := os.Stat(path); err == nil { | ||
// Wait until browser has exited | ||
watcher, err := fsnotify.NewWatcher() | ||
if err != nil { | ||
handlePanic("could not start lockfile watcher", err) | ||
return errors.Join(ErrCouldNotStartFileWatcher, err) | ||
} | ||
defer watcher.Close() | ||
|
||
done := make(chan struct{}) | ||
go func() { | ||
for { | ||
select { | ||
case event, ok := <-watcher.Events: | ||
if !ok { | ||
return | ||
} | ||
|
||
// Stop the app | ||
if event.Op&fsnotify.Remove == fsnotify.Remove { | ||
done <- struct{}{} | ||
if err = watcher.Add(path); err != nil { | ||
return errors.Join(ErrCouldNotAddPathToFileWatcher, err) | ||
} | ||
|
||
return | ||
} | ||
for { | ||
select { | ||
case event, ok := <-watcher.Events: | ||
if !ok { | ||
return nil | ||
} | ||
|
||
case err, ok := <-watcher.Errors: | ||
if !ok { | ||
return | ||
} | ||
if event.Op&fsnotify.Remove == fsnotify.Remove { | ||
return nil | ||
} | ||
|
||
handlePanic("could not continue watching lockfile", err) | ||
case err, ok := <-watcher.Errors: | ||
if !ok { | ||
return nil | ||
} | ||
} | ||
}() | ||
|
||
err = watcher.Add(path) | ||
if err != nil { | ||
handlePanic("could not watch lockfile", err) | ||
return errors.Join(ErrCouldNotWatchFile, err) | ||
} | ||
} | ||
|
||
<-done | ||
} | ||
|
||
return nil | ||
} |