github.com/pojntfx/hydrapp/hydrapp@v0.0.0-20240516002902-d08759d6ca9f/pkg/utils/lock.go (about)

     1  package utils
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/fsnotify/fsnotify"
     7  )
     8  
     9  func WaitForLock(path string, handlePanic func(msg string, err error)) {
    10  	if _, err := os.Stat(path); err == nil {
    11  		// Wait until browser has exited
    12  		watcher, err := fsnotify.NewWatcher()
    13  		if err != nil {
    14  			handlePanic("could not start lockfile watcher", err)
    15  		}
    16  		defer watcher.Close()
    17  
    18  		done := make(chan struct{})
    19  		go func() {
    20  			for {
    21  				select {
    22  				case event, ok := <-watcher.Events:
    23  					if !ok {
    24  						return
    25  					}
    26  
    27  					// Stop the app
    28  					if event.Op&fsnotify.Remove == fsnotify.Remove {
    29  						done <- struct{}{}
    30  
    31  						return
    32  					}
    33  
    34  				case err, ok := <-watcher.Errors:
    35  					if !ok {
    36  						return
    37  					}
    38  
    39  					handlePanic("could not continue watching lockfile", err)
    40  				}
    41  			}
    42  		}()
    43  
    44  		err = watcher.Add(path)
    45  		if err != nil {
    46  			handlePanic("could not watch lockfile", err)
    47  		}
    48  
    49  		<-done
    50  	}
    51  }